Skip to content

Claude's answers, rendered: Markdown, math, charts and diagrams drawn in the Claude Code terminal. Independent project, not affiliated with Anthropic.

TypeScript claude-code-mod

md-preview 0.1.0: Claude's answers as rendered Markdown pictures

razorback1679f243a9f704
diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json
new file mode 100644
index 0000000..9a6bd03
--- /dev/null
+++ b/.claude-plugin/marketplace.json
@@ -0,0 +1,8 @@
+{
+ "name": "razorback16",
+ "owner": { "name": "razorback16" },
+ "metadata": {
+ "description": "md-preview: Claude's answers drawn as rendered Markdown in your terminal"
+ },
+ "plugins": [{ "name": "md-preview", "source": "./" }]
+}
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
new file mode 100644
index 0000000..0d65784
--- /dev/null
+++ b/.claude-plugin/plugin.json
@@ -0,0 +1,24 @@
+{
+ "name": "md-preview",
+ "version": "0.1.0",
+ "description": "Draws Claude's answers as rendered Markdown pictures, like VS Code's preview, with live Typst for diagrams, charts and math",
+ "author": {
+ "name": "razorback16",
+ "url": "https://github.com/razorback16"
+ },
+ "homepage": "https://github.com/razorback16/claude-md-preview",
+ "repository": "https://github.com/razorback16/claude-md-preview",
+ "documentationUrl": "https://github.com/razorback16/claude-md-preview#readme",
+ "license": "MIT",
+ "keywords": [
+ "markdown",
+ "preview",
+ "typst",
+ "terminal",
+ "kitty",
+ "ghostty",
+ "iterm2",
+ "themes"
+ ],
+ "types": "./types/index.d.ts"
+}
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..a7d11fe
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,5 @@
+.DS_Store
+*.log
+node_modules/
+.mcpb-cache/
+.claude-plugin/types/
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..89b56d0
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 razorback16
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..68eb773
--- /dev/null
+++ b/README.md
@@ -0,0 +1,138 @@
+# md-preview
+
+A Claude Code mod that draws Claude's answers as rendered Markdown pictures, with a look close to VS Code's Markdown preview. Claude can also put live Typst in an answer, for diagrams, charts and math.
+
+Only the drawing changes. The saved answer stays Markdown.
+
+## What it draws
+
+- Headings, lists, task lists, tables, block quotes, links, footnotes and horizontal rules
+- Code blocks with syntax colours, in your terminal's font (found for iTerm2 and Ghostty; else Menlo, SF Mono or DejaVu Sans Mono)
+- Math (`$…$` and `$$…$$`, LaTeX syntax, through mitex)
+- Images from `![alt](path)`. A relative path starts from the session's folder. Remote images show as an alt-text box.
+- Live Typst: a fenced block with the language `typst` (or `typ`) is rendered, not shown as code. These packages are in the mod and work offline:
+
+ ```
+ #import "@preview/cetz:0.5.2"
+ #import "@preview/cetz-plot:0.1.4": plot, chart
+ #import "@preview/fletcher:0.5.8" as fletcher: diagram, node, edge
+ ```
+
+ A `theme` dictionary (`theme.fg`, `theme.muted`, `theme.blue`, `theme.palette`, `theme.width`, …) is in scope, so drawings match the terminal's colours. The mod tells Claude about this in a short part of the system prompt.
+
+## Requirements
+
+- Claude Code 2.1.301 or later (tested on 2.1.301)
+- [Typst](https://typst.app) 0.15 (tested on 0.15.1)
+- macOS (tested). Linux can work, but it is not tested.
+- A terminal where Claude Code draws pictures:
+ - **Ghostty and kitty:** pictures work with no setting.
+ - **iTerm2 (3.7.5 tested), WezTerm, Warp, Konsole:** set `CLAUDE_CODE_FORCE_TERMINAL_IMAGES=1` before you start Claude Code.
+ - Not inside tmux or screen (unless forced), and not over ssh. Set `MD_PREVIEW_FORCE=1` to try anyway.
+ - Background sessions (agent view, forks, `claude attach`) cannot draw pictures.
+
+ Where pictures cannot draw, the mod shows the normal text.
+
+## Install
+
+1. Install Typst: `brew install typst` (or see [Typst's install page](https://github.com/typst/typst#installation)).
+2. At the prompt of a Claude Code session in the terminal, type:
+
+ ```
+ /plugin install md-preview --marketplace razorback16/claude-md-preview
+ ```
+
+ Answer `y` to add the marketplace, then push Enter to install for your user. The mod starts at once, with no restart.
+
+From a shell:
+
+```
+claude plugin install md-preview --marketplace razorback16/claude-md-preview
+```
+
+To try it from a clone without installing: `claude --plugin-dir /path/to/claude-md-preview`.
+
+## Use
+
+| Command | What it does |
+|---|---|
+| `/md-preview` | Shows the state, the text size and the terminal font that the mod found |
+| `/md-preview on` / `off` | Turns the pictures on or off (kept for later sessions) |
+| `/md-preview size <80–200>` | Text size in percent. 100 is the same visual size as your terminal text. |
+| `/md-preview theme` | Lists the themes, shows which one is in use, and shows the folder for your own themes |
+| `/md-preview theme <name>` | Changes to that theme (kept for later sessions) |
+
+## Themes
+
+A theme sets the colours, fonts and spacing of the picture. Two themes are in the mod:
+
+| Name | Looks like |
+|---|---|
+| `vscode-modern` (default) | VS Code's Markdown preview with Dark Modern / Light Modern |
+| `vscode` | The same, with the Dark+ / Light+ colours |
+
+Each theme has a dark and a light part. The mod uses the part that agrees with Claude Code's theme.
+
+### Make your own theme
+
+1. Make a folder: `~/.claude/md-preview/themes/<name>/`.
+2. Put a `theme.json` in it. Write only the keys that you change. The mod merges your file over the base theme, `vscode` (not over the default, `vscode-modern`).
+3. Run `/md-preview theme <name>`. You do not have to restart.
+
+Example: pink inline code with rounder boxes.
+
+```json
+{
+ "name": "Pink code",
+ "dark": { "inline-code-fg": "#ff79c6", "inline-code-bg": "#ff79c626" },
+ "light": { "inline-code-fg": "#c2185b" },
+ "inline-code": { "radius-px": 8 }
+}
+```
+
+- A user theme with the same folder name as a built-in theme is used in its place. It is still merged over the built-in `vscode`.
+- Colours are `#rgb`, `#rgba`, `#rrggbb` or `#rrggbbaa`. The picture has no background, so a translucent colour (for example `#ffffff1a`) looks correct on all terminal colours.
+- A value of the wrong type is ignored, and the `vscode` value is used. If the file is not valid JSON, the theme is skipped, the default theme is used, and `/md-preview theme` tells you why.
+- For your own syntax colours, put TextMate theme files in the folder and name them: `"syntax": { "dark": "dark.tmTheme", "light": "light.tmTheme" }`. A file that you name must exist.
+
+All keys, their units and their defaults are in [`render/themes/README.md`](render/themes/README.md).
+
+The `vscode` and `vscode-modern` values come from VS Code (MIT licence, Copyright (c) 2015 - present Microsoft Corporation). The `LICENSE` file is in each of those folders.
+
+## How it works
+
+1. A `ui.render` hook on `AssistantMessage` gets each block of the answer as Markdown.
+2. When the text stops changing for 400 ms, the mod writes the block to a JSON file and runs `typst compile` with `render/md.typ`. Long answers are cut at block boundaries into pages. One page is one PNG.
+3. The hook draws one `Image` per PNG, in place of the text.
+4. Text size: the mod finds the terminal font (iTerm2 profile, Ghostty config, else Menlo metrics) and the cell size in pixels. Typst then measures both fonts so that 100% looks as large as the terminal text.
+5. If a compile fails (a bad Typst block or an unknown LaTeX command), the mod compiles once more in safe mode: Typst blocks and math show as code. A dim line under the picture names the error. If that also fails, the normal text shows.
+6. Pictures are kept in `${TMPDIR}/md-preview-<uid>/`. Folders older than 2 days are deleted at start.
+
+## Limitations
+
+- **Copying text from a picture does not work.** A picture fills its cells with kitty placeholder characters (U+10EEEE plus combining marks). Claude Code's mouse selection copies those cells directly to the clipboard, and no mod hook runs before that copy. So a paste gives strange characters, not the text. Use Claude Code's `/copy` to copy the last answer as Markdown (`/copy 2` for the one before it; it shows a picker for the full answer or one code block, unless "Skip the /copy picker" is on in `/config`), or turn the mod off (`/md-preview off`) to select text. To stop the clipboard write on select, set `copyOnSelect` to `false` in `/config`.
+- **Search does not find text in a picture.**
+- **While Claude writes**, the answer shows as normal text. The picture comes about 0.4 s after the text stops changing, plus 0.15–0.6 s to compile.
+- **Short summaries** between tool calls stay as text.
+- **Typst blocks:** `#page`, `#pagebreak` and `#set page` are errors. A package that is not in the mod cannot be downloaded (the network is blocked for Typst), so its block shows as code.
+- **Security:** Typst runs with `--root /`, so a Typst block can read any file that you can read and draw it in the picture. Nothing leaves the computer.
+- **The look is close to VS Code, not exact:** Typst does not use CSS. Raw HTML in Markdown is shown in a simple form or dropped. Loose lists have tight spacing.
+- **A picture that the terminal dropped from its image memory** (after many large pictures) is not sent again when you scroll back to it.
+- **`auto` theme** is drawn as dark.
+
+## Develop
+
+```
+git clone https://github.com/razorback16/claude-md-preview
+cd claude-md-preview
+claude --plugin-dir . # once: Claude Code writes the API types to .claude-plugin/types/
+npx -p typescript tsc -p . # type check
+claude plugin test . # tests
+claude plugin validate .
+```
+
+`.claude-plugin/types/` is not in git. `tsconfig.json` extends the `tsconfig.json` in it, so run Claude Code with the folder once before `tsc`.
+
+## Licence
+
+MIT, see [`LICENSE`](LICENSE). The vendored Typst packages and the VS Code theme values keep their own licences: see [`THIRD-PARTY-NOTICES.md`](THIRD-PARTY-NOTICES.md).
diff --git a/THIRD-PARTY-NOTICES.md b/THIRD-PARTY-NOTICES.md
new file mode 100644
index 0000000..25ecded
--- /dev/null
+++ b/THIRD-PARTY-NOTICES.md
@@ -0,0 +1,29 @@
+# Third-party notices
+
+md-preview is MIT licensed (see `LICENSE`). It includes the work of others, each under its own licence. Each folder below holds that project's licence file.
+
+## Typst packages (in `render/packages/preview/`)
+
+These are copies of the published packages from [Typst Universe](https://typst.app/universe), so the mod works offline.
+
+| Package | Version | Licence |
+|---|---|---|
+| [cmarker](https://typst.app/universe/package/cmarker) | 0.1.6 | MIT |
+| [mitex](https://typst.app/universe/package/mitex) | 0.2.7 | Apache-2.0 |
+| [cetz](https://typst.app/universe/package/cetz) | 0.5.2, 0.3.4 | LGPL-3.0-or-later |
+| [cetz-plot](https://typst.app/universe/package/cetz-plot) | 0.1.4 | LGPL-3.0-or-later |
+| [fletcher](https://typst.app/universe/package/fletcher) | 0.5.8 | MIT |
+| [oxifmt](https://typst.app/universe/package/oxifmt) | 1.0.0 | MIT OR Apache-2.0 |
+| [oxifmt](https://typst.app/universe/package/oxifmt) | 0.2.1 | MIT-0 |
+
+cetz 0.3.4 and oxifmt are there because other packages import them.
+
+cetz and cetz-plot are under the LGPL-3.0. Their full licence text is in their folders. The LGPL-3.0 refers to the GPL-3.0, which is at https://www.gnu.org/licenses/gpl-3.0.html.
+
+## VS Code (in `render/themes/vscode/` and `render/themes/vscode-modern/`)
+
+The colours, sizes and spacing of the two built-in themes come from [VS Code](https://github.com/microsoft/vscode): its Markdown preview styles (`markdown.css`, `highlight.css`) and its Dark+, Light+, Dark Modern and Light Modern themes. MIT, Copyright (c) 2015 - present Microsoft Corporation. The `source` key in each `theme.json` names the files.
+
+## show-your-work
+
+The one-line Perl command that reads the terminal's cell size in pixels (`CELL_SH` in `hooks/register.tsx`) comes from [show-your-work](https://github.com/iamumeransari/claude-show-your-work). MIT, Copyright (c) 2026 Umer Ansari.
diff --git a/hooks/hooks.json b/hooks/hooks.json
new file mode 100644
index 0000000..5a63f64
--- /dev/null
+++ b/hooks/hooks.json
@@ -0,0 +1 @@
+{ "modules": ["./register.tsx"] }
diff --git a/hooks/register.tsx b/hooks/register.tsx
new file mode 100644
index 0000000..a5693bc
--- /dev/null
+++ b/hooks/register.tsx
@@ -0,0 +1,1122 @@
+// md-preview: draws Claude's answers (AssistantMessage blocks) as pictures of
+// rendered Markdown, made by Typst from the template in ../render/md.typ.
+// The stored message never changes; only its drawing does.
+//
+// Flow: the render hook makes a key from the text, the width, the cell size,
+// the theme and the template. A known key draws its PNGs. An unknown key
+// draws the plain text and starts a timer; when the text has been still for
+// SETTLE_MS the key is compiled (at most MAX_RUNNING at once), and the `done`
+// atom goes up so every reader draws again and finds the PNGs.
+import { atom, read, update } from 'claude-code'
+import type { EngineInterface, Register, RenderInput } from 'claude-code'
+
+import type { MdPreviewTheme } from '../types'
+
+// ---- Settings -------------------------------------------------------------
+
+// The widest picture, in terminal columns.
+export const MAX_COLUMNS = 120
+// The bullet column to the left of an answer.
+const GUTTER = 2
+// Claude Code's own reply bullet: ⏺ on macOS, ● elsewhere.
+const bulletOf = (isMac: boolean) => (isMac ? '⏺' : '●')
+// The engine's answer row has a blank row above it; ours keeps it.
+const MARGIN_TOP = 1
+// The template's body text size in pt; the page width is chosen so that this
+// text looks as big as the terminal's own (see fontFit).
+const BODY_PT = 11
+// `/md-preview size`: a percent on top of that match.
+export const DEFAULT_SIZE = 100
+export const MIN_SIZE = 80
+export const MAX_SIZE = 200
+// Wait this long after the last change of a block's text before compiling.
+const SETTLE_MS = 400
+const MAX_RUNNING = 2
+// A segment is cut to be about this many rows; an Image is 255 rows at most.
+export const SEGMENT_ROWS = 160
+const MAX_IMAGE_ROWS = 255
+// The cell in device pixels when the tty reports none (tmux, a relay): an
+// 8 x 16 point cell at Retina scale 2. A reported cell outside 4 to 64 px
+// wide is not trusted.
+export const DEFAULT_CELL: Cell = { width: 16, height: 32 }
+// Part of every key: bump it when the interface with the template changes.
+const TEMPLATE_VERSION = '7'
+const COMPILE_TIMEOUT_MS = 20000
+const ALT_CHARS = 200
+// Where Typst is when the login shell's PATH does not find it. `~` is $HOME.
+const TYPST_FALLBACKS = ['/opt/homebrew/bin/typst', '/usr/local/bin/typst', '/usr/bin/typst', '/snap/bin/typst', '~/.cargo/bin/typst', '~/.local/bin/typst']
+const NO_TYPST = 'md-preview: install Typst (brew install typst) to see rendered answers'
+// Typst downloads a package it doesn't find under --package-path; a proxy
+// nobody listens on makes that fail at once, so a live block never fetches.
+const NO_NETWORK = 'http://127.0.0.1:9'
+// The base every theme merges over (its theme.json and syntax files).
+export const BASE_THEME = 'vscode'
+// The theme used when none is chosen, or when the chosen one is not usable.
+export const DEFAULT_THEME = 'vscode-modern'
+// The two modes a theme has syntax colours for.
+const MODES = ['dark', 'light'] as const
+
+// What Claude is told while the mod draws its answers (a system prompt
+// section, added last).
+export const TYPST_PROMPT = `Your replies in this terminal are drawn as rendered Markdown pictures (VS Code preview look), so use Markdown freely: headings, tables, task lists, code blocks, $math$ (LaTeX), images by absolute path.
+For anything Markdown can't show well — diagrams, flow charts, plots, coloured tables, complex layouts or math — write a fenced \`\`\`typst block: it is rendered live with Typst 0.15 (full Typst markup; begin code lines with #).
+Packages available offline:
+#import "@preview/cetz:0.5.2"
+#import "@preview/cetz-plot:0.1.4": plot, chart
+#import "@preview/fletcher:0.5.8" as fletcher: diagram, node, edge
+A \`theme\` dictionary is in scope: theme.fg, theme.muted, theme.link, theme.border, theme.accent, theme.bg, theme.code-bg, theme.red/green/blue/yellow/orange/purple, theme.palette (6 colours), theme.width (content width), theme.dark (bool).
+Default strokes in cetz, fletcher and cetz-plot are black and invisible on a dark theme, so always pass theme colours: cetz \`set-style(stroke: theme.fg)\`; fletcher \`diagram(node-stroke: theme.fg, edge-stroke: theme.fg, ...)\`; cetz-plot \`set-style(axes: (stroke: theme.fg, tick: (stroke: theme.fg)), legend: (fill: theme.bg, stroke: theme.border))\`; fills like \`theme.blue.transparentize(70%)\`; size drawings to theme.width at most.
+Inside a typst block, #page, #pagebreak and #set page are errors. If a block fails to compile, it is shown as code instead.
+The stored text stays Markdown, so keep replies readable as plain text too.`
+
+// ---- State ----------------------------------------------------------------
+
+const isOn = atom({ plugin: 'md-preview', key: 'isOn' } as const, true)
+const done = atom({ plugin: 'md-preview', key: 'done' } as const, 0)
+
+export type Cell = { width: number; height: number }
+// Per 1 em (render/measure.typ): `adv` the width of "0", `xh` the x-height,
+// `avg` the mean advance over a lowercase pangram.
+export type FontMetrics = { adv: number; xh: number; avg: number }
+// `term` the terminal's font (null when unknown or not installed), `menlo`
+// the template's code font, `body` its text font.
+export type Metrics = { term: FontMetrics | null; menlo: FontMetrics; body: FontMetrics }
+// Measured with Typst on macOS: Menlo and SF Pro Text.
+export const DEFAULT_METRICS: Metrics = {
+ term: null,
+ menlo: { adv: 0.602, xh: 0.547, avg: 0.602 },
+ body: { adv: 0.63, xh: 0.526, avg: 0.483 },
+}
+type Env = {
+ typst: string | null
+ canDraw: boolean
+ cache: string
+ cwd: string
+ root: string
+ isMac: boolean
+ stamp: string
+ home: string
+ // The terminal's font family ('' when not known) and the fonts' metrics.
+ termFont: string
+ metrics: Metrics
+}
+type Page = { file: string; width: number; height: number; alt: string }
+type Result = { pages: Page[]; columns: number; bulletRow: number; note?: string }
+type Job = {
+ key: string
+ requestId: string
+ text: string
+ columns: number
+ cell: Cell
+ theme: MdPreviewTheme
+ size: number
+ themeDir: string
+ env: Env
+}
+// The active theme: its name, folder, and the mtimes of its files and the
+// base theme's, which are part of every key.
+export type Look = { name: string; dir: string; stamp: string }
+
+// Module state: lost on a hot reload, which is fine. The PNGs stay on disk
+// with a pages.json beside them, so a key compiled before is read back.
+let env: Env | null = null
+let envLoading: Promise<Env> | null = null
+let cell: Cell | null = null
+let theme: MdPreviewTheme = 'dark'
+let size = DEFAULT_SIZE
+let look: Look | null = null
+let lastView = ''
+let measureTimer: { cancel: () => void } | null = null
+const results = new Map<string, Result | 'failed'>()
+const timers = new Map<string, { key: string; cancel: () => void }>()
+const queue: Job[] = []
+const running = new Set<string>()
+// The last result drawn per message, so a width change keeps the old picture
+// (scaled) until the new one is ready instead of falling back to text.
+const shown = new Map<string, { textHash: string; result: Result }>()
+// ---- Pure functions (tested) ----------------------------------------------
+
+// FNV-1a over the parts, twice with different offsets: 16 hex digits.
+export function hashOf(parts: readonly (string | number)[]): string {
+ const s = parts.join('\u0000')
+ let a = 0x811c9dc5
+ let b = 0x050c5d1f
+ for (let i = 0; i < s.length; i++) {
+ const c = s.charCodeAt(i)
+ a = Math.imul(a ^ c, 0x01000193) >>> 0
+ b = Math.imul(b ^ c, 0x01000193) >>> 0
+ }
+ return a.toString(16).padStart(8, '0') + b.toString(16).padStart(8, '0')
+}
+
+export function themeOf(value: unknown): MdPreviewTheme {
+ return typeof value === 'string' && /light/i.test(value) ? 'light' : 'dark'
+}
+
+// The columns a picture takes: the viewport less the bullet, MAX_COLUMNS at most.
+export function columnsFor(viewportColumns: number | undefined): number {
+ return Math.max(20, Math.min(MAX_COLUMNS, (viewportColumns ?? 80) - GUTTER))
+}
+
+// How wide a column is in the page's pt so the template's 11 pt body text
+// looks as big as the terminal's text, `sizePercent` on top. A terminal em is
+// a cell / the advance of its font; the body font is matched to it by
+// x-height and average width together (sqrt of the two ratios), since a
+// proportional font at the same em looks smaller. Code is set in the
+// terminal's font at the terminal's size: `code` is its size / body size.
+// The template uses `code` only for a theme that sets "size": "terminal"
+// for code; the vscode themes draw code at body size, as VS Code does.
+export function fontFit(m: Metrics, sizePercent = 100) {
+ const t = m.term ?? m.menlo
+ const ratio = Math.sqrt((t.xh / m.body.xh) * (t.avg / m.body.avg))
+ const scale = sizePercent / 100
+ return {
+ columnPt: Math.round(((BODY_PT * t.adv) / (ratio * scale)) * 10000) / 10000,
+ code: Math.round((1 / ratio) * 10000) / 10000,
+ ratio,
+ }
+}
+
+// The page width in pt and the ppi that make the PNG exactly as wide as the
+// box in device pixels; `rowPt` is one terminal row in the page's pt.
+export function sizing(columns: number, px: Cell, columnPt: number) {
+ const widthPt = Math.round(columns * columnPt * 100) / 100
+ const widthPx = Math.round(columns * px.width)
+ const ppi = widthPx / (widthPt / 72)
+ return { widthPt, widthPx, ppi, rowPt: (px.height * 72) / ppi }
+}
+
+// `/md-preview` arguments: on, off, size <80-200>, or nothing (show state).
+export type Command =
+ | { kind: 'on' | 'off' | 'show' }
+ | { kind: 'size'; percent: number }
+ | { kind: 'theme'; name?: string }
+ | { kind: 'bad' }
+export function parseCommand(args: string): Command {
+ const typed = args.trim().split(/\s+/).filter(Boolean)
+ const words = typed.map(w => w.toLowerCase())
+ if (!words.length) return { kind: 'show' }
+ if (words[0] === 'theme') {
+ if (typed.length === 1) return { kind: 'theme' }
+ if (typed.length === 2 && isThemeName(typed[1]!)) return { kind: 'theme', name: typed[1]! }
+ return { kind: 'bad' }
+ }
+ if (words.length === 1 && (words[0] === 'on' || words[0] === 'off')) return { kind: words[0] }
+ if (words[0] === 'size' && words.length === 2 && /^\d+%?$/.test(words[1]!)) {
+ const percent = Number.parseInt(words[1]!, 10)
+ if (percent >= MIN_SIZE && percent <= MAX_SIZE) return { kind: 'size', percent }
+ }
+ return { kind: 'bad' }
+}
+
+// A theme folder's name: letters, digits, `.`, `_`, `-`.
+export const isThemeName = (name: string) => /^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(name)
+
+// `syntax`: the tmTheme file theme.json names for a mode, relative to the
+// theme folder; a mode it does not name uses the base theme's file.
+export type ThemeSyntax = Partial<Record<(typeof MODES)[number], string>>
+export type ThemeInfo = { name: string; dir: string; isUser: boolean; title: string; description: string; syntax: ThemeSyntax }
+export type ThemeProblem = { name: string; dir: string; isUser: boolean; reason: string }
+
+// One theme folder from its theme.json text: usable, or why not.
+export function themeEntry(name: string, dir: string, isUser: boolean, json: string): ThemeInfo | ThemeProblem {
+ if (!isThemeName(name)) return { name, dir, isUser, reason: 'the folder name has characters other than letters, digits, ., _ and -' }
+ let data: unknown
+ try {
+ data = JSON.parse(json)
+ } catch (err) {
+ return { name, dir, isUser, reason: `theme.json is not valid JSON (${err instanceof Error ? err.message : String(err)})` }
+ }
+ if (!data || typeof data !== 'object' || Array.isArray(data)) return { name, dir, isUser, reason: 'theme.json is not a JSON object' }
+ const field = (key: string) => {
+ const v = (data as Record<string, unknown>)[key]
+ return typeof v === 'string' ? v : ''
+ }
+ const named = (data as Record<string, unknown>).syntax
+ const syntax: ThemeSyntax = {}
+ if (named !== undefined) {
+ if (!named || typeof named !== 'object' || Array.isArray(named)) return { name, dir, isUser, reason: '"syntax" is not an object of file names' }
+ for (const mode of MODES) {
+ const file = (named as Record<string, unknown>)[mode]
+ if (file === undefined) continue
+ if (!isSyntaxPath(file)) return { name, dir, isUser, reason: `"syntax.${mode}" must be a file name in the theme folder (no "/" at the start, no "..")` }
+ syntax[mode] = file
+ }
+ }
+ return { name, dir, isUser, title: field('name') || name, description: field('description'), syntax }
+}
+
+// A tmTheme path in theme.json: relative to the theme folder and inside it.
+export const isSyntaxPath = (file: unknown): file is string =>
+ typeof file === 'string' && file.trim() !== '' && !file.startsWith('/') && !file.includes('\\') && !file.split('/').includes('..')
+
+// The files a theme's pictures depend on: its theme.json, the base
+// theme.json it merges over, and for each mode the tmTheme it names, else
+// the base theme's. A missing `theme` (not found yet) counts as the base.
+export function themeFiles(theme: ThemeInfo | undefined, base: ThemeInfo | undefined, root: string): string[] {
+ const baseDir = base?.dir ?? `${root}/render/themes/${BASE_THEME}`
+ const files = [`${theme?.dir ?? baseDir}/theme.json`, `${baseDir}/theme.json`]
+ for (const mode of MODES) {
+ const own = theme?.syntax[mode]
+ files.push(own ? `${theme!.dir}/${own}` : `${baseDir}/${base?.syntax[mode] ?? `${mode}.tmTheme`}`)
+ }
+ return files
+}
+
+// Built-in themes, then user themes: a usable user theme replaces the
+// built-in of the same name; a broken one is only reported.
+export function pickThemes(found: readonly (ThemeInfo | ThemeProblem)[]): { themes: Map<string, ThemeInfo>; problems: ThemeProblem[] } {
+ const themes = new Map<string, ThemeInfo>()
+ const problems: ThemeProblem[] = []
+ for (const isUser of [false, true]) {
+ for (const one of found) {
+ if (one.isUser !== isUser) continue
+ if ('reason' in one) problems.push(one)
+ else themes.set(one.name, one)
+ }
+ }
+ return { themes, problems }
+}
+
+// The theme to draw with: the wanted one, else the default theme, else the
+// base theme (`isFallback`). The base theme's own folder is used even before
+// it is found on disk.
+export function chooseTheme(themes: ReadonlyMap<string, ThemeInfo>, wanted: string, root: string): { name: string; dir: string; isFallback: boolean } {
+ const got = themes.get(wanted)
+ if (got) return { name: got.name, dir: got.dir, isFallback: false }
+ const fallback = themes.get(DEFAULT_THEME)
+ if (fallback) return { name: fallback.name, dir: fallback.dir, isFallback: true }
+ const base = themes.get(BASE_THEME)
+ return { name: BASE_THEME, dir: base?.dir ?? `${root}/render/themes/${BASE_THEME}`, isFallback: wanted !== BASE_THEME }
+}
+
+// What `/md-preview theme` lists.
+export function themeListing(themes: ReadonlyMap<string, ThemeInfo>, problems: readonly ThemeProblem[], active: string, userDir: string): string {
+ const lines = [...themes.values()]
+ .sort((a, b) => a.name.localeCompare(b.name))
+ .map(t => `${t.name === active ? '*' : '-'} ${t.name} (${t.isUser ? 'user' : 'built-in'})${t.description ? `: ${t.description}` : ''}`)
+ const skipped = problems.map(p => ` skipped ${p.name} (${p.isUser ? 'user' : 'built-in'}): ${p.reason}`)
+ return [
+ `Themes (* = active):`,
+ ...(lines.length ? lines : ['- none found']),
+ ...skipped,
+ `User themes go in ${userDir}/<name>/theme.json. Switch with /md-preview theme <name>.`,
+ ].join('\n')
+}
+
+// Every input a picture depends on, as one key.
+export function renderKey(o: {
+ textHash: string
+ columns: number
+ cell: Cell
+ size: number
+ mode: MdPreviewTheme
+ termFont: string
+ columnPt: number
+ templateStamp: string
+ look: Look
+}): string {
+ return hashOf([
+ o.textHash, o.columns, o.cell.width, o.cell.height, o.size, o.mode, o.termFont, o.columnPt,
+ o.templateStamp, o.look.name, o.look.dir, o.look.stamp, TEMPLATE_VERSION,
+ ])
+}
+
+// Where the first line of a page's text lies with no top margin, in the
+// template's pt (measured from its PNGs at 11 pt body text): the centre of
+// its ink, and the top of its ink. By what the answer starts with.
+export type FirstLine = 'para' | 'h1' | 'h2' | 'h3' | 'h4' | 'quote' | 'code' | 'table'
+const FIRST_LINE: Record<FirstLine, { centre: number; inkTop: number }> = {
+ para: { centre: 7.45, inkTop: 2.55 },
+ h1: { centre: 20.36, inkTop: 5.82 },
+ h2: { centre: 13.09, inkTop: 3.64 },
+ h3: { centre: 9.09, inkTop: 2.55 },
+ h4: { centre: 7.27, inkTop: 2.18 },
+ quote: { centre: 13.45, inkTop: 8.36 },
+ code: { centre: 17.09, inkTop: 12.36 },
+ table: { centre: 11.27, inkTop: 6.18 },
+}
+
+export function firstLineOf(md: string): FirstLine {
+ const line = md.split('\n').find(l => l.trim()) ?? ''
+ const heading = /^ {0,3}(#{1,6})\s/.exec(line)
+ if (heading) return (['h1', 'h2', 'h3'] as const)[heading[1]!.length - 1] ?? 'h4'
+ if (/^ {0,3}>/.test(line)) return 'quote'
+ if (FENCE.test(line)) return 'code'
+ if (/^ {0,3}\|/.test(line)) return 'table'
+ return 'para'
+}
+
+// The first page's top margin (pt, may be negative) that puts the centre of
+// the first line of text on the centre of a terminal row, and which row that
+// is: row 0 when the line fits there, else the first row its ink can reach
+// without being cut at the picture's top. The bullet is drawn on that row.
+export function alignFirstLine(kind: FirstLine, rowPt: number): { topPt: number; bulletRow: number } {
+ const { centre, inkTop } = FIRST_LINE[kind]
+ const bulletRow = Math.max(0, Math.ceil((centre - inkTop + 0.5) / rowPt - 0.5 - 1e-9))
+ return { topPt: Math.round(((bulletRow + 0.5) * rowPt - centre) * 100) / 100, bulletRow }
+}
+
+// The rows an Image of this PNG takes when it is drawn `columns` wide. The
+// template pads each page to whole rows, so this rounds (no stretch).
+export function rowsFor(page: { width: number; height: number }, columns: number, px: Cell): number {
+ const scale = Math.min(1, (columns * px.width) / page.width)
+ return Math.max(1, Math.min(MAX_IMAGE_ROWS, Math.round((page.height * scale) / px.height)))
+}
+
+// The cell in device pixels from `rows cols xpixel ypixel` (TIOCGWINSZ).
+// iTerm2 (3.5+), Ghostty, kitty and WezTerm report device pixels already, so
+// there is no backing-scale step. Null where the tty reports no pixels or a
+// cell that can't be right (under 4 or over 64 px wide).
+export function cellOf(stdout: string): Cell | null {
+ const [rows, columns, x, y] = stdout.trim().split(/\s+/).map(Number)
+ if (!rows || !columns || !x || !y) return null
+ const width = x / columns
+ const height = y / rows
+ return width >= 4 && width <= 64 && height >= 4 ? { width, height } : null
+}
+
+// "MesloLGS-NF-Regular 14" (iTerm2's Normal Font) → PostScript name and size.
+export function parseFontSpec(spec: string): { name: string; size: number } | null {
+ const m = /^\s*(\S.*?)\s+(\d+(?:\.\d+)?)\s*$/.exec(spec)
+ return m ? { name: m[1]!, size: Number(m[2]) } : null
+}
+
+// The Normal Font of the iTerm2 profile in use: the bookmark named
+// ITERM_PROFILE, else the default bookmark. `bookmarks` is the JSON of the
+// plist's "New Bookmarks" array.
+export function itermFontOf(bookmarks: string, profile: string | undefined, defaultGuid: string): string | null {
+ let list: unknown
+ try {
+ list = JSON.parse(bookmarks)
+ } catch {
+ return null
+ }
+ if (!Array.isArray(list)) return null
+ type Mark = { Name?: unknown; Guid?: unknown; 'Normal Font'?: unknown }
+ const marks = list.filter((x): x is Mark => !!x && typeof x === 'object')
+ const mark = (profile ? marks.find(b => b.Name === profile) : undefined) ?? marks.find(b => b.Guid === defaultGuid.trim())
+ const font = mark?.['Normal Font']
+ return typeof font === 'string' && font.trim() ? font.trim() : null
+}
+
+// The first `font-family = X` of `ghostty +show-config`.
+export function ghosttyFontOf(config: string): string | null {
+ for (const line of config.split('\n')) {
+ const m = /^\s*font-family\s*=\s*(.*?)\s*$/.exec(line)
+ const family = m?.[1]?.replace(/^"(.*)"$/, '$1').trim()
+ if (family) return family
+ }
+ return null
+}
+
+// The typst command and its environment. Network off (see NO_NETWORK) and a
+// package cache of our own, so only the vendored packages load.
+export function typstCall(o: {
+ typst: string
+ root: string
+ cache: string
+ ppi: number
+ inputs: Readonly<Record<string, string | number>>
+ out: string
+}): { argv: string[]; env: Record<string, string> } {
+ const argv = [
+ o.typst, 'compile',
+ '--root', '/',
+ '--package-path', `${o.root}/render/packages`,
+ '--format', 'png',
+ '--diagnostic-format', 'short',
+ '--ppi', o.ppi.toFixed(4),
+ ...Object.entries(o.inputs).flatMap(([k, v]) => ['--input', `${k}=${v}`]),
+ `${o.root}/render/md.typ`,
+ o.out,
+ ]
+ return { argv, env: noNetworkEnv(o.cache) }
+}
+
+export function noNetworkEnv(cache: string): Record<string, string> {
+ return {
+ HTTPS_PROXY: NO_NETWORK,
+ HTTP_PROXY: NO_NETWORK,
+ ALL_PROXY: NO_NETWORK,
+ https_proxy: NO_NETWORK,
+ http_proxy: NO_NETWORK,
+ all_proxy: NO_NETWORK,
+ NO_PROXY: '',
+ no_proxy: '',
+ TYPST_PACKAGE_CACHE_PATH: `${cache}/pkg-cache`,
+ }
+}
+
+// Width and height from a PNG's first 24 bytes (signature, then IHDR).
+export function pngSize(bytes: readonly number[]): { width: number; height: number } | null {
+ const sig = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]
+ if (bytes.length < 24 || sig.some((v, i) => bytes[i] !== v)) return null
+ const at = (i: number) => ((bytes[i]! << 24) | (bytes[i + 1]! << 16) | (bytes[i + 2]! << 8) | bytes[i + 3]!) >>> 0
+ const width = at(16)
+ const height = at(20)
+ return width && height ? { width, height } : null
+}
+
+// `od -An -v -tx1` output for several files, each followed by a line `@`.
+export function parseOd(stdout: string): number[][] {
+ return stdout
+ .split(/^@$/m)
+ .slice(0, -1)
+ .map(part => part.split(/\s+/).filter(Boolean).map(hex => Number.parseInt(hex, 16)))
+}
+
+// A set flag: anything but empty, 0, false, no or off.
+export const isSet = (value: string | undefined) => !!value && !/^(0|false|no|off)$/i.test(value.trim())
+
+// Whether the engine draws pictures here; elsewhere an Image shows only its
+// alt, so the text is better. Claude Code turns kitty graphics on by itself
+// only for kitty and Ghostty; any other terminal draws only when
+// CLAUDE_CODE_FORCE_TERMINAL_IMAGES is set, and tmux or screen only then.
+// Over ssh the terminal can't read our files, so only MD_PREVIEW_FORCE draws.
+export function canDrawIn(env: { program: string; term: string; kitty: boolean; tmux: boolean; ssh: boolean; engineForced: boolean; modForced: boolean }): boolean {
+ if (env.ssh) return env.modForced
+ if (env.engineForced || env.modForced) return true
+ if (env.tmux) return false
+ return /ghostty/i.test(env.program + env.term) || /kitty/i.test(env.term) || env.kitty
+}
+
+const FENCE = /^( {0,3})(`{3,}|~{3,})\s*([^\s`]*)/
+export const isTypstInfo = (info: string) => /^(typst|typ)$/i.test(info)
+// Any failed compile is tried once more with `safe=1`: the template then
+// shows typst fences and math as code and images as alt boxes, which is how
+// a bad typst block or an unknown LaTeX command still draws.
+export function shouldRetrySafe(exitCode: number): boolean {
+ return exitCode !== 0
+}
+
+// One block of Markdown: lines between blank lines outside fences, or one
+// fenced block that starts at the margin.
+export type Block = { lines: string[]; fence?: { mark: string; info: string }; isMath?: boolean }
+
+export function blocksOf(md: string): Block[] {
+ const blocks: Block[] = []
+ let cur: Block | null = null
+ let open: { char: string; len: number } | null = null
+ let inMath = false
+ const close = () => {
+ if (cur && cur.lines.length) blocks.push(cur)
+ cur = null
+ }
+ for (const line of md.replace(/\r\n?/g, '\n').split('\n')) {
+ if (open) {
+ cur!.lines.push(line)
+ const m = FENCE.exec(line)
+ if (m && m[2]![0] === open.char && m[2]!.length >= open.len && line.trim() === m[2]) {
+ open = null
+ if (cur!.fence) close()
+ }
+ continue
+ }
+ if (inMath) {
+ cur!.lines.push(line)
+ if (line.trim() === '$$') inMath = false
+ continue
+ }
+ const m = FENCE.exec(line)
+ if (m) {
+ open = { char: m[2]![0]!, len: m[2]!.length }
+ // A fence at the margin is a block of its own; an indented one (in a
+ // list item) stays with the item.
+ if (m[1] === '') {
+ close()
+ cur = { lines: [line], fence: { mark: m[2]!, info: m[3] ?? '' } }
+ } else (cur ??= { lines: [] }).lines.push(line)
+ continue
+ }
+ if (line.trim() === '') {
+ close()
+ continue
+ }
+ ;(cur ??= { lines: [] }).lines.push(line)
+ if (line.trim() === '$$') {
+ inMath = true
+ cur.isMath = true
+ }
+ }
+ close()
+ return blocks
+}
+
+// A rough count of the rows a block takes once drawn `columns` wide.
+export function rowsOfBlock(block: Block, columns: number): number {
+ const isCode = !!block.fence
+ const perRow = columns * (isCode ? 1.0 : 1.15)
+ let rows = 1
+ for (const line of block.lines) {
+ rows += Math.ceil(Math.max(1, line.length) / perRow) * (isCode ? 1.1 : 1.3)
+ if (/^#{1,2}\s/.test(line)) rows += 1.5
+ }
+ if (block.fence && isTypstInfo(block.fence.info)) rows += 20
+ return rows
+}
+
+const LINK_DEF = /^ {0,3}\[(?!\^)[^\]]+\]:\s*\S/
+const FOOTNOTE_DEF = /^ {0,3}\[\^[^\]]+\]:/
+
+// Splits an answer into segments of about `budget` rows at block boundaries.
+// A fence is never split, but a long plain code fence is cut into several
+// fences of the same language; a typst fence always stays whole. A block that
+// starts indented (a list item's continuation) never starts a segment. Text
+// with footnotes stays one segment; link definitions go into every segment.
+export function splitSegments(md: string, columns: number, budget = SEGMENT_ROWS): string[] {
+ const blocks = blocksOf(md)
+ if (!blocks.length) return []
+ const outside = blocks.filter(b => !b.fence).flatMap(b => b.lines)
+ if (outside.some(line => FOOTNOTE_DEF.test(line))) return [md]
+ const defs = outside.filter(line => LINK_DEF.test(line))
+
+ const pieces: Block[] = []
+ for (const block of blocks) {
+ const { fence } = block
+ if (fence && !isTypstInfo(fence.info) && rowsOfBlock(block, columns) > budget && block.lines.length > 2) {
+ const body = block.lines.slice(1, -1)
+ const per = Math.max(1, Math.floor(budget / Math.max(1.1, rowsOfBlock(block, columns) / block.lines.length)) - 2)
+ for (let i = 0; i < body.length; i += per) {
+ pieces.push({ lines: [block.lines[0]!, ...body.slice(i, i + per), fence.mark], fence })
+ }
+ } else pieces.push(block)
+ }
+
+ const segments: Block[][] = [[]]
+ let used = 0
+ for (const piece of pieces) {
+ const need = rowsOfBlock(piece, columns)
+ const canCut = !/^\s/.test(piece.lines[0] ?? '')
+ if (used + need > budget && segments.at(-1)!.length && canCut) {
+ segments.push([])
+ used = 0
+ }
+ segments.at(-1)!.push(piece)
+ used += need
+ }
+ const texts = segments.map(seg => seg.map(b => b.lines.join('\n')).join('\n\n'))
+ if (texts.length < 2 || !defs.length) return texts
+ return texts.map(t => `${t}\n\n${defs.filter(d => !t.includes(d)).join('\n')}`.trimEnd())
+}
+
+// The local image paths Markdown names outside code fences.
+const IMAGE = /!\[([^\]]*)\]\(\s*<?([^)\s>]+)>?(?:\s+"[^"]*")?\s*\)/g
+
+export function localImages(md: string): string[] {
+ const found: string[] = []
+ let open: { char: string; len: number } | null = null
+ for (const line of md.split('\n')) {
+ const m = FENCE.exec(line)
+ if (open) {
+ if (m && m[2]![0] === open.char && m[2]!.length >= open.len && line.trim() === m[2]) open = null
+ } else if (m) open = { char: m[2]![0]!, len: m[2]!.length }
+ else for (const ref of line.matchAll(IMAGE)) if (!/^[a-z][a-z0-9+.-]*:/i.test(ref[2]!) || /^file:/i.test(ref[2]!)) found.push(ref[2]!)
+ }
+ return found
+}
+
+// Where an image path leads, as the template resolves it: `file://` dropped,
+// `%20` a space, a relative path joined to `base`.
+export function imagePathOf(path: string, base: string): string {
+ const plain = path.trim().replace(/^file:\/\//i, '').replace(/%20/g, ' ')
+ return plain.startsWith('/') ? plain : `${base.replace(/\/+$/, '')}/${plain.replace(/^\.\//, '')}`
+}
+
+// A short one-line plain text of some Markdown, for an Image's alt.
+export function plainOf(md: string, max = ALT_CHARS): string {
+ const flat = md
+ .replace(/^ {0,3}(`{3,}|~{3,}).*$/gm, ' ')
+ .replace(/!\[([^\]]*)\]\([^)]*\)/g, '$1')
+ .replace(/\[([^\]]*)\]\([^)]*\)/g, '$1')
+ .replace(/<[^>]+>/g, ' ')
+ .replace(/^\s{0,3}(#{1,6}|>+|[-*+]|\d+[.)])\s+/gm, '')
+ .replace(/[*_`~|]+/g, '')
+ .replace(/\s+/g, ' ')
+ .trim()
+ return flat.length > max ? `${flat.slice(0, max - 1).trimEnd()}…` : flat || ' '
+}
+
+export const firstLine = (text: string) => text.split('\n').find(l => l.trim())?.trim() ?? ''
+
+// ---- Work on the host -----------------------------------------------------
+
+const CELL_SH = `perl -e 'open(T, "</dev/tty") or exit 1; my $w = " " x 8; ioctl(T, ($^O eq "darwin" ? 0x40087468 : 0x5413), $w) or exit 1; print join(" ", unpack("S4", $w))'`
+// Makes the cache folder, drops key folders not touched for 2 days, and
+// prints the folder and the OS name.
+const CACHE_SH = `d="\${TMPDIR:-/tmp}"; d="\${d%/}/md-preview-$(id -u)"; mkdir -p "$d" && chmod 700 "$d" && { find "$d" -mindepth 1 -maxdepth 1 -type d -mtime +2 ! -name pkg-cache -exec rm -rf {} + 2>/dev/null; printf '%s\\n%s\\n' "$d" "$(uname -s)"; }`
+const ITERM_BOOKMARKS_SH = `defaults export com.googlecode.iterm2 - | plutil -extract "New Bookmarks" json -o - -`
+const ITERM_DEFAULT_SH = `defaults read com.googlecode.iterm2 "Default Bookmark Guid"`
+// A PostScript name (argv[0]) to its family name.
+const FAMILY_JXA = 'function run(argv) { ObjC.import("AppKit"); var f = $.NSFont.fontWithNameSize(argv[0], 12); return f.isNil() ? "" : f.familyName.js }'
+const GHOSTTY_SH = `"\${GHOSTTY_BIN_DIR:+\$GHOSTTY_BIN_DIR/}ghostty" +show-config`
+const HEADERS_SH = `for f in "$@"; do head -c 24 "$f" | od -An -v -tx1; echo @; done`
+
+// /md-preview; registered at session start and again in setUp, so it is
+// there after a hot reload too.
+async function registerCommand($: EngineInterface) {
+ await $.command.register({
+ name: 'md-preview',
+ description: "Draw Claude's answers as rendered Markdown pictures: on, off, size <80-200> (text size in % of the terminal's), theme [name] (list or switch themes)",
+ argumentHint: '[on|off|size <percent>|theme [name]]',
+ }).catch(() => undefined)
+}
+
+// Redraws every reader of `done`; an invalidate where the write is refused.
+function refresh($: EngineInterface) {
+ void update($, done, n => n + 1).catch(() => $.ui.invalidate('ui.render'))
+}
+
+async function findTypst($: EngineInterface): Promise<string | null> {
+ for (const flag of ['-lc', '-c']) {
+ const got = await $.process.run(['sh', flag, 'command -v typst'], { timeoutMs: 5000 }).catch(() => null)
+ const path = got?.exitCode === 0 ? firstLine(got.stdout) : ''
+ if (path.startsWith('/')) return path
+ }
+ const home = (await $.env.get('HOME').catch(() => undefined)) ?? ''
+ for (const each of TYPST_FALLBACKS) {
+ if (each.startsWith('~/') && !home) continue
+ const path = each.startsWith('~/') ? `${home}${each.slice(1)}` : each
+ if (await $.fs.exists(path).catch(() => false)) return path
+ }
+ return null
+}
+
+async function measureCell($: EngineInterface): Promise<Cell | null> {
+ const tty = await $.process.run(['sh', '-c', CELL_SH], { timeoutMs: 5000 }).catch(() => null)
+ return tty?.exitCode === 0 ? cellOf(tty.stdout) : null
+}
+
+// The terminal's font family: iTerm2's profile font, Ghostty's font-family;
+// '' elsewhere or when it can't be read.
+async function termFontOf($: EngineInterface, program: string, isMac: boolean): Promise<string> {
+ if (/^iTerm/i.test(program) && isMac) {
+ const profile = await $.env.get('ITERM_PROFILE')
+ const [marks, guid] = await Promise.all([
+ $.process.run(['sh', '-c', ITERM_BOOKMARKS_SH], { timeoutMs: 5000 }).catch(() => null),
+ $.process.run(['sh', '-c', ITERM_DEFAULT_SH], { timeoutMs: 5000 }).catch(() => null),
+ ])
+ const spec = parseFontSpec(itermFontOf(marks?.stdout ?? '', profile, guid?.stdout ?? '') ?? '')
+ if (!spec) return ''
+ const named = await $.process.run(['osascript', '-l', 'JavaScript', '-e', FAMILY_JXA, spec.name], { timeoutMs: 5000 }).catch(() => null)
+ return named?.exitCode === 0 ? firstLine(named.stdout) : ''
+ }
+ if (/ghostty/i.test(program)) {
+ const shown = await $.process.run(['sh', '-c', GHOSTTY_SH], { timeoutMs: 5000 }).catch(() => null)
+ return ghosttyFontOf(shown?.stdout ?? '') ?? ''
+ }
+ return ''
+}
+
+// The argv that measures the fonts: the active theme's body and code fonts
+// (theme.typ reads theme.json, which needs `--root /`).
+export const measureCall = (typst: string, root: string, family: string, themeDir: string) => [
+ typst, 'eval', 'query(<m>).first().value', '--in', `${root}/render/measure.typ`, '--root', '/',
+ '--input', `term-font=${family}`, '--input', `theme-dir=${themeDir}`,
+]
+
+// The fonts' metrics from render/measure.typ; the macOS defaults when that fails.
+async function measureFonts($: EngineInterface, typst: string, root: string, cache: string, family: string, themeDir: string): Promise<Metrics> {
+ const argv = measureCall(typst, root, family, themeDir)
+ const got = await $.process.run(argv, { timeoutMs: 10000, env: noNetworkEnv(cache) }).catch(() => null)
+ try {
+ const m = JSON.parse(got?.stdout ?? '') as Metrics
+ const ok = (x: FontMetrics | null | undefined) => !!x && x.adv > 0 && x.xh > 0 && x.avg > 0
+ if (ok(m.menlo) && ok(m.body)) return { term: ok(m.term) ? m.term : null, menlo: m.menlo, body: m.body }
+ } catch {}
+ return DEFAULT_METRICS
+}
+
+// The built-in themes under render/themes and the user's under
+// ~/.claude/md-preview/themes, read fresh each call.
+async function scanThemes($: EngineInterface, root: string, home: string) {
+ const found: (ThemeInfo | ThemeProblem)[] = []
+ for (const [base, isUser] of [[`${root}/render/themes`, false], [userThemesOf(home), true]] as const) {
+ const entries = await $.fs.list(base).catch(() => [])
+ for (const entry of entries) {
+ if (entry.kind === 'file') continue
+ const dir = `${base}/${entry.name}`
+ const json = await $.fs.read(`${dir}/theme.json`).catch(() => null)
+ if (json === null) continue
+ const one = themeEntry(entry.name, dir, isUser, json)
+ const lost = 'reason' in one ? [] : await missingSyntax($, one)
+ found.push(lost.length ? { name: one.name, dir, isUser, reason: `theme.json names syntax files that do not exist: ${lost.join(', ')}` } : one)
+ }
+ }
+ return pickThemes(found)
+}
+
+// The syntax files a theme names that are not on disk (they fail the compile).
+async function missingSyntax($: EngineInterface, theme: ThemeInfo) {
+ const lost: string[] = []
+ for (const mode of MODES) {
+ const file = theme.syntax[mode]
+ if (file && !(await $.fs.exists(`${theme.dir}/${file}`).catch(() => false))) lost.push(file)
+ }
+ return lost
+}
+
+const userThemesOf = (home: string) => `${home || '~'}/.claude/md-preview/themes`
+
+// The mtimes of the files a theme's pictures depend on (themeFiles): a
+// change to any of them makes new keys.
+async function stampTheme($: EngineInterface, files: readonly string[]): Promise<string> {
+ const times: string[] = []
+ for (const file of files) {
+ const stat = await $.fs.stat(file).catch(() => null)
+ times.push(String(stat?.mtimeMs ?? 0))
+ }
+ return times.join(',')
+}
+
+// Picks the stored theme (or the default one), sets `look`, and says when the
+// stored one was not usable.
+async function applyTheme($: EngineInterface, root: string, home: string, wanted: string) {
+ const { themes, problems } = await scanThemes($, root, home)
+ const chosen = chooseTheme(themes, wanted, root)
+ // theme.typ always merges over the built-in vscode, also when a user theme
+ // has that name, so the stamp uses the built-in one.
+ const builtIn = themes.get(BASE_THEME)
+ const files = themeFiles(themes.get(chosen.name), builtIn?.isUser ? undefined : builtIn, root)
+ look = { name: chosen.name, dir: chosen.dir, stamp: await stampTheme($, files) }
+ return { themes, problems, chosen }
+}
+
+// Once per load: the cache folder, Typst, the terminal and its font, the
+// theme, the cell. A failed setup is tried again on the next call.
+function setUp($: EngineInterface): Promise<Env> {
+ envLoading ??= (async () => {
+ await registerCommand($)
+ const made = await $.process.run(['sh', '-c', CACHE_SH]).catch(() => null)
+ const [made1 = '', os = ''] = (made?.stdout ?? '').split('\n')
+ const cache = made1.trim() || '/tmp/md-preview'
+ const program = (await $.env.get('TERM_PROGRAM')) ?? ''
+ const term = (await $.env.get('TERM')) ?? ''
+ const canDraw = canDrawIn({
+ program,
+ term,
+ kitty: !!(await $.env.get('KITTY_WINDOW_ID')),
+ tmux: !!(await $.env.get('TMUX')) || /^tmux|^screen/i.test(term),
+ ssh: !!(await $.env.get('SSH_CONNECTION')) || !!(await $.env.get('SSH_TTY')),
+ engineForced: isSet(await $.env.get('CLAUDE_CODE_FORCE_TERMINAL_IMAGES')),
+ modForced: isSet(await $.env.get('MD_PREVIEW_FORCE')),
+ })
+ const root = $.plugin.root
+ const template = await $.fs.stat(`${root}/render/md.typ`).catch(() => null)
+ const rows = await $.config.list().catch(() => [])
+ theme = themeOf(rows.find(row => row.key === 'theme')?.value)
+ const kept = Number(await $.store.get('size').catch(() => undefined))
+ size = kept >= MIN_SIZE && kept <= MAX_SIZE ? kept : DEFAULT_SIZE
+ if ((await $.store.get('enabled').catch(() => undefined)) === false) await update($, isOn, () => false).catch(() => undefined)
+ const isMac = os.trim() === 'Darwin'
+ cell = await measureCell($)
+ const typst = await findTypst($)
+ if (!typst) {
+ try {
+ $.ui.toast(NO_TYPST, { timeoutMs: 8000 })
+ } catch {}
+ }
+ const termFont = await termFontOf($, program, isMac).catch(() => '')
+ const home = (await $.env.get('HOME')) ?? ''
+ const stored = await $.store.get('theme-name').catch(() => undefined)
+ const wanted = typeof stored === 'string' && stored ? stored : DEFAULT_THEME
+ const applied = await applyTheme($, root, home, wanted).catch(() => null)
+ if (!applied) look = { name: BASE_THEME, dir: `${root}/render/themes/${BASE_THEME}`, stamp: '0' }
+ else if (applied.chosen.isFallback) {
+ try {
+ $.ui.toast(`md-preview: theme ${wanted} not found, using ${applied.chosen.name}`, { timeoutMs: 8000 })
+ } catch {}
+ }
+ env = {
+ typst,
+ canDraw,
+ cache,
+ cwd: await $.session.cwd().catch(() => '/'),
+ root,
+ isMac,
+ stamp: String(template?.mtimeMs ?? 0),
+ home,
+ termFont,
+ metrics: typst ? await measureFonts($, typst, root, cache, termFont, look?.dir ?? `${root}/render/themes/${BASE_THEME}`) : DEFAULT_METRICS,
+ }
+ refresh($)
+ return env
+ })().catch((err: unknown) => {
+ envLoading = null
+ throw err
+ })
+ return envLoading
+}
+
+// A changed viewport may mean a changed font size: measure the cell again,
+// at most once a second, and redraw only when it really changed.
+function noteViewport($: EngineInterface, view: { columns: number; rows: number }) {
+ const seen = `${view.columns}x${view.rows}`
+ if (seen === lastView) return
+ const isFirst = lastView === ''
+ lastView = seen
+ if (isFirst || !env) return
+ measureTimer?.cancel()
+ measureTimer = $.clock.after(1000, () => {
+ void measureCell($).then(next => {
+ if (next?.width === cell?.width && next?.height === cell?.height) return
+ cell = next
+ refresh($)
+ })
+ })
+}
+
+async function logDebug($: EngineInterface, cache: string, text: string) {
+ const stamp = new Date().toISOString()
+ await $.process.run(['sh', '-c', 'cat >> "$1"', 'sh', `${cache}/debug.log`], { stdin: `[${stamp}] ${text.trimEnd()}\n` }).catch(() => undefined)
+}
+
+// The images that exist, for the template's allow-list: it draws any other
+// as its alt, so one bad path doesn't fail the page.
+async function existingImages($: EngineInterface, segments: readonly string[], base: string): Promise<string[]> {
+ const found: string[] = []
+ for (const path of new Set(segments.flatMap(localImages))) {
+ const full = imagePathOf(path, base)
+ if (await $.fs.exists(full).catch(() => false)) found.push(path, full)
+ }
+ return found
+}
+
+async function runTypst($: EngineInterface, job: Job, segments: readonly string[], dir: string, tag: string, isSafe: boolean) {
+ const fit = fontFit(job.env.metrics, job.size)
+ const { widthPt, ppi, rowPt } = sizing(job.columns, job.cell, fit.columnPt)
+ const { topPt } = alignFirstLine(firstLineOf(segments[0] ?? ''), rowPt)
+ const { argv, env: vars } = typstCall({
+ typst: job.env.typst!,
+ root: job.env.root,
+ cache: job.env.cache,
+ ppi,
+ inputs: {
+ theme: job.theme,
+ width: widthPt,
+ top: topPt,
+ row: Math.round(rowPt * 10000) / 10000,
+ code: fit.code,
+ ...(job.env.termFont ? { 'term-font': job.env.termFont } : {}),
+ 'theme-dir': job.themeDir,
+ doc: `${dir}/doc.json`,
+ ...(isSafe ? { safe: 1 } : {}),
+ },
+ out: `${dir}/${tag}-{0p}.png`,
+ })
+ return $.process
+ .run(argv, { timeoutMs: COMPILE_TIMEOUT_MS, env: vars })
+ .catch((err: unknown) => ({ exitCode: 1, stdout: '', stderr: `typst did not run: ${String(err)}` }))
+}
+
+async function compile($: EngineInterface, job: Job): Promise<Result | 'failed'> {
+ const dir = `${job.env.cache}/${job.key}`
+ const kept = await $.fs.read(`${dir}/pages.json`).catch(() => null)
+ if (kept) return JSON.parse(kept) as Result
+
+ const segments = splitSegments(job.text, job.columns)
+ const images = await existingImages($, segments, job.env.cwd)
+ await $.fs.write(`${dir}/doc.json`, JSON.stringify({ base: job.env.cwd, segments, images }))
+
+ let tag = 'a'
+ let ran = await runTypst($, job, segments, dir, tag, false)
+ let note: string | undefined
+ if (ran.exitCode !== 0) {
+ await logDebug($, job.env.cache, `compile ${job.key} failed:\n${ran.stderr}`)
+ if (!shouldRetrySafe(ran.exitCode)) return 'failed'
+ note = firstLine(ran.stderr.split('\n').find(l => /error:/i.test(l)) ?? ran.stderr).replace(/^.*error:\s*/i, '')
+ tag = 'b'
+ ran = await runTypst($, job, segments, dir, tag, true)
+ if (ran.exitCode !== 0) {
+ await logDebug($, job.env.cache, `compile ${job.key} with safe=1 failed:\n${ran.stderr}`)
+ return 'failed'
+ }
+ }
+
+ const files = (await $.fs.list(dir))
+ .filter(f => f.kind === 'file' && f.name.startsWith(`${tag}-`) && f.name.endsWith('.png'))
+ .map(f => f.name)
+ .sort((x, y) => Number(x.replace(/\D/g, '')) - Number(y.replace(/\D/g, '')))
+ .map(name => `${dir}/${name}`)
+ if (!files.length) return 'failed'
+ const heads = await $.process.run(['sh', '-c', HEADERS_SH, 'sh', ...files])
+ const sizes = parseOd(heads.stdout).map(pngSize)
+ if (sizes.length !== files.length || sizes.some(s => !s)) {
+ await logDebug($, job.env.cache, `compile ${job.key}: could not read PNG sizes`)
+ return 'failed'
+ }
+ const pages = files.map((file, i) => ({ file, ...sizes[i]!, alt: plainOf(segments[i] ?? job.text) }))
+ const { rowPt } = sizing(job.columns, job.cell, fontFit(job.env.metrics, job.size).columnPt)
+ const { bulletRow } = alignFirstLine(firstLineOf(segments[0] ?? ''), rowPt)
+ const result: Result = { pages, columns: job.columns, bulletRow, ...(note ? { note } : {}) }
+ await $.fs.write(`${dir}/pages.json`, JSON.stringify(result))
+ return result
+}
+
+function pump($: EngineInterface) {
+ while (running.size < MAX_RUNNING && queue.length) {
+ const job = queue.shift()!
+ running.add(job.key)
+ void compile($, job)
+ .catch(async (err: unknown) => {
+ await logDebug($, job.env.cache, `compile ${job.key} threw: ${String(err)}`)
+ return 'failed' as const
+ })
+ .then(result => {
+ results.set(job.key, result)
+ running.delete(job.key)
+ refresh($)
+ pump($)
+ })
+ }
+}
+
+function enqueue($: EngineInterface, job: Job) {
+ if (results.has(job.key) || running.has(job.key)) return
+ // A newer text of the same message replaces its job still waiting.
+ const stale = queue.findIndex(j => j.requestId === job.requestId || j.key === job.key)
+ if (stale >= 0) queue.splice(stale, 1)
+ queue.push(job)
+ pump($)
+}
+
+// Compiles once the message's text has been still for SETTLE_MS.
+function schedule($: EngineInterface, job: Job) {
+ const was = timers.get(job.requestId)
+ if (was?.key === job.key) return
+ was?.cancel()
+ const timer = $.clock.after(SETTLE_MS, () => {
+ timers.delete(job.requestId)
+ enqueue($, job)
+ })
+ timers.set(job.requestId, { key: job.key, cancel: () => timer.cancel() })
+}
+
+type Drawn = RenderInput<'AssistantMessage', 'terminal'>
+
+function drawPages($: EngineInterface, e: Drawn, result: Result, columns: number, px: Cell) {
+ const { Box, Text, Image } = $.ui.resolve(e)
+ return (
+ <Box flexDirection="row" marginTop={MARGIN_TOP}>
+ <Box width={GUTTER} flexShrink={0} marginTop={result.bulletRow}>
+ <Text>{e.props.isFirstOfReply ? bulletOf(env?.isMac ?? true) : ' '}</Text>
+ </Box>
+ <Box flexDirection="column">
+ {result.pages.map((page, i) => {
+ const rows = rowsFor(page, columns, px)
+ return (
+ <Image
+ key={`p${i}`}
+ source={{ file: page.file, format: 'png', generation: columns * 1000 + rows }}
+ columns={columns}
+ rows={rows}
+ alt={page.alt}
+ />
+ )
+ })}
+ {result.note ? <Text dimColor wrap="truncate-end">Typst error: {result.note}</Text> : null}
+ </Box>
+ </Box>
+ )
+}
+
+// ---- Hooks ----------------------------------------------------------------
+
+export const register: Register = on => {
+ on('session.start', async ($, e, next) => {
+ await registerCommand($)
+ void setUp($).catch(() => undefined)
+ return next(e)
+ })
+
+ on('command.run', { command: 'md-preview' }, async ($, e) => {
+ const asked = parseCommand(e.args)
+ if (asked.kind === 'on' || asked.kind === 'off') {
+ await update($, isOn, () => asked.kind === 'on')
+ await $.store.set('enabled', asked.kind === 'on')
+ return { text: `md-preview is ${asked.kind}.` }
+ }
+ if (asked.kind === 'size') {
+ size = asked.percent
+ await $.store.set('size', size)
+ refresh($)
+ return { text: `md-preview draws text at ${size}% of the terminal's text size (100% matches it).` }
+ }
+ if (asked.kind === 'theme') {
+ const ready = await setUp($)
+ const was = look
+ const wanted = asked.name ?? look?.name ?? DEFAULT_THEME
+ const { themes, problems, chosen } = await applyTheme($, ready.root, ready.home, wanted)
+ if (asked.name && chosen.isFallback) {
+ if (was) look = was
+ const names = [...themes.keys()].sort().join(', ') || 'none'
+ return { text: `No usable theme named ${asked.name}. Themes: ${names}.\n${themeListing(themes, problems, was?.name ?? DEFAULT_THEME, userThemesOf(ready.home))}` }
+ }
+ if (asked.name) await $.store.set('theme-name', chosen.name)
+ if (look?.name !== was?.name || look?.dir !== was?.dir || look?.stamp !== was?.stamp) {
+ // The theme's fonts set the column width and the code size.
+ if (ready.typst && look) ready.metrics = await measureFonts($, ready.typst, ready.root, ready.cache, ready.termFont, look.dir)
+ refresh($)
+ }
+ const head = asked.name ? `md-preview uses the theme ${chosen.name}.\n` : ''
+ return { text: `${head}${themeListing(themes, problems, chosen.name, userThemesOf(ready.home))}` }
+ }
+ const state = (await read($, isOn)) ? 'on' : 'off'
+ const ready = await setUp($)
+ const font = ready.termFont ? `terminal font ${ready.termFont}` : 'terminal font not known (Menlo assumed)'
+ const typst = ready.typst ? `Typst: ${ready.typst}` : 'Typst: not found (brew install typst)'
+ const terminal = ready.canDraw ? 'this terminal draws pictures' : 'Claude Code draws no pictures here (it does in kitty and Ghostty, elsewhere with CLAUDE_CODE_FORCE_TERMINAL_IMAGES=1, never in tmux or over ssh), so answers stay text'
+ const usage = `Use /md-preview on, /md-preview off, /md-preview size <${MIN_SIZE}-${MAX_SIZE}>, or /md-preview theme [name].`
+ const bad = asked.kind === 'bad' ? `Not understood: "${e.args.trim()}". ` : ''
+ return { text: `${bad}md-preview is ${state}, theme ${look?.name ?? DEFAULT_THEME}, text size ${size}%, ${font}. ${typst}; ${terminal}. ${usage}` }
+ })
+
+ on('config.set', { key: 'theme' }, async ($, e, next) => {
+ const set = await next(e)
+ if (set.value !== undefined && themeOf(set.value) !== theme) {
+ theme = themeOf(set.value)
+ refresh($)
+ }
+ return set
+ }).catch(($, e, next) => next(e))
+
+ on('prompt.compose', async ($, e, next) => {
+ const composed = await next(e)
+ if (!e.surfaces.includes('terminal') || !(await read($, isOn))) return composed
+ const ready = env ?? (await setUp($).catch(() => null))
+ if (!ready?.typst || !ready.canDraw) return composed
+ return { sections: [...composed.sections, { id: 'md-preview:typst', text: TYPST_PROMPT, scope: 'session' as const }] }
+ })
+
+ on('ui.render', { component: 'AssistantMessage' }, async ($, e, next) => {
+ if (e.surface !== 'terminal' || e.props.isSummary || !e.props.text.trim()) return next(e)
+ if (!(await read($, isOn))) return next(e)
+ // Read so a finished render draws this message again.
+ await read($, done)
+ if (!env) {
+ void setUp($).catch(() => undefined)
+ return next(e)
+ }
+ if (!env.typst || !env.canDraw) return next(e)
+ if (e.viewport) noteViewport($, e.viewport)
+
+ const columns = columnsFor(e.viewport?.columns)
+ const px = cell ?? DEFAULT_CELL
+ const textHash = hashOf([e.props.text])
+ const active = look ?? { name: DEFAULT_THEME, dir: `${env.root}/render/themes/${DEFAULT_THEME}`, stamp: '0' }
+ const key = renderKey({
+ textHash, columns, cell: px, size, mode: theme, termFont: env.termFont,
+ columnPt: fontFit(env.metrics, size).columnPt, templateStamp: env.stamp, look: active,
+ })
+ const got = results.get(key)
+ if (got === 'failed') return next(e)
+ if (got) {
+ shown.set(e.requestId, { textHash, result: got })
+ return drawPages($, e, got, columns, px)
+ }
+ schedule($, { key, requestId: e.requestId, text: e.props.text, columns, cell: px, theme, size, themeDir: active.dir, env })
+ // Same text at another width: the old picture until the new one is ready.
+ const was = shown.get(e.requestId)
+ return was && was.textHash === textHash ? drawPages($, e, was.result, columns, px) : next(e)
+ })
+}
diff --git a/render/fonts.typ b/render/fonts.typ
new file mode 100644
index 0000000..afe0f99
--- /dev/null
+++ b/render/fonts.typ
@@ -0,0 +1,5 @@
+// Font lists shared by md.typ and measure.typ. They come from the active
+// theme (theme.typ: `fonts.body` and `fonts.code`, merged over vscode).
+#import "theme.typ": fonts
+#let sans = fonts.body
+#let mono-base = fonts.code
diff --git a/render/md.typ b/render/md.typ
new file mode 100644
index 0000000..46bdc08
--- /dev/null
+++ b/render/md.typ
@@ -0,0 +1,531 @@
+// md-preview: draws Markdown segments like VS Code's Markdown preview
+// (the colours come from the theme). One segment = one page = one PNG.
+//
+// typst compile --root / --package-path <render>/packages --format png --ppi <ppi>
+// --input theme=dark|light --input width=<page width in pt>
+// --input doc=<absolute path of JSON> [--input safe=1]
+// --input theme-dir=<absolute theme folder> (themes/README.md; merged over vscode)
+// <render>/md.typ <outdir>/<a|b>-{0p}.png
+//
+// doc JSON: { "base": "/dir/for/relative/images", "segments": ["md", ...],
+// "images": ["/abs/path.png", ...] (optional allow-list) }
+//
+// safe=1: the retry mode after a failed compile. `typst` fences are shown as
+// code (no eval), math is shown as code (no mitex), images are alt boxes.
+
+#import "@preview/cmarker:0.1.6"
+#import "@preview/mitex:0.2.7": mitex
+
+// ---------- inputs ----------
+#let inp = sys.inputs
+#let dark = inp.at("theme", default: "dark") != "light"
+#let safe = inp.at("safe", default: "0") not in ("", "0", "false", "no", "off")
+#let page-w = float(inp.at("width", default: "600")) * 1pt
+// No left margin, so the text starts in the column normal replies start in.
+#let margin-left = 0pt
+#let margin-right = 4pt
+#let margin-y = 6pt
+// The first page's top margin in pt: the hooks module sets it so the first
+// line of text sits on the terminal row of the reply bullet.
+#let first-top = float(inp.at("top", default: "6")) * 1pt
+// One terminal row in pt: each page is padded to a whole number of rows, so
+// its picture fills its box exactly. 0 = no padding.
+#let row = float(inp.at("row", default: "0")) * 1pt
+// Code size as a fraction of the body text (the hooks module sets it so code
+// in the terminal's font is the terminal's own size).
+#let code-scale = float(inp.at("code", default: "0.9"))
+#let doc = if "doc" in inp { json(inp.doc) } else {
+ (base: "", segments: ("*md-preview:* no `doc` input given.",))
+}
+#let base = str(doc.at("base", default: ""))
+#let allow = doc.at("images", default: none)
+#let segments = doc.at("segments", default: ())
+#if type(segments) == str { segments = (segments,) }
+#if segments.len() == 0 { segments = ("",) }
+
+// ---------- theme ----------
+// Colours, fonts and element sizes come from the active theme
+// (theme.typ reads themes/<name>/theme.json, merged over themes/vscode).
+// Theme keys named *-px are CSS px of VS Code's preview (14px body) at our
+// 11pt body; *-em are em of the element's own text.
+#import "theme.typ": T, C, syntax, at-level
+#let px = 11pt / 14
+// The font lists live in fonts.typ, which render/measure.typ reads too.
+#import "fonts.typ": sans, mono-base
+// The terminal's own font first for code, so code looks like the terminal
+// (unless the theme sets fonts.use-terminal-font to false).
+#let term-font = inp.at("term-font", default: "")
+#let mono = if term-font != "" and T.fonts.use-terminal-font { (term-font,) + mono-base } else { mono-base }
+#let content-w = page-w - margin-left - margin-right
+// Code size as a fraction of the body text: the theme's number, or
+// "terminal" for the hooks module's `code` input (terminal-sized code).
+#let code-size(v) = if v == "terminal" { code-scale } else if type(v) in (int, float) { float(v) } else { code-scale }
+#let E = T // element settings, read as E.heading, E.quote, ...
+
+// What a live ```typst block sees as `theme`.
+#let theme = (
+ dark: dark,
+ fg: C.fg,
+ muted: C.muted,
+ link: C.link,
+ border: C.border,
+ accent: C.accent,
+ bg: C.bg,
+ code-bg: C.code-bg,
+ red: C.red,
+ green: C.green,
+ blue: C.blue,
+ yellow: C.yellow,
+ orange: C.orange,
+ purple: C.purple,
+ palette: (C.blue, C.orange, C.green, C.red, C.purple, C.yellow),
+ width: content-w,
+ page-width: page-w,
+ text-size: 11pt,
+ sans: sans,
+ mono: mono,
+)
+
+// ---------- page and text ----------
+#set document(title: "md-preview")
+#set page(width: page-w, height: auto, margin: (left: margin-left, right: margin-right, y: margin-y), fill: none)
+// CSS-like line boxes: line-height 22px at 14px.
+#set text(
+ font: sans, size: 11pt, fill: C.fg, hyphenate: false, lang: "en",
+ top-edge: "ascender", bottom-edge: "descender",
+)
+#set par(leading: E.text.leading-em * 1em, spacing: E.text.paragraph-em * 1em, justify: false)
+#set block(spacing: E.text.paragraph-em * 1em)
+
+// ---------- headings ----------
+#set heading(numbering: none)
+#show heading: it => {
+ let lvl = calc.min(it.level, 6)
+ let H = E.heading
+ let size = at-level(H.size-em, lvl - 1) * 1em
+ let above = at-level(H.above-em, lvl - 1) * 11pt
+ let below = at-level(H.below-em, lvl - 1) * 11pt
+ set text(size: size, weight: H.weight)
+ set par(leading: H.leading-em * 1em)
+ if lvl <= H.rule-levels {
+ block(
+ width: 100%, above: above, below: below, sticky: true,
+ inset: (bottom: H.rule-pad-em * 1em), stroke: (bottom: px + C.border),
+ it.body,
+ )
+ } else {
+ block(width: 100%, above: above, below: below, sticky: true, it.body)
+ }
+}
+
+// ---------- links, emphasis ----------
+#show link: set text(fill: C.link)
+#set strike(stroke: 0.06em)
+
+// ---------- lists ----------
+// "disc", "circle" and "square" draw CSS-like markers (0.35em, centred
+// 0.31em above the baseline, as measured in VS Code); any other string is
+// used as text.
+#let list-marker(m) = {
+ let d = 0.35em
+ let lift = 0.31em - d / 2
+ if m == "disc" { box(baseline: -lift, circle(radius: d / 2, fill: C.fg, stroke: none)) }
+ else if m == "circle" { box(baseline: -lift, circle(radius: d / 2 - 0.03em, stroke: 0.06em + C.fg)) }
+ else if m == "square" { box(baseline: -lift, square(size: d * 0.9, fill: C.fg, stroke: none)) }
+ else { [#m] }
+}
+#set list(
+ marker: E.list.markers.map(list-marker),
+ indent: E.list.indent-em * 1em, body-indent: E.list.gap-em * 1em, spacing: E.list.item-spacing-em * 1em,
+)
+#set enum(
+ numbering: "1.",
+ indent: E.list.number-indent-em * 1em, body-indent: E.list.number-gap-em * 1em, spacing: E.list.item-spacing-em * 1em,
+)
+
+// ---------- code ----------
+#set raw(theme: syntax(), tab-size: 4)
+// Typst shrinks raw text to 0.8em by default, hence the / 0.8.
+#show raw: set text(font: mono, top-edge: "ascender", bottom-edge: "descender")
+#show raw.where(block: false): set text(size: code-size(E.inline-code.size) / 0.8 * 1em)
+#show raw.where(block: true): set text(size: code-size(E.code-block.size) / 0.8 * 1em)
+// Inline code: like VS Code's `code { padding: 1px 3px; border-radius: 4px }`,
+// the background covers the code font's ascender to descender plus the
+// padding. highlight (not box) so long inline code can wrap across lines.
+#show raw.where(block: false): it => context {
+ let IC = E.inline-code
+ let asc = measure(text(top-edge: "ascender", bottom-edge: "baseline", "x")).height
+ let desc = measure(text(top-edge: "baseline", bottom-edge: "descender", "x")).height
+ let pad-x = IC.pad-x-px * px
+ let pad-y = IC.pad-y-px * px
+ h(pad-x)
+ highlight(
+ fill: C.inline-code-bg, extent: pad-x, radius: IC.radius-px * px,
+ top-edge: asc + pad-y, bottom-edge: -(desc + pad-y),
+ text(fill: C.inline-code-fg, it),
+ )
+ h(pad-x)
+}
+// Code blocks: VS Code's `pre` (padding 16px, radius 3px, 1px border) with
+// `code { line-height: 1.357em }`.
+#show raw.where(block: true): it => context {
+ let CB = E.code-block
+ let area = measure(text(top-edge: "ascender", bottom-edge: "descender", "x")).height
+ set par(leading: calc.max(0pt, CB.line-height * text.size - area), justify: false)
+ block(
+ width: 100%, fill: C.code-bg, stroke: CB.border-px * px + C.code-border,
+ radius: CB.radius-px * px, inset: CB.pad-px * px, above: 1.2em, below: 1.2em,
+ text(fill: C.code-fg, it),
+ )
+}
+
+// ---------- block quotes ----------
+#show quote.where(block: true): it => {
+ let Q = E.quote
+ block(
+ width: 100%, fill: C.quote-bg, radius: Q.radius-px * px,
+ stroke: (left: Q.bar-px * px + C.quote-border),
+ inset: (left: (Q.pad-left-px + Q.bar-px) * px, right: Q.pad-right-px * px, y: Q.pad-y-em * 1em),
+ it.body,
+ )
+}
+
+// ---------- tables ----------
+#set table(
+ inset: (x: E.table.pad-x-px * px, y: E.table.pad-y-px * px),
+ stroke: (x, y) => if y == 1 { (top: E.table.border-px * px + C.th-border) } else if y > 1 { (top: E.table.border-px * px + C.border) },
+)
+#show table.cell.where(y: 0): set text(weight: E.table.header-weight)
+#show table: set par(leading: 0.38em)
+
+// ---------- footnotes ----------
+#set footnote.entry(separator: line(length: 30%, stroke: px + C.border), gap: 0.5em)
+#show footnote.entry: set text(size: 0.9em, fill: C.muted)
+
+// ---------- long words, URLs and paths must wrap ----------
+// A token of 30+ non-space characters gets break chances after each
+// character, so it wraps like CSS `word-wrap: break-word` instead of
+// running off the page.
+#show regex("\S{30,}"): it => it.text.clusters().join(sym.zws)
+
+// ---------- helpers ----------
+#let alt-box(alt, why: none) = box(
+ stroke: px + C.muted, inset: (x: 4pt, y: 1.5pt), outset: (y: 1pt), radius: 3pt,
+ text(fill: C.muted, size: 0.9em, {
+ "🖼 "
+ if alt == none or alt == "" { if why == none { "image" } else { why } } else { alt }
+ }),
+)
+
+#let image-exts = ("png", "jpg", "jpeg", "gif", "svg", "webp")
+
+#let resolve(p) = {
+ let p = p.trim()
+ if p.starts-with("file://") { p = p.slice(7) }
+ p = p.replace("%20", " ")
+ if p.starts-with("/") { p } else if base == "" { none } else {
+ base.trim("/", at: end) + "/" + p.trim("./", at: start, repeat: false)
+ }
+}
+
+#let md-image(path, alt: none, want: none, ..rest) = {
+ let path = if type(path) == str { path } else { "" }
+ let alt = if alt == none { none } else if type(alt) == str { alt } else { none }
+ if safe or path == "" { return alt-box(alt) }
+ // Remote (http:, https:, data:, ...) images cannot be loaded.
+ if path.match(regex("^[A-Za-z][A-Za-z0-9+.-]+:")) != none and not path.starts-with("file://") {
+ return alt-box(alt)
+ }
+ let full = resolve(path)
+ if full == none { return alt-box(alt) }
+ let ext = lower(full.split(".").last())
+ if ext not in image-exts { return alt-box(alt) }
+ if allow != none and full not in allow and path not in allow { return alt-box(alt) }
+ box(layout(size => {
+ let nat = measure(image(full))
+ // CSS px -> pt at our scale; never wider than the column (max-width: 100%).
+ let w = if want == none { nat.width * (11 / 14) } else if type(want) == ratio {
+ want * size.width
+ } else { want }
+ let w = calc.min(w, size.width)
+ image(full, width: w, alt: alt)
+ }))
+}
+
+// <img src=... alt=... width=...>
+#let html-img(attrs) = {
+ let src = attrs.at("src", default: "")
+ let alt = attrs.at("alt", default: none)
+ // width="40" (CSS px) or width="50%"
+ let w = attrs.at("width", default: none)
+ let w = if w == none { none } else if w.match(regex("^\d+(\.\d+)?%$")) != none {
+ float(w.trim("%", at: end)) * 1%
+ } else if w.match(regex("^\d+(\.\d+)?(px)?$")) != none {
+ float(w.trim("px", at: end)) * px
+ } else { none }
+ md-image(src, alt: alt, want: w)
+}
+
+// [@x] (citation / reference). Footnote refs work; anything else is drawn
+// as plain text so a missing label can never fail the compile.
+#let md-ref(target, supplement: auto, ..rest) = context {
+ let found = if type(target) == label { query(target) } else { () }
+ if found.len() == 1 and found.first().func() == footnote {
+ ref(target)
+ } else if supplement != auto and supplement != none {
+ supplement
+ } else {
+ let name = if type(target) == label { str(target) } else { repr(target) }
+ "[@" + name.replace(regex("^s\d+-"), "") + "]"
+ }
+}
+
+// [text](#anchor): link inside the segment when the label exists, else text.
+#let md-link(dest, ..args) = {
+ if type(dest) == label {
+ let body = args.pos().at(0, default: none)
+ context {
+ if query(dest).len() == 1 { link(dest, ..args) } else {
+ text(fill: C.link, if body == none { str(dest) } else { body })
+ }
+ }
+ } else if type(dest) == str and dest.trim() == "" {
+ // [text]() : an empty URL is an error in Typst.
+ let body = args.pos().at(0, default: none)
+ text(fill: C.link, if body == none { "" } else { body })
+ } else {
+ link(dest, ..args)
+ }
+}
+
+// <a href=...>; <a name=...> (no href) is just its text.
+#let html-a(attrs, body) = {
+ let href = attrs.at("href", default: "")
+ if href.trim() == "" { body } else if href.starts-with("#") {
+ text(fill: C.link, body)
+ } else { link(href, body) }
+}
+
+// ---------- HTML tables (<table><tr><td>) ----------
+// cmarker's own version fails on bad rowspan/colspan or an empty table.
+// Same tagging scheme as cmarker: [#metadata((tag, data))#body].
+#let tagged(c, tags) = (
+ type(c) == content and c.func() == [].func() and c.children.len() == 2
+ and c.children.at(0).func() == metadata
+ and type(c.children.at(0).value) == array and c.children.at(0).value.len() == 2
+ and c.children.at(0).value.at(0) in tags
+)
+#let untag(c, tags) = {
+ let kids = if tagged(c, tags) { (c,) } else if type(c) == content and c.func() == [].func() { c.children } else { () }
+ kids.filter(k => tagged(k, tags)).map(k => (k.children.at(0).value.at(0), k.children.at(0).value.at(1), k.children.at(1)))
+}
+#let span-attr(attrs, key) = {
+ let v = str(attrs.at(key, default: "1")).trim()
+ if v.match(regex("^[1-9][0-9]{0,2}$")) != none { int(v) } else { 1 }
+}
+#let html-cell(attrs, body) = [#metadata(("<td>", attrs))#body]
+#let html-table(attrs, body) = {
+ let rows = (header: (), body: (), footer: ())
+ for (tag, _, child) in untag(body, ("<tr>", "<thead>", "<tfoot>", "<tbody>")) {
+ if tag == "<thead>" {
+ for (_, _, row) in untag(child, ("<tr>",)) { rows.header.push(untag(row, ("<td>",))) }
+ } else if tag == "<tfoot>" {
+ for (_, _, row) in untag(child, ("<tr>",)) { rows.footer.push(untag(row, ("<td>",))) }
+ } else if tag == "<tbody>" {
+ for (_, _, row) in untag(child, ("<tr>",)) { rows.body.push(untag(row, ("<td>",))) }
+ } else {
+ rows.body.push(untag(child, ("<td>",)))
+ }
+ }
+ let all = rows.header + rows.body + rows.footer
+ if all.len() == 0 { return body }
+ // Count the columns each row really needs, rowspans from above included.
+ let need = all.map(_ => 0)
+ let i = 0
+ let bounds = ()
+ for (k, section) in rows {
+ let stop = i + section.len()
+ bounds.push((k, i, stop))
+ for row in section {
+ for (_, a, _) in row {
+ for r in range(i, calc.min(i + span-attr(a, "rowspan"), stop)) {
+ need.at(r) += span-attr(a, "colspan")
+ }
+ }
+ i += 1
+ }
+ }
+ let columns = calc.max(0, ..need)
+ if columns == 0 { return body }
+ let cells = (:)
+ for (k, start, stop) in bounds {
+ let out = ()
+ for (j, row) in rows.at(k).enumerate() {
+ let y = start + j
+ for (_, a, td) in row {
+ out.push(table.cell(
+ y: y,
+ colspan: calc.min(span-attr(a, "colspan"), columns),
+ rowspan: calc.max(1, calc.min(span-attr(a, "rowspan"), stop - y)),
+ td,
+ ))
+ }
+ }
+ cells.insert(k, out)
+ }
+ let args = ()
+ if cells.header.len() != 0 { args.push(table.header(..cells.header)) }
+ args += cells.body
+ if cells.footer.len() != 0 { args.push(table.footer(..cells.footer)) }
+ table(columns: columns, ..args)
+}
+
+#let md-rule() = block(above: E.rule.gap-em * 1em, below: E.rule.gap-em * 1em, line(length: 100%, stroke: E.rule.border-px * px + C.border))
+
+// ---------- task lists: "- [x] done" / "- [ ] todo" ----------
+#let checkbox(checked) = box(
+ width: 0.95em, height: 0.95em, baseline: 0.12em, radius: 2.5 * px,
+ fill: if checked { C.accent } else { none },
+ stroke: if checked { 0.8 * px + C.accent } else { 1.2 * px + C.muted },
+ if checked {
+ place(curve(
+ stroke: (paint: C.check, thickness: 0.13em, cap: "round", join: "round"),
+ curve.move((0.22em, 0.5em)),
+ curve.line((0.42em, 0.7em)),
+ curve.line((0.75em, 0.27em)),
+ ))
+ },
+)
+
+// Text of an element when it is plain text or a space, else none.
+#let plain(c) = {
+ // Escaped "\[" arrives as a `symbol` element; plain text as `text`.
+ if type(c) == str { c } else if c == [ ] { " " } else if c.func() != raw and "text" in c.fields() and type(c.text) == str {
+ c.text
+ } else { none }
+}
+
+// If an item body starts with "[ ] " / "[x] ", return (checked, rest).
+#let task-split(body) = {
+ if type(body) != content { return none }
+ let kids = if body.func() == [].func() { body.children } else { (body,) }
+ let acc = ""
+ let n = 0
+ for c in kids {
+ if acc.len() >= 4 { break }
+ let t = plain(c)
+ if t == none { break }
+ acc += t
+ n += 1
+ }
+ let m = acc.match(regex("^\[([ xX])\][ \t]"))
+ if m == none or m.end != acc.len() {
+ // The 4 characters may sit in one text with more text after them.
+ if m != none and m.end < acc.len() and n > 0 {
+ let first-rest = acc.slice(m.end)
+ return (m.captures.at(0) != " ", (first-rest, ..kids.slice(n)).join())
+ }
+ return none
+ }
+ (m.captures.at(0) != " ", kids.slice(n).join())
+}
+
+#let md-list(..args) = {
+ let items = args.pos()
+ let tasks = items.map(task-split)
+ if tasks.all(t => t == none) { return list(..args) }
+ if tasks.all(t => t != none) {
+ // GitHub-style: no bullet, the checkbox sits where the bullet would.
+ let rows = tasks.map(t => (
+ align(right, checkbox(t.at(0))),
+ t.at(1),
+ ))
+ pad(left: 0.45em, grid(
+ columns: (1.4em, 1fr), column-gutter: 0.55em, row-gutter: 0.38em + 0.15em,
+ ..rows.flatten(),
+ ))
+ } else {
+ list(..args.named(), ..items.zip(tasks).map(((it, t)) => if t == none { it } else {
+ [#checkbox(t.at(0)) #t.at(1)]
+ }))
+ }
+}
+
+// "1. [x] done": keep the number, put the checkbox after it.
+#let md-enum(..args) = {
+ let items = args.pos().map(it => {
+ let t = task-split(it)
+ if t == none { it } else { [#checkbox(t.at(0)) #t.at(1)] }
+ })
+ enum(..args.named(), ..items)
+}
+
+// ---------- ```typst fences: live Typst ----------
+#let live-langs = ("typst", "typ")
+#let md-raw(src, block: false, lang: none, ..args) = {
+ let l = if lang == none { "" } else { lower(str(lang).trim()) }
+ if block and not safe and l in live-langs {
+ // Inside a block, so #pagebreak() and #set page() are errors (one
+ // segment must stay one page); a column break is dropped.
+ std.block(width: 100%, above: 1.2em, below: 1.2em, {
+ show colbreak: none
+ eval(src, mode: "markup", scope: (theme: theme))
+ })
+ } else if block and safe and l in live-langs {
+ // Retry mode: show the source, with a note that it was not drawn.
+ std.block(above: 1.2em, below: 0pt, sticky: true,
+ text(size: 0.85em, fill: C.muted, style: "italic")[Typst source (not drawn: the answer failed to compile)])
+ raw(src, block: true, lang: "typst")
+ } else {
+ raw(src, block: block, lang: lang, ..args)
+ }
+}
+
+// ---------- math ----------
+#let md-math = if safe {
+ (src, block: false) => if block { raw(src, block: true, lang: "latex") } else { raw(src) }
+} else { mitex }
+
+#let kbd(attrs, body) = box(
+ stroke: px + C.border, inset: (x: 3pt, y: 1pt), outset: (y: 1pt), radius: 3pt,
+ text(font: mono, size: 0.9em, body),
+)
+
+// ---------- render ----------
+#for (i, seg) in segments.enumerate() {
+ let md = if type(seg) == str { seg } else { str(seg) }
+ let top = if i == 0 { first-top } else { margin-y }
+ let body = cmarker.render(
+ md,
+ smart-punctuation: false,
+ raw-typst: false,
+ math: md-math,
+ label-prefix: "s" + str(i) + "-",
+ html: (
+ img: ("void", html-img),
+ a: html-a,
+ table: html-table,
+ td: html-cell,
+ th: (attrs, body) => html-cell(attrs, strong(body)),
+ tbody: (attrs, body) => [#metadata(("<tbody>", attrs))#body],
+ kbd: kbd,
+ ),
+ scope: (
+ image: md-image,
+ raw: md-raw,
+ ref: md-ref,
+ link: md-link,
+ list: md-list,
+ enum: md-enum,
+ rule: md-rule,
+ ),
+ )
+ // Pad the bottom so the page is a whole number of terminal rows.
+ context {
+ // No bottom margin: text is measured to its descenders, so the last line
+ // ends the page and the next row is the engine's own gap.
+ let total = top + measure(block(width: content-w, body)).height
+ let pad = if row > 0pt { calc.ceil(total / row - 0.001) * row - total } else { 0pt }
+ page(margin: (top: top, bottom: pad), body)
+ }
+}
diff --git a/render/measure.typ b/render/measure.typ
new file mode 100644
index 0000000..bbfb403
--- /dev/null
+++ b/render/measure.typ
@@ -0,0 +1,24 @@
+// Font metrics for the hooks module, read with
+// typst eval 'query(<m>).first().value' --in measure.typ --input term-font=<family>
+// Per 1 em: `adv` the width of "0", `xh` the x-height, `avg` the mean
+// advance over a lowercase pangram. `term` is none when the family is not
+// installed (Typst would fall back to another font).
+#import "fonts.typ": sans, mono-base
+#let fam = sys.inputs.at("term-font", default: "")
+#let probe = "the quick brown fox jumps over the lazy dog"
+#let m(fonts, body, edge) = measure(text(
+ font: fonts, size: 100pt, top-edge: edge, bottom-edge: "baseline", fallback: false, body,
+))
+#let metrics(fonts) = (
+ adv: m(fonts, "0", "cap-height").width / 100pt,
+ xh: m(fonts, "x", "x-height").height / 100pt,
+ avg: m(fonts, probe, "cap-height").width / 100pt / probe.len(),
+)
+#context {
+ let found = fam != "" and m((fam,), "0", "cap-height").width != m(("Nonexistent Font Zz",), "0", "cap-height").width
+ [#metadata((
+ term: if found { metrics((fam,)) } else { none },
+ menlo: metrics(mono-base),
+ body: metrics(sans),
+ )) <m>]
+}
diff --git a/render/packages/preview/cetz-plot/0.1.4/LICENSE b/render/packages/preview/cetz-plot/0.1.4/LICENSE
new file mode 100644
index 0000000..65c5ca8
--- /dev/null
+++ b/render/packages/preview/cetz-plot/0.1.4/LICENSE
@@ -0,0 +1,165 @@
+ GNU LESSER GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+
+ This version of the GNU Lesser General Public License incorporates
+the terms and conditions of version 3 of the GNU General Public
+License, supplemented by the additional permissions listed below.
+
+ 0. Additional Definitions.
+
+ As used herein, "this License" refers to version 3 of the GNU Lesser
+General Public License, and the "GNU GPL" refers to version 3 of the GNU
+General Public License.
+
+ "The Library" refers to a covered work governed by this License,
+other than an Application or a Combined Work as defined below.
+
+ An "Application" is any work that makes use of an interface provided
+by the Library, but which is not otherwise based on the Library.
+Defining a subclass of a class defined by the Library is deemed a mode
+of using an interface provided by the Library.
+
+ A "Combined Work" is a work produced by combining or linking an
+Application with the Library. The particular version of the Library
+with which the Combined Work was made is also called the "Linked
+Version".
+
+ The "Minimal Corresponding Source" for a Combined Work means the
+Corresponding Source for the Combined Work, excluding any source code
+for portions of the Combined Work that, considered in isolation, are
+based on the Application, and not on the Linked Version.
+
+ The "Corresponding Application Code" for a Combined Work means the
+object code and/or source code for the Application, including any data
+and utility programs needed for reproducing the Combined Work from the
+Application, but excluding the System Libraries of the Combined Work.
+
+ 1. Exception to Section 3 of the GNU GPL.
+
+ You may convey a covered work under sections 3 and 4 of this License
+without being bound by section 3 of the GNU GPL.
+
+ 2. Conveying Modified Versions.
+
+ If you modify a copy of the Library, and, in your modifications, a
+facility refers to a function or data to be supplied by an Application
+that uses the facility (other than as an argument passed when the
+facility is invoked), then you may convey a copy of the modified
+version:
+
+ a) under this License, provided that you make a good faith effort to
+ ensure that, in the event an Application does not supply the
+ function or data, the facility still operates, and performs
+ whatever part of its purpose remains meaningful, or
+
+ b) under the GNU GPL, with none of the additional permissions of
+ this License applicable to that copy.
+
+ 3. Object Code Incorporating Material from Library Header Files.
+
+ The object code form of an Application may incorporate material from
+a header file that is part of the Library. You may convey such object
+code under terms of your choice, provided that, if the incorporated
+material is not limited to numerical parameters, data structure
+layouts and accessors, or small macros, inline functions and templates
+(ten or fewer lines in length), you do both of the following:
+
+ a) Give prominent notice with each copy of the object code that the
+ Library is used in it and that the Library and its use are
+ covered by this License.
+
+ b) Accompany the object code with a copy of the GNU GPL and this license
+ document.
+
+ 4. Combined Works.
+
+ You may convey a Combined Work under terms of your choice that,
+taken together, effectively do not restrict modification of the
+portions of the Library contained in the Combined Work and reverse
+engineering for debugging such modifications, if you also do each of
+the following:
+
+ a) Give prominent notice with each copy of the Combined Work that
+ the Library is used in it and that the Library and its use are
+ covered by this License.
+
+ b) Accompany the Combined Work with a copy of the GNU GPL and this license
+ document.
+
+ c) For a Combined Work that displays copyright notices during
+ execution, include the copyright notice for the Library among
+ these notices, as well as a reference directing the user to the
+ copies of the GNU GPL and this license document.
+
+ d) Do one of the following:
+
+ 0) Convey the Minimal Corresponding Source under the terms of this
+ License, and the Corresponding Application Code in a form
+ suitable for, and under terms that permit, the user to
+ recombine or relink the Application with a modified version of
+ the Linked Version to produce a modified Combined Work, in the
+ manner specified by section 6 of the GNU GPL for conveying
+ Corresponding Source.
+
+ 1) Use a suitable shared library mechanism for linking with the
+ Library. A suitable mechanism is one that (a) uses at run time
+ a copy of the Library already present on the user's computer
+ system, and (b) will operate properly with a modified version
+ of the Library that is interface-compatible with the Linked
+ Version.
+
+ e) Provide Installation Information, but only if you would otherwise
+ be required to provide such information under section 6 of the
+ GNU GPL, and only to the extent that such information is
+ necessary to install and execute a modified version of the
+ Combined Work produced by recombining or relinking the
+ Application with a modified version of the Linked Version. (If
+ you use option 4d0, the Installation Information must accompany
+ the Minimal Corresponding Source and Corresponding Application
+ Code. If you use option 4d1, you must provide the Installation
+ Information in the manner specified by section 6 of the GNU GPL
+ for conveying Corresponding Source.)
+
+ 5. Combined Libraries.
+
+ You may place library facilities that are a work based on the
+Library side by side in a single library together with other library
+facilities that are not Applications and are not covered by this
+License, and convey such a combined library under terms of your
+choice, if you do both of the following:
+
+ a) Accompany the combined library with a copy of the same work based
+ on the Library, uncombined with any other library facilities,
+ conveyed under the terms of this License.
+
+ b) Give prominent notice with the combined library that part of it
+ is a work based on the Library, and explaining where to find the
+ accompanying uncombined form of the same work.
+
+ 6. Revised Versions of the GNU Lesser General Public License.
+
+ The Free Software Foundation may publish revised and/or new versions
+of the GNU Lesser General Public License from time to time. Such new
+versions will be similar in spirit to the present version, but may
+differ in detail to address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Library as you received it specifies that a certain numbered version
+of the GNU Lesser General Public License "or any later version"
+applies to it, you have the option of following the terms and
+conditions either of that published version or of any later version
+published by the Free Software Foundation. If the Library as you
+received it does not specify a version number of the GNU Lesser
+General Public License, you may choose any version of the GNU Lesser
+General Public License ever published by the Free Software Foundation.
+
+ If the Library as you received it specifies that a proxy can decide
+whether future versions of the GNU Lesser General Public License shall
+apply, that proxy's public statement of acceptance of any version is
+permanent authorization for you to choose that version for the
+Library.
diff --git a/render/packages/preview/cetz-plot/0.1.4/README.md b/render/packages/preview/cetz-plot/0.1.4/README.md
new file mode 100644
index 0000000..3f36cda
--- /dev/null
+++ b/render/packages/preview/cetz-plot/0.1.4/README.md
@@ -0,0 +1,89 @@
+# CeTZ-Plot
+
+CeTZ-Plot is a library that adds plots and charts to [CeTZ](https://github.com/cetz-package/cetz), a library for drawing with [Typst](https://typst.app).
+
+CeTZ-Plot requires CeTZ version ≥ 0.5.0!
+
+## Examples
+<!-- img width is set so the table gets evenly spaced by GitHubs css -->
+<table>
+<tr>
+ <td>
+ <a href="gallery/line.typ">
+ <img src="gallery/line.png" width="250px" alt="Line plot example">
+ </a>
+ </td>
+ <td>
+ <a href="gallery/piechart.typ">
+ <img src="gallery/piechart.png" width="250px" alt="Piechart example">
+ </a>
+ </td>
+ <td>
+ <a href="gallery/barchart.typ">
+ <img src="gallery/barchart.png" width="250px" alt="Barchart example">
+ </a>
+ </td>
+</tr><tr>
+ <td>Plot</td>
+ <td>Pie Chart</td>
+ <td>Clustered Barchart</td>
+</tr>
+<tr>
+ <td>
+ <a href="gallery/pyramid.typ">
+ <img src="gallery/pyramid.png" width="250px" alt="Stacked pyramid chart example">
+ </a>
+ </td>
+ <td colspan="2">
+ <a href="gallery/process.typ">
+ <img src="gallery/process.png" width="500px" alt="Process chart example">
+ </a>
+ </td>
+</tr><tr>
+ <td>Pyramid</td>
+ <td colspan="2">Process</td>
+</tr>
+<tr>
+ <td>
+ <a href="gallery/circular.typ">
+ <img src="gallery/circular.png" width="250px" alt="Circular process chart example">
+ </a>
+ </td>
+</tr><tr>
+ <td>Cycle</td>
+</tr>
+</table>
+
+*Click on the example image to jump to the code.*
+
+
+## Usage
+
+For information, see the [manual ](./manual.pdf?raw=true).
+
+To use this package, simply add the following code to your document:
+```
+#import "@preview/cetz:0.5.2"
+#import "@preview/cetz-plot:0.1.4": plot, chart
+
+#cetz.canvas({
+ // Your plot/chart code goes here
+})
+```
+
+## Installing
+
+To install the CeTZ-Plot package under [your local typst package dir](https://github.com/typst/packages?tab=readme-ov-file#local-packages) you can use the `install` script from the repository.
+
+### Just
+
+This project uses [just](https://github.com/casey/just), a handy command runner.
+
+You can run all commands without having `just` installed, just have a look into the `justfile`.
+To install `just` on your system, use your systems package manager. On Windows, [Cargo](https://doc.rust-lang.org/cargo/) (`cargo install just`), [Chocolatey](https://chocolatey.org/) (`choco install just`) and [some other sources](https://just.systems/man/en/chapter_4.html) can be used. You need to run it from a `sh` compatible shell on Windows (e.g git-bash).
+
+## Testing
+
+This package comes with some unit tests under the `tests` directory.
+To run all tests you can run the `just test` target. You need to have
+[`tytanic`](https://github.com/tingerrr/tytanic/) in your `PATH`: `cargo install tytanic --git https://github.com/tingerrr/tytanic`.
diff --git a/render/packages/preview/cetz-plot/0.1.4/src/axes.typ b/render/packages/preview/cetz-plot/0.1.4/src/axes.typ
new file mode 100644
index 0000000..8b1f3ef
--- /dev/null
+++ b/render/packages/preview/cetz-plot/0.1.4/src/axes.typ
@@ -0,0 +1,921 @@
+#import "/src/cetz.typ": util, draw, vector, matrix, styles, process, drawable, path-util, process
+#import "/src/plot/formats.typ"
+
+/// Default axis style
+///
+/// #show-parameter-block("tick-limit", "int", default: 100, [Upper major tick limit.])
+/// #show-parameter-block("minor-tick-limit", "int", default: 1000, [Upper minor tick limit.])
+/// #show-parameter-block("auto-tick-factors", "array", [List of tick factors used for automatic tick step determination.])
+/// #show-parameter-block("auto-tick-count", "int", [Number of ticks to generate by default.])
+/// #show-parameter-block("stroke", "stroke", [Axis stroke style.])
+/// #show-parameter-block("label.offset", "number", [Distance to move axis labels away from the axis.])
+/// #show-parameter-block("label.anchor", "anchor", [Anchor of the axis label to use for it's placement.])
+/// #show-parameter-block("label.angle", "angle", [Angle of the axis label.])
+/// #show-parameter-block("axis-layer", "float", [Layer to draw axes on (see cetz' `on-layer`)])
+/// #show-parameter-block("grid-layer", "float", [Layer to draw the grid on (see cetz' `on-layer`)])
+/// #show-parameter-block("background-layer", "float", [Layer to draw the background on (see cetz' `on-layer`)])
+/// #show-parameter-block("padding", "number", [Extra distance between axes and plotting area. For schoolbook axes, this is the length of how much axes grow out of the plotting area.])
+/// #show-parameter-block("overshoot", "number", [School-book style axes only: Extra length to add to the end (right, top) of axes.])
+/// #show-parameter-block("tick.stroke", "stroke", [Major tick stroke style.])
+/// #show-parameter-block("tick.minor-stroke", "stroke", [Minor tick stroke style.])
+/// #show-parameter-block("tick.offset", ("number", "ratio"), [Major tick offset along the tick's direction, can be relative to the length.])
+/// #show-parameter-block("tick.minor-offset", ("number", "ratio"), [Minor tick offset along the tick's direction, can be relative to the length.])
+/// #show-parameter-block("tick.length", ("number"), [Major tick length.])
+/// #show-parameter-block("tick.minor-length", ("number", "ratio"), [Minor tick length, can be relative to the major tick length.])
+/// #show-parameter-block("tick.label.offset", ("number"), [Major tick label offset away from the tick.])
+/// #show-parameter-block("tick.label.angle", ("angle"), [Major tick label angle.])
+/// #show-parameter-block("tick.label.anchor", ("anchor"), [Anchor of major tick labels used for positioning.])
+/// #show-parameter-block("tick.label.show", ("auto", "bool"), default: auto, [Set visibility of tick labels. A value of `auto` shows tick labels for all but mirrored axes.])
+/// #show-parameter-block("grid.stroke", "stroke", [Major grid line stroke style.])
+/// #show-parameter-block("break-point.width", "number", [Axis break width along the axis.])
+/// #show-parameter-block("break-point.length", "number", [Axis break length.])
+/// #show-parameter-block("minor-grid.stroke", "stroke", [Minor grid line stroke style.])
+/// #show-parameter-block("shared-zero", ("bool", "content"), default: "$0$", [School-book style axes only: Content to display at the plots origin (0,0). If set to `false`, nothing is shown. Having this set, suppresses auto-generated ticks for $0$!])
+#let default-style = (
+ tick-limit: 100,
+ minor-tick-limit: 1000,
+ auto-tick-factors: (1, 1.5, 2, 2.5, 3, 4, 5, 6, 8, 10), // Tick factor to try
+ auto-tick-count: 11, // Number of ticks the plot tries to place
+ fill: none,
+ stroke: auto,
+ label: (
+ offset: .2cm, // Axis label offset
+ anchor: auto, // Axis label anchor
+ angle: auto, // Axis label angle
+ ),
+ axis-layer: 0,
+ grid-layer: 0,
+ background-layer: 0,
+ padding: 0,
+ tick: (
+ fill: none,
+ stroke: black + 1pt,
+ minor-stroke: black + .5pt,
+ offset: 0,
+ minor-offset: 0,
+ length: .1cm, // Tick length: Number
+ minor-length: 70%, // Minor tick length: Number, Ratio
+ label: (
+ offset: .15cm, // Tick label offset
+ angle: 0deg, // Tick label angle
+ anchor: auto, // Tick label anchor
+ "show": auto, // Show tick labels for axes in use
+ )
+ ),
+ break-point: (
+ width: .75cm,
+ length: .15cm,
+ ),
+ grid: (
+ stroke: (paint: gray.lighten(50%), thickness: 1pt),
+ ),
+ minor-grid: (
+ stroke: (paint: gray.lighten(50%), thickness: .5pt),
+ ),
+)
+
+// Default Scientific Style
+#let default-style-scientific = util.merge-dictionary(default-style, (
+ left: (tick: (label: (anchor: "east"))),
+ bottom: (tick: (label: (anchor: "north"))),
+ right: (tick: (label: (anchor: "west"))),
+ top: (tick: (label: (anchor: "south"))),
+ stroke: (cap: "square"),
+ padding: 0,
+))
+
+// Default Schoolbook Style
+#let default-style-schoolbook = util.merge-dictionary(default-style, (
+ x: (stroke: auto, fill: none, mark: (start: none, end: "straight"),
+ tick: (label: (anchor: "north"))),
+ y: (stroke: auto, fill: none, mark: (start: none, end: "straight"),
+ tick: (label: (anchor: "east"))),
+ label: (offset: .1cm),
+ origin: (label: (offset: .05cm)),
+ padding: .1cm, // Axis padding on both sides outsides the plotting area
+ overshoot: .5cm, // Axis end "overshoot" out of the plotting area
+ tick: (
+ offset: -50%,
+ minor-offset: -50%,
+ length: .2cm,
+ minor-length: 70%,
+ ),
+ shared-zero: $0$, // Show zero tick label at (0, 0)
+))
+
+#let _prepare-style(ctx, style) = {
+ if type(style) != dictionary { return style }
+
+ let res = util.resolve-number.with(ctx)
+ let rel-to(v, to) = {
+ if type(v) == ratio {
+ return v * to / 100%
+ } else {
+ return res(v)
+ }
+ }
+
+ style.tick.length = res(style.tick.length)
+ style.tick.offset = rel-to(style.tick.offset, style.tick.length)
+ style.tick.minor-length = rel-to(style.tick.minor-length, style.tick.length)
+ style.tick.minor-offset = rel-to(style.tick.minor-offset, style.tick.minor-length)
+ style.tick.label.offset = res(style.tick.label.offset)
+
+ // Break points
+ style.break-point.width = res(style.break-point.width)
+ style.break-point.length = res(style.break-point.length)
+
+ // Padding
+ style.padding = res(style.padding)
+
+ if "overshoot" in style {
+ style.overshoot = res(style.overshoot)
+ }
+
+ return style
+}
+
+#let _get-axis-style(ctx, style, name) = {
+ if not name in style {
+ return style
+ }
+
+ style = styles.resolve(style, merge: style.at(name))
+ return _prepare-style(ctx, style)
+}
+
+#let _get-grid-type(axis) = {
+ let grid = axis.ticks.at("grid", default: false)
+ if grid == "major" or grid == true { return 1 }
+ if grid == "minor" { return 2 }
+ if grid == "both" { return 3 }
+ return 0
+}
+
+#let _inset-axis-points(ctx, style, axis, start, end) = {
+ if axis == none { return (start, end) }
+
+ let (low, high) = axis.inset.map(v => util.resolve-number(ctx, v))
+
+ let is-horizontal = start.at(1) == end.at(1)
+ if is-horizontal {
+ start = vector.add(start, (low, 0))
+ end = vector.sub(end, (high, 0))
+ } else {
+ start = vector.add(start, (0, low))
+ end = vector.sub(end, (0, high))
+ }
+ return (start, end)
+}
+
+#let _draw-axis-line(start, end, axis, is-horizontal, style) = {
+ let enabled = if axis != none and axis.show-break {
+ axis.min > 0 or axis.max < 0
+ } else { false }
+
+ if enabled {
+ let size = if is-horizontal {
+ (style.break-point.width, 0)
+ } else {
+ (0, style.break-point.width, 0)
+ }
+
+ let up = if is-horizontal {
+ (0, style.break-point.length)
+ } else {
+ (style.break-point.length, 0)
+ }
+
+ let add-break(is-end) = {
+ let a = ()
+ let b = (rel: vector.scale(size, .3), update: false)
+ let c = (rel: vector.add(vector.scale(size, .4), vector.scale(up, -1)), update: false)
+ let d = (rel: vector.add(vector.scale(size, .6), vector.scale(up, +1)), update: false)
+ let e = (rel: vector.scale(size, .7), update: false)
+ let f = (rel: size)
+
+ let mark = if is-end {
+ style.at("mark", default: none)
+ }
+ draw.line(a, b, c, d, e, f, stroke: style.stroke, mark: mark)
+ }
+
+ draw.merge-path({
+ draw.move-to(start)
+ if axis.min > 0 {
+ add-break(false)
+ draw.line((rel: size, to: start), end)
+ } else if axis.max < 0 {
+ draw.line(start, (rel: vector.scale(size, -1), to: end))
+ add-break(true)
+ }
+ }, stroke: style.stroke, mark: style.at("mark", default: none))
+ } else {
+ draw.line(start, end, stroke: style.stroke, mark: style.at("mark", default: none))
+ }
+}
+
+// Construct Axis Object
+//
+// - min (number): Minimum value
+// - max (number): Maximum value
+// - ticks (dictionary): Tick settings:
+// - step (number): Major tic step
+// - minor-step (number): Minor tic step
+// - decimals (int): Tick float decimal length
+// - label (content): Axis label
+// - mode (string): Axis scaling function. Takes `lin` or `log`
+// - base (number): Base for tick labels when logarithmically scaled.
+#let axis(min: -1, max: 1, label: none,
+ ticks: (step: auto, minor-step: none,
+ decimals: 2, grid: false,
+ format: "float"
+ ),
+ mode: auto, base: auto) = (
+ min: min, max: max, ticks: ticks, label: label, inset: (0, 0), show-break: false, mode: mode, base: base
+)
+
+// Format a tick value
+#let format-tick-value(value, tic-options) = {
+ // Without it we get negative zero in conversion
+ // to content! Typst has negative zero floats.
+ if value == 0 { value = 0 }
+
+ if type(value) != std.content {
+ let format = tic-options.at("format", default: "float")
+ if format == none {
+ value = []
+ } else if type(format) == std.content {
+ value = format
+ } else if type(format) == function {
+ value = (format)(value)
+ } else if format == "sci" {
+ value = formats.sci(value, digits: tic-options.at("decimals", default: 2))
+ } else {
+ value = formats.decimal(value, digits: tic-options.at("decimals", default: 2))
+ }
+ } else if type(value) != std.content {
+ value = str(value)
+ }
+
+ return value
+}
+
+// Get value on axis [0, 1]
+//
+// - axis (axis): Axis
+// - v (number): Value
+// -> float
+#let value-on-axis(axis, v) = {
+ if v == none { return }
+ let (min, max) = (axis.min, axis.max)
+ if axis.mode == "log" {
+ min = calc.log(min)
+ max = calc.log(max)
+ v = calc.log(v)
+ }
+
+ let dt = max - min; if dt == 0 { dt = 1 }
+ return (v - min) / dt
+}
+
+// Compute list of linear ticks for axis
+//
+// - axis (axis): Axis
+#let compute-linear-ticks(axis, style, add-zero: true) = {
+ let (min, max) = (axis.min, axis.max)
+ let dt = max - min; if (dt == 0) { dt = 1 }
+ let ticks = axis.ticks
+ let ferr = util.float-epsilon
+ let tick-limit = style.tick-limit
+ let minor-tick-limit = style.minor-tick-limit
+
+ let l = ()
+ if ticks != none {
+ let major-tick-values = ()
+ if "step" in ticks and ticks.step != none {
+ assert(ticks.step >= 0,
+ message: "Axis tick step must be positive and non 0.")
+ if axis.min > axis.max { ticks.step *= -1 }
+
+ let s = 1 / ticks.step
+
+ let num-ticks = int(max * s + 1.5) - int(min * s)
+ assert(num-ticks <= tick-limit,
+ message: "Number of major ticks exceeds limit " + str(tick-limit))
+
+ let n = range(int(min * s), int(max * s + 1.5))
+ for t in n {
+ let v = (t / s - min) / dt
+ if t / s == 0 and not add-zero { continue }
+
+ if v >= 0 - ferr and v <= 1 + ferr {
+ l.push((v, format-tick-value(t / s, ticks), true))
+ major-tick-values.push(v)
+ }
+ }
+ }
+
+ if "minor-step" in ticks and ticks.minor-step != none {
+ assert(ticks.minor-step >= 0,
+ message: "Axis minor tick step must be positive")
+ if axis.min > axis.max { ticks.minor-step *= -1 }
+
+ let s = 1 / ticks.minor-step
+
+ let num-ticks = int(max * s + 1.5) - int(min * s)
+ assert(num-ticks <= minor-tick-limit,
+ message: "Number of minor ticks exceeds limit " + str(minor-tick-limit))
+
+ let n = range(int(min * s), int(max * s + 1.5))
+ for t in n {
+ let v = (t / s - min) / dt
+ if v in major-tick-values {
+ // Prefer major ticks over minor ticks
+ continue
+ }
+
+ if v != none and v >= 0 and v <= 1 + ferr {
+ l.push((v, none, false))
+ }
+ }
+ }
+
+ }
+
+ return l
+}
+
+// Compute list of linear ticks for axis
+//
+// - axis (axis): Axis
+#let compute-logarithmic-ticks(axis, style, add-zero: true) = {
+ let ferr = util.float-epsilon
+ let (min, max) = (
+ calc.log(calc.max(axis.min, ferr), base: axis.base),
+ calc.log(calc.max(axis.max, ferr), base: axis.base)
+ )
+ let dt = max - min; if (dt == 0) { dt = 1 }
+ let ticks = axis.ticks
+
+ let tick-limit = style.tick-limit
+ let minor-tick-limit = style.minor-tick-limit
+ let l = ()
+
+ if ticks != none {
+ let major-tick-values = ()
+ if "step" in ticks and ticks.step != none {
+ assert(ticks.step >= 0,
+ message: "Axis tick step must be positive and non 0.")
+ if axis.min > axis.max { ticks.step *= -1 }
+
+ let s = 1 / ticks.step
+
+ let num-ticks = int(max * s + 1.5) - int(min * s)
+ assert(num-ticks <= tick-limit,
+ message: "Number of major ticks exceeds limit " + str(tick-limit))
+
+ let n = range(
+ int(min * s),
+ int(max * s + 1.5)
+ )
+
+ for t in n {
+ let v = (t / s - min) / dt
+ if t / s == 0 and not add-zero { continue }
+
+ if v >= 0 - ferr and v <= 1 + ferr {
+ l.push((v, format-tick-value( calc.pow(axis.base, t / s), ticks), true))
+ major-tick-values.push(v)
+ }
+ }
+ }
+
+ if "minor-step" in ticks and ticks.minor-step != none {
+ assert(ticks.minor-step >= 0,
+ message: "Axis minor tick step must be positive")
+ if axis.min > axis.max { ticks.minor-step *= -1 }
+
+ let s = 1 / ticks.step
+ let n = range(int(min * s)-1, int(max * s + 1.5)+1)
+
+ for t in n {
+ for vv in range(1, int(axis.base / ticks.minor-step)) {
+
+ let v = ( (calc.log(vv * ticks.minor-step, base: axis.base) + t)/ s - min) / dt
+ if v in major-tick-values {continue}
+
+ if v != none and v >= 0 and v <= 1 + ferr {
+ l.push((v, none, false))
+ }
+
+ }
+
+ }
+ }
+ }
+
+ return l
+}
+
+// Get list of fixed axis ticks
+//
+// - axis (axis): Axis object
+#let fixed-ticks(axis) = {
+ let l = ()
+ if "list" in axis.ticks {
+ for t in axis.ticks.list {
+ let (v, label) = (none, none)
+ if type(t) in (float, int) {
+ v = t
+ label = format-tick-value(t, axis.ticks)
+ } else {
+ (v, label) = t
+ }
+
+ v = value-on-axis(axis, v)
+ if v != none and v >= 0 and v <= 1 {
+ l.push((v, label, true))
+ }
+ }
+ }
+ return l
+}
+
+// Compute list of axis ticks
+//
+// A tick triple has the format:
+// (rel-value: float, label: content, major: bool)
+//
+// - axis (axis): Axis object
+#let compute-ticks(axis, style, add-zero: true) = {
+ let find-max-n-ticks(axis, n: 11) = {
+ let dt = calc.abs(axis.max - axis.min)
+ let scale = calc.floor(calc.log(dt, base: 10) - 1)
+ if scale > 5 or scale < -5 {return none}
+
+ let (step, best) = (none, 0)
+ for s in style.auto-tick-factors {
+ s = s * calc.pow(10, scale)
+
+ let divs = calc.abs(dt / s)
+ if divs >= best and divs <= n {
+ step = s
+ best = divs
+ }
+ }
+ return step
+ }
+
+ if axis == none or axis.ticks == none { return () }
+ if axis.ticks.step == auto {
+ axis.ticks.step = find-max-n-ticks(axis, n: style.auto-tick-count)
+ }
+ if axis.ticks.minor-step == auto {
+ axis.ticks.minor-step = if axis.ticks.step != none {
+ axis.ticks.step / 5
+ } else {
+ none
+ }
+ }
+
+ let ticks = if axis.mode == "log" {
+ compute-logarithmic-ticks(axis, style, add-zero: add-zero)
+ } else {
+ compute-linear-ticks(axis, style, add-zero: add-zero)
+ }
+ ticks += fixed-ticks(axis)
+ return ticks
+}
+
+// Prepares the axis post creation. The given axis
+// must be completely set-up, including its interval.
+// Returns the prepared axis
+#let prepare-axis(ctx, axis, name) = {
+ let style = styles.resolve(ctx.style, root: "axes",
+ base: default-style-scientific)
+ style = _prepare-style(ctx, style)
+ style = _get-axis-style(ctx, style, name)
+
+ if type(axis.inset) != array {
+ axis.inset = (axis.inset, axis.inset)
+ }
+
+ axis.inset = axis.inset.map(v => util.resolve-number(ctx, v))
+
+ if axis.show-break {
+ if axis.min > 0 {
+ axis.inset.at(0) += style.break-point.width
+ } else if axis.max < 0 {
+ axis.inset.at(1) += style.break-point.width
+ }
+ }
+
+ return axis
+}
+
+// Transform a single vector along a x, y and z axis
+//
+// - size (vector): Coordinate system size
+// - x-axis (axis): X axis
+// - y-axis (axis): Y axis
+// - z-axis (axis): Z axis
+// - vec (vector): Input vector to transform
+// -> vector
+#let transform-vec(size, x-axis, y-axis, z-axis, vec) = {
+ let axes = (x-axis, y-axis)
+
+ let (x, y,) = for (dim, axis) in axes.enumerate() {
+ let s = size.at(dim) - axis.inset.sum()
+ let o = axis.inset.at(0)
+
+ let transform-func(n) = if axis.mode == "log" {
+ calc.log(calc.max(n, util.float-epsilon), base: axis.base)
+ } else {
+ n
+ }
+
+ let range = transform-func(axis.max) - transform-func(axis.min)
+
+ let f = s / range
+ ((transform-func(vec.at(dim)) - transform-func(axis.min)) * f + o,)
+ }
+
+ return (x, y, 0)
+}
+
+// Draw inside viewport coordinates of two axes
+//
+// - size (vector): Axis canvas size (relative to origin)
+// - x (axis): Horizontal axis
+// - y (axis): Vertical axis
+// - z (axis): Z axis
+// - name (string,none): Group name
+#let axis-viewport(size, x, y, z, body, name: none) = {
+ draw.group(name: name, (ctx => {
+ let transform = ctx.transform
+
+ ctx.transform = matrix.ident(4)
+ let (ctx, drawables, bounds) = process.many(ctx, util.resolve-body(ctx, body))
+
+ ctx.transform = transform
+
+ let transform-vec = transform-vec.with(size, x, y, none)
+
+ drawables = drawables.map(d => {
+ if "segments" in d {
+ d.segments = d.segments.map(((origin, closed, elements)) => {
+ elements = elements.map(((kind, ..pts)) => {
+ (kind, ..(pts.map(transform-vec)))
+ })
+ (transform-vec(origin), closed, elements)
+ })
+ }
+ if "pos" in d {
+ d.pos = transform-vec(d.pos)
+ }
+ return d
+ })
+
+ return (
+ ctx: ctx,
+ drawables: drawable.apply-transform(ctx.transform, drawables)
+ )
+ },))
+}
+
+// Draw grid lines for the ticks of an axis
+//
+// - cxt (context):
+// - axis (dictionary): The axis
+// - ticks (array): The computed ticks
+// - low (vector): Start position of a grid-line at tick 0
+// - high (vector): End position of a grid-line at tick 0
+// - dir (vector): Normalized grid direction vector along the grid axis
+// - style (style): Axis style
+#let draw-grid-lines(ctx, axis, ticks, low, high, dir, style) = {
+ let offset = (0,0)
+ if axis.inset != none {
+ let (inset-low, inset-high) = axis.inset.map(v => util.resolve-number(ctx, v))
+ offset = vector.scale(vector.norm(dir), inset-low)
+ dir = vector.sub(dir, vector.scale(vector.norm(dir), inset-low + inset-high))
+ }
+
+ let kind = _get-grid-type(axis)
+ if kind > 0 {
+ for (distance, label, is-major) in ticks {
+ let offset = vector.add(vector.scale(dir, distance), offset)
+ let start = vector.add(low, offset)
+ let end = vector.add(high, offset)
+
+ // Draw a major line
+ if is-major and (kind == 1 or kind == 3) {
+ draw.line(start, end, stroke: style.grid.stroke)
+ }
+ // Draw a minor line
+ if not is-major and kind >= 2 {
+ draw.line(start, end, stroke: style.minor-grid.stroke)
+ }
+ }
+ }
+}
+
+// Place a list of tick marks and labels along a path
+#let place-ticks-on-line(ticks, start, stop, style, flip: false, is-mirror: false) = {
+ let dir = vector.sub(stop, start)
+ let norm = vector.norm((-dir.at(1), dir.at(0), dir.at(2, default: 0)))
+
+ let def(v, d) = {
+ return if v == none or v == auto {d} else {v}
+ }
+
+ let show-label = style.tick.label.show
+ if show-label == auto {
+ show-label = not is-mirror
+ }
+
+ for (distance, label, is-major) in ticks {
+ let offset = style.tick.offset
+ let length = if is-major { style.tick.length } else { style.tick.minor-length }
+ if flip {
+ offset *= -1
+ length *= -1
+ }
+
+ let pt = vector.lerp(start, stop, distance)
+ let a = vector.add(pt, vector.scale(norm, offset))
+ let b = vector.add(a, vector.scale(norm, length))
+
+ draw.line(a, b, stroke: style.tick.stroke)
+
+ if show-label and label != none {
+ let offset = style.tick.label.offset
+ if flip {
+ offset *= -1
+ length *= -1
+ }
+
+ let c = vector.sub(if length <= 0 { b } else { a },
+ vector.scale(norm, offset))
+
+ let angle = def(style.tick.label.angle, 0deg)
+ let anchor = def(style.tick.label.anchor, "center")
+
+ draw.content(c, [#label], angle: angle, anchor: anchor)
+ }
+ }
+}
+
+// Draw up to four axes in an "scientific" style at origin (0, 0)
+//
+// - size (array): Size (width, height)
+// - left (axis): Left (y) axis
+// - bottom (axis): Bottom (x) axis
+// - right (axis): Right axis
+// - top (axis): Top axis
+// - name (string): Object name
+// - draw-unset (bool): Draw axes that are set to `none`
+// - ..style (any): Style
+#let scientific(size: (1, 1),
+ left: none,
+ right: auto,
+ bottom: none,
+ top: auto,
+ draw-unset: true,
+ name: none,
+ ..style) = {
+ import draw: *
+
+ if right == auto {
+ if left != none {
+ right = left; right.is-mirror = true
+ } else {
+ right = none
+ }
+ }
+ if top == auto {
+ if bottom != none {
+ top = bottom; top.is-mirror = true
+ } else {
+ top = none
+ }
+ }
+
+ group(name: name, ctx => {
+ let (w, h) = size
+ anchor("origin", (0, 0))
+
+ let style = style.named()
+ style = styles.resolve(ctx.style, merge: style, root: "axes",
+ base: default-style-scientific)
+ style = _prepare-style(ctx, style)
+
+ // Compute ticks
+ let x-ticks = compute-ticks(bottom, style)
+ let y-ticks = compute-ticks(left, style)
+ let x2-ticks = compute-ticks(top, style)
+ let y2-ticks = compute-ticks(right, style)
+
+ // Draw frame
+ if style.fill != none {
+ on-layer(style.background-layer, {
+ rect((0,0), (w,h), fill: style.fill, stroke: none)
+ })
+ }
+
+ // Draw grid
+ group(name: "grid", ctx => {
+ let axes = (
+ ("bottom", (0,0), (0,h), (+w,0), x-ticks, bottom),
+ ("top", (0,h), (0,0), (+w,0), x2-ticks, top),
+ ("left", (0,0), (w,0), (0,+h), y-ticks, left),
+ ("right", (w,0), (0,0), (0,+h), y2-ticks, right),
+ )
+ for (name, start, end, direction, ticks, axis) in axes {
+ if axis == none { continue }
+
+ let style = _get-axis-style(ctx, style, name)
+ let is-mirror = axis.at("is-mirror", default: false)
+
+ if not is-mirror {
+ on-layer(style.grid-layer, {
+ draw-grid-lines(ctx, axis, ticks, start, end, direction, style)
+ })
+ }
+ }
+ })
+
+ // Draw axes
+ group(name: "axes", {
+ let axes = (
+ ("bottom", (0, 0), (w, 0), (0, -1), false, x-ticks, bottom,),
+ ("top", (0, h), (w, h), (0, +1), true, x2-ticks, top,),
+ ("left", (0, 0), (0, h), (-1, 0), true, y-ticks, left,),
+ ("right", (w, 0), (w, h), (+1, 0), false, y2-ticks, right,)
+ )
+ let label-placement = (
+ bottom: ("south", "north", 0deg),
+ top: ("north", "south", 0deg),
+ left: ("west", "south", 90deg),
+ right: ("east", "north", 90deg),
+ )
+
+ for (name, start, end, outsides, flip, ticks, axis) in axes {
+ let style = _get-axis-style(ctx, style, name)
+ let is-mirror = axis == none or axis.at("is-mirror", default: false)
+ let is-horizontal = name in ("bottom", "top")
+
+ if style.padding != 0 {
+ let padding = vector.scale(outsides, style.padding)
+ start = vector.add(start, padding)
+ end = vector.add(end, padding)
+ }
+
+ let (data-start, data-end) = _inset-axis-points(ctx, style, axis, start, end)
+
+ let path = _draw-axis-line(start, end, axis, is-horizontal, style)
+ on-layer(style.axis-layer, {
+ group(name: "axis", {
+ if draw-unset or axis != none {
+ path;
+ place-ticks-on-line(ticks, data-start, data-end, style, flip: flip, is-mirror: is-mirror)
+ }
+ })
+
+ if axis != none and axis.label != none and not is-mirror {
+ let offset = vector.scale(outsides, style.label.offset)
+ let (group-anchor, content-anchor, angle) = label-placement.at(name)
+
+ if style.label.anchor != auto {
+ content-anchor = style.label.anchor
+ }
+ if style.label.angle != auto {
+ angle = style.label.angle
+ }
+
+ content((rel: offset, to: "axis." + group-anchor),
+ [#axis.label],
+ angle: angle,
+ anchor: content-anchor)
+ }
+ })
+ }
+ })
+ })
+}
+
+// Draw two axes in a "school book" style
+//
+// - x-axis (axis): X axis
+// - y-axis (axis): Y axis
+// - size (array): Size (width, height)
+// - x-position (number): X Axis position
+// - y-position (number): Y Axis position
+// - name (string): Object name
+// - ..style (any): Style
+#let school-book(x-axis, y-axis,
+ size: (1, 1),
+ x-position: 0,
+ y-position: 0,
+ name: none,
+ ..style) = {
+ import draw: *
+
+ group(name: name, ctx => {
+ let (w, h) = size
+ anchor("origin", (0, 0))
+
+ let style = style.named()
+ style = styles.resolve(
+ ctx.style,
+ merge: style,
+ root: "axes",
+ base: default-style-schoolbook)
+ style = _prepare-style(ctx, style)
+
+ let x-position = calc.min(calc.max(y-axis.min, x-position), y-axis.max)
+ let y-position = calc.min(calc.max(x-axis.min, y-position), x-axis.max)
+ let x-y = value-on-axis(y-axis, x-position) * h
+ let y-x = value-on-axis(x-axis, y-position) * w
+
+ let shared-zero = style.shared-zero != false and x-position == 0 and y-position == 0
+
+ let x-ticks = compute-ticks(x-axis, style, add-zero: not shared-zero)
+ let y-ticks = compute-ticks(y-axis, style, add-zero: not shared-zero)
+
+ // Draw grid
+ group(name: "grid", ctx => {
+ let axes = (
+ ("x", (0,0), (0,h), (+w,0), x-ticks, x-axis),
+ ("y", (0,0), (w,0), (0,+h), y-ticks, y-axis),
+ )
+
+ for (name, start, end, direction, ticks, axis) in axes {
+ if axis == none { continue }
+
+ let style = _get-axis-style(ctx, style, name)
+ on-layer(style.grid-layer, {
+ draw-grid-lines(ctx, axis, ticks, start, end, direction, style)
+ })
+ }
+ })
+
+ // Draw axes
+ group(name: "axes", {
+ let axes = (
+ ("x", (0, x-y), (w, x-y), (1, 0), false, x-ticks, x-axis),
+ ("y", (y-x, 0), (y-x, h), (0, 1), true, y-ticks, y-axis),
+ )
+ let label-pos = (
+ x: ("north", (0,-1)),
+ y: ("east", (-1,0)),
+ )
+
+ on-layer(style.axis-layer, {
+ for (name, start, end, dir, flip, ticks, axis) in axes {
+ let style = _get-axis-style(ctx, style, name)
+
+ let pad = style.padding
+ let overshoot = style.overshoot
+ let vstart = vector.sub(start, vector.scale(dir, pad))
+ let vend = vector.add(end, vector.scale(dir, pad + overshoot))
+ let is-horizontal = name == "x"
+
+ let (data-start, data-end) = _inset-axis-points(ctx, style, axis, start, end)
+ group(name: "axis", {
+ _draw-axis-line(vstart, vend, axis, is-horizontal, style)
+ place-ticks-on-line(ticks, data-start, data-end, style, flip: flip)
+ })
+
+ if axis.label != none {
+ let (content-anchor, offset-dir) = label-pos.at(name)
+
+ let angle = if style.label.angle not in (none, auto) {
+ style.label.angle
+ } else { 0deg }
+ if style.label.anchor not in (none, auto) {
+ content-anchor = style.label.anchor
+ }
+
+ let offset = vector.scale(offset-dir, style.label.offset)
+ content((rel: offset, to: vend),
+ [#axis.label],
+ angle: angle,
+ anchor: content-anchor)
+ }
+ }
+
+ if shared-zero {
+ let pt = (rel: (-style.tick.label.offset, -style.tick.label.offset),
+ to: (y-x, x-y))
+ let zero = if type(style.shared-zero) == std.content {
+ style.shared-zero
+ } else {
+ $0$
+ }
+ content(pt, zero, anchor: "north-east")
+ }
+ })
+ })
+ })
+}
diff --git a/render/packages/preview/cetz-plot/0.1.4/src/axis.typ b/render/packages/preview/cetz-plot/0.1.4/src/axis.typ
new file mode 100644
index 0000000..6d43446
--- /dev/null
+++ b/render/packages/preview/cetz-plot/0.1.4/src/axis.typ
@@ -0,0 +1,25 @@
+#let lin-axis(name, min, max) = {
+ (name: name,
+ mode: "lin",
+ min: min,
+ max: max,)
+}
+
+#let log-axis(name, min, max, base: 10) = {
+ (name: name,
+ mode: "log",
+ min: min,
+ max: max,
+ base: base,)
+}
+
+///
+#let setup-cartesian-axis(ctx, axis, begin, end) = {
+ if not "plot-axes" in ctx {
+ ctx.cetz-plot-axes = (:)
+ }
+
+ ctx.cetz-plot-axes.insert(axis.name, axis)
+
+ return ctx
+}
diff --git a/render/packages/preview/cetz-plot/0.1.4/src/cetz.typ b/render/packages/preview/cetz-plot/0.1.4/src/cetz.typ
new file mode 100644
index 0000000..8a95d8f
--- /dev/null
+++ b/render/packages/preview/cetz-plot/0.1.4/src/cetz.typ
@@ -0,0 +1,2 @@
+// Import cetz into the root scope. Import cetz by importing this file only!
+#import "@preview/cetz:0.5.2": *
diff --git a/render/packages/preview/cetz-plot/0.1.4/src/chart.typ b/render/packages/preview/cetz-plot/0.1.4/src/chart.typ
new file mode 100644
index 0000000..c9344a7
--- /dev/null
+++ b/render/packages/preview/cetz-plot/0.1.4/src/chart.typ
@@ -0,0 +1,6 @@
+#import "chart/boxwhisker.typ": boxwhisker, boxwhisker-default-style
+#import "chart/barchart.typ": barchart, barchart-default-style
+#import "chart/columnchart.typ": columnchart, columnchart-default-style
+#import "chart/piechart.typ": piechart, piechart-default-style
+#import "chart/radarchart.typ": radarchart, radarchart-default-style
+#import "chart/pyramid.typ": pyramid, pyramid-default-style
diff --git a/render/packages/preview/cetz-plot/0.1.4/src/chart/barchart.typ b/render/packages/preview/cetz-plot/0.1.4/src/chart/barchart.typ
new file mode 100644
index 0000000..79c9f3e
--- /dev/null
+++ b/render/packages/preview/cetz-plot/0.1.4/src/chart/barchart.typ
@@ -0,0 +1,145 @@
+#import "/src/cetz.typ": draw, styles, palette
+
+#import "/src/plot.typ"
+
+#let barchart-default-style = (
+ axes: (tick: (length: 0), grid: (stroke: (dash: "dotted", paint: gray))),
+ bar-width: .8,
+ cluster-gap: 0,
+ error: (
+ whisker-size: .25,
+ ),
+ y-inset: 1,
+)
+
+/// Draw a bar chart. A bar chart is a chart that represents data with
+/// rectangular bars that grow from left to right, proportional to the values
+/// they represent.
+///
+/// === Styling
+/// Can be applied with `cetz.draw.set-style(barchart: (bar-width: 1))`.
+///
+/// *Root*: `barchart`.
+/// #show-parameter-block("bar-width", "float", default: .8, [
+/// Width of a single bar (basic) or a cluster of bars (clustered) in the plot.])
+/// #show-parameter-block("y-inset", "float", default: 1, [
+/// Distance of the plot data to the plot's edges on the y-axis of the plot.])
+/// #show-parameter-block("cluster-gap", "float", default: 0, [
+/// Spacing between bars insides a cluster.])
+/// You can use any `plot` or `axes` related style keys, too.
+///
+/// The `barchart` function is a wrapper of the `plot` API. Arguments passed
+/// to `..plot-args` are passed to the `plot.plot` function.
+///
+/// - data (array): Array of data rows. A row can be of type array or
+/// dictionary, with `label-key` and `value-key` being
+/// the keys to access a rows label and value(s).
+///
+/// *Example*
+/// ```typc
+/// (([A], 1), ([B], 2), ([C], 3),)
+/// ```
+/// - label-key (int,string): Key to access the label of a data row.
+/// This key is used as argument to the
+/// rows `.at(..)` function.
+/// - value-key (int,string): Key(s) to access values of a data row.
+/// These keys are used as argument to the
+/// rows `.at(..)` function.
+/// - error-key (none,int,string,array): Key(s) to access error values of a data row.
+/// These keys are used as argument to the
+/// rows `.at(..)` function.
+/// - mode (string): Chart mode:
+/// / basic: Single bar per data row
+/// / clustered: Group of bars per data row
+/// / stacked: Stacked bars per data row
+/// / stacked100: Stacked bars per data row relative
+/// to the sum of the row
+/// - size (array): Chart size as width and height tuple in canvas unist;
+/// width can be set to `auto`.
+/// - bar-style (style,function): Style or function (idx => style) to use for
+/// each bar, accepts a palette function.
+/// - y-label (content,none): Y axis label
+/// - x-label (content,none): x axis label
+/// - labels (none,content): Legend labels per x value group
+/// - ..plot-args (any): Arguments to pass to `plot.plot`
+#let barchart(data,
+ label-key: 0,
+ value-key: 1,
+ error-key: none,
+ mode: "basic",
+ size: (auto, 1),
+ bar-style: palette.red,
+ x-label: none,
+ x-format: auto,
+ y-label: none,
+ labels: none,
+ ..plot-args
+ ) = {
+ assert(type(label-key) in (int, str))
+ if mode == "basic" {
+ assert(type(value-key) in (int, str))
+ } else {
+ assert(type(value-key) == array)
+ }
+
+ if type(value-key) != array {
+ value-key = (value-key,)
+ }
+
+ if error-key == none {
+ error-key = ()
+ } else if type(error-key) != array {
+ error-key = (error-key,)
+ }
+
+ if type(size) != array {
+ size = (size, auto)
+ }
+ if size.at(1) == auto {
+ size.at(1) = (data.len() + 1)
+ }
+
+ let y-tic-list = data.enumerate().map(((i, t)) => {
+ (data.len() - i - 1, t.at(label-key))
+ })
+
+ let x-format = x-format
+ if x-format == auto {
+ x-format = if mode == "stacked100" {plot.formats.decimal.with(suffix: [%])} else {auto}
+ }
+
+ data = data.enumerate().map(((i, d)) => {
+ (data.len() - i - 1, value-key.map(k => d.at(k, default: 0)).flatten(), error-key.map(k => d.at(k, default: 0)).flatten())
+ })
+
+ draw.group(ctx => {
+ let style = styles.resolve(ctx.style, merge: (:),
+ root: "barchart", base: barchart-default-style)
+ draw.set-style(..style)
+
+ let y-inset = calc.max(style.y-inset, style.bar-width / 2)
+ plot.plot(size: size,
+ axis-style: "scientific-auto",
+ x-label: x-label,
+ x-grid: true,
+ x-format: x-format,
+ y-label: y-label,
+ y-min: -y-inset,
+ y-max: data.len() + y-inset - 1,
+ y-tick-step: none,
+ y-ticks: y-tic-list,
+ plot-style: bar-style,
+ ..plot-args,
+ {
+ plot.add-bar(data,
+ x-key: 0,
+ y-key: 1,
+ error-key: if mode in ("basic", "clustered") { 2 },
+ mode: mode,
+ labels: labels,
+ bar-width: -style.bar-width,
+ cluster-gap: style.cluster-gap,
+ axes: ("y", "x"))
+ })
+ })
+}
diff --git a/render/packages/preview/cetz-plot/0.1.4/src/chart/barcol-common.typ b/render/packages/preview/cetz-plot/0.1.4/src/chart/barcol-common.typ
new file mode 100644
index 0000000..0c09a52
--- /dev/null
+++ b/render/packages/preview/cetz-plot/0.1.4/src/chart/barcol-common.typ
@@ -0,0 +1,40 @@
+// Valid bar- and columnchart modes
+#let barchart-modes = (
+ "basic", "clustered", "stacked", "stacked100"
+)
+
+// Functions for max value calculation
+#let barchart-max-value-fn = (
+ basic: (data, value-key) => {
+ calc.max(0, ..data.map(t => t.at(value-key)))
+ },
+ clustered: (data, value-key) => {
+ calc.max(0, ..data.map(t => calc.max(
+ ..value-key.map(k => t.at(k)))))
+ },
+ stacked: (data, value-key) => {
+ calc.max(0, ..data.map(t =>
+ value-key.map(k => t.at(k)).sum()))
+ },
+ stacked100: (..) => {
+ 100
+ }
+)
+
+// Functions for min value calculation
+#let barchart-min-value-fn = (
+ basic: (data, value-key) => {
+ calc.min(0, ..data.map(t => t.at(value-key)))
+ },
+ clustered: (data, value-key) => {
+ calc.min(0, ..data.map(t => calc.max(
+ ..value-key.map(k => t.at(k)))))
+ },
+ stacked: (data, value-key) => {
+ calc.min(0, ..data.map(t =>
+ value-key.map(k => t.at(k)).sum()))
+ },
+ stacked100: (..) => {
+ 0
+ }
+)
diff --git a/render/packages/preview/cetz-plot/0.1.4/src/chart/boxwhisker.typ b/render/packages/preview/cetz-plot/0.1.4/src/chart/boxwhisker.typ
new file mode 100644
index 0000000..ffb9e8a
--- /dev/null
+++ b/render/packages/preview/cetz-plot/0.1.4/src/chart/boxwhisker.typ
@@ -0,0 +1,97 @@
+#import "/src/cetz.typ": draw, styles, palette, util, vector, intersection
+
+#import "/src/plot.typ"
+
+#let boxwhisker-default-style = (
+ axes: (tick: (length: 0), grid: (stroke: (dash: "dotted", paint: gray))),
+ box-width: 0.75,
+ whisker-width: 0.5,
+ mark-size: 0.15,
+)
+
+/// Add one or more box or whisker plots.
+///
+/// ```cexample
+/// chart.boxwhisker(size: (2,2), label-key: none,
+/// y-min: 0, y-max: 70, y-tick-step: 20,
+/// (x: 1, min: 15, max: 60,
+/// q1: 25, q2: 35, q3: 50))
+/// ```
+///
+/// === Styling
+/// *Root* `boxwhisker`
+/// #show-parameter-block("box-width", "float", default: .75, [
+/// The width of the box. Since boxes are placed 1 unit next to each other,
+/// a width of $1$ would make neighbouring boxes touch.])
+/// #show-parameter-block("whisker-width", "float", default: .5, [
+/// The width of the whisker, that is the horizontal bar on the top and bottom
+/// of the box.])
+/// #show-parameter-block("mark-size", "float", default: .15, [
+/// The scaling of the mark for the boxes outlier values in canvas units.])
+/// You can use any `plot` or `axes` related style keys, too.
+///
+/// - data (array, dictionary): Dictionary or array of dictionaries containing the
+/// needed entries to plot box and whisker plot.
+///
+/// See `plot.add-boxwhisker` for more details.
+///
+/// *Examples:*
+/// - ```typc
+/// (x: 1 // Location on x-axis
+/// outliers: (7, 65, 69), // Optional outliers
+/// min: 15, max: 60 // Minimum and maximum
+/// q1: 25, // Quartiles: Lower
+/// q2: 35, // Median
+/// q3: 50) // Upper
+/// ```
+/// - size (array): Size of chart. If the second entry is auto, it automatically scales to accommodate the number of entries plotted
+/// - label-key (integer, string): Index in the array where labels of each entry is stored
+/// - mark (string): Mark to use for plotting outliers. Set `none` to disable. Defaults to "x"
+/// - ..plot-args (any): Additional arguments are passed to `plot.plot`
+#let boxwhisker(data,
+ size: (1, auto),
+ label-key: 0,
+ mark: "*",
+ ..plot-args
+ ) = {
+ if type(data) == dictionary { data = (data,) }
+
+ if type(size) != array {
+ size = (size, auto)
+ }
+ if size.at(1) == auto {
+ size.at(1) = (data.len() + 1)
+ }
+
+ let x-tick-list = data.enumerate().map(((i, t)) => {
+ (i + 1, if label-key != none { t.at(label-key, default: i) } else { [] })
+ })
+
+ draw.group(ctx => {
+ let style = styles.resolve(ctx.style, merge: (:),
+ root: "boxwhisker", base: boxwhisker-default-style)
+ draw.set-style(..style)
+
+ plot.plot(
+ size: size,
+ axis-style: "scientific-auto",
+ x-tick-step: none,
+ x-ticks: x-tick-list,
+ y-grid: true,
+ x-label: none,
+ y-label: none,
+ ..plot-args,
+ {
+ for (i, row) in data.enumerate() {
+ plot.add-boxwhisker(
+ (x: i + 1, ..row),
+ box-width: style.box-width,
+ whisker-width: style.whisker-width,
+ style: (:),
+ mark: mark,
+ mark-size: style.mark-size
+ )
+ }
+ })
+ })
+}
diff --git a/render/packages/preview/cetz-plot/0.1.4/src/chart/columnchart.typ b/render/packages/preview/cetz-plot/0.1.4/src/chart/columnchart.typ
new file mode 100644
index 0000000..5a9f4ea
--- /dev/null
+++ b/render/packages/preview/cetz-plot/0.1.4/src/chart/columnchart.typ
@@ -0,0 +1,140 @@
+#import "/src/cetz.typ": draw, styles, palette, util, vector, intersection
+
+#import "/src/plot.typ"
+
+#let columnchart-default-style = (
+ axes: (tick: (length: 0), grid: (stroke: (dash: "dotted"))),
+ bar-width: .8,
+ cluster-gap: 0,
+ error: (
+ whisker-size: .25,
+ ),
+ x-inset: 1,
+)
+
+/// Draw a column chart. A column chart is a chart that represents data with
+/// rectangular bars that grow from bottom to top, proportional to the values
+/// they represent.
+///
+/// === Styling
+/// *Root*: `columnchart`.
+/// #show-parameter-block("bar-width", "float", default: .8, [
+/// Width of a single bar (basic) or a cluster of bars (clustered) in the plot.])
+/// #show-parameter-block("x-inset", "float", default: 1, [
+/// Distance of the plot data to the plot's edges on the x-axis of the plot.])
+/// You can use any `plot` or `axes` related style keys, too.
+///
+/// The `columnchart` function is a wrapper of the `plot` API. Arguments passed
+/// to `..plot-args` are passed to the `plot.plot` function.
+///
+/// - data (array): Array of data rows. A row can be of type array or
+/// dictionary, with `label-key` and `value-key` being
+/// the keys to access a rows label and value(s).
+///
+/// *Example*
+/// ```typc
+/// (([A], 1), ([B], 2), ([C], 3),)
+/// ```
+/// - label-key (int,string): Key to access the label of a data row.
+/// This key is used as argument to the
+/// rows `.at(..)` function.
+/// - value-key (int,string): Key(s) to access value(s) of data row.
+/// These keys are used as argument to the
+/// rows `.at(..)` function.
+/// - error-key (none,int,string,array): Key(s) to access error values of a data row.
+/// These keys are used as argument to the rows `.at(..)` function.
+/// - mode (string): Chart mode:
+/// / basic: Single bar per data row
+/// / clustered: Group of bars per data row
+/// / stacked: Stacked bars per data row
+/// / stacked100: Stacked bars per data row relative
+/// to the sum of the row
+/// - size (array): Chart size as width and height tuple in canvas unist;
+/// width can be set to `auto`.
+/// - bar-style (style,function): Style or function (idx => style) to use for
+/// each bar, accepts a palette function.
+/// - y-label (content,none): Y axis label
+/// - x-label (content,none): x axis label
+/// - labels (none,content): Legend labels per y value group
+/// - ..plot-args (any): Arguments to pass to `plot.plot`
+#let columnchart(data,
+ label-key: 0,
+ value-key: 1,
+ error-key: none,
+ mode: "basic",
+ size: (auto, 1),
+ bar-style: palette.red,
+ x-label: none,
+ y-format: auto,
+ y-label: none,
+ labels: none,
+ ..plot-args
+ ) = {
+ assert(type(label-key) in (int, str))
+ if mode == "basic" {
+ assert(type(value-key) in (int, str))
+ }
+
+ if type(value-key) != array {
+ value-key = (value-key,)
+ }
+
+ if error-key == none {
+ error-key = ()
+ } else if type(error-key) != array {
+ error-key = (error-key,)
+ }
+
+ if type(size) != array {
+ size = (auto, size)
+ }
+ if size.at(0) == auto {
+ size.at(0) = (data.len() + 1)
+ }
+
+ let x-tic-list = data.enumerate().map(((i, t)) => {
+ (i, t.at(label-key))
+ })
+
+ let y-format = y-format
+ if y-format == auto {
+ y-format = if mode == "stacked100" {plot.formats.decimal.with(suffix: [%])} else {auto}
+ }
+
+ data = data.enumerate().map(((i, d)) => {
+ (i, value-key.map(k => d.at(k)).flatten(), error-key.map(k => d.at(k, default: 0)).flatten())
+ })
+
+ draw.group(ctx => {
+ let style = styles.resolve(ctx.style, merge: (:),
+ root: "columnchart", base: columnchart-default-style)
+ draw.set-style(..style)
+
+ let x-inset = calc.max(style.x-inset, style.bar-width / 2)
+ plot.plot(size: size,
+ axis-style: "scientific-auto",
+ y-grid: true,
+ y-label: y-label,
+ y-format: y-format,
+ x-min: -x-inset,
+ x-max: data.len() + x-inset - 1,
+ x-tick-step: none,
+ x-ticks: x-tic-list,
+ x-label: x-label,
+ plot-style: bar-style,
+ ..plot-args,
+ {
+ plot.add-bar(data,
+ x-key: 0,
+ y-key: 1,
+ error-key: if mode in ("basic", "clustered") { 2 },
+ mode: mode,
+ labels: labels,
+ bar-width: style.bar-width,
+ cluster-gap: style.cluster-gap,
+ error-style: style.error,
+ whisker-size: style.error.whisker-size,
+ axes: ("x", "y"))
+ })
+ })
+}
diff --git a/render/packages/preview/cetz-plot/0.1.4/src/chart/piechart.typ b/render/packages/preview/cetz-plot/0.1.4/src/chart/piechart.typ
new file mode 100644
index 0000000..e32fcac
--- /dev/null
+++ b/render/packages/preview/cetz-plot/0.1.4/src/chart/piechart.typ
@@ -0,0 +1,495 @@
+#import "/src/cetz.typ": draw, styles, palette, util, vector, intersection
+#import "/src/plot/legend.typ"
+
+// Piechart Label Kind
+#let label-kind = (value: "VALUE", percentage: "%", label: "LABEL")
+
+// Piechart Default Style
+#let default-style = (
+ stroke: auto,
+ fill: auto,
+ /// Outer chart radius
+ radius: 1,
+ /// Inner slice radius
+ inner-radius: 0,
+ /// Gap between items. This can be a canvas length or an angle
+ gap: 0.5deg,
+ /// Outset offset, absolute or relative to radius
+ outset-offset: 10%,
+ /// Pie outset mode:
+ /// - "OFFSET": Offset slice position by outset-offset
+ /// - "RADIUS": Offset slice radius by outset-offset (the slice gets scaled)
+ outset-mode: "OFFSET",
+ /// Pie start angle
+ start: 90deg,
+ /// Pie stop angle
+ stop: 360deg + 90deg,
+ /// Pie rotation direction (true = clockwise, false = anti-clockwise)
+ clockwise: true,
+ outer-label: (
+ /// Label kind
+ /// If set to a function, that function gets called with (value, label) of each item
+ content: label-kind.label,
+ /// Absolute radius or percentage of radius
+ radius: 125%,
+ /// Absolute angle or auto to use secant of the slice as direction
+ angle: 0deg,
+ /// Label anchor
+ anchor: "center",
+ ),
+ inner-label: (
+ /// Label kind
+ /// If set to a function, that function gets called with (value, label) of each item
+ content: none,
+ /// Absolute radius or percentage of the mid between radius and inner-radius
+ radius: 150%,
+ /// Absolute angle or auto to use secant of the slice as direction
+ angle: 0deg,
+ /// Label anchor
+ anchor: "center",
+ ),
+ legend: (
+ ..legend.default-style,
+
+ /// Label used for the legend
+ /// The legend gets rendered as soon as at least one item with a label
+ /// exists and the `legend-label.content` is set != none. This field
+ /// accepts the same values as inner-label.content or outer-label.content.
+ label: "LABEL",
+
+ /// Anchor of the charts data bounding box to place the legend relative to
+ position: "south",
+
+ /// Anchor of the legend bounding box to use as origin
+ anchor: "north",
+
+ /// Custom preview function override
+ /// The function takes an item dictionary an is responsible for drawing
+ /// the preview icon. Stroke and fill styles are set to match the items
+ /// style.
+ preview: none,
+
+ /// See lenged.typ for the following style keys
+ orientation: ltr,
+ offset: (0,-.5em),
+ stroke: none,
+ item: (
+ spacing: .25,
+ preview: (
+ width: .3,
+ height: .3,
+ ),
+ ),
+ )
+)
+#let piechart-default-style = default-style
+
+
+/// Draw a pie- or donut-chart
+///
+/// ```cexample
+/// let data = (24, 31, 18, 21, 23, 18, 27, 17, 26, 13)
+/// let colors = gradient.linear(red, blue, green, yellow)
+///
+/// chart.piechart(
+/// data,
+/// radius: 1.5,
+/// slice-style: colors,
+/// inner-radius: .5,
+/// outer-label: (content: "%",))
+/// ```
+///
+/// === Styling
+/// *Root* `piechart` \
+/// #show-parameter-block("radius", ("number"), [
+/// Outer radius of the chart.], default: 1)
+/// #show-parameter-block("inner-radius", ("number"), [
+/// Inner radius of the chart slices. If greater than zero, the chart becomes
+/// a "donut-chart".], default: 0)
+/// #show-parameter-block("gap", ("number", "angle"), [
+/// Gap between chart slices to leave empty. This does not increase the charts
+/// radius by pushing slices outwards, but instead shrinks the slice. Big
+/// values can result in slices becoming invisible if no space is left.], default: 0.5deg)
+/// #show-parameter-block("outset-offset", ("number", "ratio"), [
+/// Absolute, or radius relative distance to push slices marked for
+/// "outsetting" outwards from the center of the chart.], default: 10%)
+/// #show-parameter-block("outset-offset", ("string"), [
+/// The mode of how to perform "outsetting" of slices:
+/// - "OFFSET": Offset slice position by `outset-offset`, increasing their gap to their siblings
+/// - "RADIUS": Offset slice radius by `outset-offset`, which scales the slice and leaves the gap unchanged], default: "OFFSET")
+/// #show-parameter-block("start", ("angle"), [
+/// The pie-charts start angle (ccw). You can use this to draw charts not forming a full circle.], default: 90deg)
+/// #show-parameter-block("stop", ("angle"), [
+/// The pie-charts stop angle (ccw).], default: 360deg + 90deg)
+/// #show-parameter-block("clockwise", ("bool"), [
+/// The pie-charts rotation direction.], default: true)
+/// #show-parameter-block("outer-label.content", ("none","string","function"), [
+/// Content to display outsides the charts slices.
+/// There are the following predefined values:
+/// / LABEL: Display the slices label (see `label-key`)
+/// / %: Display the percentage of the items value in relation to the sum of
+/// all values, rounded to the next integer
+/// / VALUE: Display the slices value
+/// If passed a `<function>` of the format `(value, label) => content`,
+/// that function gets called with each slices value and label and must return
+/// content, that gets displayed.], default: "LABEL")
+/// #show-parameter-block("outer-label.radius", ("number","ratio"), [
+/// Absolute, or radius relative distance from the charts center to position
+/// outer labels at.], default: 125%)
+/// #show-parameter-block("outer-label.angle", ("angle","auto"), [
+/// The angle of the outer label. If passed `auto`, the label gets rotated,
+/// so that the baseline is parallel to the slices secant. ], default: 0deg)
+/// #show-parameter-block("outer-label.anchor", ("string"), [
+/// The anchor of the outer label to use for positioning.], default: "center")
+/// #show-parameter-block("inner-label.content", ("none","string","function"), [
+/// Content to display insides the charts slices.
+/// See `outer-label.content` for the possible values.], default: none)
+/// #show-parameter-block("inner-label.radius", ("number","ratio"), [
+/// Distance of the inner label to the charts center. If passed a `<ratio>`,
+/// that ratio is relative to the mid between the inner and outer radius (`inner-radius` and `radius`)
+/// of the chart], default: 150%)
+/// #show-parameter-block("inner-label.angle", ("angle","auto"), [
+/// See `outer-label.angle`.], default: 0deg)
+/// #show-parameter-block("inner-label.anchor", ("string"), [
+/// See `outer-label.anchor`.], default: "center")
+/// #show-parameter-block("legend.label", ("none","string","function"), [
+/// See `outer-label.content`. The legend gets shown if this key is set != none.], default: "LABEL")
+///
+/// === Anchors
+/// The chart places one anchor per item at the radius of it's slice that
+/// gets named `"item-<index>"` (outer radius) and `"item-<index>-inner"` (inner radius),
+/// where index is the index of the sclice data in `data`.
+///
+/// - data (array): Array of data items. A data item can be:
+/// - A number: A number that is used as the fraction of the slice
+/// - An array: An array which is read depending on value-key, label-key and outset-key
+/// - A dictionary: A dictionary which is read depending on value-key, label-key and outset-key
+/// - value-key (none,int,string): Key of the "value" of a data item. If for example
+/// data items are passed as dictionaries, the value-key is the key of the dictionary to
+/// access the items chart value.
+/// - label-key (none,int,string): Same as the value-key but for getting an items label content.
+/// - outset-key (none,int,string): Same as the value-key but for getting if an item should get outset (highlighted). The
+/// outset can be a bool, float or ratio. If of type `bool`, the outset distance from the
+/// style gets used.
+/// - outset (none,int,array): A single or multiple indices of items that should get offset from the center to the outsides
+/// of the chart. Only used if outset-key is none!
+/// - slice-style (function,array,gradient): Slice style of the following types:
+/// - function: A function of the form `index => style` that must return a style dictionary.
+/// This can be a `palette` function.
+/// - array: An array of style dictionaries or fill colors of at least one item. For each slice the style at the slices
+/// index modulo the arrays length gets used.
+/// - gradient: A gradient that gets sampled for each data item using the the slices
+/// index divided by the number of slices as position on the gradient.
+/// If one of stroke or fill is not in the style dictionary, it is taken from the charts style.
+#let piechart(data,
+ value-key: none,
+ label-key: none,
+ outset-key: none,
+ outset: none,
+ slice-style: palette.red,
+ name: none,
+ ..style) = {
+ import draw: *
+
+ // Prepare data by converting it to tuples of the format
+ // (value, label, outset)
+ data = data.enumerate().map(((i, item)) => (
+ if value-key != none {
+ item.at(value-key)
+ } else {
+ item
+ },
+ if label-key != none {
+ item.at(label-key)
+ } else {
+ none
+ },
+ if outset-key != none {
+ item.at(outset-key, default: false)
+ } else if outset != none {
+ i == outset or (type(outset) == array and i in outset)
+ } else {
+ false
+ }
+ ))
+
+ let visible-data = data.filter(((value, ..)) => value != 0)
+
+ let sum = visible-data.map(((value, ..)) => value).sum()
+ if sum == 0 {
+ sum = 1
+ }
+
+ group(name: name, ctx => {
+ anchor("default", (0,0))
+
+ let style = styles.resolve(ctx.style,
+ merge: style.named(), root: "piechart", base: default-style)
+
+ let gap = style.gap
+ if type(gap) != angle {
+ gap = gap / (2 * calc.pi * style.radius) * 360deg
+ }
+ assert(gap < 360deg / visible-data.len(),
+ message: "Gap angle is too big for " + str(visible-data.len()) + "items. Maximum gap angle: " + repr(360deg / visible-data.len()))
+
+ let radius = style.radius
+ assert(radius > 0,
+ message: "Radius must be > 0.")
+
+ let inner-radius = style.inner-radius
+ assert(inner-radius >= 0 and inner-radius <= radius,
+ message: "Radius must be >= 0 and <= radius.")
+
+ assert(style.outset-mode in ("OFFSET", "RADIUS"),
+ message: "Outset mode must be 'OFFSET' or 'RADIUS', but is: " + str(style.outset-mode))
+
+ let style-at = if type(slice-style) == function {
+ slice-style
+ } else if type(slice-style) == array {
+ i => {
+ let s = slice-style.at(calc.rem(i, slice-style.len()))
+ if type(s) == color {
+ (fill: s)
+ } else {
+ s
+ }
+ }
+ } else if type(slice-style) == gradient {
+ i => (fill: slice-style.sample(i / visible-data.len() * 100%))
+ }
+
+ let start-angle = style.start
+ let stop-angle = style.stop
+ let f = (stop-angle - start-angle) / sum
+
+ let get-item-label(item, kind) = {
+ let (value, label, ..) = item
+ if kind == label-kind.value {
+ [#value]
+ } else if kind == label-kind.percentage {
+ [#{calc.round(value / sum * 100)}%]
+ } else if kind == label-kind.label {
+ label
+ } else if type(kind) == function {
+ (kind)(value, label)
+ }
+ }
+
+ let start = start-angle
+ let enum-items = (if style.clockwise {
+ data.enumerate().rev()
+ } else {
+ data.enumerate()
+ })
+ group(name: "chart", {
+ for (i, item) in enum-items.filter((value, ..) => value != 0) {
+ let (value, label, outset) = item
+ if value == 0 { continue }
+
+ let origin = (0,0)
+ let radius = radius
+ let inner-radius = inner-radius
+
+ // Calculate item angles
+ let delta = f * value
+ let end = start + delta
+
+ // Apply item outset
+ let outset-offset = if outset == true {
+ style.outset-offset
+ } else if outset == false {
+ 0
+ } else if type(outset) in (float, ratio) {
+ outset
+ } else {
+ panic("Invalid type for outset. Expected bool, float or ratio, got: " + repr(outset))
+ }
+ if type(outset-offset) == ratio {
+ outset-offset = outset-offset * radius / 100%
+ }
+
+ if outset-offset != 0 {
+ if style.outset-mode == "OFFSET" {
+ let dir = (calc.cos((start + end) / 2), calc.sin((start + end) / 2))
+ origin = vector.add(origin, vector.scale(dir, outset-offset))
+ radius += outset-offset
+ } else {
+ radius += outset-offset
+ if inner-radius > 0 {
+ inner-radius += outset-offset
+ }
+ }
+ }
+
+ // Calculate gap angles
+ let outer-gap = gap
+ let gap-dist = outer-gap / 360deg * 2 * calc.pi * radius
+ let inner-gap = if inner-radius > 0 {
+ gap-dist / (2 * calc.pi * inner-radius) * 360deg
+ } else {
+ 1 / calc.pi * 360deg
+ }
+
+ // Calculate angle deltas
+ let outer-angle = end - start - outer-gap * 2
+ let inner-angle = end - start - inner-gap * 2
+ let mid-angle = (start + end) / 2
+
+ // Skip negative values
+ if outer-angle < 0deg {
+ // TODO: Add a warning as soon as Typst is ready!
+ continue
+ }
+
+ let circle-arclen(radius, angle: 90deg) = {
+ calc.abs(angle / 360deg * 2 * calc.pi * radius)
+ }
+
+ // A sharp item is an item that should be round but is sharp due to the gap being big
+ let is-sharp = inner-radius == 0 or circle-arclen(inner-radius, angle: inner-angle) > circle-arclen(radius, angle: outer-angle)
+
+ let inner-origin = vector.add(origin, if inner-radius == 0 {
+ if gap-dist >= 0 {
+ let outer-end = vector.scale((calc.cos(end - outer-gap), calc.sin(end - outer-gap)), radius)
+ let inner-end = vector.scale((calc.cos(end - inner-gap), calc.sin(end - inner-gap)), gap-dist)
+ let outer-start = vector.scale((calc.cos(start + outer-gap), calc.sin(start + outer-gap)), radius)
+ let inner-start = vector.scale((calc.cos(start + inner-gap), calc.sin(start + inner-gap)), gap-dist)
+
+ intersection.line-line(outer-end, inner-end, outer-start, inner-start, ray: true)
+ } else {
+ (0,0)
+ }
+ } else if is-sharp {
+ let outer-end = vector.scale((calc.cos(end - outer-gap), calc.sin(end - outer-gap)), radius)
+ let inner-end = vector.scale((calc.cos(end - inner-gap), calc.sin(end - inner-gap)), inner-radius)
+ let outer-start = vector.scale((calc.cos(start + outer-gap), calc.sin(start + outer-gap)), radius)
+ let inner-start = vector.scale((calc.cos(start + inner-gap), calc.sin(start + inner-gap)), inner-radius)
+
+ intersection.line-line(outer-end, inner-end, outer-start, inner-start, ray: true)
+ } else {
+ (0,0)
+ })
+
+ // Draw one segment
+ let stroke = style-at(i).at("stroke", default: style.stroke)
+ let fill = style-at(i).at("fill", default: style.fill)
+ if visible-data.len() == 1 {
+ // If the chart has only one segment, we may have to fake a path
+ // with a hole in it by using a combination of multiple arcs.
+ if inner-radius > 0 {
+ // Split the circle/arc into two arcs
+ // and fill them
+ merge-path({
+ arc(origin, start: start-angle, stop: mid-angle, radius: radius, anchor: "origin")
+ arc(origin, stop: start-angle, start: mid-angle, radius: inner-radius, anchor: "origin")
+ }, close: false, fill:fill, stroke: none)
+ merge-path({
+ arc(origin, start: mid-angle, stop: stop-angle, radius: radius, anchor: "origin")
+ arc(origin, stop: mid-angle, start: stop-angle, radius: inner-radius, anchor: "origin")
+ }, close: false, fill:fill, stroke: none)
+
+ // Create arcs for the inner and outer border and stroke them.
+ // If the chart is not a full circle, we have to merge two arc
+ // at their ends to create closing lines
+ if stroke != none {
+ if calc.abs(stop-angle - start-angle) != 360deg {
+ merge-path({
+ arc(origin, start: start, stop: end, radius: inner-radius, anchor: "origin")
+ arc(origin, start: end, stop: start, radius: radius, anchor: "origin")
+ }, close: true, fill: none, stroke: stroke)
+ } else {
+ arc(origin, start: start, stop: end, radius: inner-radius, fill: none, stroke: stroke, anchor: "origin")
+ arc(origin, start: start, stop: end, radius: radius, fill: none, stroke: stroke, anchor: "origin")
+ }
+ }
+ } else {
+ arc(origin, start: start, stop: end, radius: radius, fill: fill, stroke: stroke, mode: "PIE", anchor: "origin")
+ }
+ } else {
+ // Draw a normal segment
+ if inner-origin != none {
+ merge-path({
+ arc(origin, start: start + outer-gap, stop: end - outer-gap, anchor: "origin",
+ radius: radius)
+ if inner-radius > 0 and not is-sharp {
+ if inner-angle < 0deg {
+ arc(inner-origin, stop: end - inner-gap, delta: inner-angle, anchor: "origin",
+ radius: inner-radius)
+ } else {
+ arc(inner-origin, start: end - inner-gap, delta: -inner-angle, anchor: "origin",
+ radius: inner-radius)
+ }
+ } else {
+ line((rel: (end - outer-gap, radius), to: origin),
+ inner-origin,
+ (rel: (start + outer-gap, radius), to: origin))
+ }
+ }, close: true, fill: fill, stroke: stroke)
+ }
+ }
+
+ // Place outer label
+ let outer-label = get-item-label(item, style.outer-label.content)
+ if outer-label != none {
+ let r = style.outer-label.radius
+ if type(r) == ratio {r = r * radius / 100%}
+
+ let dir = (r * calc.cos(mid-angle), r * calc.sin(mid-angle))
+ let pt = vector.add(origin, dir)
+
+ let angle = style.outer-label.angle
+ if angle == auto {
+ angle = vector.add(pt, (dir.at(1), -dir.at(0)))
+ }
+
+ content(pt, outer-label, angle: angle, anchor: style.outer-label.anchor)
+ }
+
+ // Place inner label
+ let inner-label = get-item-label(item, style.inner-label.content)
+ if inner-label != none {
+ let r = style.inner-label.radius
+ if type(r) == ratio {r = r * (radius + inner-radius) / 200%}
+
+ let dir = (r * calc.cos(mid-angle), r * calc.sin(mid-angle))
+ let pt = vector.add(origin, dir)
+
+ let angle = style.inner-label.angle
+ if angle == auto {
+ angle = vector.add(pt, (dir.at(1), -dir.at(0)))
+ }
+
+ on-layer(1, content(pt, inner-label, angle: angle, anchor: style.inner-label.anchor))
+ }
+
+ // Place item anchor
+ anchor("item-" + str(i), (rel: (mid-angle, radius), to: origin))
+ anchor("item-" + str(i) + "-inner", (rel: (mid-angle, inner-radius), to: origin))
+
+ start = end
+ }
+ })
+
+ legend.legend((name: "chart", anchor: style.legend.position), {
+ let preview-fn = if style.legend.preview != none {
+ style.legend.preview
+ } else {
+ (_) => { rect((0,0), (1,1)) }
+ }
+
+ for (i, item) in enum-items.rev() {
+ let label = get-item-label(item, style.legend.label)
+ let preview = (item) => {
+ let stroke = style-at(i).at("stroke", default: style.stroke)
+ let fill = style-at(i).at("fill", default: style.fill)
+
+ set-style(stroke: stroke, fill: fill)
+ preview-fn(item)
+ }
+
+ legend.item(label, preview)
+ }
+ }, ..style.at("legend", default: (:)))
+ })
+}
diff --git a/render/packages/preview/cetz-plot/0.1.4/src/chart/pyramid.typ b/render/packages/preview/cetz-plot/0.1.4/src/chart/pyramid.typ
new file mode 100644
index 0000000..8b008ad
--- /dev/null
+++ b/render/packages/preview/cetz-plot/0.1.4/src/chart/pyramid.typ
@@ -0,0 +1,467 @@
+#import "/src/cetz.typ": draw, styles, palette, coordinate
+
+// Pyramid Chart Label Kind
+#let label-kind = (value: "VALUE", percentage: "%", label: "LABEL")
+
+// Pyramid Chart Default Style
+#let default-style = (
+ stroke: auto,
+ fill: auto,
+ /// Gap between levels to leave empty.
+ /// If `mode` is "AREA-HEIGHT", the value must be a ratio and will be proportional to the height of the first level
+ gap: 0,
+ /// Pyramid mode defining how to shape each level:
+ /// - "REGULAR": All levels have the same height and make a perfectly triangular pyramid
+ /// - "AREA-HEIGHT": The area of each level is proportional to its value. Only the height is adapted, keeping the pyramid triangular
+ /// - "HEIGHT": The height of each level is proportional to its value. The pyramid is kept as a perfect triangle
+ /// - "WIDTH": The height of each level is fixed, but its width is proportional to the value. The pyramid might not be perfectly triangular
+ mode: "REGULAR",
+ /// Height of each level
+ level-height: 1,
+ inner-label: (
+ /// Label kind
+ /// If set to a function, that function gets called with (value, label) of each item
+ content: "LABEL",
+ force-inside: false
+ ),
+ side-label: (
+ /// Label kind
+ /// If set to a function, that function gets called with (value, label) of each item
+ content: none,
+ side: "west"
+ )
+)
+
+#let pyramid-default-style = default-style
+
+/// Draw a pyramid chart
+///
+/// ```cexample
+/// let data = (
+/// "transcendence",
+/// "self-actualization",
+/// "aesthetic",
+/// "cognitive",
+/// "esteem",
+/// "belonging and love",
+/// "safety",
+/// "physiological"
+/// )
+/// let colors = (
+/// rgb("#FFFFC5"), rgb("#FEB6A5"),
+/// rgb("#FFD89F"), rgb("#C6C6C6"),
+/// rgb("#D4D1FF"), rgb("#FFB7CD"),
+/// rgb("#F7BCFF"), rgb("#BDE0B0"),
+/// )
+///
+/// chart.pyramid(
+/// data,
+/// level-style: colors,
+/// level-height: 0.7)
+/// ```
+///
+/// === Styling
+/// *Root* `pyramid` \
+/// #show-parameter-block("level-height", ("number"), [
+/// Minimum level height.], default: 1)
+/// #show-parameter-block("gap", ("number", "ratio"), [
+/// Gap between levels to leave empty. If `mode` is "AREA-HEIGHT", the value must be a ratio and will be proportional to the height of the first level.], default: 0)
+/// #show-parameter-block("mode", ("string"), [
+/// The mode of how to shape each level:
+/// - "REGULAR": All levels have the same height and make a perfectly triangular pyramid
+/// - "AREA-HEIGHT": The area of each level is proportional to its value. Only the height is adapted, keeping the pyramid triangular
+/// - "HEIGHT": The height of each level is proportional to its value. The pyramid is kept as a perfect triangle
+/// - "WIDTH": The height of each level is fixed, but its width is proportional to the value. The pyramid might not be perfectly triangular], default: "REGULAR")
+/// #show-parameter-block("side-label.content", ("none","string","function"), [
+/// Content to display outsides the charts levels, on the side.
+/// There are the following predefined values:
+/// / LABEL: Display the levels label (see `label-key`)
+/// / %: Display the percentage of the items value in relation to the sum of
+/// all values, rounded to the next integer
+/// / VALUE: Display the levels value
+/// If passed a `<function>` of the format `(value, label) => content`,
+/// that function gets called with each levels value and label and must return
+/// content, that gets displayed.], default: none)
+/// #show-parameter-block("side-label.side", ("string"), [
+/// The side of the chart on which to place side labels, either "west" or "east"], default: "west")
+/// #show-parameter-block("inner-label.content", ("none","string","function"), [
+/// Content to display insides the charts levels.
+/// See `side-label.content` for the possible values.], default: "LABEL")
+/// #show-parameter-block("inner-label.force-inside", ("boolean"), [
+/// If false, labels are automatically placed outside their correspoding levels if they don't fit inside. If true, they are always placed inside.], default: false)
+///
+/// === Anchors
+/// The chart places one anchor per item at the center of its level that
+/// gets named `"levels.<index>"`, one on the middle of its left side named `"levels.<index>.west"`, and one on the right side named `"levels.<index>.east"`,
+/// where index is the index of the level data in `data`.
+///
+/// - data (array): Array of data items. A data item can be:
+/// - A number: A number that is used as the fraction of the level
+/// - An array: An array which is read depending on value-key and label-key
+/// - A dictionary: A dictionary which is read depending on value-key and label-key
+/// - value-key (none,int,string): Key of the "value" of a data item. If for example
+/// data items are passed as dictionaries, the value-key is the key of the dictionary to
+/// access the items chart value.
+/// - label-key (none,int,string): Same as the value-key but for getting an items label content.
+/// - level-style (function,array,gradient): Level style of the following types:
+/// - function: A function of the form `index => style` that must return a style dictionary.
+/// This can be a `palette` function.
+/// - array: An array of style dictionaries or fill colors of at least one item. For each level the style at the levels
+/// index modulo the arrays length gets used.
+/// - gradient: A gradient that gets sampled for each data item using the the levels
+/// index divided by the number of levels as position on the gradient.
+/// If one of stroke or fill is not in the style dictionary, it is taken from the charts style.
+#let pyramid(
+ data,
+ value-key: none,
+ label-key: none,
+ level-style: palette.red,
+ name: none,
+ ..style
+) = {
+ // Prepare data by converting it to tuples of the format
+ // (value, label)
+ data = data.enumerate().map(((i, item)) => (
+ if value-key != none {
+ item.at(value-key)
+ } else {
+ none
+ },
+ if label-key != none {
+ item.at(label-key)
+ } else {
+ item
+ }
+ ))
+
+ draw.group(name: name, ctx => {
+ draw.anchor("default", (0, 0))
+
+ let style = styles.resolve(
+ ctx.style,
+ merge: style.named(),
+ root: "pyramid",
+ base: default-style
+ )
+
+ let mode = style.mode
+ let gap = style.gap
+
+ assert(mode in ("REGULAR", "AREA-HEIGHT", "HEIGHT", "AREA-WIDTH", "WIDTH"),
+ message: "Mode must be 'REGULAR', 'AREA-HEIGHT', 'HEIGHT', 'AREA-WIDTH' or 'WIDTH', but is: " + str(mode))
+
+
+ if mode == "AREA-HEIGHT" {
+ if gap == 0 {
+ gap = 0%
+ }
+ assert(type(gap) == ratio, message: "When mode is set to 'AREA-HEIGHT', gap must be of type ratio, but is: " + str(type(gap)))
+ }
+
+ assert(style.side-label.side in ("west", "east"),
+ message: "Side label side must either be 'west' or 'east', but is: " + str(style.side-label.side))
+
+ let style-at = if type(level-style) == function {
+ level-style
+ } else if type(level-style) == array {
+ i => {
+ let s = level-style.at(calc.rem(i, level-style.len()))
+ if type(s) == color or type(s) == gradient {
+ (fill: s)
+ } else {
+ s
+ }
+ }
+ } else if type(level-style) == gradient {
+ i => (fill: level-style.sample(i / data.len() * 100%))
+ }
+
+ let total = data.map(d => d.first()).sum()
+ let get-item-label(item, kind) = {
+ let (value, label, ..) = item
+ if kind == label-kind.value {
+ [#value]
+ } else if kind == label-kind.percentage {
+ if total == none {
+ panic("Using percentage label without values")
+ }
+ [#{calc.round(value / total * 100)}%]
+ } else if kind == label-kind.label {
+ label
+ } else if type(kind) == function {
+ (kind)(value, label)
+ }
+ }
+
+ let rect-overlaps-trapezoid(rect, trapezoid) = {
+ let r = rect
+ let t = trapezoid
+ let side-m = (t.y1 - t.y2) / (t.x1 - t.x2)
+ let side-h = t.y1 - side-m * t.x1
+
+ let x-side = (r.y - side-h) / side-m
+
+ return if r.y > t.y1 {
+ r.x < t.x1
+ } else {
+ r.x < x-side
+ }
+ }
+
+ let total-gaps = style.gap * data.len()
+ let total-height = if mode in ("REGULAR", "WIDTH") {
+ style.level-height * data.len()
+ } else if mode == "HEIGHT" {
+
+ }
+
+ total-height += total-gaps
+
+ let base-width = if mode == "REGULAR" {
+ 2 * total-height / calc.sqrt(3)
+
+ }
+
+ let enum-items = data.enumerate()
+
+ // Array of levels
+ // level = (
+ // y,
+ // h,
+ // w-top,
+ // w-bottom,
+ // item
+ // )
+ let levels = ()
+
+ if mode == "REGULAR" {
+ levels = enum-items.map(((i, item)) => (
+ i * (style.level-height + style.gap),
+ style.level-height,
+ auto,
+ auto,
+ item
+ ))
+ } else if mode == "WIDTH" {
+ let w = 0
+ let last-val = 0
+ levels = ()
+ for (i, item) in enum-items {
+ let val = item.first()
+ let y = i * (style.level-height + style.gap)
+ let h = style.level-height
+ let y2 = y + h
+ let w1 = w
+ let w2 = if i == 0 {
+ y2 / calc.sqrt(3)
+ } else {
+ w * val / last-val
+ }
+ w = w2
+ last-val = val
+ levels.push((
+ y,
+ h,
+ w1,
+ w2,
+ item
+ ))
+ }
+ } else if mode == "HEIGHT" {
+ let smallest = calc.min(
+ ..data.map(d => d.first())
+ .filter(v => v != 0)
+ )
+
+ let get-height(value) = {
+ return value / smallest * style.level-height
+ }
+
+ let y = 0
+ for (i, item) in enum-items {
+ let h = get-height(item.first())
+ levels.push((
+ y,
+ h,
+ auto,
+ auto,
+ item
+ ))
+ y += h + style.gap
+ }
+
+ } else if mode == "AREA-HEIGHT" {
+ let y = 0
+ let get-area(y, h) = {
+ return h * (2 *y + h) / 2
+ }
+ let h-for-area(y, area) = {
+ /*
+ A = (2yh + h²)/2
+ 2 * A = 2yh + h²
+ h² + 2yh - 2A = 0
+
+ h = -y +- sqrt(y² + 2A)
+ */
+
+ let delta = calc.sqrt(y * y + 2 * area)
+ return delta - y
+ }
+
+ let first-val = enum-items.first().last().first()
+ let first-area = 1 / calc.sqrt(3)
+ let thinnest = 1
+
+ for (i, item) in enum-items {
+ let h = if i == 0 {
+ 1
+ } else {
+ let area = item.first() / first-val * first-area
+ h-for-area(y, area)
+ }
+
+ levels.push((
+ y,
+ h,
+ auto,
+ auto,
+ item
+ ))
+ thinnest = calc.min(thinnest, h)
+ y += h + gap / 100%
+ }
+
+ let f = style.level-height / thinnest
+
+ levels = levels.map(((y, h, w1, w2, item)) => (
+ y * f,
+ h * f,
+ w1,
+ w2,
+ item
+ ))
+ }
+
+ let anchors = ()
+ draw.group(name: "chart", {
+ draw.group(name: "levels", {
+ for (i, level) in levels.enumerate() {
+ let (
+ y,
+ h,
+ width-top,
+ width-bottom,
+ (value, label)
+ ) = level
+
+ let y2 = y + h
+ if width-top == auto {
+ width-top = y / calc.sqrt(3)
+ }
+ if width-bottom == auto {
+ width-bottom = y2 / calc.sqrt(3)
+ }
+
+ let stroke = style-at(i).at("stroke", default: style.stroke)
+ let fill = style-at(i).at("fill", default: style.fill)
+
+ let lvl-name = str(i)
+ draw.group(name: lvl-name, {
+ draw.line(
+ (-width-top, -y),
+ (width-top, -y),
+ (width-bottom, -y2),
+ (-width-bottom, -y2),
+ close: true,
+ fill: fill,
+ stroke: stroke
+ )
+ let my = -(y + y2)/2
+ draw.anchor(
+ "west",
+ (-(width-top + width-bottom)/2, my)
+ )
+ draw.anchor(
+ "east",
+ ((width-top + width-bottom)/2, my)
+ )
+ draw.anchor("center", (0, my))
+ draw.anchor("default", (0, my))
+ })
+
+ let inner-label = get-item-label(
+ (value, label),
+ style.inner-label.content
+ )
+
+ if inner-label != none {
+ let my = if width-top == 0 {
+ -y - 2*h/3
+ } else {
+ -y - h/2
+ }
+ let m = measure(inner-label)
+ let rw = m.width / ctx.length
+ let rh = m.height / ctx.length
+ let rect = (
+ x: -rw / 2,
+ y: my + rh / 2,
+ w: rw,
+ h: rh
+ )
+ let trapezoid = (
+ y1: -y,
+ y2: -y2,
+ x1: -width-top,
+ x2: -width-bottom
+ )
+
+ let mid = (0, my)
+ if not style.inner-label.force-inside and rect-overlaps-trapezoid(rect, trapezoid) {
+ let (anchor, f) = if calc.rem(i, 2) == 0 {
+ ("west", 1)
+ } else {
+ ("east", -1)
+ }
+
+ let dy = 0.1 * h
+ let pt = (
+ rel: (
+ f * ((-my + dy) / calc.sqrt(3) + .5),
+ dy
+ ),
+ to: mid
+ )
+
+ draw.line(mid, pt)
+ draw.content(
+ pt,
+ inner-label,
+ anchor: anchor,
+ padding: 3pt
+ )
+ } else {
+ draw.content(
+ mid,
+ inner-label
+ )
+ }
+ }
+ }
+ })
+ if style.side-label.content != none {
+ let side = style.side-label.side
+ let corner = "levels.north-" + side
+ for (i, item) in enum-items {
+ let lvl-pt = "levels." + str(i)
+ let pos = (lvl-pt, "-|", corner)
+ draw.content(
+ pos,
+ get-item-label(item, style.side-label.content),
+ anchor: ("west":"east","east":"west").at(side)
+ )
+ }
+ }
+ })
+ })
+}
diff --git a/render/packages/preview/cetz-plot/0.1.4/src/chart/radarchart.typ b/render/packages/preview/cetz-plot/0.1.4/src/chart/radarchart.typ
new file mode 100644
index 0000000..3dbbdb4
--- /dev/null
+++ b/render/packages/preview/cetz-plot/0.1.4/src/chart/radarchart.typ
@@ -0,0 +1,176 @@
+#import "/src/cetz.typ": draw, palette, styles
+
+#import "/src/plot.typ"
+
+#let radarchart-default-style = (
+ web-style: (
+ stroke: black.lighten(40%),
+ ),
+ web-ticks: 4,
+ web-label-offset: 0.4,
+ center-pos: (0, 0),
+ radius: 2,
+)
+
+/// Draw a radar chart (also known as spider chart or web chart). A radar
+/// chart is a chart that represents multivariate data in the form of a
+/// two-dimensional chart of three or more quantitative variables represented as
+/// axes starting from the same point.
+///
+/// ```cexample
+/// chart.radarchart(
+/// (
+/// [A],
+/// [B],
+/// [C],
+/// [D],
+/// [E],
+/// [F],
+/// ),
+/// (0.3, 0.6, 0.3, 0.4, 0.8, 1),
+/// )
+/// ```
+/// === Styling
+/// Can be applied with `cetz.draw.set-style(radarchart: (web-ticks: 6))`.
+///
+/// *Root*: `radarchart`.
+/// #show-parameter-block("web-style", "style", default: (stroke: black.lighten(40%)), [
+/// Style of the web in the background of the chart.])
+/// #show-parameter-block("web-ticks", ("int", "array"), default: 4, [
+/// Amount of layers of the web or an array containing the distance of each web layer to draw.])
+/// #show-parameter-block("web-label-offset", "float", default: 0.4, [
+/// Distance from the end of the web to the label.])
+/// #show-parameter-block("center-pos", "float", default: 1, [
+/// Coordinate of the center of the chart.])
+/// #show-parameter-block("radius", "float", default: 2, [
+/// Radius of the radar chart.])
+///
+/// - labels (array): Array of content. Each entry is the label
+/// of one coordinate axis.
+///
+/// *Example*
+/// ```typc
+/// ([A], [B], [C])
+/// ```
+/// - data (array): Array of data rows. A row can be of type array of float or
+/// array of array of float. All float values must be within the
+/// the range $0 <= "value" <= "radius"$. Each of the data rows must
+/// contain the same amount of items as `labels`.
+///
+/// *Example*
+/// ```typc
+/// ((0.5, 0.3, 0.9), (0.3, 0.5, 0.2))
+/// ```
+/// - data-style (function, array): Style per data row. Can be either
+/// - function: A function of the form `index => style` that must return a style dictionary.
+/// This can be a `palette` function.
+/// - array of style dictionaries: The dictionary at index `i` contains the style for the data row at index `i`.
+/// - array of colors: The dictionary at index `i` contains the fill color for the data row at index `i`.
+///
+#let radarchart(
+ labels,
+ data,
+ data-style: palette.red,
+ ..style,
+) = {
+ assert(type(labels) == array)
+ assert(labels.len() >= 3)
+
+ assert(type(data) == array)
+ assert(data.len() != 0)
+ if type(data.at(0)) != array {
+ // only one single data line
+ data = (data,)
+ }
+
+ // ensure that all data lines have the same amount of coordinates
+ let size = labels.len()
+ for line in data {
+ assert(line.len() == size)
+ }
+
+ draw.group(ctx => {
+ let style = styles.resolve(
+ ctx.style,
+ merge: style.named(),
+ root: "radarchart",
+ base: radarchart-default-style,
+ )
+ draw.set-style(..style)
+
+ let center-pos = style.at("center-pos")
+ let radius = style.at("radius")
+ let web-ticks = style.at("web-ticks")
+ let web-label-offset = style.at("web-label-offset")
+
+ // ensure that no data point overflows out of the chart
+ for line in data {
+ for value in line {
+ assert(0 <= value and value <= radius)
+ }
+ }
+
+ assert(radius > 0)
+ assert(type(web-ticks) in (int, array))
+ if type(web-ticks) == int {
+ // automatically calculate ticks amount of equidistant ticks
+ web-ticks = range(web-ticks).map(i => (i + 1) / web-ticks)
+ }
+
+ let angle-step = 360deg / labels.len()
+
+ // draw labels and lines from center to label
+ // each of these axis is assigned the label "axis-{i}"
+ for (i, label) in labels.enumerate() {
+ let axis-name = "axis-" + str(i)
+ draw.line(
+ center-pos,
+ (
+ rel: (-angle-step * i + 90deg, radius),
+ ),
+ name: axis-name,
+ )
+ draw.content(
+ (axis-name + ".start", radius + web-label-offset, axis-name + ".end"),
+ label,
+ )
+ }
+
+ // web drawing logic
+ for tick in web-ticks {
+ let web-points = ()
+ for i in range(labels.len()) {
+ web-points.push((
+ rel: (-angle-step * i + 90deg, radius * tick),
+ to: center-pos,
+ ))
+ }
+ draw.line(..web-points, close: true, ..style.at("web-style"))
+ }
+
+ // draw the coordinates of each data line as a polygon
+ for (line-index, line) in data.enumerate() {
+ let pts = ()
+ for (i, value) in line.enumerate() {
+ let axis-name = "axis-" + str(i)
+ pts.push((axis-name + ".start", radius * value, axis-name + ".end"))
+ }
+
+ let polygon-style = (:)
+ if type(data-style) == array {
+ let s = data-style.at(line-index)
+ if type(data-style.at(line-index)) == dictionary {
+ // data-style = style dict
+ polygon-style = s
+ } else {
+ // data-style = list of colors -> fill polygon with these colors
+ polygon-style = (fill: s)
+ }
+ } else if type(data-style) == function {
+ // data-style = method taking the index as param
+ polygon-style = data-style(line-index)
+ }
+ draw.line(..pts, close: true, ..polygon-style)
+ }
+ })
+}
diff --git a/render/packages/preview/cetz-plot/0.1.4/src/clip.typ b/render/packages/preview/cetz-plot/0.1.4/src/clip.typ
new file mode 100644
index 0000000..b4eac3b
--- /dev/null
+++ b/render/packages/preview/cetz-plot/0.1.4/src/clip.typ
@@ -0,0 +1,65 @@
+#import "/src/cetz.typ": vector
+
+/// Clip a single component of a list of vectors between [min, max]
+/// and returns a list of clipped shapes.
+#let clip-component-axis(component, min, max, points) = {
+ if points == () {
+ return ()
+ }
+
+ // List of tuples (index, ratio, inside)
+ let intersections = ()
+
+ // Collect all intersections
+ let inside = auto
+ for (i, pt) in points.enumerate() {
+ let v = pt.at(component, default: min)
+ let this-inside = min <= v and v <= max
+
+ if inside == auto {
+ inside = this-inside
+ } else if inside != this-inside {
+ inside = not inside
+ if this-inside {
+ intersections.push((i, (v - min) / (max - min), inside))
+ } else {
+ intersections.push((i, (v - min) / (max - min), inside))
+ }
+ }
+ }
+
+ // Clip intersections
+ if intersections != () {
+ let shapes = ()
+
+ let start = none
+ let start-ratio = none
+ for (i, ratio, this-inside) in intersections {
+ if this-inside {
+ start = i
+ start-ratio = ratio
+ } else {
+ let start-pt = if start == 0 or start == points.len() - 1 {
+ points.at(start)
+ } else {
+ vector.lerp(points.at(start - 1), points.at(start), start-ratio)
+ }
+
+ let end-pt = if i == points.len() - 1 {
+ points.last()
+ } else {
+ vector.lerp(points.at(i - 1), points.at(i), ratio)
+ }
+
+ shapes.push((
+ start-pt, ..points.slice(start, i), end-pt,
+ ))
+ start = none
+ }
+ }
+
+ return shapes
+ }
+
+ return (points,)
+}
diff --git a/render/packages/preview/cetz-plot/0.1.4/src/coordinates.typ b/render/packages/preview/cetz-plot/0.1.4/src/coordinates.typ
new file mode 100644
index 0000000..c4734df
--- /dev/null
+++ b/render/packages/preview/cetz-plot/0.1.4/src/coordinates.typ
@@ -0,0 +1,25 @@
+#import "/src/cetz.typ": draw
+
+/// Coordinate resolve that just forwards (plot: (x, y)) coordinates
+/// as (x, y).
+#let stup-resolver(ctx, point) = {
+ if type(point) == dictionary and "plot" in point {
+ return point.plot
+ }
+
+ return point
+}
+
+/// Plot axis coordinate resolver
+let default-resolver(ctx, point) = {
+ if type(point) == dictionary and "plot" in point {
+ let names = point.at("axes", default: ("x", "y"))
+
+ let p = point.plot
+ return names.map(name => ctx.cetz-plot-axes.at(name)).enumerate().map(((i, ax)) => {
+ (ax.to)(p.at(i))
+ })
+ }
+
+ return c
+}
diff --git a/render/packages/preview/cetz-plot/0.1.4/src/grid-layout.typ b/render/packages/preview/cetz-plot/0.1.4/src/grid-layout.typ
new file mode 100644
index 0000000..4e9f05d
--- /dev/null
+++ b/render/packages/preview/cetz-plot/0.1.4/src/grid-layout.typ
@@ -0,0 +1,43 @@
+#import "/src/cetz.typ"
+
+#let grid(columns: 2, ..items) = {
+ let items = items.pos()
+ let valign = (horizon,) * columns
+
+ (ctx => {
+ let rows = ()
+ let cells = ()
+
+ for (i, item) in items.enumerate() {
+ let (bounds: bounds, drawables: drawables, ..) = cetz.process.many(ctx, item)
+
+ let width = bounds.high.at(0) - bounds.low.at(0)
+ let height = bounds.high.at(1) - bounds.low.at(1)
+ cells.push(((width, height), drawables))
+ }
+
+ let height = 0
+ for i in range(0, items.len()) {
+ let size = cells.at(i).at(0)
+ height = calc.max(size.at(1), height)
+ if calc.rem(i, columns) == 0{
+ rows.push(height)
+ height = 0
+ }
+ }
+
+ cells = cells.enumerate().map(((i, (size, cell))) => {
+ let t = cetz.matrix.ident()
+ let row = rows.at(int(i / columns))
+
+ t = cetz.matrix.transform-translate(0, -(row - size.at(1)) / 2, 0)
+
+ cetz.drawable.apply-transform(t, cell)
+ })
+
+ return (
+ ctx: ctx,
+ drawables: cells.join(),
+ )
+ },)
+}
diff --git a/render/packages/preview/cetz-plot/0.1.4/src/lib.typ b/render/packages/preview/cetz-plot/0.1.4/src/lib.typ
new file mode 100644
index 0000000..9a1f4c1
--- /dev/null
+++ b/render/packages/preview/cetz-plot/0.1.4/src/lib.typ
@@ -0,0 +1,6 @@
+#let version = version(0,1,4)
+
+#import "/src/axes.typ"
+#import "/src/plot.typ"
+#import "/src/chart.typ"
+#import "/src/smartart.typ"
diff --git a/render/packages/preview/cetz-plot/0.1.4/src/plot.typ b/render/packages/preview/cetz-plot/0.1.4/src/plot.typ
new file mode 100644
index 0000000..f0f55ca
--- /dev/null
+++ b/render/packages/preview/cetz-plot/0.1.4/src/plot.typ
@@ -0,0 +1,567 @@
+#import "/src/cetz.typ": util, draw, matrix, vector, styles, palette
+#import util: bezier
+
+#import "/src/axes.typ"
+#import "/src/plot/sample.typ": sample-fn, sample-fn2
+#import "/src/plot/line.typ": add, add-hline, add-vline, add-fill-between
+#import "/src/plot/contour.typ": add-contour
+#import "/src/plot/boxwhisker.typ": add-boxwhisker
+#import "/src/plot/util.typ" as plot-util
+#import "/src/plot/legend.typ" as plot-legend
+#import "/src/plot/annotation.typ": annotate, calc-annotation-domain
+#import "/src/plot/bar.typ": add-bar
+#import "/src/plot/errorbar.typ": add-errorbar
+#import "/src/plot/mark.typ"
+#import "/src/plot/violin.typ": add-violin
+#import "/src/plot/formats.typ"
+#import plot-legend: add-legend
+
+#let default-colors = (blue, red, green, yellow, black)
+
+#let default-plot-style(i) = {
+ let color = default-colors.at(calc.rem(i, default-colors.len()))
+ return (stroke: color,
+ fill: color.lighten(75%))
+}
+
+#let default-mark-style(i) = {
+ return default-plot-style(i)
+}
+
+/// Create a plot environment. Data to be plotted is given by passing it to the
+/// `plot.add` or other plotting functions. The plot environment supports different
+/// axis styles to draw, see its parameter `axis-style:`.
+///
+/// ```cexample
+/// plot.plot(size: (2,2), x-tick-step: none, y-tick-step: none, {
+/// plot.add(((0,0), (1,1), (2,.5), (4,3)))
+/// })
+/// ```
+///
+/// To draw elements insides a plot, using the plots coordinate system, use
+/// the `plot.annotate(..)` function.
+///
+/// === Options
+///
+/// You can use the following options to customize each axis of the plot. You must pass them as named arguments prefixed by the axis name followed by a dash (`-`) they should target. Example: `x-min: 0`, `y-ticks: (..)` or `x2-label: [..]`.
+///
+/// #show-parameter-block("label", ("none", "content"), default: "none", [
+/// The axis' label. If and where the label is drawn depends on the `axis-style`.])
+/// #show-parameter-block("min", ("auto", "float"), default: "auto", [
+/// Axis lower domain value. If this is set greater than than `max`, the axis' direction is swapped])
+/// #show-parameter-block("max", ("auto", "float"), default: "auto", [
+/// Axis upper domain value. If this is set to a lower value than `min`, the axis' direction is swapped])
+/// #show-parameter-block("equal", ("string"), default: "none", [
+/// Set the axis domain to keep a fixed aspect ratio by multiplying the other axis domain by the plots aspect ratio,
+/// depending on the other axis orientation (see `horizontal`).
+/// This can be useful to force one axis to grow or shrink with another one.
+/// You can only "lock" two axes of different orientations.
+/// ```cexample
+/// plot.plot(size: (2,1), x-tick-step: 1, y-tick-step: 1,
+/// x-equal: "y",
+/// {
+/// plot.add(domain: (0, 2 * calc.pi),
+/// t => (calc.cos(t), calc.sin(t)))
+/// })
+/// ```
+/// ])
+/// #show-parameter-block("horizontal", ("bool"), default: "axis name dependant", [
+/// If true, the axis is considered an axis that gets drawn horizontally, vertically otherwise.
+/// The default value depends on the axis name on axis creation. Axes which name start with `x` have this
+/// set to `true`, all others have it set to `false`. Each plot has to use one horizontal and one
+/// vertical axis for plotting, a combination of two y-axes will panic: ("y", "y2").
+/// ])
+/// #show-parameter-block("tick-step", ("none", "auto", "float"), default: "auto", [
+/// The increment between tick marks on the axis. If set to `auto`, an
+/// increment is determined. When set to `none`, incrementing tick marks are disabled.])
+/// #show-parameter-block("minor-tick-step", ("none", "float"), default: "none", [
+/// Like `tick-step`, but for minor tick marks. In contrast to ticks, minor ticks do not have labels.])
+/// #show-parameter-block("ticks", ("none", "array"), default: "none", [
+/// A List of custom tick marks to additionally draw along the axis. They can be passed as
+/// an array of `<float>` values or an array of `(<float>, <content>)` tuples for
+/// setting custom tick mark labels per mark.
+///
+/// ```cexample
+/// plot.plot(x-tick-step: none, y-tick-step: none,
+/// x-min: 0, x-max: 4,
+/// x-ticks: (1, 2, 3),
+/// y-min: 1, y-max: 2,
+/// y-ticks: ((1, [One]), (2, [Two])),
+/// {
+/// plot.add(((0,0),))
+/// })
+/// ```
+///
+/// Examples: `(1, 2, 3)` or `((1, [One]), (2, [Two]), (3, [Three]))`])
+/// #show-parameter-block("format", ("none", "string", "function"), default: "float", [
+/// How to format the tick label: You can give a function that takes a `<float>` and return
+/// `<content>` to use as the tick label. You can also give one of the predefined options:
+/// / float: Floating point formatting rounded to two digits after the point (see `decimals`)
+/// / sci: Scientific formatting with $times 10^n$ used as exponet syntax
+///
+/// ```cexample
+/// let formatter(v) = if v != 0 {$ #{v/calc.pi} pi $} else {$ 0 $}
+/// plot.plot(x-tick-step: calc.pi, y-tick-step: none,
+/// x-min: 0, x-max: 2 * calc.pi,
+/// x-format: formatter,
+/// {
+/// plot.add(((0,0),))
+/// })
+/// ```
+/// ])
+/// #show-parameter-block("decimals", ("int"), default: "2", [
+/// Number of decimals digits to display for tick labels, if the format is set
+/// to `"float"`.
+/// ])
+/// #show-parameter-block("mode", ("none", "string"), default: "none", [
+/// The scaling function of the axis. Takes `lin` (default) for linear scaling,
+/// and `log` for logarithmic scaling.])
+/// #show-parameter-block("base", ("none", "number"), default: "none", [
+/// The base to be used when labeling axis ticks in logarithmic scaling])
+/// #show-parameter-block("grid", ("bool", "string"), default: "false", [
+/// If `true` or `"major"`, show grid lines for all major ticks. If set
+/// to `"minor"`, show grid lines for minor ticks only.
+/// The value `"both"` enables grid lines for both, major- and minor ticks.
+///
+/// ```cexample
+/// plot.plot(x-tick-step: 1, y-tick-step: 1,
+/// y-minor-tick-step: .2,
+/// x-min: 0, x-max: 2, x-grid: true,
+/// y-min: 0, y-max: 2, y-grid: "both", {
+/// plot.add(((0,0),))
+/// })
+/// ```
+/// ])
+/// #show-parameter-block("break", ("bool"), default: "false", [
+/// If true, add a "sawtooth" at the start or end of the axis line, depending
+/// on the axis bounds. If the axis min. value is > 0, a sawtooth is added
+/// to the start of the axes, if the axis max. value is < 0, a sawtooth is added
+/// to its end.])
+///
+/// - body (body): Calls of `plot.add` or `plot.add-*` commands. Note that normal drawing
+/// commands like `line` or `rect` are not allowed inside the plots body, instead wrap
+/// them in `plot.annotate`, which lets you select the axes used for drawing.
+/// - size (array): Plot size tuple of `(<width>, <height>)` in canvas units.
+/// This is the plots inner plotting size without axes and labels.
+/// - axis-style (none, string): How the axes should be styled:
+/// / scientific: Frames plot area using a rectangle and draw axes `x` (bottom), `y` (left), `x2` (top), and `y2` (right) around it.
+/// If `x2` or `y2` are unset, they mirror their opposing axis.
+/// / scientific-auto: Draw set (used) axes `x` (bottom), `y` (left), `x2` (top) and `y2` (right) around
+/// the plotting area, forming a rect if all axes are in use or a L-shape if only `x` and `y` are in use.
+/// / school-book: Draw axes `x` (horizontal) and `y` (vertical) as arrows pointing to the right/top with both crossing at $(0, 0)$
+/// / left: Draw axes `x` and `y` as arrows, while the y axis stays on the left (at `x.min`)
+/// and the x axis at the bottom (at `y.min`)
+/// / `none`: Draw no axes (and no ticks).
+///
+/// ```cexample-vertical
+/// let opts = (x-tick-step: none, y-tick-step: none, size: (2,1))
+/// let data = plot.add(((-1,-1), (1,1),), mark: "o")
+///
+/// for name in (none, "school-book", "left", "scientific") {
+/// plot.plot(axis-style: name, ..opts, data, name: "plot")
+/// content(((0,-1), "-|", "plot.south"), repr(name))
+/// set-origin((3.5,0))
+/// }
+/// ```
+/// - plot-style (style,function): Styling to use for drawing plot graphs.
+/// This style gets inherited by all plots and supports `palette` functions.
+/// The following style keys are supported:
+/// #show-parameter-block("stroke", ("none", "stroke"), default: 1pt, [
+/// Stroke style to use for stroking the graph.
+/// ])
+/// #show-parameter-block("fill", ("none", "paint"), default: none, [
+/// Paint to use for filled graphs. Note that not all graphs may support filling and
+/// that you may have to enable filling per graph, see `plot.add(fill: ..)`.
+/// ])
+/// - mark-style (style,function): Styling to use for drawing plot marks.
+/// This style gets inherited by all plots and supports `palette` functions.
+/// The following style keys are supported:
+/// #show-parameter-block("stroke", ("none", "stroke"), default: 1pt, [
+/// Stroke style to use for stroking the mark.
+/// ])
+/// #show-parameter-block("fill", ("none", "paint"), default: none, [
+/// Paint to use for filling marks.
+/// ])
+/// - fill-below (bool): If true, the filled shape of plots is drawn _below_ axes.
+/// - name (string): The plots element name to be used when referring to anchors
+/// - legend (none, auto, coordinate): The position the legend will be drawn at. See plot-legends for information about legends. If set to `<auto>`, the legend's "default-placement" styling will be used. If set to a `<coordinate>`, it will be taken as relative to the plot's origin.
+/// - legend-anchor (auto, string): Anchor of the legend group to use as its origin.
+/// If set to `auto` and `lengend` is one of the predefined legend anchors, the
+/// opposite anchor to `legend` gets used.
+/// - legend-style (style): Style key-value overwrites for the legend style with style root `legend`.
+/// - ..options (any): Axis options, see _options_ below.
+#let plot(body,
+ size: (1, 1),
+ axis-style: "scientific",
+ name: none,
+ plot-style: default-plot-style,
+ mark-style: default-mark-style,
+ fill-below: true,
+ legend: auto,
+ legend-anchor: auto,
+ legend-style: (:),
+ ..options
+ ) = draw.group(name: name, ctx => {
+ draw.assert-version(version(0, 5, 0), max: version(0, 6, 0))
+
+ // Create plot context object
+ let make-ctx(x, y, size) = {
+ assert(x != none, message: "X axis does not exist")
+ assert(y != none, message: "Y axis does not exist")
+ assert(size.at(0) > 0 and size.at(1) > 0, message: "Plot size must be > 0")
+
+ let x-scale = ((x.max - x.min) / size.at(0))
+ let y-scale = ((y.max - y.min) / size.at(1))
+
+ if y.horizontal {
+ (x-scale, y-scale) = (y-scale, x-scale)
+ }
+
+ return (x: x, y: y, size: size, x-scale: x-scale, y-scale: y-scale)
+ }
+
+ // Setup data viewport
+ let data-viewport(data, x, y, size, body, name: none) = {
+ if body == none or body == () { return }
+
+ assert.ne(x.horizontal, y.horizontal,
+ message: "Data must use one horizontal and one vertical axis!")
+
+ // If y is the horizontal axis, swap x and y
+ // coordinates by swapping the transformation
+ // matrix columns.
+ if y.horizontal {
+ (x, y) = (y, x)
+ body = draw.set-ctx(ctx => {
+ let ((x0, x1, x2, x3),
+ (y0, y1, y2, y3),
+ (z0, z1, z2, z3),
+ (w0, w1, w2, w3)) = ctx.transform
+ ctx.transform = ((x1, x0, x2, x3),
+ (y1, y0, y2, y3),
+ (z1, z0, z2, z3),
+ (w1, w0, w2, w3))
+ return ctx
+ }) + body
+ }
+
+ // Setup the viewport
+ axes.axis-viewport(size, x, y, none, body, name: name)
+ }
+
+ let data = ()
+ let anchors = ()
+ let annotations = ()
+ let body = if body != none { body } else { () }
+
+ for cmd in body {
+ assert(type(cmd) == dictionary and "type" in cmd,
+ message: "Expected plot sub-command in plot body")
+ if cmd.type == "anchor" {
+ anchors.push(cmd)
+ } else if cmd.type == "annotation" {
+ annotations.push(cmd)
+ } else { data.push(cmd) }
+ }
+
+ assert(axis-style in (none, "scientific", "scientific-auto", "school-book", "left"),
+ message: "Invalid plot style")
+
+ // Create axes for data & annotations
+ let axis-dict = (:)
+ for d in data + annotations {
+ if "axes" not in d { continue }
+
+ for (i, name) in d.axes.enumerate() {
+ if not name in axis-dict {
+ axis-dict.insert(name, axes.axis(
+ min: none, max: none))
+ }
+
+ let axis = axis-dict.at(name)
+ let domain = if i == 0 {
+ d.at("x-domain", default: (none, none))
+ } else {
+ d.at("y-domain", default: (none, none))
+ }
+ if domain != (none, none) {
+ axis.min = util.min(axis.min, ..domain)
+ axis.max = util.max(axis.max, ..domain)
+ }
+
+ axis-dict.at(name) = axis
+ }
+ }
+
+ // Create axes for anchors
+ for a in anchors {
+ for (i, name) in a.axes.enumerate() {
+ if not name in axis-dict {
+ axis-dict.insert(name, axes.axis(min: none, max: none))
+ }
+ }
+ }
+
+ // Adjust axis bounds for annotations
+ for a in annotations {
+ let (x, y) = a.axes.map(name => axis-dict.at(name))
+ (x, y) = calc-annotation-domain(ctx, x, y, a)
+ axis-dict.at(a.axes.at(0)) = x
+ axis-dict.at(a.axes.at(1)) = y
+ }
+
+ // Set axis options
+ axis-dict = plot-util.setup-axes(ctx, axis-dict, options.named(), size)
+
+ // Prepare styles
+ for i in range(data.len()) {
+ if "style" not in data.at(i) { continue }
+
+ let style-base = plot-style
+ if type(style-base) == function {
+ style-base = (style-base)(i)
+ }
+ assert.eq(type(style-base), dictionary,
+ message: "plot-style must be of type dictionary")
+
+ if type(data.at(i).style) == function {
+ data.at(i).style = (data.at(i).style)(i)
+ }
+ assert.eq(type(style-base), dictionary,
+ message: "data plot-style must be of type dictionary")
+
+ data.at(i).style = util.merge-dictionary(
+ style-base, data.at(i).style)
+
+ if "mark-style" in data.at(i) {
+ let mark-style-base = mark-style
+ if type(mark-style-base) == function {
+ mark-style-base = (mark-style-base)(i)
+ }
+ assert.eq(type(mark-style-base), dictionary,
+ message: "mark-style must be of type dictionary")
+
+ if type(data.at(i).mark-style) == function {
+ data.at(i).mark-style = (data.at(i).mark-style)(i)
+ }
+
+ if type(data.at(i).mark-style) == dictionary {
+ data.at(i).mark-style = util.merge-dictionary(
+ mark-style-base,
+ data.at(i).mark-style
+ )
+ }
+ }
+ }
+
+ draw.group(name: "plot", {
+ draw.anchor("origin", (0, 0))
+
+ // Prepare
+ for i in range(data.len()) {
+ if "axes" not in data.at(i) { continue }
+
+ let (x, y) = data.at(i).axes.map(name => axis-dict.at(name))
+ let plot-ctx = make-ctx(x, y, size)
+
+ if "plot-prepare" in data.at(i) {
+ data.at(i) = (data.at(i).plot-prepare)(data.at(i), plot-ctx)
+ assert(data.at(i) != none,
+ message: "Plot prepare(self, cxt) returned none!")
+ }
+ }
+
+ // Background Annotations
+ for a in annotations.filter(a => a.background) {
+ let (x, y) = a.axes.map(name => axis-dict.at(name))
+ let plot-ctx = make-ctx(x, y, size)
+
+ data-viewport(a, x, y, size, {
+ draw.anchor("default", (0, 0))
+ a.body
+ })
+ }
+
+ // Fill
+ if fill-below {
+ for d in data {
+ if "axes" not in d { continue }
+
+ let (x, y) = d.axes.map(name => axis-dict.at(name))
+ let plot-ctx = make-ctx(x, y, size)
+
+ data-viewport(d, x, y, size, {
+ draw.anchor("default", (0, 0))
+ draw.set-style(..d.style)
+
+ if "plot-fill" in d {
+ (d.plot-fill)(d, plot-ctx)
+ }
+ })
+ }
+ }
+
+ if axis-style in ("scientific", "scientific-auto") {
+ let draw-unset = if axis-style == "scientific" {
+ true
+ } else {
+ false
+ }
+
+ let mirror = if axis-style == "scientific" {
+ auto
+ } else {
+ none
+ }
+
+ axes.scientific(
+ size: size,
+ draw-unset: draw-unset,
+ bottom: axis-dict.at("x", default: none),
+ top: axis-dict.at("x2", default: mirror),
+ left: axis-dict.at("y", default: none),
+ right: axis-dict.at("y2", default: mirror),)
+ } else if axis-style == "left" {
+ axes.school-book(
+ size: size,
+ axis-dict.x,
+ axis-dict.y,
+ x-position: axis-dict.y.min,
+ y-position: axis-dict.x.min)
+ } else if axis-style == "school-book" {
+ axes.school-book(
+ size: size,
+ axis-dict.x,
+ axis-dict.y,)
+ }
+
+ // Stroke + Mark data
+ for d in data {
+ if "axes" not in d { continue }
+
+ let (x, y) = d.axes.map(name => axis-dict.at(name))
+ let plot-ctx = make-ctx(x, y, size)
+
+ data-viewport(d, x, y, size, {
+ draw.anchor("default", (0, 0))
+ draw.set-style(..d.style)
+
+ if not fill-below and "plot-fill" in d {
+ (d.plot-fill)(d, plot-ctx)
+ }
+ if "plot-stroke" in d {
+ (d.plot-stroke)(d, plot-ctx)
+ }
+ })
+
+ if "mark" in d and d.mark != none {
+ draw.scope({
+ if y.horizontal {
+ draw.set-ctx(ctx => {
+ let ((x0, x1, x2, x3),
+ (y0, y1, y2, y3),
+ (z0, z1, z2, z3),
+ (w0, w1, w2, w3)) = ctx.transform
+ ctx.transform = ((x1, x0, x2, x3),
+ (y1, y0, y2, y3),
+ (z1, z0, z2, z3),
+ (w1, w0, w2, w3))
+ return ctx
+ })
+ }
+
+ draw.set-style(..d.style, ..d.mark-style)
+ mark.draw-mark(d.data, x, y, d.mark, d.mark-size, size)
+ })
+ }
+ }
+
+ // Foreground Annotations
+ for a in annotations.filter(a => not a.background) {
+ let (x, y) = a.axes.map(name => axis-dict.at(name))
+ let plot-ctx = make-ctx(x, y, size)
+
+ data-viewport(a, x, y, size, {
+ draw.anchor("default", (0, 0))
+ a.body
+ })
+ }
+
+ // Place anchors
+ for a in anchors {
+ let (x, y) = a.axes.map(name => axis-dict.at(name))
+ let plot-ctx = make-ctx(x, y, size)
+
+ let pt = a.position.enumerate().map(((i, v)) => {
+ if v == "min" { return axis-dict.at(a.axes.at(i)).min }
+ if v == "max" { return axis-dict.at(a.axes.at(i)).max }
+ return v
+ })
+ pt = axes.transform-vec(size, x, y, none, pt)
+ if pt != none {
+ draw.anchor(a.name, pt)
+ }
+ }
+ })
+
+ // Draw the legend
+ if legend != none {
+ let items = data.filter(d => "label" in d and d.label != none)
+ if items.len() > 0 {
+ let legend-style = styles.resolve(ctx.style,
+ base: plot-legend.default-style, merge: legend-style, root: "legend")
+
+ plot-legend.add-legend-anchors(legend-style, "plot", size)
+ plot-legend.legend(legend, anchor: legend-anchor, {
+ for item in items {
+ let preview = if "plot-legend-preview" in item {
+ _ => {(item.plot-legend-preview)(item) }
+ } else {
+ auto
+ }
+
+ plot-legend.item(item.label, preview,
+ mark: item.at("mark", default: none),
+ mark-size: item.at("mark-size", default: none),
+ mark-style: item.at("mark-style", default: none),
+ ..item.at("style", default: (:)))
+ }
+ }, ..legend-style)
+ }
+ }
+
+ draw.copy-anchors("plot")
+})
+
+/// Add an anchor to a plot environment
+///
+/// This function is similar to `draw.anchor` but it takes an additional
+/// axis tuple to specify which axis coordinate system to use.
+///
+/// ```cexample
+/// plot.plot(size: (2,2), name: "plot",
+/// x-tick-step: none, y-tick-step: none, {
+/// plot.add(((0,0), (1,1), (2,.5), (4,3)))
+/// plot.add-anchor("pt", (1,1))
+/// })
+///
+/// line("plot.pt", ((), "|-", (0,1.5)), mark: (start: ">"), name: "line")
+/// content("line.end", [Here], anchor: "south", padding: .1)
+/// ```
+///
+/// - name (string): Anchor name
+/// - position (tuple): Tuple of x and y values.
+/// Both values can have the special values "min" and
+/// "max", which resolve to the axis min/max value.
+/// Position is in axis space defined by the axes passed to `axes`.
+/// - axes (tuple): Name of the axes to use `("x", "y")` as coordinate
+/// system for `position`. Note that both axes must be used,
+/// as `add-anchors` does not create them on demand.
+#let add-anchor(name, position, axes: ("x", "y")) = {
+ ((
+ type: "anchor",
+ name: name,
+ position: position,
+ axes: axes,
+ ),)
+}
diff --git a/render/packages/preview/cetz-plot/0.1.4/src/plot/annotation.typ b/render/packages/preview/cetz-plot/0.1.4/src/plot/annotation.typ
new file mode 100644
index 0000000..d4d4479
--- /dev/null
+++ b/render/packages/preview/cetz-plot/0.1.4/src/plot/annotation.typ
@@ -0,0 +1,75 @@
+#import "/src/cetz.typ"
+#import cetz: draw, process, util, matrix
+#import "util.typ"
+#import "sample.typ"
+
+/// Add an annotation to the plot
+///
+/// An annotation is a sub-canvas that uses the plots coordinates specified
+/// by its x and y axis.
+///
+/// ```cexample
+/// plot.plot(size: (2,2), x-tick-step: none, y-tick-step: none, {
+/// plot.add(domain: (0, 2*calc.pi), calc.sin)
+/// plot.annotate({
+/// rect((0, -1), (calc.pi, 1), fill: rgb(50,50,200,50))
+/// content((calc.pi, 0), [Here])
+/// })
+/// })
+/// ```
+///
+/// Bounds calculation is done naively, therefore fixed size content _can_ grow
+/// out of the plot. You can adjust the padding manually to adjust for that. The
+/// feature of solving the correct bounds for fixed size elements might be added
+/// in the future.
+///
+/// - body (drawable): Elements to draw
+/// - axes (axes): X and Y axis names
+/// - resize (bool): If true, the plots axes get adjusted to contain the annotation
+/// - padding (none,number,dictionary): Annotation padding that is used for axis
+/// adjustment
+/// - background (bool): If true, the annotation is drawn behind all plots, in the background.
+/// If false, the annotation is drawn above all plots.
+#let annotate(body, axes: ("x", "y"), resize: true, padding: none, background: false) = {
+ ((
+ type: "annotation",
+ body: {
+ draw.set-style(mark: (transform-shape: false))
+ body;
+ },
+ axes: axes,
+ resize: resize,
+ background: background,
+ padding: cetz.util.as-padding-dict(padding),
+ ),)
+}
+
+// Returns the adjusted axes for the annotation object
+//
+// -> array Tuple of x and y axis
+#let calc-annotation-domain(ctx, x, y, annotation) = {
+ if not annotation.resize {
+ return (x, y)
+ }
+
+ ctx.transform = matrix.ident(4)
+ let (ctx: ctx, bounds: bounds, drawables: _) = process.many(ctx, annotation.body)
+ if bounds == none {
+ return (x, y)
+ }
+
+ let (x-min, y-min, ..) = bounds.low
+ let (x-max, y-max, ..) = bounds.high
+
+ x-min -= annotation.padding.left
+ x-max += annotation.padding.right
+ y-min -= annotation.padding.bottom
+ y-max += annotation.padding.top
+
+ x.min = calc.min(x.min, x-min)
+ x.max = calc.max(x.max, x-max)
+ y.min = calc.min(y.min, y-min)
+ y.max = calc.max(y.max, y-max)
+
+ return (x, y)
+}
diff --git a/render/packages/preview/cetz-plot/0.1.4/src/plot/bar.typ b/render/packages/preview/cetz-plot/0.1.4/src/plot/bar.typ
new file mode 100644
index 0000000..f817f38
--- /dev/null
+++ b/render/packages/preview/cetz-plot/0.1.4/src/plot/bar.typ
@@ -0,0 +1,264 @@
+#import "/src/cetz.typ": draw, util
+
+#import "errorbar.typ": draw-errorbar
+
+#let _transform-row(row, x-key, y-key, error-key) = {
+ let x = row.at(x-key)
+ let y = if y-key == auto {
+ row.slice(1)
+ } else if type(y-key) == array {
+ y-key.map(k => row.at(k, default: 0))
+ } else {
+ row.at(y-key, default: 0)
+ }
+ let err = if error-key == none {
+ 0
+ } else if type(error-key) == array {
+ error-key.map(k => row.at(k, default: 0))
+ } else {
+ row.at(error-key, default: 0)
+ }
+
+ if type(y) != array { y = (y,) }
+ if type(err) != array { err = (err,) }
+
+ (x, y.flatten(), err.flatten())
+}
+
+// Get a single items min and maximum y-value
+#let _minmax-value(row) = {
+ let min = none
+ let max = none
+
+ let y = row.at(1)
+ let e = row.at(2)
+ for i in range(0, y.len()) {
+ let i-min = y.at(i) - e.at(i, default: 0)
+ if min == none { min = i-min }
+ else { min = calc.min(min, i-min) }
+
+ let i-max = y.at(i) + e.at(i, default: 0)
+ if max == none { max = i-max }
+ else { max = calc.max(max, i-max) }
+ }
+
+ return (min: min, max: max)
+}
+
+// Functions for max value calculation
+#let _max-value-fn = (
+ basic: (data, min: 0) => {
+ calc.max(min, ..data.map(t => _minmax-value(t).max))
+ },
+ clustered: (data, min: 0) => {
+ calc.max(min, ..data.map(t => _minmax-value(t).max))
+ },
+ stacked: (data, min: 0) => {
+ calc.max(min, ..data.map(t => t.at(1).sum()))
+ },
+ stacked100: (.., min: 0) => {min + 100}
+)
+
+// Functions for min value calculation
+#let _min-value-fn = (
+ basic: (data, min: 0) => {
+ calc.min(min, ..data.map(t => _minmax-value(t).min))
+ },
+ clustered: (data, min: 0) => {
+ calc.min(min, ..data.map(t => _minmax-value(t).min))
+ },
+ stacked: (data, min: 0) => {
+ calc.min(min, ..data.map(t => t.at(1).sum()))
+ },
+ stacked100: (.., min: 0) => {min}
+)
+
+#let _prepare(self, ctx) = {
+ return self
+}
+
+#let _get-x-offset(position, width) = {
+ if position == "start" { 0 }
+ else if position == "end" { width }
+ else { width / 2 }
+}
+
+#let _draw-rects(filling, self, ctx, ..args) = {
+ let x-axis = ctx.x
+ let y-axis = ctx.y
+
+ let bars = ()
+ let errors = ()
+
+ let w = self.bar-width
+ for d in self.data {
+ let (x, n, len, y-min, y-max, err) = d
+
+ let w = self.bar-width
+ let gap = self.cluster-gap * if w > 0 { -1 } else { +1 }
+ w += gap * (len - 1)
+
+ let x-offset = _get-x-offset(self.bar-position, self.bar-width)
+ x-offset += gap * n
+
+ let left = x - x-offset
+ let right = left + w
+ let width = (right - left) / len
+
+ if self.mode in ("basic", "clustered") {
+ left = left + width * n
+ right = left + width
+ }
+
+ if (left <= x-axis.max and right >= x-axis.min and
+ y-min <= y-axis.max and y-max >= y-axis.min) {
+ left = calc.max(left, x-axis.min)
+ right = calc.min(right, x-axis.max)
+ y-min = calc.max(y-min, y-axis.min)
+ y-max = calc.min(y-max, y-axis.max)
+
+ draw.rect((left, y-min), (right, y-max))
+
+ if not filling and err != 0 {
+ let y-whisker-size = self.whisker-size * ctx.x-scale
+ draw-errorbar(((left + right) / 2, y-max),
+ 0, err, 0, y-whisker-size / 2, self.style + self.error-style)
+ }
+ }
+ }
+}
+
+#let _stroke(self, ctx) = {
+ _draw-rects(false, self, ctx, fill: none)
+}
+
+#let _fill(self, ctx) = {
+ _draw-rects(true, self, ctx, stroke: none)
+}
+
+/// Add a bar- or column-chart to the plot
+///
+/// A bar- or column-chart is a chart where values are drawn as rectangular boxes.
+///
+/// - data (array): Array of data items. An item is an array containing a x an one or more y values.
+/// For example `(0, 1)` or `(0, 10, 5, 30)`. Depending on the `mode`, the data items
+/// get drawn as either clustered or stacked rects.
+/// - x-key (int,string): Key to use for retrieving a bars x-value from a single data entry.
+/// This value gets passed to the `.at(...)` function of a data item.
+/// - y-key (auto,int,string,array): Key to use for retrieving a bars y-value. For clustered/stacked
+/// data, this must be set to a list of keys (e.g. `range(1, 4)`). If set to `auto`, att but the first
+/// array-values of a data item are used as y-values.
+/// - error-key (none,int,string,array): Key(s) to use for retrieving a bars y-error.
+/// - mode (string): The mode on how to group data items into bars:
+/// / basic: Add one bar per data value. If the data contains multiple values,
+/// group those bars next to each other.
+/// / clustered: Like "basic", but take into account the maximum number of values of all items
+/// and group each cluster of bars together having the width of the widest cluster.
+/// / stacked: Stack bars of subsequent item values onto the previous bar, generating bars
+/// with the height of the sume of all an items values.
+/// / stacked100: Like "stacked", but scale each bar to height $100$, making the different
+/// bars percentages of the sum of an items values.
+/// - labels (none,content,array): A single legend label for "basic" bar-charts, or a
+/// a list of legend labels per bar category, if the mode is one of "clustered", "stacked" or "stacked100".
+/// - bar-width (float): Width of one data item on the y axis
+/// - bar-position (string): Positioning of data items relative to their x value.
+/// - "start": The lower edge of the data item is on the x value (left aligned)
+/// - "center": The data item is centered on the x value
+/// - "end": The upper edge of the data item is on the x value (right aligned)
+/// - cluster-gap (float): Spacing between bars insides a cluster.
+/// - style (dictionary): Plot style
+/// - axes (axes): Plot axes. To draw a horizontal growing bar chart, you can swap the x and y axes.
+#let add-bar(data,
+ x-key: 0,
+ y-key: auto,
+ error-key: none,
+ mode: "basic",
+ labels: none,
+ bar-width: 1,
+ bar-position: "center",
+ cluster-gap: 0,
+ whisker-size: .25,
+ error-style: (:),
+ style: (:),
+ axes: ("x", "y")) = {
+ assert(mode in ("basic", "clustered", "stacked", "stacked100"),
+ message: "Mode must be basic, clustered, stacked or stacked100, but is " + mode)
+ assert(bar-position in ("start", "center", "end"),
+ message: "Invalid bar-position '" + bar-position + "'. Allowed values are: start, center, end")
+ assert(bar-width != 0,
+ message: "Option bar-width must be != 0, but is " + str(bar-width))
+ if error-key != none {
+ assert(y-key != auto,
+ message: "Bar value-key must be set != auto if error-key is set")
+ assert(mode in ("basic", "clustered"),
+ message: "Error bars are supported for basic or clustered only, got " + mode)
+ }
+
+ // Transform data to (x, y, error) triplets
+ let data = data.map(row => _transform-row(row, x-key, y-key, error-key))
+
+ let n = util.max(..data.map(d => d.at(1).len()))
+ let x-offset = _get-x-offset(bar-position, bar-width)
+ let x-domain = (util.min(..data.map(d => d.at(0))) - x-offset,
+ util.max(..data.map(d => d.at(0))) - x-offset + bar-width)
+ let y-domain = (_min-value-fn.at(mode)(data),
+ _max-value-fn.at(mode)(data))
+
+ // For stacked 100%, multiply each column/bar
+ if mode == "stacked100" {
+ data = data.map(((x, y, err)) => {
+ let f = 100 / y.sum()
+ return (x, y.map(v => v * f), err)
+ })
+ }
+
+ // Transform data from (x, ..y) to (x, n, len, y-min, y-max) per y
+ let stacked = mode in ("stacked", "stacked100")
+ let clustered = mode == "clustered"
+ let bar-data = if mode == "basic" {
+ range(0, data.len()).map(_ => ())
+ } else {
+ range(0, n).map(_ => ())
+ }
+
+ let j = 0
+ for (x, y, err) in data {
+ let len = if clustered { n } else { y.len() }
+ let sum = 0
+ for (i, y) in y.enumerate() {
+ let err = err.at(i, default: 0)
+ if stacked {
+ bar-data.at(i).push((x, i, len, sum, sum + y, err))
+ } else if clustered {
+ bar-data.at(i).push((x, i, len, 0, y, err))
+ } else {
+ bar-data.at(j).push((x, i, len, 0, y, err))
+ }
+ sum += y
+ }
+ j += 1
+ }
+
+ let labels = if type(labels) == array { labels } else { (labels,) }
+ range(0, bar-data.len()).map(i => (
+ type: "bar",
+ label: labels.at(i, default: none),
+ axes: axes,
+ mode: mode,
+ data: bar-data.at(i),
+ x-domain: x-domain,
+ y-domain: y-domain,
+ style: style,
+ bar-width: bar-width,
+ bar-position: bar-position,
+ cluster-gap: cluster-gap,
+ whisker-size: whisker-size,
+ error-style: error-style,
+ plot-prepare: _prepare,
+ plot-stroke: _stroke,
+ plot-fill: _fill,
+ plot-legend-preview: self => {
+ draw.rect((0,0), (1,1), ..self.style)
+ }
+ ))
+}
diff --git a/render/packages/preview/cetz-plot/0.1.4/src/plot/boxwhisker.typ b/render/packages/preview/cetz-plot/0.1.4/src/plot/boxwhisker.typ
new file mode 100644
index 0000000..fcdb91b
--- /dev/null
+++ b/render/packages/preview/cetz-plot/0.1.4/src/plot/boxwhisker.typ
@@ -0,0 +1,118 @@
+#import "/src/cetz.typ": draw, util
+
+/// Add one or more box or whisker plots
+///
+/// ```cexample
+/// plot.plot(size: (2,2), x-tick-step: none, y-tick-step: none, {
+/// plot.add-boxwhisker((x: 1, // Location on x-axis
+/// outliers: (7, 65, 69), // Optional outlier values
+/// min: 15, max: 60, // Minimum and maximum
+/// q1: 25, // Quartiles: Lower
+/// q2: 35, // Median
+/// q3: 50)) // Upper
+/// })
+/// ```
+///
+/// - data (array, dictionary): dictionary or array of dictionaries containing the
+/// needed entries to plot box and whisker plot.
+///
+/// The following fields are supported:
+/// - `x` (number) X-axis value
+/// - `min` (number) Minimum value
+/// - `max` (number) Maximum value
+/// - `q1`, `q2`, `q3` (number) Quartiles from lower to to upper
+/// - `outliers` (array of number) Optional outliers
+///
+/// - axes (array): Name of the axes to use ("x", "y"), note that not all
+/// plot styles are able to display a custom axis!
+/// - style (style): Style to use, can be used with a palette function
+/// - box-width (float): Width from edge-to-edge of the box of the box and whisker in plot units. Defaults to 0.75
+/// - whisker-width (float): Width from edge-to-edge of the whisker of the box and whisker in plot units. Defaults to 0.5
+/// - mark (string): Mark to use for plotting outliers. Set `none` to disable. Defaults to "x"
+/// - mark-size (float): Size of marks for plotting outliers. Defaults to 0.15
+/// - label (none,content): Legend label to show for this plot.
+#let add-boxwhisker(data,
+ label: none,
+ axes: ("x", "y"),
+ style: (:),
+ box-width: 0.75,
+ whisker-width: 0.5,
+ mark: "*",
+ mark-size: 0.15) = {
+ // Add multiple boxes as multiple calls to
+ // add-boxwhisker
+ if type(data) == array {
+ for it in data {
+ add-boxwhisker(
+ it,
+ axes:axes,
+ style: style,
+ box-width: box-width,
+ whisker-width: whisker-width,
+ mark: mark,
+ mark-size: mark-size)
+ }
+ return
+ }
+
+ assert("x" in data, message: "Specify 'x', the x value at which to display the box and whisker")
+ assert("q1" in data, message: "Specify 'q1', the lower quartile")
+ assert("q2" in data, message: "Specify 'q2', the median")
+ assert("q3" in data, message: "Specify 'q3', the upper quartile")
+ assert("min" in data, message: "Specify 'min', the minimum excluding outliers")
+ assert("max" in data, message: "Specify 'max', the maximum excluding outliers")
+ assert(data.q1 <= data.q2 and data.q2 <= data.q3,
+ message: "The quartiles q1, q2 and q3 must follow q1 < q2 < q3")
+ assert(data.min <= data.q1 and data.max >= data.q2,
+ message: "The minimum and maximum must be <= q1 and >= q3")
+
+ // Y domain
+ let max-value = util.max(data.max, ..data.at("outliers", default: ()))
+ let min-value = util.min(data.min, ..data.at("outliers", default: ()))
+
+ let prepare(self, ctx) = {
+ return self
+ }
+
+ let stroke(self, ctx) = {
+ let data = self.bw-data
+
+ // Box
+ draw.rect((data.x - box-width / 2, data.q1),
+ (data.x + box-width / 2, data.q3),
+ ..self.style)
+
+ // Mean
+ draw.line((data.x - box-width / 2, data.q2),
+ (data.x + box-width / 2, data.q2),
+ ..self.style)
+
+ // whiskers
+ let whisker(x, start, end) = {
+ draw.line((x, start),(x, end),..self.style)
+ draw.line((x - whisker-width / 2, end),(x + whisker-width / 2, end), ..self.style)
+ }
+ whisker(data.x, data.q3, data.max)
+ whisker(data.x, data.q1, data.min)
+ }
+
+ ((
+ type: "boxwhisker",
+ label: label,
+ axes: axes,
+ bw-data: data,
+ style: style,
+ plot-prepare: prepare,
+ plot-stroke: stroke,
+ x-domain: (data.x - calc.max(whisker-width, box-width),
+ data.x + calc.max(whisker-width, box-width)),
+ y-domain: (min-value, max-value),
+ ) + (if "outliers" in data { (
+ type: "boxwhisker-outliers",
+ data: data.outliers.map(it => (data.x, it)),
+ axes: axes,
+ mark: mark,
+ mark-size: mark-size,
+ mark-style: (:)
+ ) }),)
+}
diff --git a/render/packages/preview/cetz-plot/0.1.4/src/plot/contour.typ b/render/packages/preview/cetz-plot/0.1.4/src/plot/contour.typ
new file mode 100644
index 0000000..94b6b56
--- /dev/null
+++ b/render/packages/preview/cetz-plot/0.1.4/src/plot/contour.typ
@@ -0,0 +1,370 @@
+#import "/src/cetz.typ": draw
+
+#import "util.typ"
+#import "sample.typ"
+
+// Find contours of a 2D array by using marching squares algorithm
+//
+// - data (array): A 2D array of floats where the first index is the row and the second index is the column
+// - offset (float): Z value threshold of a cell compare with `op` to, to count as true
+// - op (auto,string,function): Z value comparison oparator:
+// / `">", ">=", "<", "<=", "!=", "=="`: Use the passed operator to compare z.
+// / `auto`: Use ">=" for positive z values, "<=" for negative z values.
+// / `<function>`: If set to a function, that function gets called
+// with two arguments, the z value `z1` to compare against and
+// the z value `z2` of the data and must return a boolean: `(z1, z2) => boolean`.
+// - interpolate (bool): Enable cell interpolation for smoother lines
+// - connect-domain (bool): Treat the sample domain boundary as an exterior edge.
+// This closes regions against the plot boundary, which is useful for fills but
+// not for contour lines.
+// - contour-limit (int): Contour limit after which the algorithm panics
+// -> array: Array of contour point arrays
+#let find-contours(data,
+ offset,
+ op: auto,
+ interpolate: true,
+ connect-domain: false,
+ contour-limit: 50) = {
+ assert(data != none and type(data) == array,
+ message: "Data must be of type array")
+ assert(type(offset) in (int, float),
+ message: "Offset must be numeric")
+
+ let n-rows = data.len()
+ let n-cols = data.at(0).len()
+ if n-rows < 2 or n-cols < 2 {
+ return ()
+ }
+
+ assert(op == auto or type(op) in (str, function),
+ message: "Operator must be of type auto, string or function")
+ if op == auto {
+ op = if offset < 0 { "<=" } else { ">=" }
+ }
+ if type(op) == str {
+ assert(op in ("<", "<=", ">", ">=", "==", "!="),
+ message: "Operator must be one of: <, <=, >, >=, != or ==")
+ }
+
+ // Return if data is set
+ let is-set = if type(op) == function {
+ v => op(offset, v)
+ } else if op == "==" {
+ v => v == offset
+ } else if op == "!=" {
+ v => v != offset
+ } else if op == "<" {
+ v => v < offset
+ } else if op == "<=" {
+ v => v <= offset
+ } else if op == ">" {
+ v => v > offset
+ } else if op == ">=" {
+ v => v >= offset
+ }
+
+ // Build a binary map that has 0 for unset and 1 for set cells
+ let bin-data = data.map(r => r.map(is-set))
+
+ // Get case (0 to 15)
+ let get-case(tl, tr, bl, br) = {
+ int(tl) * 8 + int(tr) * 4 + int(br) * 2 + int(bl)
+ }
+
+ let lerp(a, b) = {
+ if a == b { return a }
+ else if a == none { return 1 }
+ else if b == none { return 0 }
+ return (offset - a) / (b - a)
+ }
+
+ let segments = ()
+ let x-range = if connect-domain { range(-1, n-cols) } else { range(0, n-cols - 1) }
+ let y-range = if connect-domain { range(-1, n-rows) } else { range(0, n-rows - 1) }
+
+ // Get binary data at x, y
+ let get-bin(x, y) = {
+ if x >= 0 and x < n-cols and y >= 0 and y < n-rows {
+ return bin-data.at(y).at(x)
+ }
+ return false
+ }
+
+ // Get data point for x, y coordinate
+ let get-data(x, y) = {
+ if x >= 0 and x < n-cols and y >= 0 and y < n-rows {
+ return float(data.at(y).at(x))
+ }
+ return none
+ }
+
+ for y in y-range {
+ for x in x-range {
+ let tl = get-bin(x, y)
+ let tr = get-bin(x + 1, y)
+ let bl = get-bin(x, y + 1)
+ let br = get-bin(x + 1, y + 1)
+
+ // Corner data
+ //
+ // nw-----ne
+ // | |
+ // | |
+ // | |
+ // sw-----se
+ let nw = get-data(x, y)
+ let ne = get-data(x + 1, y)
+ let se = get-data(x + 1, y + 1)
+ let sw = get-data(x, y + 1)
+
+ // Interpolated edge points
+ //
+ // +-- a --+
+ // | |
+ // d b
+ // | |
+ // +-- c --+
+ let a = (x + .5, y)
+ let b = (x + 1, y + .5)
+ let c = (x + .5, y + 1)
+ let d = (x, y + .5)
+ if interpolate {
+ a = (x + lerp(nw, ne), y)
+ b = (x + 1, y + lerp(ne, se))
+ c = (x + lerp(sw, se), y + 1)
+ d = (x, y + lerp(nw, sw))
+ }
+
+ let case = get-case(tl, tr, bl, br)
+ if case in (1, 14) {
+ segments.push((d, c))
+ } else if case in (2, 13) {
+ segments.push((b, c))
+ } else if case in (3, 12) {
+ segments.push((d, b))
+ } else if case in (4, 11) {
+ segments.push((a, b))
+ } else if case == 5 {
+ segments.push((d, a))
+ segments.push((c, b))
+ } else if case in (6, 9) {
+ segments.push((c, a))
+ } else if case in (7, 8) {
+ segments.push((d, a))
+ } else if case == 10 {
+ segments.push((a, b))
+ segments.push((c, d))
+ }
+ }
+ }
+
+ // Join lines to one or more contours
+ // This is done by searching for the next line
+ // that starts at the current contours head or tail
+ // point. If found, push the other coordinate to
+ // the contour. If no line could be found, push a
+ // new contour.
+ let contours = ()
+ while segments.len() > 0 {
+ if contours.len() == 0 {
+ contours.push(segments.remove(0))
+ }
+
+ let found = false
+
+ let i = 0
+ while i < segments.len() {
+ let (a, b) = segments.at(i)
+ let (h, t) = (contours.last().first(),
+ contours.last().last())
+ if a == t {
+ contours.last().push(b)
+ segments.remove(i)
+ found = true
+ } else if b == t {
+ contours.last().push(a)
+ segments.remove(i)
+ found = true
+ } else if a == h {
+ contours.last().insert(0, b)
+ segments.remove(i)
+ found = true
+ } else if b == h {
+ contours.last().insert(0, a)
+ segments.remove(i)
+ found = true
+ } else {
+ i += 1
+ }
+ }
+
+ // Insert the next contour
+ if not found {
+ contours.push(segments.remove(0))
+ }
+
+ // Check limit
+ assert(contours.len() <= contour-limit,
+ message: "Countour limit reached! Raise contour-limit if you " +
+ "think this is not an error")
+ }
+
+ return contours
+}
+
+// Convert contour data points from sample-space to plot coordinates.
+#let _scale-contours(contours, x-min, y-min, dx, dy, z) = {
+ contours.map(contour => (
+ z: z,
+ line-data: contour.map(pt => (
+ pt.at(0) * dx + x-min,
+ pt.at(1) * dy + y-min,
+ )),
+ ))
+}
+
+// Prepare line data
+#let _prepare(self, ctx) = {
+ let (x, y) = (ctx.x, ctx.y)
+
+ self.stroke-contours = self.stroke-contours.map(c => {
+ c.stroke-paths = util.compute-stroke-paths(c.line-data, x, y)
+ return c
+ })
+
+ if self.fill {
+ self.fill-contours = self.fill-contours.map(c => {
+ c.fill-paths = util.compute-fill-paths(c.line-data, x, y)
+ return c
+ })
+ }
+
+ return self
+}
+
+// Stroke line data
+#let _stroke(self, ctx) = {
+ for c in self.stroke-contours {
+ for p in c.stroke-paths {
+ draw.line(..p, fill: none, close: p.first() == p.last())
+ }
+ }
+}
+
+// Fill line data
+#let _fill(self, ctx) = {
+ if not self.fill { return }
+ for c in self.fill-contours {
+ for p in c.fill-paths {
+ draw.line(..p, stroke: none, close: p.first() == p.last())
+ }
+ }
+}
+
+/// Add a contour plot of a sampled function or a matrix.
+///
+/// ```cexample
+/// plot.plot(size: (2,2), x-tick-step: none, y-tick-step: none, {
+/// plot.add-contour(x-domain: (-3, 3), y-domain: (-3, 3),
+/// style: (fill: rgb(50,50,250,50)),
+/// fill: true,
+/// op: "<", // Find contours where data < z
+/// z: (2.5, 2, 1), // Z values to find contours for
+/// (x, y) => calc.sqrt(x * x + y * y))
+/// })
+/// ```
+///
+/// - data (array, function): A function of the signature `(x, y) => z`
+/// or an array of arrays of floats (a matrix) where the first
+/// index is the row and the second index is the column.
+/// - z (float, array): Z values to plot. Contours containing values
+/// above z (z >= 0) or below z (z < 0) get plotted.
+/// If you specify multiple z values, they get plotted in the order of specification.
+/// - x-domain (domain): X axis domain used if `data` is a function, that is the
+/// domain inside the function gets sampled.
+/// - y-domain (domain): Y axis domain used if `data` is a function, see `x-domain`.
+/// - x-samples (int): X axis domain samples (2 < n). Note that contour finding
+/// can be quite slow. Using a big sample count can improve accuracy but can
+/// also lead to bad compilation performance.
+/// - y-samples (int): Y axis domain samples (2 < n)
+/// - interpolate (bool): Use linear interpolation between sample values which can
+/// improve the resulting plot, especially if the contours are curved.
+/// - op (auto,string,function): Z value comparison oparator:
+/// / `">", ">=", "<", "<=", "!=", "=="`: Use the operator for comparison of `z` to
+/// the values from `data`.
+/// / `auto`: Use ">=" for positive z values, "<=" for negative z values.
+/// / `<function>`: Call comparison function of the format `(plot-z, data-z) => boolean`,
+/// where `plot-z` is the z-value from the plots `z` argument and `data-z`
+/// is the z-value of the data getting plotted. The function must return true
+/// if at the combinations of arguments a contour is detected.
+/// - fill (bool): Fill each contour
+/// - style (style): Style to use for plotting, can be used with a palette function. Note
+/// that all z-levels use the same style!
+/// - axes (axes): Name of the axes to use for plotting.
+/// - limit (int): Limit of contours to create per z value before the function panics
+/// - label (none,content): Plot legend label to show. The legend preview for
+/// contour plots is a little rectangle drawn with the contours style.
+#let add-contour(data,
+ label: none,
+ z: (1,),
+ x-domain: (0, 1),
+ y-domain: (0, 1),
+ x-samples: 25,
+ y-samples: 25,
+ interpolate: true,
+ op: auto,
+ axes: ("x", "y"),
+ style: (:),
+ fill: false,
+ limit: 50,
+ ) = {
+ // Sample a x/y function
+ if type(data) == function {
+ data = sample.sample-fn2(data,
+ x-domain, y-domain,
+ x-samples, y-samples)
+ }
+
+ // Find matrix dimensions
+ assert(type(data) == array)
+ let (x-min, x-max) = x-domain
+ let dx = (x-max - x-min) / (data.at(0).len() - 1)
+ let (y-min, y-max) = y-domain
+ let dy = (y-max - y-min) / (data.len() - 1)
+
+ let stroke-contours = ()
+ let fill-contours = ()
+ let z = if type(z) == array { z } else { (z,) }
+ for z in z {
+ stroke-contours += _scale-contours(
+ find-contours(data, z, op: op, interpolate: interpolate, contour-limit: limit),
+ x-min, y-min, dx, dy, z)
+
+ if fill {
+ fill-contours += _scale-contours(
+ find-contours(data, z, op: op, interpolate: interpolate, connect-domain: true, contour-limit: limit),
+ x-min, y-min, dx, dy, z)
+ }
+ }
+
+ return ((
+ type: "contour",
+ label: label,
+ stroke-contours: stroke-contours,
+ fill-contours: fill-contours,
+ axes: axes,
+ x-domain: x-domain,
+ y-domain: y-domain,
+ style: style,
+ fill: fill,
+ mark: none,
+ mark-style: none,
+ plot-prepare: _prepare,
+ plot-stroke: _stroke,
+ plot-fill: _fill,
+ plot-legend-preview: self => {
+ if not self.fill { self.style.fill = none }
+ draw.rect((0,0), (1,1), ..self.style)
+ }
+ ),)
+}
diff --git a/render/packages/preview/cetz-plot/0.1.4/src/plot/errorbar.typ b/render/packages/preview/cetz-plot/0.1.4/src/plot/errorbar.typ
new file mode 100644
index 0000000..88dc8fa
--- /dev/null
+++ b/render/packages/preview/cetz-plot/0.1.4/src/plot/errorbar.typ
@@ -0,0 +1,118 @@
+#import "/src/cetz.typ": draw, util, vector
+
+#let _draw-whisker(pt, dir, ..style) = {
+ let a = vector.add(pt, vector.scale(dir, -1))
+ let b = vector.add(pt, vector.scale(dir, +1))
+
+ draw.line(a, b, ..style)
+}
+
+#let draw-errorbar(pt, x, y, x-whisker-size, y-whisker-size, style) = {
+ if type(x) != array { x = (-x, x) }
+ if type(y) != array { y = (-y, y) }
+
+ let (x-min, x-max) = x
+ let x-min-pt = vector.add(pt, (x-min, 0))
+ let x-max-pt = vector.add(pt, (x-max, 0))
+ if x-min != 0 or x-max != 0 {
+ draw.line(x-min-pt, x-max-pt, ..style)
+ if x-whisker-size > 0 {
+ if x-min != 0 {
+ _draw-whisker(x-min-pt, (0, x-whisker-size), ..style)
+ }
+ if x-max != 0 {
+ _draw-whisker(x-max-pt, (0, x-whisker-size), ..style)
+ }
+ }
+ }
+
+ let (y-min, y-max) = y
+ let y-min-pt = vector.add(pt, (0, y-min))
+ let y-max-pt = vector.add(pt, (0, y-max))
+ if y-min != 0 or y-max != 0 {
+ draw.line(y-min-pt, y-max-pt, ..style)
+ if y-whisker-size > 0 {
+ if y-min != 0 {
+ _draw-whisker(y-min-pt, (y-whisker-size, 0), ..style)
+ }
+ if y-max != 0 {
+ _draw-whisker(y-max-pt, (y-whisker-size, 0), ..style)
+ }
+ }
+ }
+}
+
+#let _prepare(self, ctx) = {
+ return self
+}
+
+#let _stroke(self, ctx) = {
+ let x-whisker-size = self.whisker-size * ctx.y-scale
+ let y-whisker-size = self.whisker-size * ctx.x-scale
+
+ draw-errorbar((self.x, self.y),
+ self.x-error, self.y-error,
+ x-whisker-size, y-whisker-size,
+ self.style)
+}
+
+/// Add x- and/or y-error bars
+///
+/// - pt (tuple): Error-bar center coordinate tuple: `(x, y)`
+/// - x-error (float,tuple): Single error or tuple of errors along the x-axis
+/// - y-error (float,tuple): Single error or tuple of errors along the y-axis
+/// - mark (none,string): Mark symbol to show at the error position (`pt`).
+/// - mark-size (number): Size of the mark symbol.
+/// - mark-style (style): Extra style to apply to the mark symbol.
+/// - whisker-size (float): Width of the error bar whiskers in canvas units.
+/// - style (dictionary): Style for the error bars
+/// - label (none,content): Label to tsh
+/// - axes (axes): Plot axes. To draw a horizontal growing bar chart, you can swap the x and y axes.
+#let add-errorbar(pt,
+ x-error: 0,
+ y-error: 0,
+ label: none,
+ mark: "o",
+ mark-size: .2,
+ mark-style: (:),
+ whisker-size: .5,
+ style: (:),
+ axes: ("x", "y")) = {
+ assert(x-error != 0 or y-error != 0,
+ message: "Either x-error or y-error must be set.")
+
+ let (x, y) = pt
+
+ if type(x-error) != array {
+ x-error = (x-error, x-error)
+ }
+ if type(y-error) != array {
+ y-error = (y-error, y-error)
+ }
+
+ x-error.at(0) = calc.abs(x-error.at(0)) * -1
+ y-error.at(0) = calc.abs(y-error.at(0)) * -1
+
+ let x-domain = x-error.map(v => v + x)
+ let y-domain = y-error.map(v => v + y)
+
+ return ((
+ type: "errorbar",
+ label: label,
+ axes: axes,
+ data: ((x,y),),
+ x: x,
+ y: y,
+ x-error: x-error,
+ y-error: y-error,
+ x-domain: x-domain,
+ y-domain: y-domain,
+ mark: mark,
+ mark-size: mark-size,
+ mark-style: mark-style,
+ whisker-size: whisker-size,
+ style: style,
+ plot-prepare: _prepare,
+ plot-stroke: _stroke,
+ ),)
+}
diff --git a/render/packages/preview/cetz-plot/0.1.4/src/plot/formats.typ b/render/packages/preview/cetz-plot/0.1.4/src/plot/formats.typ
new file mode 100644
index 0000000..bb43902
--- /dev/null
+++ b/render/packages/preview/cetz-plot/0.1.4/src/plot/formats.typ
@@ -0,0 +1,164 @@
+// Compare two floats
+#let _compare(a, b, eps: 1e-6) = {
+ return calc.abs(a - b) <= eps
+}
+
+// Pre-computed table of fractions
+#let _common-denoms = range(2, 11 + 1).map(d => {
+ (d, range(1, d).map(n => n/d))
+})
+
+#let _find-fraction(v, denom: auto, eps: 1e-6) = {
+ let i = calc.floor(v)
+ let f = v - i
+ if _compare(f, 0, eps: eps) {
+ return $#v$
+ }
+
+ let denom = if denom != auto {
+ for n in range(1, denom) {
+ if _compare(f, n/denom, eps: eps) {
+ denom
+ }
+ }
+ } else {
+ (() => {
+ for ((denom, tab)) in _common-denoms {
+ for vv in tab {
+ if _compare(f, vv, eps: eps) {
+ return denom
+ }
+ }
+ }
+ })()
+ }
+
+ if denom != none {
+ return if v < 0 { $-$ } else {} + $#calc.round(calc.abs(v) * denom)/#denom$
+ }
+}
+
+/// Fraction tick formatter
+///
+/// ```cexample
+/// plot.plot(size: (5,1),
+/// x-format: plot.formats.fraction,
+/// x-tick-step: 1/5,
+/// y-tick-step: none, {
+/// plot.add(calc.sin, domain: (-1, 1))
+/// })
+/// ```
+///
+/// - value (number): Value to format
+/// - denom (auto, int): Denominator for result fractions. If set to `auto`,
+/// a hardcoded fraction table is used for finding fractions with a
+/// denominator <= 11.
+/// - eps (number): Epsilon used for comparison
+/// -> Content if a matching fraction could be found or none
+#let fraction(value, denom: auto, eps: 1e-6) = {
+ return _find-fraction(value, denom: denom, eps: eps)
+}
+
+/// Multiple of tick formatter
+///
+/// ```cexample
+/// plot.plot(size: (5,1),
+/// x-format: plot.formats.multiple-of,
+/// x-tick-step: calc.pi/4,
+/// y-tick-step: none, {
+/// plot.add(calc.sin, domain: (-calc.pi, 1.5 * calc.pi))
+/// })
+/// ```
+///
+/// - value (number): Value to format
+/// - factor (number): Factor value is expected to be a multiple of.
+/// - symbol (content): Suffix symbol. For `value` = 0, the symbol is not
+/// appended.
+/// - fraction (none, true, int): If not none, try finding matching fractions
+/// using the same mechanism as `fraction`. If set to an integer, that integer
+/// is used as denominator. If set to `none` or `false`, or if no fraction
+/// could be found, a real number with `digits` digits is used.
+/// - digits (int): Number of digits to use for rounding
+/// - eps (number): Epsilon used for comparison
+/// - prefix (content): Content to prefix
+/// - suffix (content): Content to append
+/// -> Content if a matching fraction could be found or none
+#let multiple-of(value, factor: calc.pi, symbol: $pi$, fraction: true, digits: 2, eps: 1e-6, prefix: [], suffix: []) = {
+ if _compare(value, 0, eps: eps) {
+ return $0$
+ }
+
+ let a = value / factor
+ if _compare(a, 1, eps: eps) {
+ return prefix + symbol + suffix
+ } else if _compare(a, -1, eps: eps) {
+ return prefix + $-$ + symbol + suffix
+ }
+
+ if fraction != none {
+ let frac = _find-fraction(a, denom: if fraction == true { auto } else { fraction })
+ if frac != none {
+ return prefix + frac + symbol + suffix
+ }
+ }
+
+ return prefix + $#calc.round(a, digits: digits)$ + symbol + suffix
+}
+
+/// Scientific notation tick formatter
+///
+/// ```cexample
+/// plot.plot(size: (5,1),
+/// x-format: plot.formats.sci,
+/// x-tick-step: 1e3,
+/// y-tick-step: none, {
+/// plot.add(x => x, domain: (-2e3, 2e3))
+/// })
+/// ```
+///
+/// - value (number): Value to format
+/// - digits (int): Number of digits for rounding the factor
+/// - prefix (content): Content to prefix
+/// - suffix (content): Content to append
+/// -> Content
+#let sci(value, digits: 2, prefix: [], suffix: []) = {
+ let exponent = if value != 0 {
+ calc.floor(calc.log(calc.abs(value), base: 10))
+ } else {
+ 0
+ }
+
+ let ee = calc.pow(10.0, calc.abs(exponent + 1))
+ if exponent > 0 {
+ value = value / ee * 10
+ } else if exponent < 0 {
+ value = value * ee * 10
+ }
+
+ value = calc.round(value, digits: digits)
+ if exponent <= -1 or exponent >= 1 {
+ return prefix + $#value times 10^#exponent$ + suffix
+ }
+
+ return prefix + $#value$ + suffix
+}
+
+/// Rounded decimal number formatter
+///
+/// ```cexample
+/// plot.plot(size: (5,1),
+/// x-format: plot.formats.decimal,
+/// x-tick-step: .5,
+/// y-tick-step: none, {
+/// plot.add(x => x, domain: (-1, 1))
+/// })
+/// ```
+///
+/// - value (number): Value to format
+/// - digits (int): Number of digits to round to
+/// - prefix (content): Content to prefix
+/// - suffix (content): Content to append
+/// -> Content
+#let decimal(value, digits: 2, prefix: [], suffix: []) = {
+ prefix + $#calc.round(value, digits: digits)$ + suffix
+}
diff --git a/render/packages/preview/cetz-plot/0.1.4/src/plot/legend.typ b/render/packages/preview/cetz-plot/0.1.4/src/plot/legend.typ
new file mode 100644
index 0000000..94838d4
--- /dev/null
+++ b/render/packages/preview/cetz-plot/0.1.4/src/plot/legend.typ
@@ -0,0 +1,242 @@
+#import "/src/cetz.typ"
+#import cetz: draw, styles
+#import draw: group
+
+#import "mark.typ": draw-mark-shape
+
+#let default-style = (
+ orientation: ttb,
+ default-position: "north-east",
+ layer: 1, // Legend layer
+ fill: rgb(255,255,255,200), // Legend background
+ stroke: black, // Legend border
+ padding: .1, // Legend border padding
+ offset: (0, 0), // Legend displacement
+ spacing: .1, // Spacing between anchor and legend
+ item: (
+ radius: 0,
+ spacing: 0, // Extra spacing between items
+ preview: (
+ width: .75, // Preview width
+ height: .3, // Preview height
+ margin: .1 // Distance between preview and label
+ )
+ ),
+ radius: 0,
+ scale: 100%,
+)
+
+// Map position to legend group anchor
+#let auto-group-anchor = (
+ inner-north-west: "north-west",
+ inner-north: "north",
+ inner-north-east: "north-east",
+ inner-south-west: "south-west",
+ inner-south: "south",
+ inner-south-east: "south-east",
+ inner-west: "west",
+ inner-east: "east",
+ north-west: "north-east",
+ north: "south",
+ north-east: "north-west",
+ south-west: "south-east",
+ south: "north",
+ south-east: "south-west",
+ east: "west",
+ west: "east",
+)
+
+// Generate legend positioning anchors
+#let add-legend-anchors(style, element, size) = {
+ import draw: *
+ let (w, h) = size
+ let (xo, yo) = {
+ let spacing = style.at("spacing", default: (0, 0))
+ if type(spacing) == array {
+ spacing
+ } else {
+ (spacing, spacing)
+ }
+ }
+
+ anchor("north", (rel: (w / 2, yo), to: (element + ".north", "-|", element + ".origin")))
+ anchor("south", (rel: (w / 2, -yo), to: (element + ".south", "-|", element + ".origin")))
+ anchor("east", (rel: (xo, h / 2), to: (element + ".east", "|-", element + ".origin")))
+ anchor("west", (rel: (-xo, h / 2), to: (element + ".west", "|-", element + ".origin")))
+ anchor("north-east", (rel: (xo, h), to: (element + ".north-east", "|-", element + ".origin")))
+ anchor("north-west", (rel: (-xo, h), to: (element + ".north-west", "|-", element + ".origin")))
+ anchor("south-east", (rel: (xo, 0), to: (element + ".south-east", "|-", element + ".origin")))
+ anchor("south-west", (rel: (-xo, 0), to: (element + ".south-west", "|-", element + ".origin")))
+ anchor("inner-north", (rel: (w / 2, h - yo), to: element + ".origin"))
+ anchor("inner-north-east", (rel: (w - xo, h - yo), to: element + ".origin"))
+ anchor("inner-north-west", (rel: (yo, h - yo), to: element + ".origin"))
+ anchor("inner-south", (rel: (w / 2, yo), to: element + ".origin"))
+ anchor("inner-south-east", (rel: (w - xo, yo), to: element + ".origin"))
+ anchor("inner-south-west", (rel: (xo, yo), to: element + ".origin"))
+ anchor("inner-east", (rel: (w - xo, h / 2), to: element + ".origin"))
+ anchor("inner-west", (rel: (xo, h / 2), to: element + ".origin"))
+}
+
+// Draw a generic item preview
+#let draw-generic-preview(item) = {
+ import draw: *
+
+ if item.at("fill", default: false) {
+ rect((0,0), (1,1), ..item.style)
+ } else {
+ line((0,.5), (1,.5), ..item.style)
+ }
+}
+
+/// Construct a legend item for use with the `legend` function
+///
+/// - label (none, auto, content): Legend label or auto to use the enumerated default label
+/// - preview (auto, function): Legend preview icon function of the format `item => elements`.
+/// Note that the canvas bounds for drawing the preview are (0,0) to (1,1).
+/// - mark (none,string): Legend mark symbol
+/// - mark-style (none,dictionary): Mark style
+/// - mark-size (number): Mark size
+/// - ..style (styles): Style keys for the single item
+#let item(label, preview, mark: none, mark-style: (:), mark-size: 1, ..style) = {
+ assert.eq(style.pos().len(), 0,
+ message: "Unexpected positional arguments")
+ return ((label: label, preview: preview,
+ mark: mark, mark-style: mark-style, mark-size: mark-size,
+ style: style.named()),)
+}
+
+/// Draw a legend
+#let legend(position, items, name: "legend", ..style) = group(name: name, ctx => {
+ draw.anchor("default", ())
+ let items = if items != none { items.filter(v => v.label != none) } else { () }
+ if items == () {
+ return
+ }
+
+ let style = styles.resolve(
+ ctx.style, merge: style.named(), base: default-style, root: "legend")
+ assert(style.orientation in (ttb, ltr),
+ message: "Unsupported legend orientation.")
+
+ // Scaling
+ draw.scale(style.scale)
+
+ // Position
+ let position = if position == auto {
+ style.default-position
+ } else {
+ position
+ }
+
+ // Adjust anchor
+ if style.anchor == auto {
+ style.anchor = if type(position) == str {
+ auto-group-anchor.at(position, default: "north-west")
+ } else {
+ "north-west"
+ }
+ }
+
+ // Apply offset
+ if style.offset not in (none, (0,0)) {
+ position = (rel: style.offset, to: position)
+ }
+
+ // Draw items
+ draw.on-layer(style.layer, {
+ draw.group(name: "items", padding: style.padding, ctx => {
+ import draw: *
+
+ set-origin(position)
+ anchor("default", (0,0))
+
+ let pt = (0, 0)
+ for (i, item) in items.enumerate() {
+ let (label, preview) = item
+ if label == none {
+ continue
+ } else if label == auto {
+ label = $ f_(#i) $
+ }
+
+ group({
+ anchor("default", (0,0))
+
+ let row-height = style.item.preview.height
+ let preview-width = style.item.preview.width
+ let preview-a = (0, -row-height / 2)
+ let preview-b = (preview-width, +row-height / 2)
+ let label-west = (preview-width + style.item.preview.margin, 0)
+
+ // Draw item preview
+ let draw-preview = if preview == auto { draw-generic-preview } else { preview }
+ group({ // BUG: scope in group seems to be bugged, we use group instead
+ set-viewport(preview-a, preview-b, bounds: (1, 1, 0))
+ (draw-preview)(item)
+ })
+
+ // Draw mark preview
+ let mark = item.at("mark", default: none)
+ if mark != none {
+ draw-mark-shape((preview-a, 50%, preview-b),
+ calc.min(style.item.preview.width / 2, item.mark-size),
+ mark,
+ item.mark-style)
+ }
+
+ // Draw label
+ content(label-west,
+ text(top-edge: "ascender", bottom-edge: "descender", align(left + horizon, label)),
+ name: "label", anchor: "west")
+ }, name: "item", anchor: if style.orientation == ltr { "west" } else { "north-west" })
+
+ if style.orientation == ttb {
+ set-origin((rel: (0, -style.item.spacing),
+ to: "item.south-west"))
+ } else if style.orientation == ltr {
+ set-origin((rel: (style.item.spacing, 0),
+ to: "item.east"))
+ }
+ }
+ }, anchor: style.anchor)
+ })
+
+ // Fill legend background
+ draw.on-layer(style.layer - .5, {
+ draw.rect("items.south-west",
+ "items.north-east", fill: style.fill, stroke: style.stroke, radius: style.radius)
+ })
+})
+
+/// Function for manually adding a legend item from within
+/// a plot environment
+///
+/// - label (content): Legend label
+/// - preview (auto,function): Legend preview function of the format `() => elements`.
+/// The preview canvas bounds are between (0,0) and (1,1).
+/// If set to `auto`, a straight line is drawn.
+///
+/// ```cexample
+/// plot.plot(size: (1,1), x-tick-step: none, y-tick-step: none, {
+/// plot.add(((0,0), (1,1))) // Some data
+/// plot.add-legend([Custom item], preview: () => {
+/// import cetz.draw: *
+/// circle((.5,.5), radius: .5) // Draw a custom preview
+/// // between (0,0) and (1,1)
+/// })
+/// plot.add-legend([Another item])
+/// })
+/// ```
+#let add-legend(label, preview: auto) = {
+ assert(preview == auto or type(preview) == function,
+ message: "Expected auto or function, got " + repr(type(preview)))
+
+ return ((
+ type: "legend-item",
+ label: label,
+ style: (:),
+ axes: ("x", "y"),
+ ) + if preview != auto {
+ (plot-legend-preview: _ => { preview() })
+ },)
+}
diff --git a/render/packages/preview/cetz-plot/0.1.4/src/plot/line.typ b/render/packages/preview/cetz-plot/0.1.4/src/plot/line.typ
new file mode 100644
index 0000000..aa89623
--- /dev/null
+++ b/render/packages/preview/cetz-plot/0.1.4/src/plot/line.typ
@@ -0,0 +1,527 @@
+#import "/src/cetz.typ": draw
+
+#import "util.typ"
+#import "sample.typ"
+
+// Transform points
+//
+// - data (array): Data points
+// - line (str,dictionary): Line line
+#let transform-lines(data, line) = {
+ let hvh-data(t) = {
+ if type(t) == ratio {
+ t = t / 1%
+ }
+ t = calc.max(0, calc.min(t, 1))
+
+ let pts = ()
+
+ let len = data.len()
+ for i in range(0, len) {
+ pts.push(data.at(i))
+
+ if i < len - 1 {
+ let (a, b) = (data.at(i), data.at(i+1))
+ if t == 0 {
+ pts.push((a.at(0), b.at(1)))
+ } else if t == 1 {
+ pts.push((b.at(0), a.at(1)))
+ } else {
+ let x = a.at(0) + (b.at(0) - a.at(0)) * t
+ pts.push((x, a.at(1)))
+ pts.push((x, b.at(1)))
+ }
+ }
+ }
+ return pts
+ }
+
+ if type(line) == str {
+ line = (type: line)
+ }
+
+ let line-type = line.at("type", default: "raw")
+ assert(line-type in ("raw", "linear", "spline", "vh", "hv", "hvh"))
+
+ // Transform data into line-data
+ let line-data = if line-type == "linear" {
+ return util.linearized-data(data, line.at("epsilon", default: 0))
+ } else if line-type == "spline" {
+ return util.sampled-spline-data(data,
+ line.at("tension", default: .5),
+ line.at("samples", default: 15))
+ } else if line-type == "vh" {
+ return hvh-data(0)
+ } else if line-type == "hv" {
+ return hvh-data(1)
+ } else if line-type == "hvh" {
+ return hvh-data(line.at("mid", default: .5))
+ } else {
+ return data
+ }
+}
+
+// Fill a plot by generating a fill path to y value `to`
+#let fill-segments-to(segments, to) = {
+ for s in segments {
+ let low = calc.min(..s.map(v => v.at(0)))
+ let high = calc.max(..s.map(v => v.at(0)))
+
+ let origin = (low, to)
+ let target = (high, to)
+
+ draw.line(origin, ..s, target, stroke: none)
+ }
+}
+
+// Fill a shape by generating a fill path for each segment
+#let fill-shape(paths) = {
+ for p in paths {
+ draw.line(..p, stroke: none)
+ }
+}
+
+// Prepare line data
+#let _prepare(self, ctx) = {
+ let (x, y) = (ctx.x, ctx.y)
+
+ // Generate stroke paths
+ self.stroke-paths = util.compute-stroke-paths(self.line-data, x, y)
+
+ // Compute fill paths if filling is requested
+ self.hypograph = self.at("hypograph", default: false)
+ self.epigraph = self.at("epigraph", default: false)
+ self.fill = self.at("fill", default: false)
+ if self.hypograph or self.epigraph or self.fill {
+ self.fill-paths = util.compute-fill-paths(self.line-data, x, y)
+ }
+
+ return self
+}
+
+// Stroke line data
+#let _stroke(self, ctx) = {
+ let (x, y) = (ctx.x, ctx.y)
+
+ for p in self.stroke-paths {
+ draw.line(..p, fill: none)
+ }
+}
+
+// Fill line data
+#let _fill(self, ctx) = {
+ let (x, y) = (ctx.x, ctx.y)
+
+ if self.hypograph {
+ fill-segments-to(self.fill-paths, y.min)
+ }
+ if self.epigraph {
+ fill-segments-to(self.fill-paths, y.max)
+ }
+ if self.fill {
+ if self.at("fill-type", default: "axis") == "shape" {
+ fill-shape(self.fill-paths)
+ } else {
+ fill-segments-to(self.fill-paths,
+ calc.max(calc.min(y.max, 0), y.min))
+ }
+ }
+}
+
+/// Add data to a plot environment.
+///
+/// Note: You can use this for scatter plots by setting
+/// the stroke style to `none`: `add(..., style: (stroke: none))`.
+///
+/// Must be called from the body of a `plot(..)` command.
+///
+/// - domain (domain): Domain of `data`, if `data` is a function. Has no effect
+/// if `data` is not a function.
+/// - hypograph (bool): Fill hypograph; uses the `hypograph` style key for
+/// drawing
+/// - epigraph (bool): Fill epigraph; uses the `epigraph` style key for
+/// drawing
+/// - fill (bool): Fill the shape of the plot
+/// - fill-type (string): Fill type:
+/// / `"axis"`: Fill the shape to y = 0
+/// / `"shape"`: Fill the complete shape
+/// - samples (int): Number of times the `data` function gets called for
+/// sampling y-values. Only used if `data` is of type function. This parameter gets
+/// passed onto `sample-fn`.
+/// - sample-at (array): Array of x-values the function gets sampled at in addition
+/// to the default sampling. This parameter gets passed to `sample-fn`.
+/// - line (string, dictionary): Line type to use. The following types are
+/// supported:
+/// / `"raw"`: Plot raw data
+/// / `"linear"`: Linearize data
+/// / `"spline"`: Calculate a Catmull-Rom curve through all points
+/// / `"vh"`: Move vertical and then horizontal
+/// / `"hv"`: Move horizontal and then vertical
+/// / `"hvh"`: Add a vertical step in the middle
+///
+/// If the value is a dictionary, the type must be
+/// supplied via the `type` key. The following extra
+/// attributes are supported:
+/// / `"samples" <int>`: Samples of splines
+/// / `"tension" <float>`: Tension of splines
+/// / `"mid" <float>`: Mid-Point of hvh lines (0 to 1)
+/// / `"epsilon" <float>`: Linearization slope epsilon for
+/// use with `"linear"`, defaults to 0.
+///
+/// ```cexample-vertical
+/// let points(offset: 0) = ((0,0), (1,1), (2,0), (3,1), (4,0)).map(((x,y)) => {
+/// (x,y + offset * 1.5)
+/// })
+/// plot.plot(size: (12, 3), axis-style: none, {
+/// plot.add(points(offset: 5), line: (type: "hvh", mid: .1))
+/// plot.add(points(offset: 4), line: "hvh")
+/// plot.add(points(offset: 3), line: "hv")
+/// plot.add(points(offset: 2), line: "vh")
+/// plot.add(points(offset: 1), line: "spline")
+/// plot.add(points(offset: 0), line: "linear")
+/// })
+/// ```
+///
+/// - style (style): Style to use, can be used with a `palette` function
+/// - axes (axes): Name of the axes to use for plotting. Reversing the axes
+/// means rotating the plot by 90 degrees.
+/// - mark (string): Mark symbol to place at each distinct value of the
+/// graph. Uses the `mark` style key of `style` for drawing:
+///
+/// ```cexample-vertical
+/// let points(offset) = ((offset, 0), (offset, 1))
+///
+/// plot.plot(size: (12, 2), axis-style: none, {
+/// plot.add(points(0), mark: "*") // same as "x"
+/// plot.add(points(1), mark: "square")
+/// plot.add(points(2), mark: "triangle")
+/// plot.add(points(3), mark: "o")
+/// plot.add(points(4), mark: "+")
+/// plot.add(points(5), mark: "-")
+/// plot.add(points(6), mark: "|")
+/// plot.add(points(7), mark: "<>")
+/// plot.add(points(8), mark: 5) // specify an integer to use a regular polygon.
+///
+/// // Alternatively, specify custom function:
+/// plot.add(points(9), mark: (pt, size, style) => {
+/// let top = (to: pt, rel: (0, size))
+/// let bot = (to: pt, rel: (0, -size))
+/// let left = (to: pt, rel: (-size/2, 0))
+/// let right = (to: pt, rel: (size/2, 0))
+/// cetz.draw.line(top, left, bot, right, close: true, ..style)
+/// })
+/// })
+/// ```
+///
+///
+/// - mark-size (float): Mark size in canvas units
+/// - data (array,function): Array of 2D data points (numeric) or a function
+/// of the form `x => y`, where `x` is a value in `domain`
+/// and `y` must be numeric or a 2D vector (for parametric functions).
+/// ```cexample
+/// plot.plot(size: (2, 2), axis-style: none, {
+/// // Using an array of points:
+/// plot.add(((0,0), (calc.pi/2,1),
+/// (1.5*calc.pi,-1), (2*calc.pi,0)))
+/// // Sampling a function:
+/// plot.add(domain: (0, 2*calc.pi), calc.sin)
+/// })
+/// ```
+/// - label (none,content): Legend label to show for this plot.
+#let add(domain: auto,
+ hypograph: false,
+ epigraph: false,
+ fill: false,
+ fill-type: "axis",
+ style: (:),
+ mark: none,
+ mark-size: .2,
+ mark-style: (:),
+ samples: 50,
+ sample-at: (),
+ line: "raw",
+ axes: ("x", "y"),
+ label: none,
+ data
+ ) = {
+ // If data is of type function, sample it
+ if type(data) == function {
+ data = sample.sample-fn(data, domain, samples, sample-at: sample-at)
+ }
+
+ // Transform data
+ let line-data = transform-lines(data, line)
+
+ // Get x-domain
+ let x-domain = (
+ calc.min(..line-data.map(t => t.at(0))),
+ calc.max(..line-data.map(t => t.at(0)))
+ )
+
+ // Get y-domain
+ let y-domain = if line-data != none {(
+ calc.min(..line-data.map(t => t.at(1))),
+ calc.max(..line-data.map(t => t.at(1)))
+ )}
+
+ ((
+ type: "line",
+ label: label,
+ data: data, /* Raw data */
+ line-data: line-data, /* Transformed data */
+ axes: axes,
+ x-domain: x-domain,
+ y-domain: y-domain,
+ epigraph: epigraph,
+ hypograph: hypograph,
+ fill: fill,
+ fill-type: fill-type,
+ style: style,
+ mark: mark,
+ mark-size: mark-size,
+ mark-style: mark-style,
+ plot-prepare: _prepare,
+ plot-stroke: _stroke,
+ plot-fill: _fill,
+ plot-legend-preview: self => {
+ if self.fill or self.epigraph or self.hypograph {
+ draw.rect((0,0), (1,1), ..self.style)
+ } else {
+ draw.line((0,.5), (1,.5), ..self.style)
+ }
+ }
+ ),)
+}
+
+/// Add horizontal lines at one or more y-values. Every lines start and end points
+/// are at their axis bounds.
+///
+/// ```cexample
+/// plot.plot(size: (2,2), x-tick-step: none, y-tick-step: none, {
+/// plot.add(domain: (0, 4*calc.pi), calc.sin)
+/// // Add 3 horizontal lines
+/// plot.add-hline(-.5, 0, .5)
+/// })
+/// ```
+///
+/// - ..y (float): Y axis value(s) to add a line at
+/// - min (auto,float): X axis minimum value or auto to take the axis minimum
+/// - max (auto,float): X axis maximum value or auto to take the axis maximum
+/// - axes (array): Name of the axes to use for plotting
+/// - style (style): Style to use, can be used with a palette function
+/// - label (none,content): Legend label to show for this plot.
+#let add-hline(..y,
+ min: auto,
+ max: auto,
+ axes: ("x", "y"),
+ style: (:),
+ label: none,
+ ) = {
+ assert(y.pos().len() >= 1,
+ message: "Specify at least one y value")
+ assert(y.named().len() == 0)
+
+ let prepare(self, ctx) = {
+ let (x-min, x-max) = (ctx.x.min, ctx.x.max)
+ let (y-min, y-max) = (ctx.y.min, ctx.y.max)
+ let x-min = if min == auto { x-min } else { min }
+ let x-max = if max == auto { x-max } else { max }
+
+ self.lines = self.y.filter(y => y >= y-min and y <= y-max)
+ .map(y => ((x-min, y), (x-max, y)))
+ return self
+ }
+
+ let stroke(self, ctx) = {
+ for (a, b) in self.lines {
+ draw.line(a, b, fill: none)
+ }
+ }
+
+ let x-min = if min == auto { none } else { min }
+ let x-max = if max == auto { none } else { max }
+
+ ((
+ type: "hline",
+ label: label,
+ y: y.pos(),
+ x-domain: (x-min, x-max),
+ y-domain: (calc.min(..y.pos()), calc.max(..y.pos())),
+ axes: axes,
+ style: style,
+ plot-prepare: prepare,
+ plot-stroke: stroke,
+ ),)
+}
+
+/// Add vertical lines at one or more x-values. Every lines start and end points
+/// are at their axis bounds.
+///
+/// ```cexample
+/// plot.plot(size: (2,2), x-tick-step: none, y-tick-step: none, {
+/// plot.add(domain: (0, 2*calc.pi), calc.sin)
+/// // Add 3 vertical lines
+/// plot.add-vline(calc.pi/2, calc.pi, 3*calc.pi/2)
+/// })
+/// ```
+///
+/// - ..x (float): X axis values to add a line at
+/// - min (auto,float): Y axis minimum value or auto to take the axis minimum
+/// - max (auto,float): Y axis maximum value or auto to take the axis maximum
+/// - axes (array): Name of the axes to use for plotting, note that not all
+/// plot styles are able to display a custom axis!
+/// - style (style): Style to use, can be used with a palette function
+/// - label (none,content): Legend label to show for this plot.
+#let add-vline(..x,
+ min: auto,
+ max: auto,
+ axes: ("x", "y"),
+ style: (:),
+ label: none,
+ ) = {
+ assert(x.pos().len() >= 1,
+ message: "Specify at least one x value")
+ assert(x.named().len() == 0)
+
+ let prepare(self, ctx) = {
+ let (x-min, x-max) = (ctx.x.min, ctx.x.max)
+ let (y-min, y-max) = (ctx.y.min, ctx.y.max)
+ let y-min = if min == auto { y-min } else { min }
+ let y-max = if max == auto { y-max } else { max }
+
+ self.lines = self.x.filter(x => x >= x-min and x <= x-max)
+ .map(x => ((x, y-min), (x, y-max)))
+ return self
+ }
+
+ let stroke(self, ctx) = {
+ for (a, b) in self.lines {
+ draw.line(a, b, fill: none)
+ }
+ }
+
+ let y-min = if min == auto { none } else { min }
+ let y-max = if max == auto { none } else { max }
+
+ ((
+ type: "vline",
+ label: label,
+ x: x.pos(),
+ x-domain: (calc.min(..x.pos()), calc.max(..x.pos())),
+ y-domain: (y-min, y-max),
+ axes: axes,
+ style: style,
+ plot-prepare: prepare,
+ plot-stroke: stroke
+ ),)
+}
+
+/// Fill the area between two graphs. This behaves same as `add` but takes
+/// a pair of data instead of a single data array/function.
+/// The area between both function plots gets filled. For a more detailed
+/// explanation of the arguments, see @@add().
+///
+/// This can be used to display an error-band of a function.
+///
+/// ```cexample
+/// plot.plot(size: (2,2), x-tick-step: none, y-tick-step: none, {
+/// plot.add-fill-between(domain: (0, 2*calc.pi),
+/// calc.sin, // First function/data
+/// calc.cos) // Second function/data
+/// })
+/// ```
+///
+/// - domain (domain): Domain of both `data-a` and `data-b`. The domain is used for
+/// sampling functions only and has no effect on data arrays.
+/// - samples (int): Number of times the `data-a` and `data-b` function gets called for
+/// sampling y-values. Only used if `data-a` or `data-b` is of
+/// type function.
+/// - sample-at (array): Array of x-values the function(s) get sampled at in addition
+/// to the default sampling.
+/// - line (string, dictionary): Line type to use, see @@add().
+/// - style (style): Style to use, can be used with a palette function.
+/// - label (none,content): Legend label to show for this plot.
+/// - axes (array): Name of the axes to use for plotting.
+/// - data-a (array,function): Data of the first plot, see @@add().
+/// - data-b (array,function): Data of the second plot, see @@add().
+#let add-fill-between(data-a,
+ data-b,
+ domain: auto,
+ samples: 50,
+ sample-at: (),
+ line: "raw",
+ axes: ("x", "y"),
+ label: none,
+ style: (:)) = {
+ // If data is of type function, sample it
+ if type(data-a) == function {
+ data-a = sample.sample-fn(data-a, domain, samples, sample-at: sample-at)
+ }
+ if type(data-b) == function {
+ data-b = sample.sample-fn(data-b, domain, samples, sample-at: sample-at)
+ }
+
+ // Transform data
+ let line-a-data = transform-lines(data-a, line)
+ let line-b-data = transform-lines(data-b, line)
+
+ // Get x-domain
+ let x-domain = (
+ calc.min(..line-a-data.map(t => t.at(0)),
+ ..line-b-data.map(t => t.at(0))),
+ calc.max(..line-a-data.map(t => t.at(0)),
+ ..line-b-data.map(t => t.at(0)))
+ )
+
+ // Get y-domain
+ let y-domain = if line-a-data != none and line-b-data != none {(
+ calc.min(..line-a-data.map(t => t.at(1)),
+ ..line-b-data.map(t => t.at(1))),
+ calc.max(..line-a-data.map(t => t.at(1)),
+ ..line-b-data.map(t => t.at(1)))
+ )}
+
+ let prepare(self, ctx) = {
+ let (x, y) = (ctx.x, ctx.y)
+
+ // Generate stroke paths
+ self.stroke-paths = (
+ a: util.compute-stroke-paths(self.line-data.a, x, y),
+ b: util.compute-stroke-paths(self.line-data.b, x, y),
+ )
+
+ // Generate fill paths
+ self.fill-paths = util.compute-fill-paths(self.line-data.a + self.line-data.b.rev(), x, y)
+
+ return self
+ }
+
+ let stroke(self, ctx) = {
+ for p in self.stroke-paths.a {
+ draw.line(..p, fill: none)
+ }
+ for p in self.stroke-paths.b {
+ draw.line(..p, fill: none)
+ }
+ }
+
+ let fill(self, ctx) = {
+ fill-shape(self.fill-paths)
+ }
+
+ ((
+ type: "fill-between",
+ label: label,
+ axes: axes,
+ line-data: (a: line-a-data, b: line-b-data),
+ x-domain: x-domain,
+ y-domain: y-domain,
+ style: style,
+ plot-prepare: prepare,
+ plot-stroke: stroke,
+ plot-fill: fill,
+ plot-legend-preview: self => {
+ draw.rect((0,0), (1,1), ..self.style)
+ }
+ ),)
+}
diff --git a/render/packages/preview/cetz-plot/0.1.4/src/plot/mark.typ b/render/packages/preview/cetz-plot/0.1.4/src/plot/mark.typ
new file mode 100644
index 0000000..c401138
--- /dev/null
+++ b/render/packages/preview/cetz-plot/0.1.4/src/plot/mark.typ
@@ -0,0 +1,52 @@
+#import "/src/cetz.typ": draw
+#import "/src/axes.typ"
+
+// Draw mark at point with size
+#let draw-mark-shape(pt, size, mark, style) = {
+ let sx = size
+ let sy = size
+
+ let bl(pt) = (rel: (-sx/2, -sy/2), to: pt)
+ let br(pt) = (rel: (sx/2, -sy/2), to: pt)
+ let tl(pt) = (rel: (-sx/2, sy/2), to: pt)
+ let tr(pt) = (rel: (sx/2, sy/2), to: pt)
+ let ll(pt) = (rel: (-sx/2, 0), to: pt)
+ let rr(pt) = (rel: (sx/2, 0), to: pt)
+ let tt(pt) = (rel: (0, sy/2), to: pt)
+ let bb(pt) = (rel: (0, -sy/2), to: pt)
+
+ if mark == "o" {
+ draw.circle(pt, radius: (sx/2, sy/2), ..style)
+ } else if mark == "square" {
+ draw.rect(bl(pt), tr(pt), ..style)
+ } else if mark == "triangle" {
+ draw.line(bl(pt), br(pt), tt(pt), close: true, ..style)
+ } else if mark == "*" or mark == "x" {
+ draw.line(bl(pt), tr(pt), ..style)
+ draw.line(tl(pt), br(pt), ..style)
+ } else if mark == "+" {
+ draw.line(ll(pt), rr(pt), ..style);
+ draw.line(tt(pt), bb(pt), ..style)
+ } else if mark == "-" {
+ draw.line(ll(pt), rr(pt), ..style)
+ } else if mark == "|" {
+ draw.line(tt(pt), bb(pt), ..style)
+ } else if mark == "diamond" or mark == "<>" {
+ draw.line(ll(pt), tt(pt), rr(pt), bb(pt), close: true, ..style)
+ } else if type(mark) == int and mark > 2 {
+ let pts = range(mark).map(i => (to: pt, rel: (90deg + 360deg * i / mark, size/2)))
+ draw.line(..pts, close: true, ..style)
+ } else if type(mark) == function {
+ mark(pt, size, style)
+ }
+}
+
+#let draw-mark(pts, x, y, mark, mark-size, plot-size) = {
+ let pts = pts.map(pt => {
+ axes.transform-vec(plot-size, x, y, none, pt)
+ }).filter(pt => pt != none)
+
+ for pt in pts {
+ draw-mark-shape(pt, mark-size, mark, (:))
+ }
+}
diff --git a/render/packages/preview/cetz-plot/0.1.4/src/plot/sample.typ b/render/packages/preview/cetz-plot/0.1.4/src/plot/sample.typ
new file mode 100644
index 0000000..3ad881d
--- /dev/null
+++ b/render/packages/preview/cetz-plot/0.1.4/src/plot/sample.typ
@@ -0,0 +1,79 @@
+/// Sample the given single parameter function `samples` times, with values
+/// evenly spaced within the range given by `domain` and return each
+/// sampled `y` value in an array as `(x, y)` tuple.
+///
+/// If the functions first return value is a tuple `(x, y)`, then all return values
+/// must be a tuple.
+///
+/// - fn (function): Function to sample of the form `(x) => y` or `(t) => (x, y)`, where
+/// `x` or `t` are `float` values within the domain specified by `domain`.
+/// - domain (domain): Domain of `fn` used as bounding interval for the sampling points.
+/// - samples (int): Number of samples in domain.
+/// - sample-at (array): List of x values the function gets sampled at in addition
+/// to the `samples` number of samples. Values outsides the
+/// specified domain are legal.
+/// -> array: Array of (x, y) tuples
+#let sample-fn(fn, domain, samples, sample-at: ()) = {
+ assert(samples + sample-at.len() >= 2,
+ message: "You must at least sample 2 values")
+ assert(type(domain) == array and domain.len() == 2,
+ message: "Domain must be a tuple")
+
+ let (lo, hi) = domain
+
+ let y0 = (fn)(lo)
+ let is-vector = type(y0) == array
+ if not is-vector {
+ y0 = ((lo, y0), )
+ } else {
+ y0 = (y0, )
+ }
+
+ let pts = sample-at + range(0, samples).map(t => lo + t / (samples - 1) * (hi - lo))
+ pts = pts.sorted()
+
+ return pts.map(x => {
+ if is-vector {
+ (fn)(x)
+ } else {
+ (x, (fn)(x))
+ }
+ })
+}
+
+/// Samples the given two parameter function with `x-samples` and
+/// `y-samples` values evenly spaced within the range given by
+/// `x-domain` and `y-domain` and returns each sampled output in
+/// an array.
+///
+/// - fn (function): Function of the form `(x, y) => z` with all values being numbers.
+/// - x-domain (domain): Domain used as bounding interval for sampling point's x
+/// values.
+/// - y-domain (domain): Domain used as bounding interval for sampling point's y
+/// values.
+/// - x-samples (int): Number of samples in the x-domain.
+/// - y-samples (int): Number of samples in the y-domain.
+/// -> array: Array of z scalars
+#let sample-fn2(fn, x-domain, y-domain, x-samples, y-samples) = {
+ assert(x-samples >= 2,
+ message: "You must at least sample 2 x-values")
+ assert(y-samples >= 2,
+ message: "You must at least sample 2 y-values")
+ assert(type(x-domain) == array and x-domain.len() == 2,
+ message: "X-Domain must be a tuple")
+ assert(type(y-domain) == array and y-domain.len() == 2,
+ message: "Y-Domain must be a tuple")
+
+ let (x-min, x-max) = x-domain
+ let (y-min, y-max) = y-domain
+ let y-pts = range(0, y-samples)
+ let x-pts = range(0, x-samples)
+
+ return y-pts.map(y => {
+ let y = y / (y-samples - 1) * (y-max - y-min) + y-min
+ return x-pts.map(x => {
+ let x = x / (x-samples - 1) * (x-max - x-min) + x-min
+ return float((fn)(x, y))
+ })
+ })
+}
diff --git a/render/packages/preview/cetz-plot/0.1.4/src/plot/util.typ b/render/packages/preview/cetz-plot/0.1.4/src/plot/util.typ
new file mode 100644
index 0000000..8d0b03e
--- /dev/null
+++ b/render/packages/preview/cetz-plot/0.1.4/src/plot/util.typ
@@ -0,0 +1,372 @@
+#import "/src/cetz.typ"
+#import cetz.util: bezier
+
+/// Clip line-strip in rect
+///
+/// - points (array): Array of vectors representing a line-strip
+/// - low (vector): Lower clip-window coordinate
+/// - high (vector): Upper clip-window coordinate
+/// -> array List of line-strips representing the paths insides the clip-window
+#let clipped-paths(points, low, high, fill: false) = {
+ let (min-x, max-x) = (calc.min(low.at(0), high.at(0)),
+ calc.max(low.at(0), high.at(0)))
+ let (min-y, max-y) = (calc.min(low.at(1), high.at(1)),
+ calc.max(low.at(1), high.at(1)))
+
+ let in-rect(pt) = {
+ return (pt.at(0) >= min-x and pt.at(0) <= max-x and
+ pt.at(1) >= min-y and pt.at(1) <= max-y)
+ }
+
+ let interpolated-end(a, b) = {
+ if in-rect(a) and in-rect(b) {
+ return b
+ }
+
+ let (x1, y1, ..) = a
+ let (x2, y2, ..) = b
+
+ if x2 - x1 == 0 {
+ return (x2, calc.min(max-y, calc.max(y2, min-y)))
+ }
+
+ if y2 - y1 == 0 {
+ return (calc.min(max-x, calc.max(x2, min-x)), y2)
+ }
+
+ let m = (y2 - y1) / (x2 - x1)
+ let n = y2 - m * x2
+
+ let x = x2
+ let y = y2
+
+ y = calc.min(max-y, calc.max(y, min-y))
+ x = (y - n) / m
+
+ x = calc.min(max-x, calc.max(x, min-x))
+ y = m * x + n
+
+ return (x, y)
+ }
+
+ // Append path to paths and return paths
+ //
+ // If path starts or ends with a vector of another part, merge those
+ // paths instead appending path as a new path.
+ let append-path(paths, path) = {
+ if path.len() <= 1 {
+ return paths
+ }
+
+ let cmp(a, b) = {
+ return a.map(calc.round.with(digits: 8)) == b.map(calc.round.with(digits: 8))
+ }
+
+ let added = false
+ for i in range(0, paths.len()) {
+ let p = paths.at(i)
+ if cmp(p.first(), path.last()) {
+ paths.at(i) = path + p
+ added = true
+ } else if cmp(p.first(), path.first()) {
+ paths.at(i) = path.rev() + p
+ added = true
+ } else if cmp(p.last(), path.first()) {
+ paths.at(i) = p + path
+ added = true
+ } else if cmp(p.last(), path.last()) {
+ paths.at(i) = p + path.rev()
+ added = true
+ }
+ if added { break }
+ }
+
+ if not added {
+ paths.push(path)
+ }
+ return paths
+ }
+
+ let clamped-pt(pt) = {
+ return (calc.max(min-x, calc.min(pt.at(0), max-x)),
+ calc.max(min-y, calc.min(pt.at(1), max-y)))
+ }
+
+ let paths = ()
+
+ let path = ()
+ let prev = points.at(0)
+ let was-inside = in-rect(prev)
+ if was-inside {
+ path.push(prev)
+ } else if fill {
+ path.push(clamped-pt(prev))
+ }
+
+ for i in range(1, points.len()) {
+ let prev = points.at(i - 1)
+ let pt = points.at(i)
+
+ let is-inside = in-rect(pt)
+
+ let (x1, y1, ..) = prev
+ let (x2, y2, ..) = pt
+
+ // Ignore lines if both ends are outsides the x-window and on the
+ // same side.
+ if (x1 < min-x and x2 < min-x) or (x1 > max-x and x2 > max-x) {
+ if fill {
+ let clamped = clamped-pt(pt)
+ if path.last() != clamped {
+ path.push(clamped)
+ }
+ }
+ was-inside = false
+ continue
+ }
+
+ if is-inside {
+ if was-inside {
+ path.push(pt)
+ } else {
+ path.push(interpolated-end(pt, prev))
+ path.push(pt)
+ }
+ } else {
+ if was-inside {
+ path.push(interpolated-end(prev, pt))
+ } else {
+ let (a, b) = (interpolated-end(pt, prev),
+ interpolated-end(prev, pt))
+ if in-rect(a) and in-rect(b) {
+ path.push(a)
+ path.push(b)
+ } else if fill {
+ let clamped = clamped-pt(pt)
+ if path.last() != clamped {
+ path.push(clamped)
+ }
+ }
+ }
+
+ if path.len() > 0 and not fill {
+ paths = append-path(paths, path)
+ path = ()
+ }
+ }
+
+ was-inside = is-inside
+ }
+
+ // Append clamped last point if filling
+ if fill and not in-rect(points.last()) {
+ path.push(clamped-pt(points.last()))
+ }
+
+ if path.len() > 1 {
+ paths = append-path(paths, path)
+ }
+
+ return paths
+}
+
+/// Compute clipped stroke paths
+///
+/// - points (array): X/Y data points
+/// - x (axis): X-Axis
+/// - y (axis): Y-Axis
+/// -> array List of stroke paths
+#let compute-stroke-paths(points, x, y) = {
+ clipped-paths(points, (x.min, y.min), (x.max, y.max), fill: false)
+}
+
+/// Compute clipped fill path
+///
+/// - points (array): X/Y data points
+/// - x (axis): X-Axis
+/// - y (axis): Y-Axis
+/// -> array List of fill paths
+#let compute-fill-paths(points, x, y) = {
+ clipped-paths(points, (x.min, y.min), (x.max, y.max), fill: true)
+}
+
+/// Return points of a sampled catmull-rom through the
+/// input points.
+///
+/// - points (array): Array of input vectors
+/// - tension (float): Catmull-Rom tension
+/// - samples (int): Number of samples
+/// -> array Array of vectors
+#let sampled-spline-data(points, tension, samples) = {
+ assert(samples >= 1 and samples <= 100,
+ message: "Must at least use 1 sample per curve")
+
+ let curves = bezier.catmull-to-cubic(points, tension)
+ let pts = ()
+ for c in curves {
+ for t in range(0, samples + 1) {
+ let t = t / samples
+ pts.push(bezier.cubic-point(..c, t))
+ }
+ }
+ return pts
+}
+
+/// Simplify linear data by "detecting" linear sections
+/// and skipping points until the slope changes.
+/// This can have a huge impact on the number of lines
+/// getting rendered.
+///
+/// - data (array): Data points
+/// - epsilon (float): Curvature threshold to treat data as linear
+#let linearized-data(data, epsilon) = {
+ let pts = ()
+ // Current slope, set to none if infinite
+ let dx = none
+ // Previous point, last skipped point
+ let prev = none
+ let skipped = none
+ // Current direction
+ let dir = 0
+
+ let len = data.len()
+ for i in range(0, len) {
+ let pt = data.at(i)
+ if prev != none and i < len - 1 {
+ let new-dir = pt.at(0) - prev.at(0)
+ if new-dir == 0 {
+ // Infinite slope
+ if dx != none {
+ if skipped != none {pts.push(skipped); skipped = none}
+ pts.push(pt)
+ } else {
+ skipped = pt
+ }
+ dx = none
+ } else {
+ // Push the previous and the current point
+ // if slope or direction changed
+ let new-dx = ((pt.at(1) - prev.at(1)) / new-dir)
+ if dx == none or calc.abs(new-dx - dx) > epsilon or (new-dir * dir) < 0 {
+ if skipped != none {pts.push(skipped); skipped = none}
+ pts.push(pt)
+
+ dx = new-dx
+ dir = new-dir
+ } else {
+ skipped = pt
+ }
+ }
+ } else {
+ if skipped != none {pts.push(skipped); skipped = none}
+ pts.push(pt)
+ }
+
+ prev = pt
+ }
+
+ return pts
+}
+
+// Get the default axis orientation
+// depending on the axis name
+#let get-default-axis-horizontal(name) = {
+ return lower(name).starts-with("x")
+}
+
+// Setup axes dictionary
+//
+// - axis-dict (dictionary): Existing axis dictionary
+// - options (dictionary): Named arguments
+// - plot-size (tuple): Plot width, height tuple
+#let setup-axes(ctx, axis-dict, options, plot-size) = {
+ import "/src/axes.typ"
+
+ // Get axis option for name
+ let get-axis-option(axis-name, name, default) = {
+ let v = options.at(axis-name + "-" + name, default: default)
+ if v == auto { default } else { v }
+ }
+
+ for (name, axis) in axis-dict {
+ if not "ticks" in axis { axis.ticks = () }
+ axis.label = get-axis-option(name, "label", $italic(name)$)
+
+ // Configure axis bounds
+ axis.min = get-axis-option(name, "min", axis.min)
+ axis.max = get-axis-option(name, "max", axis.max)
+
+ assert(axis.min not in (none, auto) and
+ axis.max not in (none, auto),
+ message: "Axis min and max must be set.")
+ if axis.min == axis.max {
+ axis.min -= 1; axis.max += 1
+ }
+
+ axis.mode = get-axis-option(name, "mode", "lin")
+ axis.base = get-axis-option(name, "base", 10)
+
+ // Configure axis orientation
+ axis.horizontal = get-axis-option(name, "horizontal",
+ get-default-axis-horizontal(name))
+
+ // Configure ticks
+ axis.ticks.list = get-axis-option(name, "ticks", ())
+ axis.ticks.step = get-axis-option(name, "tick-step", axis.ticks.step)
+ axis.ticks.minor-step = get-axis-option(name, "minor-tick-step", axis.ticks.minor-step)
+ axis.ticks.decimals = get-axis-option(name, "decimals", 2)
+ axis.ticks.unit = get-axis-option(name, "unit", [])
+ axis.ticks.format = get-axis-option(name, "format", axis.ticks.format)
+
+ // Axis break
+ axis.show-break = get-axis-option(name, "break", false)
+ axis.inset = get-axis-option(name, "inset", (0, 0))
+
+ // Configure grid
+ axis.ticks.grid = get-axis-option(name, "grid", false)
+
+ axis-dict.at(name) = axis
+ }
+
+ // Set axis options round two, after setting
+ // axis bounds
+ for (name, axis) in axis-dict {
+ let changed = false
+
+ // Configure axis aspect ratio
+ let equal-to = get-axis-option(name, "equal", none)
+ if equal-to != none {
+ assert.eq(type(equal-to), str,
+ message: "Expected axis name.")
+ assert(equal-to != name,
+ message: "Axis can not be equal to itself.")
+
+ let other = axis-dict.at(equal-to, default: none)
+ assert(other != none,
+ message: "Other axis must exist.")
+ assert(other.horizontal != axis.horizontal,
+ message: "Equal axes must have opposing orientation.")
+
+ let (w, h) = plot-size
+ let ratio = if other.horizontal {
+ h / w
+ } else {
+ w / h
+ }
+ axis.min = other.min * ratio
+ axis.max = other.max * ratio
+
+ changed = true
+ }
+
+ if changed {
+ axis-dict.at(name) = axis
+ }
+ }
+
+ for (name, axis) in axis-dict {
+ axis-dict.at(name) = axes.prepare-axis(ctx, axis, name)
+ }
+
+ return axis-dict
+}
diff --git a/render/packages/preview/cetz-plot/0.1.4/src/plot/violin.typ b/render/packages/preview/cetz-plot/0.1.4/src/plot/violin.typ
new file mode 100644
index 0000000..5da01e9
--- /dev/null
+++ b/render/packages/preview/cetz-plot/0.1.4/src/plot/violin.typ
@@ -0,0 +1,134 @@
+#import "/src/cetz.typ": draw
+#import "util.typ"
+#import "sample.typ"
+
+#let kernel-normal(x, stdev: 1.5) = {
+ (1 / calc.sqrt(2 * calc.pi*calc.pow(stdev, 2))) * calc.exp(-(x*x) / (2 * calc.pow(stdev, 2)))
+}
+
+#let _violin-render(self, ctx, violin, filling: true) = {
+ let path = range(self.samples)
+ .map((t)=>violin.min + (violin.max - violin.min) * (t / self.samples ))
+ .map((u)=>(u, (violin.convolve)(u)))
+ .map(((u,v)) => {
+ (violin.x-position + v, u)
+ })
+
+ if self.side == "both"{
+ path += path.rev().map(((x,y))=> {(2 * violin.x-position - x,y)})
+ } else if self.side == "left"{
+ path = path.map(((x,y)) => (2 * violin.x-position - x,y))
+ }
+
+ let stroke-paths = util.compute-stroke-paths(path, ctx.x, ctx.y)
+
+ for p in stroke-paths{
+ let args = arguments(..p, closed: self.side == "both")
+ if filling {
+ args = arguments(..args, stroke: none)
+ } else {
+ args = arguments(..args, fill: none)
+ }
+ draw.line(..self.style, ..args)
+ }
+}
+
+#let _plot-prepare(self, ctx) = {
+ self.violins = self.data.map(entry=> {
+ let points = entry.at(self.y-key)
+ let (min, max) = (calc.min(..points), calc.max(..points))
+ let range = calc.abs(max - min)
+ (
+ x-position: entry.at(self.x-key),
+ points: points,
+ length: points.len(),
+ min: min - (self.extents * range),
+ max: max + (self.extents * range),
+ convolve: (t) => {
+ points.map(y => (self.kernel)((y - t) / self.bandwidth)).sum() / (points.len() * self.bandwidth)
+ }
+ )
+ })
+ return self
+}
+
+#let _plot-stroke(self, ctx) = {
+ for violin in self.violins {
+ _violin-render(self, ctx, violin, filling: false)
+ }
+}
+
+#let _plot-fill(self, ctx) = {
+ for violin in self.violins {
+ _violin-render(self, ctx, violin, filling: true)
+ }
+}
+
+#let _plot-legend-preview(self) = {
+ draw.rect((0,0), (1,1), ..self.style)
+}
+
+
+/// Add a violin plot
+///
+/// A violin plot is a chart that can be used to compare the distribution of continuous
+/// data between categories.
+///
+/// - data (array): Array of data items. An item is an array containing an `x` and one
+/// or more `y` values.
+/// - x-key (int, string): Key to use for retrieving the `x` position of the violin.
+/// - y-key (int, string): Key to use for retrieving values of points within the category.
+/// - side (string): The sides of the violin to be rendered:
+/// / left: Plot only the left side of the violin.
+/// / right: Plot only the right side of the violin.
+/// / both: Plot both sides of the violin.
+/// - kernel (function): The kernel density estimator function, which takes a single
+/// `x` value relative to the center of a distribution (0) and
+/// normalized by the bandwidth
+/// - bandwidth (float): The smoothing parameter of the kernel.
+/// - extents (float): The extension of the domain, expressed as a fraction of spread.
+/// - samples (int): The number of samples of the kernel to render.
+/// - style (dictionary): Style override dictionary.
+/// - mark-style (dictionary): (unused, will eventually be used to render interquartile ranges).
+/// - axes (axes): (unstable, documentation to follow once completed).
+/// - label (none, content): The name of the category to be shown in the legend.
+#let add-violin(
+ data,
+ x-key: 0,
+ y-key: 1,
+ side: "right",
+ kernel: kernel-normal.with(stdev: 1.5),
+ bandwidth: 1,
+ extents: 0.25,
+
+ samples: 50,
+ style: (:),
+ mark-style: (:),
+ axes: ("x", "y"),
+ label: none,
+) = {
+
+ ((
+ type: "violins",
+
+ data: data,
+ x-key: x-key,
+ y-key: y-key,
+ side: side,
+ kernel: kernel,
+ bandwidth: bandwidth,
+ extents: extents,
+
+ samples: samples,
+ style: style,
+ mark-style: mark-style,
+ axes: axes,
+ label: label,
+
+ plot-prepare: _plot-prepare,
+ plot-stroke: _plot-stroke,
+ plot-fill: _plot-fill,
+ plot-legend-preview: _plot-legend-preview,
+ ),)
+
+}
diff --git a/render/packages/preview/cetz-plot/0.1.4/src/smartart.typ b/render/packages/preview/cetz-plot/0.1.4/src/smartart.typ
new file mode 100644
index 0000000..32c7e21
--- /dev/null
+++ b/render/packages/preview/cetz-plot/0.1.4/src/smartart.typ
@@ -0,0 +1,2 @@
+#import "smartart/process.typ"
+#import "smartart/cycle.typ"
\ No newline at end of file
diff --git a/render/packages/preview/cetz-plot/0.1.4/src/smartart/common.typ b/render/packages/preview/cetz-plot/0.1.4/src/smartart/common.typ
new file mode 100644
index 0000000..9b6f819
--- /dev/null
+++ b/render/packages/preview/cetz-plot/0.1.4/src/smartart/common.typ
@@ -0,0 +1,440 @@
+#import "/src/cetz.typ" as cetz: draw, coordinate, util.resolve-number, vector
+
+/// Possible chevron caps: #cetz.smartart.process.CHEVRON-CAPS
+/// ```cexample
+/// for cap in smartart.process.CHEVRON-CAPS {
+/// smartart.process.chevron(
+/// ([Step 1], [Step 2]), spacing: 0,
+/// start-cap: cap, middle-cap: cap, end-cap: cap)
+/// translate(y: -1)
+/// }
+/// ```
+#let CHEVRON-CAPS = (
+ "(", "<", "|", ">", ")"
+)
+
+#let _draw-arrow(
+ start,
+ end,
+ height,
+ fill,
+ stroke,
+ double: false,
+ name: none
+) = {
+ let h2 = height / 2
+ let h4 = height / 4
+ draw.group(name: name, ctx => {
+ let (ctx, p1) = coordinate.resolve(ctx, start)
+ let (ctx, p2) = coordinate.resolve(ctx, end)
+ let (x1, y1, _) = p1
+ let (x2, y2, _) = p2
+ let v = vector.sub(p2, p1)
+ let d = vector.norm(v)
+ let n = (-d.at(1), d.at(0))
+ let len = vector.len(v)
+ let head-len = h2
+ /*
+ c
+ a---b\
+ p1 p2
+ g---f/
+ e
+ */
+ /*
+ i c
+ /a---b\
+ p1 p2
+ \g---f/
+ h e
+ */
+ let a = vector.add(p1, vector.scale(n, h4))
+ if double {
+ a = vector.add(
+ a,
+ vector.scale(d, head-len)
+ )
+ }
+ let b = vector.add(
+ a,
+ vector.scale(
+ d,
+ len - if double {2 * head-len} else {head-len}
+ )
+ )
+ let c = vector.add(b, vector.scale(n, h4))
+ let e = vector.add(c, vector.scale(n, -height))
+ let f = vector.add(e, vector.scale(n, h4))
+ let g = vector.sub(a, vector.scale(n, h2))
+ let pts = (
+ a, b, c, p2, e, f, g
+ )
+ if double {
+ let h = vector.sub(g, vector.scale(n, h4))
+ let i = vector.add(a, vector.scale(n, h4))
+ pts += (h, p1, i)
+ }
+
+ draw.line(
+ ..pts,
+ stroke: stroke,
+ fill: fill,
+ close: true
+ )
+ draw.anchor("start", p1)
+ draw.anchor("end", p2)
+ draw.anchor("center", (p1, 50%, p2))
+ draw.anchor("default", (p1, 50%, p2))
+ })
+}
+
+#let _draw-chevron(
+ start,
+ end,
+ thickness,
+ fill,
+ stroke,
+ start-cap,
+ end-cap,
+ cap-ratio,
+ offset-start,
+ offset-end,
+ name: none
+) = {
+ let h2 = thickness / 2
+ let h4 = thickness / 4
+ draw.group(name: name, ctx => {
+ let (ctx, p1) = coordinate.resolve(ctx, start)
+ let (ctx, p2) = coordinate.resolve(ctx, end)
+
+
+ draw.anchor("center", (p1, 50%, p2))
+ draw.anchor("default", (p1, 50%, p2))
+
+ let v = vector.sub(p2, p1)
+ let d = vector.norm(v)
+ let n = (d.at(1), d.at(0))
+
+ /*
+ > | < )
+ sa sa sa sa,
+ \ | / \
+ sb | sb |sb
+ / | \ /
+ sz sz sz sz´
+ */
+
+ let cap-width = thickness * cap-ratio / 100%
+
+ if offset-start and start-cap in ("(", "<") {
+ p1 = vector.add(p1, vector.scale(d, cap-width))
+ }
+
+ if offset-end and end-cap in (")", ">") {
+ p2 = vector.sub(p2, vector.scale(d, cap-width))
+ }
+
+ // Start cap
+ let sb = if start-cap in ("(", "<") {
+ vector.sub(p1, vector.scale(d, cap-width))
+ } else {
+ p1
+ }
+ let sa = vector.add(p1, vector.scale(n, h2))
+ if start-cap in (")", ">") {
+ sa = vector.sub(sa, vector.scale(d, cap-width))
+ }
+ let sz = vector.sub(sa, vector.scale(n, thickness))
+
+ // End cap
+ let eb = if end-cap in (")", ">") {
+ vector.add(p2, vector.scale(d, cap-width))
+ } else {
+ p2
+ }
+ let ea = vector.add(p2, vector.scale(n, h2))
+ if end-cap in ("(", "<") {
+ ea = vector.add(ea, vector.scale(d, cap-width))
+ }
+ let ez = vector.sub(ea, vector.scale(n, thickness))
+
+ draw.merge-path(
+ {
+ // Start cap
+ if start-cap in ("(", ")") {
+ draw.arc-through(sa, sb, sz)
+ } else if start-cap == "|" {
+ draw.line(sa, sz)
+ } else {
+ draw.line(sa, sb, sz)
+ }
+
+ // End cap
+ if end-cap in ("(", ")") {
+ draw.arc-through(ez, eb, ea)
+ } else if end-cap == "|" {
+ draw.line(ez, ea)
+ } else {
+ draw.line(ez, eb, ea)
+ }
+ },
+ stroke: stroke,
+ fill: fill,
+ close: true
+ )
+ draw.anchor("start", p1)
+ draw.anchor("end", p2)
+ })
+}
+
+#let _get-steps-sizes(steps, ctx, style, step-style-at) = {
+ let sizes = steps.enumerate().map(p => {
+ let (i, step) = p
+ let step-style = style.steps + step-style-at(i)
+ let padding = resolve-number(ctx, step-style.padding)
+ let max-width = resolve-number(ctx, step-style.max-width)
+ max-width -= 2 * padding
+ let m = measure(step, width: max-width * ctx.length)
+ let w = resolve-number(ctx, m.width)
+ let h = resolve-number(ctx, m.height)
+ return (w, h)
+ })
+
+ let largest-width = calc.max(..sizes.map(s => s.first()))
+ let highest-height = calc.max(..sizes.map(s => s.last()))
+
+ return (sizes, largest-width, highest-height)
+}
+
+#let _get-style-at-func(style, n-steps) = {
+ if type(style) == function {
+ style
+ } else if type(style) == array {
+ i => {
+ let s = style.at(calc.rem(i, style.len()))
+ if type(s) == color or type(s) == gradient {
+ (fill: s)
+ } else {
+ s
+ }
+ }
+ } else if type(style) == gradient {
+ i => (fill: style.sample(i / (n-steps - 1) * 100%))
+ } else {
+ i => (:)
+ }
+}
+
+#let _pos-to-anchor(pos) = {
+ if pos == left {return "west"}
+ if pos == right {return "east"}
+ if pos == top {return "north"}
+ if pos == bottom {return "south"}
+ panic("Cannot convert alignment " + repr(pos) + " to cardinal anchor")
+}
+
+#let _dir-to-anchors(dir) = {
+ return (
+ _pos-to-anchor(dir.start()),
+ _pos-to-anchor(dir.end())
+ )
+}
+
+#let _dir-to-str(dir) = {
+ if dir == ttb {return "ttb"}
+ if dir == btt {return "btt"}
+ if dir == ltr {return "ltr"}
+ if dir == rtl {return "rtl"}
+ panic("Invalid direction " + repr(dir))
+}
+
+#let _draw-step-content(step, name, width) = {
+ draw.content(
+ name + ".center",
+ box(
+ width: width,
+ align(center)[
+ #set text(bottom-edge: "baseline")
+ #step
+ ]
+ ),
+ anchor: "center"
+ )
+}
+
+#let _draw-step-frame(ctx, center, style, name, w, h) = {
+ let padding = resolve-number(ctx, style.padding)
+ let radius = resolve-number(ctx, style.radius)
+
+ if style.shape == "rect" {
+ let tl = (
+ rel: (-w / 2 - padding, h / 2 + padding),
+ to: center
+ )
+ let br = (
+ rel: (w / 2 + padding, -h / 2 - padding),
+ to: center
+ )
+
+ draw.rect(
+ tl, br,
+ name: name,
+ stroke: style.stroke,
+ fill: style.fill,
+ radius: radius
+ )
+ } else if style.shape == "circle" {
+ let w2 = w + padding * 2
+ let h2 = h + padding * 2
+ draw.circle(
+ center,
+ name: name,
+ radius: calc.sqrt(w2 * w2 + h2 * h2) / 2,
+ stroke: style.stroke,
+ fill: style.fill
+ )
+ } else if style.shape == none {
+ let tl = (
+ rel: (-w / 2 - padding, h / 2 + padding),
+ to: center
+ )
+ let br = (
+ rel: (w / 2 + padding, -h / 2 - padding),
+ to: center
+ )
+ draw.hide(draw.rect(
+ tl, br,
+ name: name,
+ stroke: none,
+ fill: none
+ ))
+ }
+}
+
+#let _draw-step(ctx, step, pos, style, name, w, h, dir: none) = {
+ /*
+ let padding = resolve-number(ctx, style.padding)
+ let radius = resolve-number(ctx, style.radius)
+
+ let tl = (
+ rel: (
+ ltr: (0, h / 2 + padding),
+ rtl: (-w - padding * 2, h / 2 + padding),
+ btt: (-w / 2 - padding, h + 2 * padding),
+ ttb: (-w / 2 - padding, 0),
+ ).at(_dir-to-str(dir)),
+ to: pos
+ )
+ let br = (
+ rel: (w + padding * 2, -h - padding * 2),
+ to: tl
+ )
+
+ draw.rect(
+ tl, br,
+ name: name,
+ stroke: style.stroke,
+ fill: style.fill,
+ radius: radius
+ )*/
+ if dir != none {
+ let padding = resolve-number(ctx, style.padding)
+ pos = (
+ rel: (
+ ltr: (w / 2 + padding, 0),
+ rtl: (-w / 2 - padding, 0),
+ btt: (0, h / 2 + padding),
+ ttb: (0, -h / 2 - padding),
+ ).at(_dir-to-str(dir)),
+ to: pos
+ )
+ }
+ _draw-step-frame(ctx, pos, style, name, w, h)
+ _draw-step-content(step, name, w * ctx.length)
+}
+
+#let _draw-arc-arrow(
+ start-angle,
+ end-angle,
+ radius,
+ height,
+ fill,
+ stroke,
+ double: false,
+ name: none
+) = {
+ let h2 = height / 2
+ let h4 = height / 4
+ let angle-range = end-angle - start-angle
+ // Angle for a length of h/2
+ let arrow-angle = (h2 / radius) * (180deg / calc.pi)
+ if angle-range < 0deg {
+ arrow-angle *= -1
+ }
+ draw.group(name: name, ctx => {
+ let pre-end-angle = end-angle - arrow-angle
+ let mid-angle = start-angle + (angle-range - arrow-angle) / 2
+ let radius-int = radius - h4
+ let radius-ext = radius + h4
+ let radius-int2 = radius - h2
+ let radius-ext2 = radius + h2
+ let post-start-angle = start-angle + arrow-angle
+
+ /*
+ c re2
+ a-m1-b\ re
+ p1 p2 r
+ g-m2-f/ ri
+ e ri2
+ */
+
+ /*
+ i c re2
+ /a-m1-b\ re
+ p1 p2 r
+ \g-m2-f/ ri
+ h e ri2
+ */
+ let p1 = (start-angle, radius)
+ let a = (
+ if double {post-start-angle} else {start-angle},
+ radius-ext
+ )
+ let m1 = (mid-angle, radius-ext)
+ let b = (pre-end-angle, radius-ext)
+ let p2 = (end-angle, radius)
+ let f = (pre-end-angle, radius-int)
+ let m2 = (mid-angle, radius-int)
+ let g = (
+ if double {post-start-angle} else {start-angle},
+ radius-int
+ )
+
+ let c = (pre-end-angle, radius-ext2)
+ let e = (pre-end-angle, radius-int2)
+
+ draw.merge-path(
+ {
+ draw.arc-through(a, m1, b)
+ draw.line((), c, p2, e, f)
+ draw.arc-through((), m2, g)
+ if double {
+ let h = (post-start-angle, radius-int2)
+ let i = (post-start-angle, radius-ext2)
+ draw.line((), h, p1, i)
+ }
+ },
+ stroke: stroke,
+ fill: fill,
+ close: true
+ )
+
+ let center = (mid-angle, radius)
+ draw.anchor("start", p1)
+ draw.anchor("end", p2)
+ draw.anchor("center", center)
+ draw.anchor("center-ext", (mid-angle, radius-ext))
+ draw.anchor("center-int", (mid-angle, radius-int))
+ draw.anchor("default", center)
+ })
+}
diff --git a/render/packages/preview/cetz-plot/0.1.4/src/smartart/cycle.typ b/render/packages/preview/cetz-plot/0.1.4/src/smartart/cycle.typ
new file mode 100644
index 0000000..0ebbff0
--- /dev/null
+++ b/render/packages/preview/cetz-plot/0.1.4/src/smartart/cycle.typ
@@ -0,0 +1,324 @@
+#import "/src/cetz.typ" as cetz: draw, styles, palette, coordinate, util.resolve-number, vector
+
+#import "common.typ": *
+
+#let cycle-basic-default-style = (
+ stroke: auto,
+ fill: auto,
+ steps: (
+ stroke: none,
+ fill: none,
+ radius: 0.2em,
+ padding: 0.6em,
+ max-width: 5em,
+ shape: "rect"
+ ),
+ arrows: (
+ stroke: none,
+ fill: "steps",
+ thickness: 1em,
+ double: false,
+ curved: true
+ )
+)
+
+/// Draw a basic cycle chart, describing cyclic steps
+///
+/// ```cexample
+/// let steps = ([Improvise], [Adapt], [Overcome])
+/// let colors = (red, orange, green).map(c => c.lighten(40%))
+///
+/// smartart.cycle.basic(
+/// steps,
+/// step-style: colors,
+/// steps: (max-width: 5cm)
+/// )
+/// ```
+///
+/// === Styling
+/// *Root* `cycle-basic` \
+/// #show-parameter-block("steps.radius", ("number", "length"), [
+/// Corner radius of the steps boxes.], default: 0.2em)
+/// #show-parameter-block("steps.padding", ("number", "length"), [
+/// Inner padding of the steps boxes.], default: 0.6em)
+/// #show-parameter-block("steps.max-width", ("number", "length"), [
+/// Maximum width of the steps boxes.], default: 5em)
+/// #show-parameter-block("steps.shape", ("str", "none"), [
+/// Shape of the steps boxes. One of `"rect"`, `"circle"` or `none`], default: "rect")
+/// #show-parameter-block("steps.fill", ("color", "gradient", "pattern", "none"), [
+/// Fill color of the steps boxes.], default: none)
+/// #show-parameter-block("steps.stroke", ("stroke", "none"), [
+/// Stroke color of the steps boxes.], default: none)
+/// #show-parameter-block("arrows.thickness", ("number", "length"), [
+/// Thickness of arrows.], default: 1em)
+/// #show-parameter-block("arrows.double", ("boolean"), [
+/// Whether arrows are uni- or bi-directional.], default: false)
+/// #show-parameter-block("arrows.curved", ("boolean"), [
+/// Whether arrows are curved or straight.], default: false)
+/// #show-parameter-block("arrows.fill", ("string", "color", "gradient", "pattern", "none"), [
+/// Fill color of the arrows. If set to "steps", the arrows will be filled with a color in between those of the neighboring steps.], default: "steps")
+/// #show-parameter-block("arrows.stroke", ("stroke", "none"), [
+/// Stroke used for the arrows.], default: none)
+///
+/// - steps (array): Array of steps (`<content>` or `<str>`)
+/// - arrow-style (function, array, gradient): Arrow style of the following types:
+/// - function: A function of the form `index => style` that must return a style dictionary.
+/// This can be a `palette` function.
+/// - array: An array of style dictionaries or fill colors of at least one item. For each arrow the style at the arrows
+/// index modulo the arrays length gets used.
+/// - gradient: A gradient that gets sampled for each data item using the arrows
+/// index divided by the number of steps as position on the gradient.
+/// If one of stroke or fill is not in the style dictionary, it is taken from the smartarts style.
+/// - step-style (function, array, gradient): Step style of the following types:
+/// - function: A function of the form `index => style` that must return a style dictionary.
+/// This can be a `palette` function.
+/// - array: An array of style dictionaries or fill colors of at least one item. For each step the style at the steps
+/// index modulo the arrays length gets used.
+/// - gradient: A gradient that gets sampled for each data item using the steps
+/// index divided by the number of steps as position on the gradient.
+/// If one of stroke or fill is not in the style dictionary, it is taken from the smartarts style.
+/// - equal-width (boolean): If true, all steps will be sized to have the same width
+/// - equal-height (boolean): If true, all steps will be sized to have the same height
+/// - ccw (boolean): If true, steps are laid out counter-clockwise. If false, they're placed clockwise. The center of the cycle is always placed at (0, 0)
+/// - radius (number, length): The radius of the cycle
+/// - offset-angle (angle): Offset of the starting angle
+/// - step-angles (none,angle,array): Angles between the steps.
+/// - none: Steps are spaced evenly.
+/// - angle: Space between the steps, with the last angle (between the last step and the first one) completing the full circle.
+/// - array: An array of angles between the steps. For n steps, the array must contain n-1 angles. The last angle is automatically computed to complete the full circle.
+#let basic(
+ steps,
+ arrow-style: auto,
+ step-style: palette.red,
+ equal-width: false,
+ equal-height: false,
+ ccw: false,
+ radius: 2,
+ offset-angle: 0deg,
+ name: none,
+ step-angles: none,
+ ..style,
+) = {
+ draw.group(name: name, ctx => {
+ draw.anchor("default", (0, 0))
+
+ let style = styles.resolve(
+ ctx.style,
+ merge: style.named(),
+ root: "cycle-basic",
+ base: cycle-basic-default-style,
+ )
+
+ let n-steps = steps.len()
+ let step-style-at = _get-style-at-func(step-style, n-steps)
+ let arrow-style-at = _get-style-at-func(arrow-style, n-steps)
+
+ let (
+ sizes,
+ largest-width,
+ highest-height,
+ ) = _get-steps-sizes(steps, ctx, style, step-style-at)
+
+ let step-angles = if step-angles == none {
+ steps.map(_ => 360deg / n-steps)
+ } else if type(step-angles) == angle {
+ assert(
+ step-angles >= 0deg,
+ message: "step-angles must be positive, use the ccw parameter to change the direction"
+ )
+ assert(
+ (steps.len() - 1) * step-angles <= 360deg,
+ message: "Sum of step angles is greater than 360°"
+ )
+ let angles = (step-angles,) * (steps.len() - 1)
+ angles + (360deg - angles.sum(default: 0deg),)
+ } else if type(step-angles) == array {
+ assert(
+ step-angles.len() == n-steps - 1,
+ message: "There must be one less step angle as there are steps. Expected " + str(n-steps - 1) + ", got " + str(step-angles.len())
+ )
+ for step-angle in step-angles {
+ assert(
+ step-angle >= 0deg,
+ message: "step-angles must be positive, use the ccw parameter to change the direction"
+ )
+ assert(
+ type(step-angle) == angle,
+ message: "All values in step-angles must be angles"
+ )
+ }
+ assert(
+ step-angles.sum(default: 0deg) <= 360deg,
+ message: "Sum of step angles is greater than 360°"
+ )
+ step-angles + (360deg - step-angles.sum(default: 0deg),)
+ } else {
+ panic("step-angles must be an angle, an array or none, got " + repr(type(step-angles)))
+ }
+ if not ccw {
+ step-angles = step-angles.map(x => x * -1)
+ }
+
+ let angle-at = i => (
+ step-angles.slice(0, i)
+ .sum(default: 0deg)
+ + 90deg
+ + offset-angle
+ )
+
+ for (i, step) in steps.enumerate() {
+ let pos = (angle-at(i), radius)
+
+ let step-style = style.steps + step-style-at(i)
+ let padding = resolve-number(ctx, step-style.padding)
+
+ let (w, h) = sizes.at(i)
+ if equal-width {
+ w = largest-width
+ }
+ if equal-height {
+ h = highest-height
+ }
+ let step-name = "step-" + str(i)
+
+ _draw-step(ctx, step, pos, step-style, step-name, w, h)
+ }
+
+ for i in range(n-steps) {
+ let angle = angle-at(i)
+ let arrow-style = style.arrows + arrow-style-at(i)
+ let arrow-stroke = arrow-style.stroke
+ let arrow-fill = arrow-style.fill
+ let arrow-thickness = arrow-style.thickness
+
+ if arrow-fill == "steps" {
+ let s1 = style.steps + step-style-at(i)
+ let s2 = style.steps + step-style-at(i + 1)
+ arrow-fill = gradient.linear(s1.fill, s2.fill).sample(50%)
+ }
+
+ let angle-step = step-angles.at(i)
+ let start-angle = angle + angle-step * 0.2
+ let end-angle = angle + angle-step * 0.8
+
+ let a1 = angle
+ let a2 = angle + angle-step / 2
+ let a3 = angle + angle-step
+ let n(a) = {
+ if a < -180deg {
+ a += 360deg
+ } else if a > 180deg {
+ a -= 360deg
+ }
+ return a
+ }
+ a1 = n(a1)
+ a2 = n(a2)
+ a3 = n(a3)
+ let pts = (
+ (a1, radius),
+ (a2, radius),
+ (a3, radius),
+ )
+ if not ccw {
+ pts = pts.rev()
+ }
+ draw.hide(draw.arc-through(
+ ..pts,
+ name: "arc-" + str(i),
+ ))
+ draw.intersections(
+ "i-" + str(i),
+ "step-" + str(i),
+ "arc-" + str(i),
+ )
+ draw.intersections(
+ "j-" + str(i),
+ "step-" + str(calc.rem(i + 1, n-steps)),
+ "arc-" + str(i),
+ )
+
+ draw.get-ctx(ctx => {
+ let (_, p1) = coordinate.resolve(ctx, "i-" + str(i) + ".0")
+ let (_, p2) = coordinate.resolve(ctx, "j-" + str(i) + ".0")
+ let start-angle = calc.atan2(p1.at(0), p1.at(1))
+ let end-angle = calc.atan2(p2.at(0), p2.at(1))
+ if ccw != (start-angle < end-angle) {
+ if ccw {
+ end-angle += 360deg
+ } else {
+ end-angle -= 360deg
+ }
+ }
+ let angle-d = end-angle - start-angle
+
+ let prev = "step-" + str(i)
+ start-angle += angle-d * 0.1
+ end-angle -= angle-d * 0.1
+ let arrow-name = "arrow-" + str(i)
+
+ let marks = (end: "straight")
+ if arrow-style.double {
+ marks.insert("start", "straight")
+ }
+
+ let arrow-thickness = arrow-thickness
+ if arrow-thickness != none {
+ arrow-thickness = resolve-number(ctx, arrow-thickness)
+ }
+
+ // Curved
+ if arrow-style.curved {
+ // Thin arrow
+ if arrow-thickness == none {
+ draw.arc-through(
+ (start-angle, radius),
+ ((start-angle + end-angle) / 2, radius),
+ (end-angle, radius),
+ stroke: arrow-stroke,
+ mark: marks,
+ name: arrow-name,
+ )
+
+ // Thick arrow
+ } else {
+ _draw-arc-arrow(
+ start-angle,
+ end-angle,
+ radius,
+ arrow-thickness,
+ arrow-fill,
+ arrow-stroke,
+ double: arrow-style.double,
+ name: arrow-name,
+ )
+ }
+
+ // Straight
+ } else {
+ let p1 = (start-angle, radius)
+ let p2 = (end-angle, radius)
+ if arrow-thickness == none {
+ draw.line(
+ p1,
+ p2,
+ stroke: arrow-stroke,
+ mark: marks,
+ name: arrow-name,
+ )
+ } else {
+ _draw-arrow(
+ p1,
+ p2,
+ arrow-thickness,
+ arrow-fill,
+ arrow-stroke,
+ double: arrow-style.double,
+ name: arrow-name,
+ )
+ }
+ }
+ })
+ }
+ })
+}
diff --git a/render/packages/preview/cetz-plot/0.1.4/src/smartart/process.typ b/render/packages/preview/cetz-plot/0.1.4/src/smartart/process.typ
new file mode 100644
index 0000000..c929a9c
--- /dev/null
+++ b/render/packages/preview/cetz-plot/0.1.4/src/smartart/process.typ
@@ -0,0 +1,605 @@
+#import "/src/cetz.typ" as cetz: draw, styles, palette, coordinate, util.resolve-number, vector
+#import "common.typ": *
+
+#let process-basic-default-style = (
+ stroke: auto,
+ fill: auto,
+ spacing: 0.2em,
+ steps: (
+ stroke: none,
+ fill: none,
+ radius: 0.2em,
+ padding: 0.6em,
+ max-width: 5em,
+ shape: "rect"
+ ),
+ arrows: (
+ stroke: none,
+ fill: "steps",
+ height: 1em,
+ width: 1.2em,
+ double: false
+ )
+)
+
+#let process-bending-default-style = (
+ stroke: auto,
+ fill: auto,
+ spacing: 0.2em,
+ steps: (
+ stroke: none,
+ fill: none,
+ radius: 0.2em,
+ padding: 0.6em,
+ max-width: 5em,
+ shape: "rect"
+ ),
+ arrows: (
+ stroke: none,
+ fill: "steps",
+ height: 1em,
+ width: 1.2em,
+ double: false
+ ),
+ layout: (
+ max-stride: 3,
+ flow: (ltr, ttb)
+ )
+)
+
+#let process-chevron-default-style = (
+ stroke: auto,
+ fill: auto,
+ spacing: 0.2em,
+ start-cap: ">",
+ middle-cap: ">",
+ end-cap: ">",
+ start-in-cap: false,
+ end-in-cap: false,
+ steps: (
+ stroke: none,
+ fill: none,
+ padding: 0.6em,
+ max-width: 5em,
+ cap-ratio: 50%
+ )
+)
+
+/// Draw a basic process chart, describing sequencial steps
+///
+/// ```cexample
+/// let steps = ([Improvise], [Adapt], [Overcome])
+/// let colors = (red, orange, green).map(c => c.lighten(40%))
+///
+/// smartart.process.basic(
+/// steps,
+/// step-style: colors,
+/// equal-width: true,
+/// steps: (max-width: 8em),
+/// dir: ttb
+/// )
+/// ```
+///
+/// === Styling
+/// *Root* `process-basic` \
+/// #show-parameter-block("spacing", ("number", "length"), [
+/// Gap between steps and arrows.], default: 0.2em)
+/// #show-parameter-block("steps.radius", ("number", "length"), [
+/// Corner radius of the steps boxes.], default: 0.2em)
+/// #show-parameter-block("steps.padding", ("number", "length"), [
+/// Inner padding of the steps boxes.], default: 0.6em)
+/// #show-parameter-block("steps.max-width", ("number", "length"), [
+/// Maximum width of the steps boxes.], default: 5em)
+/// #show-parameter-block("steps.shape", ("str", "none"), [
+/// Shape of the steps boxes. One of `"rect"`, `"circle"` or `none`], default: "rect")
+/// #show-parameter-block("steps.fill", ("color", "gradient", "pattern", "none"), [
+/// Fill color of the steps boxes.], default: none)
+/// #show-parameter-block("steps.stroke", ("stroke", "none"), [
+/// Stroke color of the steps boxes.], default: none)
+/// #show-parameter-block("arrows.width", ("number", "length"), [
+/// Width / length of arrows.], default: 1.2em)
+/// #show-parameter-block("arrows.height", ("number", "length"), [
+/// Height of arrows.], default: 1em)
+/// #show-parameter-block("arrows.double", ("boolean"), [
+/// Whether arrows are uni- or bi-directional.], default: false)
+/// #show-parameter-block("arrows.fill", ("string", "color", "gradient", "pattern", "none"), [
+/// Fill color of the arrows. If set to "steps", the arrows will be filled with a color in between those of the neighboring steps.], default: "steps")
+/// #show-parameter-block("arrows.stroke", ("stroke", "none"), [
+/// Stroke used for the arrows.], default: none)
+///
+/// - steps (array): Array of steps (`<content>` or `<str>`)
+/// - arrow-style (function, array, gradient): Arrow style of the following types:
+/// - function: A function of the form `index => style` that must return a style dictionary.
+/// This can be a `palette` function.
+/// - array: An array of style dictionaries or fill colors of at least one item. For each arrow the style at the arrows
+/// index modulo the arrays length gets used.
+/// - gradient: A gradient that gets sampled for each data item using the arrows
+/// index divided by the number of steps as position on the gradient.
+/// If one of stroke or fill is not in the style dictionary, it is taken from the smartarts style.
+/// - step-style (function, array, gradient): Step style of the following types:
+/// - function: A function of the form `index => style` that must return a style dictionary.
+/// This can be a `palette` function.
+/// - array: An array of style dictionaries or fill colors of at least one item. For each step the style at the steps
+/// index modulo the arrays length gets used.
+/// - gradient: A gradient that gets sampled for each data item using the steps
+/// index divided by the number of steps as position on the gradient.
+/// If one of stroke or fill is not in the style dictionary, it is taken from the smartarts style.
+/// - equal-width (boolean): If true, all steps will be sized to have the same width
+/// - equal-height (boolean): If true, all steps will be sized to have the same height
+/// - dir (direction): Direction in which the steps are laid out. The first step is always placed at (0, 0)
+#let basic(
+ steps,
+ arrow-style: auto,
+ step-style: palette.red,
+ equal-width: false,
+ equal-height: false,
+ dir: ltr,
+ name: none,
+ ..style
+) = {
+ draw.group(name: name, ctx => {
+ draw.anchor("default", (0, 0))
+
+ let style = styles.resolve(
+ ctx.style,
+ merge: style.named(),
+ root: "process-basic",
+ base: process-basic-default-style,
+ )
+
+ let spacing = resolve-number(ctx, style.spacing)
+
+ let n-steps = steps.len()
+ let step-style-at = _get-style-at-func(step-style, n-steps)
+ let arrow-style-at = _get-style-at-func(arrow-style, n-steps)
+
+ let (
+ sizes,
+ largest-width,
+ highest-height
+ ) = _get-steps-sizes(steps, ctx, style, step-style-at)
+
+ let vertical = dir.axis() == "vertical"
+ let reverse = dir in (rtl, ttb)
+ let adapt-offset(offset, ..args) = {
+ let offset = offset
+ if vertical {
+ if args.pos().len() != 0 {
+ offset = args.pos().first()
+ } else {
+ offset = offset.rev()
+ }
+ }
+ if reverse {
+ offset = offset.map(v => -v)
+ }
+ return offset
+ }
+
+ let (anchor-1, anchor-2) = _dir-to-anchors(dir)
+
+ for (i, step) in steps.enumerate() {
+ let pos = if i == 0 {
+ (0, 0)
+ } else {
+ (
+ rel: adapt-offset((spacing, 0)),
+ to: "arrow-" + str(i - 1) + ".end"
+ )
+ }
+
+ let step-style = style.steps + step-style-at(i)
+ let padding = resolve-number(ctx, step-style.padding)
+
+ let (w, h) = sizes.at(i)
+ if equal-width {
+ w = largest-width
+ }
+ if equal-height {
+ h = highest-height
+ }
+ let step-name = "step-" + str(i)
+
+ _draw-step(
+ ctx, step, pos, step-style, step-name, w, h,
+ dir: if i == 0 {none} else {dir}
+ )
+
+ if i != n-steps - 1 {
+ let arrow-style = style.arrows + arrow-style-at(i)
+ let arrow-stroke = arrow-style.stroke
+ let arrow-fill = arrow-style.fill
+ let arrow-w = resolve-number(ctx, arrow-style.width)
+ let arrow-h = resolve-number(ctx, arrow-style.height)
+
+ if arrow-fill == "steps" {
+ let s1 = style.steps + step-style-at(i)
+ let s2 = style.steps + step-style-at(i + 1)
+ arrow-fill = gradient.linear(s1.fill, s2.fill).sample(50%)
+ }
+
+ let prev = "step-" + str(i)
+ _draw-arrow(
+ (
+ rel: adapt-offset((spacing, 0)),
+ to: prev + "." + anchor-2
+ ),
+ (
+ rel: adapt-offset((spacing + arrow-w, 0)),
+ to: prev + "." + anchor-2
+ ),
+ arrow-h,
+ arrow-fill,
+ arrow-stroke,
+ name: "arrow-" + str(i)
+ )
+ }
+ }
+ })
+}
+
+/// Draw a chevron process chart, describing sequencial steps
+///
+/// ```cexample
+/// let steps = ([Improvise], [Adapt], [Overcome])
+/// let colors = (red, orange, green).map(c => c.lighten(40%))
+///
+/// smartart.process.chevron(
+/// steps,
+/// step-style: colors,
+/// equal-width: true,
+/// steps: (max-width: 8em, cap-ratio: 25%),
+/// dir: btt
+/// )
+/// ```
+///
+/// === Styling
+/// *Root* `process-chevron` \
+/// #show-parameter-block("spacing", ("number", "length"), [
+/// Gap between steps.], default: 0.2em)
+/// #show-parameter-block("start-cap", ("string"), [
+/// Cap at the start of the process (first step). See @@CHEVRON-CAPS for possible values.], default: ">")
+/// #show-parameter-block("mid-cap", ("string"), [
+/// Cap between steps. See @@CHEVRON-CAPS for possible values.], default: ">")
+/// #show-parameter-block("end-cap", ("string"), [
+/// Cap at the end of the process (last step). See @@CHEVRON-CAPS for possible values.], default: ">")
+/// #show-parameter-block("start-in-cap", ("boolean"), [
+/// If true, the content of the first step is shifted inside the start cap (useful with "(" or "<").], default: false)
+/// #show-parameter-block("end-in-cap", ("boolean"), [
+/// If true, the content of the last step is shifted inside the end cap (useful with ")" or ">").], default: false)
+/// #show-parameter-block("steps.padding", ("number", "length"), [
+/// Inner padding of the steps boxes.], default: 0.6em)
+/// #show-parameter-block("steps.max-width", ("number", "length"), [
+/// Maximum width of the steps boxes.], default: 5em)
+/// #show-parameter-block("steps.cap-ratio", ("ratio"), [
+/// Ratio of the caps width relative to the steps heights (or the opposite if laid out vertically).], default: 50%)
+/// #show-parameter-block("steps.fill", ("color", "gradient", "pattern", "none"), [
+/// Fill color of the steps boxes.], default: none)
+/// #show-parameter-block("steps.stroke", ("stroke", "none"), [
+/// Stroke color of the steps boxes.], default: none)
+///
+/// - steps (array): Array of steps (`<content>` or `<str>`)
+/// - step-style (function, array, gradient): Step style of the following types:
+/// - function: A function of the form `index => style` that must return a style dictionary.
+/// This can be a `palette` function.
+/// - array: An array of style dictionaries or fill colors of at least one item. For each step the style at the steps
+/// index modulo the arrays length gets used.
+/// - gradient: A gradient that gets sampled for each data item using the steps
+/// index divided by the number of steps as position on the gradient.
+/// If one of stroke or fill is not in the style dictionary, it is taken from the smartarts style.
+/// - equal-length (boolean): If true, all steps will be sized to have the same length (in the layout's direction, the other dimensions always being equal)
+/// - dir (direction): Direction in which the steps are laid out. The first step is always placed at (0, 0)
+#let chevron(
+ steps,
+ step-style: palette.red,
+ equal-length: false,
+ dir: ltr,
+ name: none,
+ ..style
+) = {
+ draw.group(name: name, ctx => {
+ draw.anchor("default", (0, 0))
+
+ let style = styles.resolve(
+ ctx.style,
+ merge: style.named(),
+ root: "process-chevron",
+ base: process-chevron-default-style,
+ )
+
+ let spacing = resolve-number(ctx, style.spacing)
+
+ let n-steps = steps.len()
+ let step-style-at = _get-style-at-func(step-style, n-steps)
+
+ let (
+ sizes,
+ largest-width,
+ highest-height
+ ) = _get-steps-sizes(steps, ctx, style, step-style-at)
+
+ let vertical = dir.axis() == "vertical"
+ let reverse = dir in (rtl, ttb)
+ let adapt-offset(offset, ..args) = {
+ let offset = offset
+ if vertical {
+ if args.pos().len() != 0 {
+ offset = args.pos().first()
+ } else {
+ offset = offset.rev()
+ }
+ }
+ if reverse {
+ offset = offset.map(v => -v)
+ }
+ return offset
+ }
+
+ let (anchor-1, anchor-2) = _dir-to-anchors(dir)
+
+ for (i, step) in steps.enumerate() {
+ let step-style = style.steps + step-style-at(i)
+
+ let step-stroke = step-style.stroke
+ let step-fill = step-style.fill
+ let padding = resolve-number(ctx, step-style.padding)
+
+ let (w, h) = sizes.at(i)
+ if equal-length {
+ if vertical {
+ h = highest-height
+ } else {
+ w = largest-width
+ }
+ }
+ let thickness = if vertical { largest-width } else { highest-height }
+ let cap-height = thickness + padding * 2
+ let cap-width = step-style.cap-ratio / 100% * cap-height
+ let step-name = "step-" + str(i)
+
+ let cap-s = if i == 0 { style.start-cap }
+ else { style.middle-cap }
+ let cap-e = if i == n-steps - 1 { style.end-cap }
+ else { style.middle-cap }
+
+ let pos = if i == 0 {
+ (0, 0)
+ } else {
+ (
+ rel: adapt-offset((
+ spacing + if cap-s != "|" {cap-width} else {0},
+ 0
+ )),
+ to: "step-" + str(i - 1) + ".end"
+ )
+ }
+ let end = (
+ rel: adapt-offset(
+ (w + padding * 2, 0),
+ (0, h + padding * 2)
+ ),
+ to: pos
+ )
+
+ _draw-chevron(
+ pos,
+ end,
+ cap-height,
+ step-fill,
+ step-stroke,
+ cap-s,
+ cap-e,
+ step-style.cap-ratio,
+ i == 0 and style.start-in-cap,
+ (i == n-steps - 1) and style.end-in-cap,
+ name: step-name
+ )
+ _draw-step-content(step, step-name, w * ctx.length)
+ }
+ })
+}
+
+/// Draw a bending process chart, describing sequencial steps in a zigzag layout
+///
+/// ```cexample
+/// let steps = ([A], [B], [C], [D], [E], [F])
+/// let colors = (
+/// red, orange, yellow.mix(green), green, green.mix(blue), blue
+/// ).map(c => c.lighten(40%))
+///
+/// smartart.process.bending(
+/// steps,
+/// step-style: colors,
+/// equal-width: true,
+/// layout: (
+/// flow: (ltr, btt), max-stride: 2
+/// )
+/// )
+/// ```
+///
+/// === Styling
+/// *Root* `process-bending` \
+/// #show-parameter-block("spacing", ("number", "length"), [
+/// Gap between steps and arrows.], default: 0.2em)
+/// #show-parameter-block("steps.radius", ("number", "length"), [
+/// Corner radius of the steps boxes.], default: 0.2em)
+/// #show-parameter-block("steps.padding", ("number", "length"), [
+/// Inner padding of the steps boxes.], default: 0.6em)
+/// #show-parameter-block("steps.max-width", ("number", "length"), [
+/// Maximum width of the steps boxes.], default: 5em)
+/// #show-parameter-block("steps.shape", ("str", "none"), [
+/// Shape of the steps boxes. One of `"rect"`, `"circle"` or `none`], default: "rect")
+/// #show-parameter-block("steps.fill", ("color", "gradient", "pattern", "none"), [
+/// Fill color of the steps boxes.], default: none)
+/// #show-parameter-block("steps.stroke", ("stroke", "none"), [
+/// Stroke color of the steps boxes.], default: none)
+/// #show-parameter-block("arrows.width", ("number", "length"), [
+/// Width / length of arrows.], default: 1.2em)
+/// #show-parameter-block("arrows.height", ("number", "length"), [
+/// Height of arrows.], default: 1em)
+/// #show-parameter-block("arrows.double", ("boolean"), [
+/// Whether arrows are uni- or bi-directional.], default: false)
+/// #show-parameter-block("layout.max-stride", ("number"), [
+/// Maximum number of steps before turning, i.e. making a zigzag.], default: 3)
+/// #show-parameter-block("layout.flow", ("array"), [
+/// Pair of directions on different axes indicating the primary and secondary layout directions.], default: (ltr, ttb))
+/// #show-parameter-block("arrows.fill", ("string", "color", "gradient", "pattern", "none"), [
+/// Fill color of the arrows. If set to "steps", the arrows will be filled with a color in between those of the neighboring steps.], default: "steps")
+/// #show-parameter-block("arrows.stroke", ("stroke", "none"), [
+/// Stroke used for the arrows.], default: none)
+///
+/// - steps (array): Array of steps (`<content>` or `<str>`)
+/// - arrow-style (function, array, gradient): Arrow style of the following types:
+/// - function: A function of the form `index => style` that must return a style dictionary.
+/// This can be a `palette` function.
+/// - array: An array of style dictionaries or fill colors of at least one item. For each arrow the style at the arrows
+/// index modulo the arrays length gets used.
+/// - gradient: A gradient that gets sampled for each data item using the arrows
+/// index divided by the number of steps as position on the gradient.
+/// If one of stroke or fill is not in the style dictionary, it is taken from the smartarts style.
+/// - step-style (function, array, gradient): Step style of the following types:
+/// - function: A function of the form `index => style` that must return a style dictionary.
+/// This can be a `palette` function.
+/// - array: An array of style dictionaries or fill colors of at least one item. For each step the style at the steps
+/// index modulo the arrays length gets used.
+/// - gradient: A gradient that gets sampled for each data item using the steps
+/// index divided by the number of steps as position on the gradient.
+/// If one of stroke or fill is not in the style dictionary, it is taken from the smartarts style.
+/// - equal-width (boolean): If true, all steps will be sized to have the same width
+/// - equal-height (boolean): If true, all steps will be sized to have the same height
+#let bending(
+ steps,
+ arrow-style: auto,
+ step-style: palette.red,
+ equal-width: false,
+ equal-height: false,
+ name: none,
+ ..style
+) = {
+ draw.group(name: name, ctx => {
+ draw.anchor("default", (0, 0))
+
+ let style = styles.resolve(
+ ctx.style,
+ merge: style.named(),
+ root: "process-bending",
+ base: process-bending-default-style,
+ )
+
+ let n-steps = steps.len()
+ let stride = style.layout.max-stride
+ if stride == none {
+ stride = n-steps
+ }
+ let (flow-primary, flow-secondary) = style.layout.flow
+ assert(
+ flow-primary.axis() != flow-secondary.axis(),
+ message: "Flow axes must be different"
+ )
+ let vertical-first = flow-primary.axis() == "vertical"
+ let primary-reversed = false
+ let secondary-reversed = false
+
+ if vertical-first {
+ primary-reversed = flow-primary == ttb
+ secondary-reversed = flow-secondary == rtl
+ } else {
+ primary-reversed = flow-primary == rtl
+ secondary-reversed = flow-secondary == ttb
+ }
+
+ let spacing = resolve-number(ctx, style.spacing)
+
+ let step-style-at = _get-style-at-func(step-style, n-steps)
+ let arrow-style-at = _get-style-at-func(arrow-style, n-steps)
+
+ let (
+ sizes,
+ largest-width,
+ highest-height
+ ) = _get-steps-sizes(steps, ctx, style, step-style-at)
+
+ let get-step-dir(i) = {
+ // If turning
+ if calc.rem(i, stride) == 0 {
+ return flow-secondary
+ }
+
+ // If "zag"
+ if calc.odd(calc.div-euclid(i, stride)) {
+ return flow-primary.inv()
+ }
+
+ // If "zig"
+ return flow-primary
+ }
+
+ let get-offset(dir, spacing: spacing) = {
+ return (
+ ttb: (0, -1),
+ btt: (0, 1),
+ ltr: (1, 0),
+ rtl: (-1, 0)
+ ).at(_dir-to-str(dir)).map(v => v * spacing)
+ }
+
+ for (i, step) in steps.enumerate() {
+ let dir = get-step-dir(i)
+ let pos = if i == 0 {
+ (0, 0)
+ } else {
+ (
+ rel: get-offset(dir),
+ to: "arrow-" + str(i - 1) + ".end"
+ )
+ }
+
+ let (anchor-1, anchor-2) = _dir-to-anchors(dir)
+ let step-style = style.steps + step-style-at(i)
+ let (w, h) = sizes.at(i)
+ if equal-width {
+ w = largest-width
+ }
+ if equal-height {
+ h = highest-height
+ }
+ let step-name = "step-" + str(i)
+
+ // Draw arrow
+ if i != 0 {
+ let arrow-style = style.arrows + arrow-style-at(i - 1)
+ let arrow-stroke = arrow-style.stroke
+ let arrow-fill = arrow-style.fill
+ let arrow-w = resolve-number(ctx, arrow-style.width)
+ let arrow-h = resolve-number(ctx, arrow-style.height)
+
+ if arrow-fill == "steps" {
+ let s1 = style.steps + step-style-at(i - 1)
+ let s2 = style.steps + step-style-at(i)
+ arrow-fill = gradient.linear(s1.fill, s2.fill).sample(50%)
+ }
+
+ let prev = "step-" + str(i - 1)
+ _draw-arrow(
+ (
+ rel: get-offset(dir),
+ to: prev + "." + anchor-2
+ ),
+ (
+ rel: get-offset(dir, spacing: spacing + arrow-w),
+ to: prev + "." + anchor-2
+ ),
+ arrow-h,
+ arrow-fill,
+ arrow-stroke,
+ name: "arrow-" + str(i - 1)
+ )
+ }
+
+ _draw-step(
+ ctx, step, pos, step-style, step-name, w, h,
+ dir: if i == 0 {none} else {dir}
+ )
+ }
+ })
+}
diff --git a/render/packages/preview/cetz-plot/0.1.4/src/spine/grid.typ b/render/packages/preview/cetz-plot/0.1.4/src/spine/grid.typ
new file mode 100644
index 0000000..d0d818e
--- /dev/null
+++ b/render/packages/preview/cetz-plot/0.1.4/src/spine/grid.typ
@@ -0,0 +1,34 @@
+#import "/src/cetz.typ": vector, draw
+
+// Draw cartesian grid in a rect
+//
+// - proj (function): Axis value->coordinate translation
+// - offset (float): Offset
+// - length (float): Length
+// - direction (vector): Direction vector
+// - ticks (array): List of ticks
+// - style (style): Style dictionary
+// - mode (int): Grid mode 0: no grid, 1 major, 2 minor, 3 both
+#let draw-cartesian(proj, offset, length, direction, ticks, style, mode) = {
+ let direction = vector.norm(direction)
+ let length = direction.map(v => {
+ v * length
+ })
+ let offset = direction.map(v => {
+ v * -offset
+ })
+
+ let major-stroke = style.stroke
+ let minor-stroke = style.minor-stroke
+
+
+ draw.on-layer(style.at("grid-layer", default: 0), {
+ for (value, _, is-major) in ticks {
+ if (if is-major { 1 } else { 2 }).bit-and(mode) != 0 {
+ let origin = vector.add(proj(value), offset)
+ draw.line(origin, vector.add(origin, length),
+ stroke: if is-major { major-stroke } else { minor-stroke })
+ }
+ }
+ })
+}
diff --git a/render/packages/preview/cetz-plot/0.1.4/typst.toml b/render/packages/preview/cetz-plot/0.1.4/typst.toml
new file mode 100644
index 0000000..3a93006
--- /dev/null
+++ b/render/packages/preview/cetz-plot/0.1.4/typst.toml
@@ -0,0 +1,15 @@
+[package]
+name = "cetz-plot"
+version = "0.1.4"
+compiler = "0.13.1"
+repository = "https://github.com/cetz-package/cetz-plot"
+entrypoint = "src/lib.typ"
+authors = [
+ "Johannes Wolf <https://github.com/johannes-wolf>",
+ "fenjalien <https://github.com/fenjalien>"
+]
+categories = [ "visualization" ]
+license = "LGPL-3.0-or-later"
+description = "Plotting module for CeTZ."
+keywords = [ "plot", "chart" ]
+exclude = [ "/gallery/*", "manual.pdf", "manual.typ" ]
diff --git a/render/packages/preview/cetz/0.3.4/LICENSE b/render/packages/preview/cetz/0.3.4/LICENSE
new file mode 100644
index 0000000..65c5ca8
--- /dev/null
+++ b/render/packages/preview/cetz/0.3.4/LICENSE
@@ -0,0 +1,165 @@
+ GNU LESSER GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+
+ This version of the GNU Lesser General Public License incorporates
+the terms and conditions of version 3 of the GNU General Public
+License, supplemented by the additional permissions listed below.
+
+ 0. Additional Definitions.
+
+ As used herein, "this License" refers to version 3 of the GNU Lesser
+General Public License, and the "GNU GPL" refers to version 3 of the GNU
+General Public License.
+
+ "The Library" refers to a covered work governed by this License,
+other than an Application or a Combined Work as defined below.
+
+ An "Application" is any work that makes use of an interface provided
+by the Library, but which is not otherwise based on the Library.
+Defining a subclass of a class defined by the Library is deemed a mode
+of using an interface provided by the Library.
+
+ A "Combined Work" is a work produced by combining or linking an
+Application with the Library. The particular version of the Library
+with which the Combined Work was made is also called the "Linked
+Version".
+
+ The "Minimal Corresponding Source" for a Combined Work means the
+Corresponding Source for the Combined Work, excluding any source code
+for portions of the Combined Work that, considered in isolation, are
+based on the Application, and not on the Linked Version.
+
+ The "Corresponding Application Code" for a Combined Work means the
+object code and/or source code for the Application, including any data
+and utility programs needed for reproducing the Combined Work from the
+Application, but excluding the System Libraries of the Combined Work.
+
+ 1. Exception to Section 3 of the GNU GPL.
+
+ You may convey a covered work under sections 3 and 4 of this License
+without being bound by section 3 of the GNU GPL.
+
+ 2. Conveying Modified Versions.
+
+ If you modify a copy of the Library, and, in your modifications, a
+facility refers to a function or data to be supplied by an Application
+that uses the facility (other than as an argument passed when the
+facility is invoked), then you may convey a copy of the modified
+version:
+
+ a) under this License, provided that you make a good faith effort to
+ ensure that, in the event an Application does not supply the
+ function or data, the facility still operates, and performs
+ whatever part of its purpose remains meaningful, or
+
+ b) under the GNU GPL, with none of the additional permissions of
+ this License applicable to that copy.
+
+ 3. Object Code Incorporating Material from Library Header Files.
+
+ The object code form of an Application may incorporate material from
+a header file that is part of the Library. You may convey such object
+code under terms of your choice, provided that, if the incorporated
+material is not limited to numerical parameters, data structure
+layouts and accessors, or small macros, inline functions and templates
+(ten or fewer lines in length), you do both of the following:
+
+ a) Give prominent notice with each copy of the object code that the
+ Library is used in it and that the Library and its use are
+ covered by this License.
+
+ b) Accompany the object code with a copy of the GNU GPL and this license
+ document.
+
+ 4. Combined Works.
+
+ You may convey a Combined Work under terms of your choice that,
+taken together, effectively do not restrict modification of the
+portions of the Library contained in the Combined Work and reverse
+engineering for debugging such modifications, if you also do each of
+the following:
+
+ a) Give prominent notice with each copy of the Combined Work that
+ the Library is used in it and that the Library and its use are
+ covered by this License.
+
+ b) Accompany the Combined Work with a copy of the GNU GPL and this license
+ document.
+
+ c) For a Combined Work that displays copyright notices during
+ execution, include the copyright notice for the Library among
+ these notices, as well as a reference directing the user to the
+ copies of the GNU GPL and this license document.
+
+ d) Do one of the following:
+
+ 0) Convey the Minimal Corresponding Source under the terms of this
+ License, and the Corresponding Application Code in a form
+ suitable for, and under terms that permit, the user to
+ recombine or relink the Application with a modified version of
+ the Linked Version to produce a modified Combined Work, in the
+ manner specified by section 6 of the GNU GPL for conveying
+ Corresponding Source.
+
+ 1) Use a suitable shared library mechanism for linking with the
+ Library. A suitable mechanism is one that (a) uses at run time
+ a copy of the Library already present on the user's computer
+ system, and (b) will operate properly with a modified version
+ of the Library that is interface-compatible with the Linked
+ Version.
+
+ e) Provide Installation Information, but only if you would otherwise
+ be required to provide such information under section 6 of the
+ GNU GPL, and only to the extent that such information is
+ necessary to install and execute a modified version of the
+ Combined Work produced by recombining or relinking the
+ Application with a modified version of the Linked Version. (If
+ you use option 4d0, the Installation Information must accompany
+ the Minimal Corresponding Source and Corresponding Application
+ Code. If you use option 4d1, you must provide the Installation
+ Information in the manner specified by section 6 of the GNU GPL
+ for conveying Corresponding Source.)
+
+ 5. Combined Libraries.
+
+ You may place library facilities that are a work based on the
+Library side by side in a single library together with other library
+facilities that are not Applications and are not covered by this
+License, and convey such a combined library under terms of your
+choice, if you do both of the following:
+
+ a) Accompany the combined library with a copy of the same work based
+ on the Library, uncombined with any other library facilities,
+ conveyed under the terms of this License.
+
+ b) Give prominent notice with the combined library that part of it
+ is a work based on the Library, and explaining where to find the
+ accompanying uncombined form of the same work.
+
+ 6. Revised Versions of the GNU Lesser General Public License.
+
+ The Free Software Foundation may publish revised and/or new versions
+of the GNU Lesser General Public License from time to time. Such new
+versions will be similar in spirit to the present version, but may
+differ in detail to address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Library as you received it specifies that a certain numbered version
+of the GNU Lesser General Public License "or any later version"
+applies to it, you have the option of following the terms and
+conditions either of that published version or of any later version
+published by the Free Software Foundation. If the Library as you
+received it does not specify a version number of the GNU Lesser
+General Public License, you may choose any version of the GNU Lesser
+General Public License ever published by the Free Software Foundation.
+
+ If the Library as you received it specifies that a proxy can decide
+whether future versions of the GNU Lesser General Public License shall
+apply, that proxy's public statement of acceptance of any version is
+permanent authorization for you to choose that version for the
+Library.
diff --git a/render/packages/preview/cetz/0.3.4/README.md b/render/packages/preview/cetz/0.3.4/README.md
new file mode 100644
index 0000000..ffb609e
--- /dev/null
+++ b/render/packages/preview/cetz/0.3.4/README.md
@@ -0,0 +1,117 @@
+# CeTZ
+
+CeTZ (CeTZ, ein Typst Zeichenpaket) is a library for drawing with [Typst](https://typst.app) with an API inspired by TikZ and [Processing](https://processing.org/).
+
+## Examples
+<!-- img width is set so the table gets evenly spaced by GitHubs css -->
+<table>
+<tr>
+ <td>
+ <a href="gallery/karls-picture.typ">
+ <img src="gallery/karls-picture.png" width="250px">
+ </a>
+ </td>
+ <td>
+ <a href="gallery/paciolis.typ">
+ <img src="gallery/paciolis.png" width="250px">
+ </a>
+ </td>
+ <td>
+ <a href="gallery/waves.typ">
+ <img src="gallery/waves.png" width="250px">
+ </a>
+ </td>
+</tr>
+<tr>
+ <td>Karl's Picture</td>
+ <td>Pacioli's construction of the icosahedron</td>
+ <td>Waves</td>
+</tr>
+<tr>
+ <td>
+ <a href="gallery/tree.typ">
+ <img src="gallery/tree.png" width="250px">
+ </a>
+ </td>
+ <td>
+ <a href="gallery/periodic-table.typ">
+ <img src="gallery/periodic-table.png" width="250px">
+ </a>
+ </td>
+ <td>
+ <a href="gallery/plate-capacitor.typ">
+ <img src="gallery/plate-capacitor.png" width="250px">
+ </a>
+ </td>
+</tr>
+<tr>
+ <td>Tree Layout</td>
+ <td>Periodic Table of Elements</td>
+ <td>Plate Capacitor</td>
+</tr>
+</table>
+
+*Click on the example image to jump to the code.*
+
+You can explore an example gallery of scientific diagrams at [janosh.github.io/diagrams](https://janosh.github.io/diagrams).
+
+## Usage
+
+For information, see the [online manual](https://cetz-package.github.io/docs).
+
+To use this package, simply add the following code to your document:
+```
+#import "@preview/cetz:0.3.4"
+
+#cetz.canvas({
+ import cetz.draw: *
+ // Your drawing code goes here
+})
+```
+
+## CeTZ Libraries
+
+- [cetz-plot - Plotting and Charts Library](https://github.com/cetz-package/cetz-plot)
+- [cetz-venn - Simple two- or three-set Venn diagrams](https://github.com/cetz-package/cetz-venn)
+
+## Installing
+
+To install the CeTZ package under [your local typst package dir](https://github.com/typst/packages?tab=readme-ov-file#local-packages) you can use the `install` script from the repository.
+
+```bash
+just install
+```
+
+The installed version can be imported by prefixing the package name with `@local`.
+
+```typ
+#import "@local/cetz:0.3.4"
+
+#cetz.canvas({
+ import cetz.draw: *
+ // Your drawing code goes here
+})
+```
+
+### Just
+
+This project uses [just](https://github.com/casey/just), a handy command runner.
+
+You can run all commands without having `just` installed, just have a look into the `justfile`.
+To install `just` on your system, use your systems package manager. On Windows, [Cargo](https://doc.rust-lang.org/cargo/) (`cargo install just`), [Chocolatey](https://chocolatey.org/) (`choco install just`) and [some other sources](https://just.systems/man/en/chapter_4.html) can be used. You need to run it from a `sh` compatible shell on Windows (e.g git-bash).
+
+## Testing
+
+This package comes with some unit tests under the `tests` directory.
+To run all tests you can run the `just test` target. You need to have
+[`tytanic`](https://github.com/tingerrr/tytanic/) in your `PATH`: `cargo install tytanic`.
+
+## Projects using CeTZ
+- [cirCeTZ](https://github.com/fenjalien/cirCeTZ) A port of [circuitikz](https://github.com/circuitikz/circuitikz) to Typst.
+- [conchord](https://github.com/sitandr/conchord) Package for writing lyrics with chords that generates fretboard diagrams using CeTZ.
+- [finite](https://github.com/jneug/typst-finite) Finite is a Typst package for rendering finite automata.
+- [fletcher](https://github.com/Jollywatt/typst-fletcher) Package for drawing commutative diagrams and figures with arrows.
+- [riesketcher](https://github.com/ThatOneCalculator/riesketcher) Package for drawing Riemann sums.
+- [chronos](https://git.kb28.ch/HEL/chronos) Package for drawing sequence diagrams.
+- [circuiteria](https://git.kb28.ch/HEL/circuiteria) Package for drawing circuits.
+- [rivet](https://git.kb28.ch/HEL/rivet-typst) Package for drawing instruction / register diagrams.
diff --git a/render/packages/preview/cetz/0.3.4/src/aabb.typ b/render/packages/preview/cetz/0.3.4/src/aabb.typ
new file mode 100644
index 0000000..f48c4dd
--- /dev/null
+++ b/render/packages/preview/cetz/0.3.4/src/aabb.typ
@@ -0,0 +1,68 @@
+#import "vector.typ"
+
+/// Compute an axis aligned bounding box (aabb) for a list of <Type>vectors</Type>.
+///
+/// - pts (array): List of <Type>vector</Type>s.
+/// - init (aabb): Initial aabb
+/// -> aabb
+#let aabb(pts, init: none) = {
+ let bounds = init
+
+ if type(pts) == array {
+ for (i, pt) in pts.enumerate() {
+ if bounds == none and i == 0 {
+ bounds = (low: pt, high: pt)
+ } else {
+ assert(type(pt) == array and pt.len() == 3, message: repr(init) + repr(pts))
+ let (x, y, z) = pt
+
+ let (lo-x, lo-y, lo-z) = bounds.low
+ bounds.low = (calc.min(lo-x, x), calc.min(lo-y, y), calc.min(lo-z, z))
+
+ let (hi-x, hi-y, hi-z) = bounds.high
+ bounds.high = (calc.max(hi-x, x), calc.max(hi-y, y), calc.max(hi-z, z))
+ }
+ }
+ return bounds
+ } else if type(pts) == dictionary {
+ if init == none {
+ return pts
+ } else {
+ return aabb((pts.low, pts.high,), init: bounds)
+ }
+ }
+
+ panic("Expected array of vectors or bbox dictionary, got: " + repr(pts))
+}
+
+/// Get the mid-point of an AABB as vector.
+///
+/// - bounds (aabb): The AABB to get the mid-point of.
+/// -> vector
+#let mid(bounds) = {
+ return vector.scale(vector.add(bounds.low, bounds.high), .5)
+}
+
+/// Get the size of an aabb as vector. This is a vector from the aabb's low to high.
+///
+/// - bounds (aabb): The aabb to get the size of.
+/// -> vector
+#let size(bounds) = {
+ return vector.sub(bounds.high, bounds.low)
+}
+
+/// Pad AABB with padding from dictionary with keys top, left, right and bottom.
+///
+/// - bounds (aabb): The AABB to pad.
+/// - padding (none, dictionary): Padding values
+///
+/// -> aabb
+#let padded(bounds, padding) = {
+ if padding != none {
+ bounds.low.at(0) -= padding.at("left", default: 0)
+ bounds.low.at(1) -= padding.at("top", default: 0)
+ bounds.high.at(0) += padding.at("right", default: 0)
+ bounds.high.at(1) += padding.at("bottom", default: 0)
+ }
+ return bounds
+}
diff --git a/render/packages/preview/cetz/0.3.4/src/anchor.typ b/render/packages/preview/cetz/0.3.4/src/anchor.typ
new file mode 100644
index 0000000..eca524b
--- /dev/null
+++ b/render/packages/preview/cetz/0.3.4/src/anchor.typ
@@ -0,0 +1,212 @@
+#import "deps.typ"
+#import deps.oxifmt: strfmt
+
+#import "util.typ"
+#import "intersection.typ"
+#import "drawable.typ"
+#import "path-util.typ"
+#import "matrix.typ"
+#import "vector.typ"
+
+// Compass direction to angle
+#let named-border-anchors = (
+ east: 0deg,
+ north-east: 45deg,
+ north: 90deg,
+ north-west: 135deg,
+ west: 180deg,
+ south-west: 225deg,
+ south: 270deg,
+ south-east: 315deg,
+)
+
+// Path anchors
+#let named-path-anchors = (
+ start: 0%,
+ mid: 50%,
+ end: 100%,
+)
+
+/// Calculates a border anchor at the given angle by testing for an intersection between a line and the given drawables. Returns `none` if no intersection is found for better error reporting.
+///
+/// - center (vector): The position from which to start the test line.
+/// - x-dist (number): The furthest distance the test line should go in the x direction.
+/// - y-dist (number): The furthest distance the test line should go in the y direction.
+/// - drawables (drawables): Drawables to test for an intersection against. Ideally should be of type path but all others are ignored.
+/// - angle (angle): The angle to check for a border anchor at.
+/// -> vector,none
+#let border(center, x-dist, y-dist, drawables, angle) = {
+ x-dist += util.float-epsilon
+ y-dist += util.float-epsilon
+
+ if type(drawables) == dictionary {
+ drawables = (drawables,)
+ }
+
+ let test-line = (
+ center,
+ (
+ center.at(0) + x-dist * calc.cos(angle),
+ center.at(1) + y-dist * calc.sin(angle),
+ center.at(2),
+ )
+ )
+
+ let pts = ()
+ for drawable in drawables {
+ if drawable.type != "path" {
+ continue
+ }
+ pts += intersection.line-path(..test-line, drawable)
+ }
+
+ if pts.len() == 1 {
+ return pts.first()
+ }
+
+
+ return if pts.len() == 1 {
+ pts.first()
+ } else if pts.len() > 1 {
+ // Find the furthest intersection point from center
+ util.sort-points-by-distance(center, pts).last()
+ }
+}
+
+
+/// Setup an anchor calculation and handling function for an element. Unifies anchor error checking and calculation of the offset transform.
+///
+/// A tuple of a transformation matrix and function will be returned.
+/// The transform is calculated by translating the given transform by the distance between the position of `offset-anchor` and `default`. It can then be used to correctly transform an element's drawables. If either are none the calculation won't happen but the transform will still be returned.
+/// The function can be used to get the transformed anchors of an element by passing it a string. An empty array can be passed to get the list of valid anchors.
+///
+/// - callback (function, auto): The function to call to get a named anchor's position. The anchor's name will be passed and it should return a <Type>vector</Type> (`str => vector`). If no named anchors exist on the element `auto` can be given instead of a function.
+/// - anchor-names (array): A list of valid anchor names. This list will be used to validate an anchor exists before `callback` is used.
+/// - default (str,none): The name of the default anchor, if one exists.
+/// - transform (matrix,none): The current transformation matrix to apply to an anchor's position before returning it. If `offset-anchor` and `default` is set, it will be first translated by the distance between them.
+/// - name (str, none): The name of the element, this is only used in the error message in the event an anchor is invalid.
+/// - offset-anchor (str, none): The name of an anchor to offset the transform by.
+/// - border-anchors (bool): If true, add border anchors.
+/// - path-anchors (bool): If true, add path anchors.
+/// - radii (none,array): Radius tuple used for border anchor calculation.
+/// - path (none,drawable): Path used for path and border anchor calculation.
+/// -> array
+#let setup(
+ callback,
+ anchor-names,
+ default: none,
+ transform: none,
+ name: none,
+ offset-anchor: none,
+ border-anchors: false,
+ path-anchors: false,
+ radii: none,
+ path: none,
+ nested-anchors: false
+ ) = {
+ // Passing no callback is valid!
+ if callback == auto {
+ callback = (anchor) => {}
+ }
+
+ // Add enabled anchor names
+ if border-anchors {
+ assert("center" in anchor-names and radii != none and path != none,
+ message: "Border anchors need a center anchor, radii and the path set!")
+ }
+ if path-anchors {
+ assert(path != none,
+ message: "Path anchors need the path set!")
+ }
+
+ // Anchor callback
+ let calculate-anchor(anchor, transform: none) = {
+ if anchor == () {
+ return (anchor-names + if border-anchors { named-border-anchors.keys() } + if path-anchors { named-path-anchors.keys() }).dedup()
+ }
+
+ let out = none
+ let nested-anchors = if type(anchor) == array {
+ if not nested-anchors {
+ anchor = anchor.join(".")
+ } else {
+ if anchor.len() > 1 {
+ anchor
+ }
+ anchor = anchor.first()
+ }
+ } else if nested-anchors and type(anchor) == str {
+ anchor = anchor.split(".")
+ if anchor.len() > 1 {
+ anchor
+ }
+ anchor = anchor.first()
+ }
+
+
+ if type(anchor) == str {
+ if anchor in anchor-names or (anchor == "default" and default != none) {
+ if anchor == "default" {
+ anchor = default
+ }
+
+ out = callback(if nested-anchors != none { nested-anchors } else { anchor })
+ } else if path-anchors and anchor in named-path-anchors {
+ anchor = named-path-anchors.at(anchor)
+ } else if border-anchors and anchor in named-border-anchors {
+ anchor = named-border-anchors.at(anchor)
+ } else if util.str-is-number(anchor) {
+ anchor = util.str-to-number(if nested-anchors != none { nested-anchors.join(".") } else { anchor })
+ } else {
+ panic(
+ strfmt(
+ "Anchor '{}' not in anchors {} for element '{}'",
+ anchor,
+ repr(anchor-names),
+ name
+ )
+ )
+ }
+ }
+
+ if out == none {
+ if type(anchor) in (ratio, float, int) {
+ assert(path-anchors, message: strfmt("Element '{}' does not support path anchors.", name))
+ out = path-util.point-on-path(path.segments, anchor)
+ } else if type(anchor) == angle {
+ assert(border-anchors, message: strfmt("Element '{}' does not support border anchors.", name))
+ out = border(callback("center"), ..radii, path, anchor)
+ assert(out != none, message: strfmt("Element '{}' does not have a border for anchor '{}'.", name, anchor))
+ } else {
+ panic(strfmt("Unknown anchor '{}' for element '{}'", repr(anchor), name))
+ }
+ }
+
+ return if transform != none {
+ util.apply-transform(
+ transform,
+ out
+ )
+ } else {
+ out
+ }
+ }
+
+ if default != none and offset-anchor != none {
+ let offset = matrix.transform-translate(
+ ..vector.sub(calculate-anchor(default), calculate-anchor(offset-anchor)).slice(0, 3)
+ )
+ transform = if transform != none {
+ matrix.mul-mat(
+ transform,
+ offset
+ )
+ } else {
+ offset
+ }
+ }
+
+ return (if transform == none { matrix.ident(4) } else { transform }, calculate-anchor.with(transform: transform))
+}
+
+
diff --git a/render/packages/preview/cetz/0.3.4/src/bezier.typ b/render/packages/preview/cetz/0.3.4/src/bezier.typ
new file mode 100644
index 0000000..2ed27fb
--- /dev/null
+++ b/render/packages/preview/cetz/0.3.4/src/bezier.typ
@@ -0,0 +1,641 @@
+// This file contains functions related to bezier curve calculation
+// Many functions are ports from https://github.com/Pomax/bezierjs
+#import "vector.typ"
+
+// Map number v from range (ds, de) to (ts, te)
+#let _map(v, ds, de, ts, te) = {
+ let d1 = de - ds
+ let d2 = te - ts
+ let v2 = v - ds
+ let r = v2 / d1
+ return ts + d2 * r
+}
+
+/// Get the point on quadratic bezier at position `t`.
+///
+/// - a (vector): Start point
+/// - b (vector): End point
+/// - c (vector): Control point
+/// - t (float): Position on curve $[0, 1]$
+/// -> vector
+#let quadratic-point(a, b, c, t) = {
+ // (1-t)^2 * a + 2 * (1-t) * t * c + t^2 b
+ return vector.add(
+ vector.add(
+ vector.scale(a, calc.pow(1-t, 2)),
+ vector.scale(c, 2 * (1-t) * t)
+ ),
+ vector.scale(b, calc.pow(t, 2))
+ )
+}
+
+/// Get the derivative (dx/dt) of a quadratic bezier at position `t`.
+///
+/// - a (vector): Start point
+/// - b (vector): End point
+/// - c (vector): Control point
+/// - t (float): Position on curve [0, 1]
+/// -> vector
+#let quadratic-derivative(a, b, c, t) = {
+ // 2(-a(1-t) + bt - 2ct + c)
+ return vector.scale(
+ vector.add(
+ vector.sub(
+ vector.add(
+ vector.scale(vector.neg(a), (1 - t)),
+ vector.scale(b, t)),
+ vector.scale(c, 2 * t)),
+ c)
+ , 2)
+}
+
+/// Get the point on a cubic bezier curve at position `t`.
+///
+/// - a (vector): Start point
+/// - b (vector): End point
+/// - c1 (vector): Control point 1
+/// - c2 (vector): Control point 2
+/// - t (float): Position on curve [0, 1]
+/// -> vector
+#let cubic-point(a, b, c1, c2, t) = {
+ // (1-t)^3*a + 3*(1-t)^2*t*c1 + 3*(1-t)*t^2*c2 + t^3*b
+ vector.add(
+ vector.add(
+ vector.scale(a, calc.pow(1-t, 3)),
+ vector.scale(c1, 3 * calc.pow(1-t, 2) * t)
+ ),
+ vector.add(
+ vector.scale(c2, 3*(1-t)*calc.pow(t,2)),
+ vector.scale(b, calc.pow(t, 3))
+ )
+ )
+}
+
+/// Get the derivative (dx/dt) of a cubic bezier at position `t`.
+///
+/// - a (vector): Start point
+/// - b (vector): End point
+/// - c1 (vector): Control point 1
+/// - c2 (vector): Control point 2
+/// - t (float): Position on curve [0, 1]
+/// -> vector
+#let cubic-derivative(a, b, c1, c2, t) = {
+ // -3(a(1-t)^2 + t(-2c2 - bt + 3 c2 t) + c1(-1 + 4t - 3t^2))
+ vector.scale(
+ vector.add(
+ vector.add(
+ vector.scale(a, calc.pow((1 - t), 2)),
+ vector.scale(
+ vector.sub(
+ vector.add(
+ vector.scale(b, -1 * t),
+ vector.scale(c2, 3 * t)
+ ),
+ vector.scale(c2, 2)
+ ),
+ t
+ )
+ ),
+ vector.scale(c1, -3 * calc.pow(t, 2) + 4 * t - 1)
+ ),
+ -3
+ )
+}
+
+/// Get a bezier curve's ABC coordinates. Returns them as a respective <Type>array</Type> of <Type>vector</Type>s.
+/// ```
+/// /A\ <-- Control point of quadratic bezier
+/// / | \
+/// / | \
+/// /_.-B-._\ <-- Point on curve
+/// ,' | ',
+/// / | \
+/// s------C------e <-- Point on line between s and e
+/// ```
+/// - s (vector): Curve start
+/// - e (vector): Curve end
+/// - B (vector): Point on curve
+/// - t (float): Position on curve $[0, 1]$
+/// - deg (int): Bezier degree (2 or 3)
+/// -> array
+#let to-abc(s, e, B, t, deg: 2) = {
+ let abc-ratio(t) = {
+ if t == 0 or t == 1 { return t }
+ let bottom = calc.pow(t, deg) + calc.pow(1 - t, deg)
+ let top = bottom - 1
+ return calc.abs(top / bottom)
+ }
+
+ let projection-ratio(t) = {
+ if t == 0 or t == 1 { return t }
+ let top = calc.pow(1 - t, deg)
+ let bottom = calc.pow(t, deg) + top
+ return top / bottom
+ }
+
+ let u = projection-ratio(t)
+ let um = 1 - u
+
+ let C = vector.add(
+ vector.scale(s, u),
+ vector.scale(e, um))
+
+ let s = abc-ratio(t)
+ let A = vector.add(
+ B,
+ vector.scale(vector.sub(B, C), 1/s))
+
+ return (A, B, C)
+}
+
+
+/// Compute the control points for a quadratic bezier through 3 points.
+///
+/// - s (vector): Curve start
+/// - e (vector): Curve end
+/// - B (vector): A point which the curve passes through
+/// -> bezier
+#let quadratic-through-3points(s, B, e) = {
+ let d1 = vector.dist(s, B)
+ let d2 = vector.dist(e, B)
+ let t = d1 / (d1 + d2)
+
+ let (A, B, C) = to-abc(s, e, B, t, deg: 2)
+
+ return (s, e, A)
+}
+
+
+/// Convert a quadratic bezier to a cubic bezier.
+///
+/// - s (vector): Curve start
+/// - e (vector): Curve end
+/// - c (vector): Control point
+/// -> bezier
+#let quadratic-to-cubic(s, e, c) = {
+ let c1 = vector.add(s, vector.scale(vector.sub(c, s), 2/3))
+ let c2 = vector.add(e, vector.scale(vector.sub(c, e), 2/3))
+ return (s, e, c1, c2)
+}
+
+/// Compute the control points for a cubic bezier through 3 points.
+///
+/// - s (vector): Curve start
+/// - e (vector): Curve end
+/// - B (vector): A point which the curve passes through
+/// -> bezier
+#let cubic-through-3points(s, B, e) = {
+ if s == B or e == B {
+ return (s, e, s, e)
+ }
+
+ let d1 = vector.dist(s, B)
+ let d2 = vector.dist(e, B)
+ let t = d1 / (d1 + d2)
+
+ let (A, _, C) = to-abc(s, e, B, t, deg: 3)
+
+ let angle = vector.angle2(s, e) - vector.angle2(s, B)
+ if angle == 0deg or calc.abs(angle) == 180deg {
+ let se = vector.dist(s, e)
+ let sB = vector.dist(s, B)
+ let eB = vector.dist(e, B)
+
+ if sB >= se and sB >= eB {
+ return (s, B, s, B)
+ } else if eB >= se and eB >= sB {
+ return (e, B, e, B)
+ }
+ return (s, e, s, e)
+ }
+
+ let bc = (if angle < 0deg or angle > 180deg { -1 } else { 1 }) * vector.dist(s, e) / 3
+ let de1 = t * bc
+ let de2 = (1 - t) * bc
+
+ let (ax, ay, az) = A
+ let (sx, sy, sz) = s
+ let (ex, ey, ez) = e
+ let (bx, by, bz) = B
+
+ import "/src/util.typ": calculate-circle-center-3pt
+ let (cx, cy, cz) = calculate-circle-center-3pt(s, B, e)
+ let tangent = (
+ (bx - (by - cy), by + (bx - cx), bz),
+ (bx + (by - cy), by - (bx - cx), bz))
+ let (dx, dy, dz) = vector.norm(vector.sub(tangent.at(1), tangent.at(0)))
+
+ let (e1x, e1y) = (
+ bx + de1 * dx,
+ by + de1 * dy)
+ let (e2x, e2y) = (
+ bx - de2 * dx,
+ by - de2 * dy)
+ let (v1x, v1y) = (
+ ax + (e1x - ax) / (1 - t),
+ ay + (e1y - ay) / (1 - t))
+ let (v2x, v2y) = (
+ ax + (e2x - ax) / t,
+ ay + (e2y - ay) / t)
+ let c1 = (
+ sx + (v1x - sx) / t,
+ sy + (v1y - sy) / t)
+ let c2 = (
+ ex + (v2x - ex) / (1 - t),
+ ey + (v2y - ey) / (1 - t))
+
+ return (s, e, c1, c2)
+}
+
+/// Split a cubic bezier into two cubic beziers at the point `t`. Returns an <Type>array</Type> of two <Type>bezier</Type>. The first holds the original curve start `s`, and the second holds the original curve end `e`.
+///
+/// - s (vector): Curve start
+/// - e (vector): Curve end
+/// - c1 (vector): Control point 1
+/// - c2 (vector): Control point 2
+/// - t (float): The point on the bezier to split, $[0, 1]$
+/// -> array
+#let split(s, e, c1, c2, t) = {
+ t = calc.max(0, calc.min(t, 1))
+
+ let split-rec(pts, t, left, right) = {
+ if pts.len() == 1 {
+ left.push(pts.at(0))
+ right.push(pts.at(0))
+ } else {
+ let new-pts = ()
+ for i in range(0, pts.len() - 1) {
+ if i == 0 {
+ left.push(pts.at(i))
+ }
+ if i == pts.len() - 2 {
+ right.push(pts.at(i + 1))
+ }
+ new-pts.push(vector.add(vector.scale(pts.at(i), (1 - t)),
+ vector.scale(pts.at(i + 1), t)))
+ }
+ (left, right) = split-rec(new-pts, t, left, right)
+ }
+ return (left, right)
+ }
+ let (left, right) = split-rec((s, c1, c2, e), t, (), ())
+
+ return ((left.at(0), left.at(3), left.at(1), left.at(2)),
+ (right.at(3), right.at(0), right.at(2), right.at(1)))
+}
+
+/// Get the approximate cubic curve length
+/// - s (vector): Curve start
+/// - e (vector): Curve end
+/// - c1 (vector): Control point 1
+/// - c2 (vector): Control point 2
+/// -> float
+#let cubic-arclen(s, e, c1, c2, samples: 10) = {
+ let d = 0
+ let last = none
+ for t in range(0, samples + 1) {
+ let pt = cubic-point(s, e, c1, c2, t / samples)
+ if last != none {
+ d += vector.dist(last, pt)
+ }
+ last = pt
+ }
+ return d
+}
+
+/// Shorten the curve by offsetting s and c1 or e and c2 by distance d. If d is positive the curve gets shortened by moving s and c1 closer to e, if d is negative, e and c2 get moved closer to s.
+///
+/// - s (vector): Curve start
+/// - e (vector): Curve end
+/// - c1 (vector): Control point 1
+/// - c2 (vector): Control point 2
+/// - d (float): Distance to shorten by
+/// -> bezier
+#let cubic-shorten-linear(s, e, c1, c2, d) = {
+ if d == 0 { return (s, e, c1, c2) }
+
+ let t = if d < 0 { 1 } else { 0 }
+ let sign = if d < 0 { -1 } else { 1 }
+
+ let a = cubic-point(s, e, c1, c2, t)
+ let b = cubic-point(s, e, c1, c2, t + sign * 0.01)
+ let offset = vector.scale(vector.norm(vector.sub(b, a)),
+ calc.abs(d))
+ if d > 0 {
+ s = vector.add(s, offset)
+ c1 = vector.add(c1, offset)
+ } else {
+ e = vector.add(e, offset)
+ c2 = vector.add(c2, offset)
+ }
+ return (s, e, c1, c2)
+}
+
+/// Approximate bezier interval `t` for a given distance `d`. If `d` is positive, the functions starts from the curve's start `s`, if `d` is negative, it starts form the curve's end `e`.
+/// - s (vector): Curve start
+/// - e (vector): Curve end
+/// - c1 (vector): Control point 1
+/// - c2 (vector): Control point 2
+/// - d (float): The distance along the bezier to find `t`.
+/// -> float
+#let cubic-t-for-distance(s, e, c1, c2, d, samples: 20) = {
+ let travel-forwards(s, e, c1, c2, d) = {
+ let sum = 0
+ for n in range(1, samples + 1) {
+ let t0 = (n - 1) / samples
+ let t1 = n / samples
+
+ let segment-dist = vector.dist(cubic-point(s, e, c1, c2, t0),
+ cubic-point(s, e, c1, c2, t1))
+ if sum <= d and d <= sum + segment-dist {
+ return t0 + (d - sum) / segment-dist / samples
+ }
+ sum += segment-dist
+ }
+ return 1
+ }
+
+ if d == 0 {
+ return 0
+ }
+
+ if d > 0 {
+ return travel-forwards(s, e, c1, c2, d)
+ } else {
+ return 1 - travel-forwards(e, s, c2, c1, -d)
+ }
+}
+
+/// Shorten curve by distance `d`. This keeps the curvature of the curve by finding new values along the original curve. If `d` is positive the curve gets shortened by moving `s` closer to `e`, if `d` is negative, `e` is moved closer to `s`. The points `s` and `e` are moved along the curve, keeping the curve's curvature the same (the control points get recalculated).
+///
+/// - s (vector): Curve start
+/// - e (vector): Curve end
+/// - c1 (vector): Control point 1
+/// - c2 (vector): Control point 2
+/// - d (float): Distance to shorten by
+/// - samples (int): Maximum of samples/steps to use
+/// -> bezier
+#let cubic-shorten(s, e, c1, c2, d, samples: 15) = {
+ if d == 0 { return (s, e, c1, c2) }
+
+ let (left, right) = split(s, e, c1, c2, cubic-t-for-distance(s, e, c1, c2, d, samples: samples))
+ return if d > 0 {
+ right
+ } else {
+ left
+ }
+}
+
+/// Find cubic curve extrema by calculating the roots of the curve's first derivative. Returns an <Type>array</Type> of <Type>vector</Type> ordered by distance along the curve from the start to its end.
+/// - s (vector): Curve start
+/// - e (vector): Curve end
+/// - c1 (vector): Control point 1
+/// - c2 (vector): Control point 2
+/// -> array
+#let cubic-extrema(s, e, c1, c2) = {
+ // Compute roots of a single dimension (x, y, z) of the
+ // curve by using the abc formula for finding roots of
+ // the curves first derivative.
+ let dim-extrema(a, b, c1, c2) = {
+ let f0 = calc.round(3*(c1 - a), digits: 8)
+ let f1 = calc.round(6*(c2 - 2*c1 + a), digits: 8)
+ let f2 = calc.round(3*(b - 3*c2 + 3*c1 - a), digits: 8)
+
+ if f1 == 0 and f2 == 0 {
+ return ()
+ }
+
+ // Linear function
+ if f2 == 0 {
+ return (-f0 / f1,)
+ }
+
+ // No real roots
+ let discriminant = f1*f1 - 4*f0*f2
+ if discriminant < 0 {
+ return ()
+ }
+
+ if discriminant == 0 {
+ return (-f1 / (2*f2),)
+ }
+
+ return ((-f1 - calc.sqrt(discriminant)) / (2*f2),
+ (-f1 + calc.sqrt(discriminant)) / (2*f2))
+ }
+
+ let pts = ()
+ let dims = calc.max(s.len(), e.len())
+ for dim in range(dims) {
+ let ts = dim-extrema(
+ s.at(dim, default: 0),
+ e.at(dim, default: 0),
+ c1.at(dim, default: 0),
+ c2.at(dim, default: 0)
+ )
+ for t in ts {
+ // Discard any root outside the bezier range
+ if t >= 0 and t <= 1 {
+ pts.push(cubic-point(s, e, c1, c2, t))
+ }
+ }
+ }
+ return pts
+}
+
+/// Returns axis aligned bounding box coordinates `(bottom-left, top-right)` for a cubic bezier curve.
+///
+/// - s (vector): Curve start
+/// - e (vector): Curve end
+/// - c1 (vector): Control point 1
+/// - c2 (vector): Control point 2
+/// -> array
+#let cubic-aabb(s, e, c1, c2) = {
+ let (lo, hi) = (s, e)
+ for dim in range(lo.len()) {
+ if lo.at(dim) > hi.at(dim) {
+ (lo.at(dim), hi.at(dim)) = (hi.at(dim), lo.at(dim))
+ }
+ }
+ for pt in cubic-extrema(s, e, c1, c2) {
+ for dim in range(pt.len()) {
+ lo.at(dim) = calc.min(lo.at(dim), hi.at(dim), pt.at(dim))
+ hi.at(dim) = calc.max(lo.at(dim), hi.at(dim), pt.at(dim))
+ }
+ }
+ return (lo, hi)
+}
+
+/// Returns a cubic bezier between points `p2` and `p3` for a catmull-rom curve through all four points.
+///
+/// - p1 (vector): Point 1
+/// - p2 (vector): Point 2
+/// - p3 (vector): Point 3
+/// - p4 (vector): Point 4
+/// - k (float): The tension of the catmull-rom curve. Must be in the range $[0, 1]$
+/// -> bezier
+#let _catmull-section-to-cubic(p1, p2, p3, p4, k) = {
+ return (p2, p3,
+ vector.add(p2, vector.scale(vector.sub(p3, p1), 1/(k * 6))),
+ vector.sub(p3, vector.scale(vector.sub(p4, p2), 1/(k * 6))))
+}
+
+/// Returns an array of cubic <Type>bezier</Type> for a catmull curve through an array of points.
+///
+/// - points (array): Array of 2d points
+/// - k (float): Strength between 0 and 1
+/// - close (bool):
+/// -> array
+#let catmull-to-cubic(points, k, close: false) = {
+ k = calc.max(k, 0.1)
+ k = if k < .5 {
+ 1 / _map(k, .5, 0, 1, 10)
+ } else {
+ _map(k, .5, 1, 1, 10)
+ }
+
+ let len = points.len()
+ if len == 2 {
+ return ((points.at(0), points.at(1),
+ points.at(0), points.at(1)),)
+ } else if len > 2 {
+ let curves = ()
+
+ let (i0, iN) = if close {
+ (-1, 0)
+ } else {
+ (0, -1)
+ }
+
+ curves.push(_catmull-section-to-cubic(points.at(i0), points.at(0),
+ points.at(1), points.at(2), k))
+ for i in range(1, len - 2, step: 1) {
+ curves.push(_catmull-section-to-cubic(
+ ..range(i - 1, i + 3).map(i => points.at(i)), k))
+ }
+
+ curves.push(_catmull-section-to-cubic(
+ points.at(-3), points.at(-2), points.at(-1), points.at(iN), k))
+
+ if close {
+ curves.push(_catmull-section-to-cubic(
+ points.at(-2), points.at(-1), points.at(0), points.at(1), k))
+ }
+
+ return curves
+ }
+ return ()
+}
+
+/// Find the roots of a cubic polynomial with the coefficients a, b, c and d.
+///
+/// -> array Array of roots
+#let _cubic-roots(a, b, c, d) = {
+ let epsilon = 1e-6
+ if calc.abs(a) < epsilon {
+ if calc.abs(b) < epsilon {
+ // Constant
+ if c == 0 {
+ return ()
+ }
+
+ // Linear
+ let root = -1 * d / c
+ if root < 0 - epsilon and root > 1 + epsilon {
+ return ()
+ }
+ return (root,)
+ }
+
+ // Quadratic
+ let dq = calc.pow(c, 2) - 4 * b * d
+ if dq >= 0 {
+ dq = calc.sqrt(dq)
+ let roots = (-1 * (dq + c) / (2 * b),
+ (dq - c) / (2 * b))
+ return roots.filter(t => t >= 0 - epsilon and t <= 1 + epsilon)
+ } else {
+ // No real roots
+ return ()
+ }
+ }
+
+ let (A, B, C) = (b/a, c/a, d/a)
+ let Q = (3 * B - calc.pow(A, 2)) / 9
+ let R = (9 * A * B - 27 * C - 2 * calc.pow(A, 3)) / 54
+ let D = calc.pow(Q, 3) + calc.pow(R, 2)
+ let aa = -A / 3
+
+ let sgn = x => { if x < 0 { -1 } else { 1 } }
+ let roots = if D >= 0 {
+ let S = sgn(R + calc.sqrt(D)) * calc.pow(calc.abs(R + calc.sqrt(D)), 1/3)
+ let T = sgn(R - calc.sqrt(D)) * calc.pow(calc.abs(R - calc.sqrt(D)), 1/3)
+
+ if (S - T) != 0 {
+ // Roots 2 and 3 are complex
+ (aa + (S + T),)
+ } else {
+ (aa + (S + T), aa - (S + T) / 2)
+ }
+ } else {
+ let th = calc.acos(R / calc.sqrt(-calc.pow(Q, 3))) / 1rad
+ let qq = 2 * calc.sqrt(-Q)
+ (qq * calc.cos(th / 3) + aa,
+ qq * calc.cos((th + 2 * calc.pi) / 3) + aa,
+ qq * calc.cos((th + 4 * calc.pi) / 3) + aa)
+ }
+
+ return roots.filter(t => t >= 0 - epsilon and t <= 1 + epsilon)
+}
+
+/// Calculate the intersection points between a 2D cubic-bezier and a straight line. Returns an array of <Type>vector</Type>
+///
+/// - s (vector): Bezier start point
+/// - e (vector): Bezier end point
+/// - c1 (vector): Bezier control point 1
+/// - c2 (vector): Bezier control point 2
+/// - la (vector): Line start point
+/// - lb (vector): Line end point
+/// - ray (bool): If set to true, ignore line length
+/// -> array
+#let line-cubic-intersections(la, lb, s, e, c1, c2, ray: false) = {
+ // Based on:
+ // http://www.particleincell.com/blog/2013/cubic-line-intersection/
+ // with some rounding improvements
+ let a = lb.at(1) - la.at(1)
+ let b = la.at(0) - lb.at(0)
+ let c = la.at(0) * (la.at(1) - lb.at(1)) + la.at(1) * (lb.at(0) - la.at(0))
+
+ /// Get cubic bezier function coefficients
+ let _cubic-coeff(a, b, c, d) = (
+ -a + 3*b - 3*c + d,
+ 3*a - 6*b + 3*c,
+ -3*a +3*b,
+ a)
+
+ let x-coeff = _cubic-coeff(s.at(0), c1.at(0), c2.at(0), e.at(0))
+ let y-coeff = _cubic-coeff(s.at(1), c1.at(1), c2.at(1), e.at(1))
+
+ let roots = _cubic-roots(a * x-coeff.at(0) + b * y-coeff.at(0),
+ a * x-coeff.at(1) + b * y-coeff.at(1),
+ a * x-coeff.at(2) + b * y-coeff.at(2),
+ a * x-coeff.at(3) + b * y-coeff.at(3) + c)
+
+ let pts = ()
+ for t in roots {
+ let pt = cubic-point(s, e, c1, c2, t)
+ if ray {
+ pts.push(pt)
+ } else {
+ let s = if calc.abs(lb.at(0) - la.at(0)) >= 1e-6 {
+ (pt.at(0) - la.at(0)) / (lb.at(0) - la.at(0))
+ } else {
+ (pt.at(1) - la.at(1)) / (lb.at(1) - la.at(1))
+ }
+ if s >= 0 and s <= 1 {
+ pts.push(pt)
+ }
+ }
+ }
+ return pts
+}
diff --git a/render/packages/preview/cetz/0.3.4/src/canvas.typ b/render/packages/preview/cetz/0.3.4/src/canvas.typ
new file mode 100644
index 0000000..d11d73f
--- /dev/null
+++ b/render/packages/preview/cetz/0.3.4/src/canvas.typ
@@ -0,0 +1,159 @@
+#import "matrix.typ"
+#import "vector.typ"
+#import "util.typ"
+#import "path-util.typ"
+#import "aabb.typ"
+#import "styles.typ"
+#import "process.typ"
+#import "version.typ"
+
+/// Sets up a canvas for drawing on.
+///
+/// - length (length, ratio): Used to specify what 1 coordinate unit is. If given a ratio, that ratio is relative to the containing elements width!
+/// - body (none, array, element): A code block in which functions from the `draw` module have been called.
+/// - background (none, color): A color to be used for the background of the canvas.
+/// - padding (none, number, array, dictionary) = none: How much padding to add to the canvas. `none` applies no padding. A number applies padding to all sides equally. A dictionary applies padding following Typst's `pad` function: https://typst.app/docs/reference/layout/pad/. An array follows CSS like padding: `(y, x)`, `(top, x, bottom)` or `(top, right, bottom, left)`.
+/// - debug (bool): Shows the bounding boxes of each element when `true`.
+/// -> content
+#let canvas(length: 1cm, debug: false, background: none, padding: none, body) = context { layout(ly => {
+ if body == none {
+ return []
+ }
+ assert(
+ type(body) == array,
+ message: "Incorrect type for body: " + repr(type(body)),
+ )
+
+ assert(type(length) in (std.length, ratio), message: "Expected `length` to be of type length or ratio, got " + repr(length))
+ let length = if type(length) == ratio {
+ length * ly.width
+ } else {
+ length.to-absolute()
+ }
+ assert(length / 1cm != 0,
+ message: "Canvas length must be != 0!")
+
+ let ctx = (
+ version: version.version,
+ length: length,
+ debug: debug,
+ background: background,
+ // Previous element position & bbox
+ prev: (pt: (0, 0, 0)),
+ style: styles.default,
+ // Current transformation matrix, a rhs coordinate system
+ // where z is sheared by a half x and y.
+ // +x = right, +y = up, +z = 1/2 (left + down)
+ transform:
+ ((1, 0,-.5, 0),
+ (0,-1,+.5, 0),
+ (0, 0, 0, 0), // FIXME: This should not be zero for Z! Changing it destroys mark & decorations in 3D space.
+ (0, 0, .0, 1)),
+ // Nodes, stores anchors and paths
+ nodes: (:),
+ // group stack
+ groups: (),
+ // user defined marks
+ marks: (
+ mnemonics: (:),
+ marks: (:),
+ )
+ )
+
+ let (ctx, bounds, drawables) = process.many(ctx, body)
+ if bounds == none {
+ return []
+ }
+
+ // Filter hidden drawables
+ drawables = drawables.filter(d => not d.hidden)
+
+ // Order draw commands by z-index
+ drawables = drawables.sorted(key: (cmd) => {
+ return cmd.at("z-index", default: 0)
+ })
+
+ // Apply padding
+ let padding = util.as-padding-dict(padding)
+ bounds = aabb.padded(bounds, padding)
+
+ let (offset-x, offset-y, ..) = bounds.low
+
+ // Final canvas size
+ let (width, height, ..) = vector.scale(aabb.size(bounds), length)
+
+ let relative = (orig, c) => {
+ return vector.sub(c, orig)
+ }
+
+ box(width: width, height: height, fill: background, align(top, {
+ for drawable in drawables {
+ // Typst path elements have strange bounding boxes. We need to
+ // offset all paths to start at (0, 0) to make gradients work.
+ let (segment-x, segment-y, _) = if drawable.type == "path" {
+ vector.sub(
+ aabb.aabb(path-util.bounds(drawable.segments)).low,
+ bounds.low)
+ } else {
+ (0, 0, 0)
+ }
+
+ place(top + left, float: false, if drawable.type == "path" {
+ let vertices = ()
+
+ let transform-point((x, y, _)) = {
+ ((x - offset-x - segment-x) * length,
+ (y - offset-y - segment-y) * length)
+ }
+
+ let last-point = none
+ for ((kind, ..rest)) in drawable.segments {
+ if kind == "sub" {
+ // TODO: Support sub-paths by converting
+ // Also support move commands.
+ // Refactor path arrays to typst style curves.
+ } else if kind == "cubic" {
+ let pts = rest.map(transform-point)
+
+ if last-point != pts.at(0) {
+ vertices.push(curve.move(pts.at(0)))
+ }
+ vertices.push(curve.cubic(pts.at(2), pts.at(3), pts.at(1)))
+ last-point = pts.at(1)
+ } else {
+ let pts = rest.map(transform-point)
+
+ if last-point != pts.at(0) {
+ vertices.push(curve.move(pts.at(0)))
+ }
+ for i in range(1, pts.len()) {
+ vertices.push(curve.line(pts.at(i)))
+ }
+ last-point = pts.last()
+ }
+ }
+
+ if (drawable.at("close", default: false)) {
+ vertices.push(curve.close(mode: "straight"))
+ }
+
+ if type(drawable.stroke) == dictionary and "thickness" in drawable.stroke and type(drawable.stroke.thickness) != std.length {
+ drawable.stroke.thickness *= length
+ }
+ std.curve(
+ stroke: drawable.stroke,
+ fill: drawable.fill,
+ fill-rule: drawable.at("fill-rule", default: "non-zero"),
+ ..vertices,
+ )
+ } else if drawable.type == "content" {
+ let (width, height) = std.measure(drawable.body)
+ move(
+ dx: (drawable.pos.at(0) - offset-x) * length - width / 2,
+ dy: (drawable.pos.at(1) - offset-y) * length - height / 2,
+ drawable.body,
+ )
+ }, dx: segment-x * length, dy: segment-y * length)
+ }
+ }))
+})}
diff --git a/render/packages/preview/cetz/0.3.4/src/complex.typ b/render/packages/preview/cetz/0.3.4/src/complex.typ
new file mode 100644
index 0000000..8e212a7
--- /dev/null
+++ b/render/packages/preview/cetz/0.3.4/src/complex.typ
@@ -0,0 +1,87 @@
+/// Returns the real part of a complex number.
+/// - V (complex): A complex number.
+/// -> float
+#let re(V) = V.at(0)
+
+/// Returns the imaginary part of a complex number.
+/// - V (complex): A complex number.
+/// -> float
+#let im(V) = V.at(1)
+
+
+/// Multiplies two complex numbers together and returns the result $V W$.
+/// - V (complex): The complex number on the left hand side.
+/// - W (complex): The complex number on the right hand side.
+#let mul(V, W) = (re(V) * re(W) - im(V) * im(W), im(V) * re(W) + re(V) * im(W))
+
+/// Calculates the conjugate of a complex number.
+/// - V (complex): A complex number.
+/// -> complex
+#let conj(V) = (re(V),-im(V))
+
+// TODO: check what "in R^2" means.
+/// Calculates the dot product of two complex numbers in R^2 $V \cdot W$.
+/// - V (complex): The complex number on the left hand side.
+/// - W (complex): The complex number on the right hand side.
+/// -> float
+#let dot(V,W) = re(mul(V,conj(W)))
+
+/// Calculates the squared normal of a complex number.
+/// - V (complex): The complex number.
+/// -> float
+#let normsq(V) = dot(V,V)
+
+
+/// Calculates the normal of a complex number
+/// - V (complex): The complex number.
+/// -> float
+#let norm(V) = calc.sqrt(normsq(V))
+
+/// Multiplies a complex number by a scale factor.
+/// - V (complex): The complex number to scale.
+/// - t (float): The scale factor.
+/// -> complex
+#let scale(V,t) = mul(V,(t,0))
+
+/// Returns a unit vector in the direction of a complex number.
+/// - V (complex): The complex number.
+/// -> vector
+#let unit(V) = scale(V, 1/norm(V))
+
+/// Inverts a complex number.
+/// - V (complex): The complex number
+/// -> complex
+#let inv(V) = scale(conj(V), 1/normsq(V))
+
+/// Divides two complex numbers.
+/// - V (complex): The complex number of the numerator.
+/// - W (complex): The complex number of the denominator.
+/// -> complex
+#let div(V,W) = mul(V,inv(W))
+
+/// Adds two complex numbers together.
+/// - V (complex): The complex number on the left hand side.
+/// - W (complex): The complex number on the right hand side.
+/// -> complex
+#let add(V,W) = (re(V) + re(W),im(V) + im(W))
+
+/// Subtracts two complex numbers together.
+/// - V (complex): The complex number on the left hand side.
+/// - W (complex): The complex number on the right hand side.
+/// -> complex
+#let sub(V,W) = (re(V) - re(W),im(V) - im(W))
+
+/// Calculates the argument of a complex number.
+/// - V (complex): The complex number.
+#let arg(V) = calc.atan2(..V) / 1rad
+
+/// Get the signed angle of two complex numbers from V to W.
+/// - V (complex): A complex number.
+/// - W (complex): A complex number.
+#let ang(V,W) = arg(div(W,V))
+
+// exp(i*a)
+#let expi(a) = (calc.cos(a),calc.sin(a))
+
+// Rotate by angle a
+#let rot(v,a) = mul(v,expi(a))
diff --git a/render/packages/preview/cetz/0.3.4/src/coordinate.typ b/render/packages/preview/cetz/0.3.4/src/coordinate.typ
new file mode 100644
index 0000000..0c0beb1
--- /dev/null
+++ b/render/packages/preview/cetz/0.3.4/src/coordinate.typ
@@ -0,0 +1,357 @@
+#import "vector.typ"
+#import "util.typ"
+#import "deps.typ"
+#import deps.oxifmt: strfmt
+
+#let resolve-xyz(c) = {
+ // (x: <number> or <none>, y: <number> or <none>, z: <number> or <none>)
+ // (x, y)
+ // (x, y, z)
+
+ return if type(c) == array {
+ vector.as-vec(c)
+ } else {
+ (
+ c.at("x", default: 0),
+ c.at("y", default: 0),
+ c.at("z", default: 0),
+ )
+ }
+}
+
+
+#let resolve-polar(c) = {
+ // (angle: <angle>, radius: <number>)
+ // (angle: <angle>, radius: (x, y))
+ // (angle, radius)
+ // (angle, (x-radius, y-radius))
+
+ let (angle, xr, yr) = if type(c) == array {
+ (
+ c.first(),
+ ..if type(c.last()) == array {
+ c.last()
+ } else {
+ (c.last(), c.last())
+ }
+ )
+ } else {
+ (
+ c.angle,
+ ..if type(c.radius) == array {
+ c.radius
+ } else {
+ (c.radius, c.radius)
+ }
+ )
+ }
+ return (
+ xr * calc.cos(angle),
+ yr * calc.sin(angle),
+ 0
+ )
+}
+
+
+#let resolve-anchor(ctx, c) = {
+ // (name: <string>, anchor: <number, angle, string> or <none>)
+ // "name.anchor"
+ // "name"
+ let (name, anchor) = if type(c) == str {
+ let (name, ..anchor) = c.split(".")
+ if anchor.len() == 0 {
+ anchor = "default"
+ }
+ (name, anchor)
+ } else {
+ (c.name, c.at("anchor", default: "default"))
+ }
+
+ // Check if node is known
+ assert(name in ctx.nodes,
+ message: "Unknown element '" + name + "' in elements " + repr(ctx.nodes.keys()))
+
+ // Resolve length anchors
+ if type(anchor) == length {
+ anchor = util.resolve-number(ctx, anchor)
+ }
+
+ // Check if anchor is known
+ let node = ctx.nodes.at(name)
+ let pos = (node.anchors)(anchor)
+
+ let pos = util.revert-transform(
+ ctx.transform,
+ pos
+ )
+
+ return pos
+}
+
+#let resolve-barycentric(ctx, c) = {
+ // dictionary of numbers
+ return vector.scale(
+ c.bary.pairs().fold(
+ (0, 0, 0),
+ (vec, (k, v)) => {
+ vector.add(
+ vec,
+ vector.scale(
+ resolve-anchor(ctx, k),
+ v
+ )
+ )
+ }
+ ),
+ 1 / c.bary.values().sum()
+ )
+}
+
+#let resolve-relative(resolve, ctx, c) = {
+ // (rel: <coordinate>, update: <bool> or <none>, to: <coordinate>)
+ let update = c.at("update", default: true)
+ let (ctx, rel) = resolve(ctx, c.rel, update: false)
+ let (ctx, to) = if "to" in c {
+ resolve(ctx, c.to, update: false)
+ } else {
+ (ctx, ctx.prev.pt)
+ }
+ c = vector.add(
+ rel,
+ to,
+ )
+ c.insert(0, update)
+ return c
+}
+
+#let resolve-tangent(resolve, ctx, c) = {
+ // (element: <string>, point: <coordinate>, solution: <integer>)
+
+ // https://stackoverflow.com/a/69641745/7142815
+ let C = resolve-anchor(ctx, c.element)
+ let (ctx, P) = resolve(ctx, c.point, update: false)
+ // Radius
+ let r = vector.len(vector.sub(resolve-anchor(ctx, c.element + ".north"), C))
+ // Vector between C and P
+ let D = vector.sub(P, C) // C - P
+ // Distance between C and P
+ let pc = vector.len(D)
+ if pc < r {
+ panic("No tangent solution for element " + c.element + " and point " + repr(c.point))
+ }
+ // Distance between P and X0
+ let d = r*r / pc
+ // Distance between X0 and X1(X2)
+ let h = calc.sqrt(r*r - d*d)
+
+ return if c.solution == 1 {
+ (
+ C.at(0) + (D.at(0) * d - D.at(1) * h) / pc,
+ C.at(1) + (D.at(1) * d + D.at(0) * h) / pc,
+ 0
+ )
+ } else {
+ (
+ C.at(0) + (D.at(0) * d + D.at(1) * h) / pc,
+ C.at(1) + (D.at(1) * d - D.at(0) * h) / pc,
+ 0
+ )
+ }
+}
+
+#let resolve-perpendicular(resolve, ctx, c) = {
+ // (horizontal: <coordinate>, vertical: <coordinate>)
+ // (horizontal, "-|", vertical)
+ // (vertical, "|-", horizontal)
+
+ let (ctx, horizontal, vertical) = resolve(ctx, ..if type(c) == array {
+ if c.at(1) == "|-" {
+ (c.first(), c.last())
+ } else {
+ // c.at(1) == "-|"
+ (c.last(), c.first())
+ }
+ } else {
+ (c.horizontal, c.vertical)
+ }, update: false)
+
+ return (
+ horizontal.at(0),
+ vertical.at(1),
+ 0
+ )
+}
+
+#let resolve-lerp(resolve, ctx, c) = {
+ // (a: <coordinate>, number: <number,ratio>,
+ // angle?: <angle>, b: <coordinate>)
+ // (a, <number, ratio>, b)
+ // (a, <number, ratio>, angle, b)
+
+ let (a, number, angle, b) = if type(c) == array {
+ if c.len() == 3 {
+ (
+ ..c.slice(0, 2),
+ none, // angle
+ c.last(),
+ )
+ } else {
+ c
+ }
+ } else {
+ (
+ c.a,
+ c.number,
+ c.at("angle", default: 0deg),
+ c.b
+ )
+ }
+
+ (ctx, a, b) = resolve(ctx, a, b)
+
+ if angle != none {
+ let (x, y, _) = vector.sub(b,a)
+ b = vector.add(
+ (
+ calc.cos(angle) * x - calc.sin(angle) * y,
+ calc.sin(angle) * x + calc.cos(angle) * y,
+ 0
+ ),
+ a,
+ )
+ }
+
+ let ab = vector.sub(b, a)
+
+ let is-absolute = type(number) != ratio
+ let distance = if is-absolute {
+ let dist = vector.len(ab)
+ if dist != 0 {
+ util.resolve-number(ctx, number) / dist
+ } else {
+ 0
+ }
+ } else {
+ number / 100%
+ }
+
+ return vector.add(a, vector.scale(ab, distance))
+}
+
+#let resolve-function(resolve, ctx, c) = {
+ let (func, ..c) = c
+ (ctx, ..c) = resolve(ctx, ..c)
+ func(..c)
+}
+
+#let resolve-pos(ctx, c) = {
+ // (name: str, pos: float, auto?: left|right, swap?: bool)
+}
+
+/// Figures out what system a coordinate belongs to and returns the corresponding string.
+/// - c (coordinate): The coordinate to find the system of.
+/// -> str
+#let resolve-system(c) = {
+ let t = if type(c) == dictionary {
+ let keys = c.keys()
+ let len = c.len()
+ if len in (1, 2, 3) and keys.all(k => k in ("x", "y", "z")) {
+ "xyz"
+ } else if len == 2 and keys.all(k => k in ("angle", "radius")) and (type(c.radius) in (int, float, length) or (type(c.radius) == array and c.radius.len() == 2)) {
+ "polar"
+ } else if len == 1 and keys == ("bary",) {
+ "barycentric"
+ } else if len in (1, 2) and keys.all(k => k in ("name", "anchor")) {
+ "anchor"
+ } else if len == 3 and keys.all(k => k in ("element", "point", "solution")) {
+ "tangent"
+ } else if len == 2 and keys.all(k => k in ("horizontal", "vertical")) {
+ "perpendicular"
+ } else if len in (1, 2, 3) and keys.all(k => k in ("rel", "to", "update")) {
+ "relative"
+ } else if len in (3, 4) and keys.all(k => k in ("a", "number", "angle", "abs", "b")) {
+ "lerp"
+ }
+ } else if type(c) == array {
+ let len = c.len()
+ let types = c.map(type)
+ if len == 0 {
+ "previous"
+ } else if len in (2, 3) and types.all(t => t in (int, float, length)) {
+ "xyz"
+ } else if len == 2 and types.first() == angle {
+ "polar"
+ } else if len == 3 and c.at(1) in ("-|", "|-") {
+ "perpendicular"
+ } else if len in (3, 4) and types.at(1) in (int, float, length, ratio) and (len == 3 or (len == 4 and types.at(2) == angle)) {
+ "lerp"
+ } else if len >= 2 and types.first() == function {
+ "function"
+ }
+ } else if type(c) == str {
+ if c.contains(".") {
+ "anchor"
+ } else {
+ "element"
+ }
+ }
+
+ if t == none {
+ panic("Failed to resolve coordinate: " + repr(c))
+ }
+ return t
+}
+
+/// Resolve a list of coordinates to absolute vectors. Returns an array of the new <Type>context</Type> then the resolved coordinate vectors.
+///
+/// ```typc example
+/// line((0,0), (1,1), name: "l")
+/// get-ctx(ctx => {
+/// // Get the vector of coordinate "l.start" and "l.end"
+/// let (ctx, a, b) = cetz.coordinate.resolve(ctx, "l.start", "l.end")
+/// content("l.start", [#a], frame: "rect", stroke: none, fill: white)
+/// content("l.end", [#b], frame: "rect", stroke: none, fill: white)
+/// })
+/// ```
+///
+/// - ctx (context): Canvas context object
+/// - ..coordinates (coordinate): List of coordinates
+/// - update (bool): Update the context's last position
+/// -> array
+#let resolve(ctx, ..coordinates, update: true) = {
+ let result = ()
+ for c in coordinates.pos() {
+ let t = resolve-system(c)
+ let out = if t == "xyz" {
+ resolve-xyz(c)
+ } else if t == "previous" {
+ ctx.prev.pt
+ } else if t == "polar" {
+ resolve-polar(c)
+ } else if t == "barycentric" {
+ resolve-barycentric(ctx, c)
+ } else if t in ("element", "anchor") {
+ resolve-anchor(ctx, c)
+ } else if t == "tangent" {
+ resolve-tangent(resolve, ctx, c)
+ } else if t == "perpendicular" {
+ resolve-perpendicular(resolve, ctx, c)
+ } else if t == "relative" {
+ (update, ..c) = resolve-relative(resolve, ctx, c)
+ c
+ } else if t == "lerp" {
+ resolve-lerp(resolve, ctx, c)
+ } else if t == "function" {
+ resolve-function(resolve, ctx, c)
+ } else {
+ panic("Failed to resolve coordinate of format: " + repr(c))
+ }.map(util.resolve-number.with(ctx))
+
+ if update {
+ ctx.prev.pt = out
+ }
+ result.push(out)
+ }
+
+ return (ctx, ..result)
+}
diff --git a/render/packages/preview/cetz/0.3.4/src/deps.typ b/render/packages/preview/cetz/0.3.4/src/deps.typ
new file mode 100644
index 0000000..607cf95
--- /dev/null
+++ b/render/packages/preview/cetz/0.3.4/src/deps.typ
@@ -0,0 +1 @@
+#import "@preview/oxifmt:0.2.1"
diff --git a/render/packages/preview/cetz/0.3.4/src/draw.typ b/render/packages/preview/cetz/0.3.4/src/draw.typ
new file mode 100644
index 0000000..4ef2e27
--- /dev/null
+++ b/render/packages/preview/cetz/0.3.4/src/draw.typ
@@ -0,0 +1,6 @@
+#import "draw/grouping.typ": intersections, group, scope, anchor, copy-anchors, set-ctx, get-ctx, for-each-anchor, on-layer, hide, floating
+#import "draw/transformations.typ": set-transform, rotate, translate, scale, set-origin, move-to, set-viewport
+#import "draw/styling.typ": set-style, fill, stroke, register-mark
+#import "draw/shapes.typ": circle, circle-through, arc, arc-through, mark, line, grid, content, rect, bezier, bezier-through, catmull, hobby, merge-path, polygon
+#import "draw/projection.typ": ortho, on-xy, on-xz, on-yz
+#import "draw/util.typ": assert-version
diff --git a/render/packages/preview/cetz/0.3.4/src/draw/grouping.typ b/render/packages/preview/cetz/0.3.4/src/draw/grouping.typ
new file mode 100644
index 0000000..ed6a046
--- /dev/null
+++ b/render/packages/preview/cetz/0.3.4/src/draw/grouping.typ
@@ -0,0 +1,562 @@
+#import "/src/process.typ"
+#import "/src/intersection.typ"
+#import "/src/path-util.typ"
+#import "/src/styles.typ"
+#import "/src/drawable.typ"
+#import "/src/vector.typ"
+#import "/src/util.typ"
+#import "/src/coordinate.typ"
+#import "/src/aabb.typ"
+#import "/src/anchor.typ" as anchor_
+#import "/src/matrix.typ"
+#import "/src/deps.typ"
+#import deps.oxifmt: strfmt
+
+#import "transformations.typ": move-to
+
+/// Hides an element.
+///
+/// Hidden elements are not drawn to the canvas, are ignored when calculating bounding boxes and discarded by [merge-path](../shapes/merge-path). All other behaviours remain the same as a non-hidden element.
+///
+/// ```typc example
+/// set-style(radius: .5)
+/// intersections("i", {
+/// circle((0,0), name: "a")
+/// circle((1,2), name: "b")
+/// // Use a hidden line to find the border intersections
+/// hide(line("a.center", "b.center"))
+/// })
+/// line("i.0", "i.1")
+/// ```
+///
+/// - body (element): One or more elements to hide
+/// - bounds (bool): If true, respect the bounding box of the hidden elements for resizing the canvas
+#let hide(body, bounds: false) = {
+ if type(body) == array {
+ return body.map(f => {
+ (ctx) => {
+ let element = f(ctx)
+ if "drawables" in element {
+ element.drawables = element.drawables.map(d => {
+ d.hidden = true
+ d.bounds = bounds
+ return d
+ })
+ }
+ return element
+ }
+ })
+ }
+ return body
+}
+
+/// Places an element without affecting bounding boxes.
+///
+/// Floating elements are drawn to the canvas but are ignored when calculating bouding boxes. All other behaviours remain the same.
+///
+/// ```typc example
+/// group(name: "g", {
+/// content((1,0), [Normal])
+/// content((0,1), [Normal])
+/// floating(content((.5,1.5), [Floating]))
+/// })
+/// set-style(stroke: red)
+/// rect("g.north-west", "g.south-east")
+/// ```
+///
+/// - body (element): One or more elements to place
+#let floating(body) = {
+ if type(body) == array {
+ return body.map(f => {
+ ctx => {
+ let element = f(ctx)
+ if "drawables" in element {
+ element.drawables = element.drawables.map(d => {
+ d.bounds = false
+ return d
+ })
+ }
+ return element
+ }
+ })
+ }
+ return body
+}
+
+/// Calculates the intersections between multiple paths and creates one anchor per intersection point.
+///
+/// All resulting anchors will be named numerically, starting at `0`. i.e., a call `intersections("a", ...)` will generate the anchors `"a.0"`, `"a.1"`, `"a.2"` to `"a.n"`, depending of the number of intersections.
+///
+/// ```typc example
+/// intersections("i", {
+/// circle((0, 0))
+/// bezier((0,0), (3,0), (1,-1), (2,1))
+/// line((0,-1), (0,1))
+/// rect((1.5,-1),(2.5,1))
+/// })
+/// for-each-anchor("i", (name) => {
+/// circle("i." + name, radius: .1, fill: blue)
+/// })
+/// ```
+///
+/// You can also use named elements:
+///
+/// ```typc example
+/// circle((0,0), name: "a")
+/// rect((0,0), (1,1), name: "b")
+/// intersections("i", "a", "b")
+/// for-each-anchor("i", (name) => {
+/// circle("i." + name, radius: .1, fill: blue)
+/// })
+/// ```
+///
+/// You can calculate intersections with hidden elements by using [hide](./hide).
+///
+/// - name (str): Name to prepend to the generated anchors. (Not to be confused with other `name` arguments that allow the use of anchor coordinates.)
+/// - ..elements (elements,str): Elements and/or element names to calculate intersections with. Elements referred to by name are (unlike elements passed) not drawn by the intersections function!
+/// - samples (int): Number of samples to use for non-linear path segments. A higher sample count can give more precise results but worse performance.
+/// - sort (none,function): A function of the form `(context, array<vector>) -> array<vector>`
+/// that gets called with the list of intersection points.
+///
+/// CeTZ provides the following sorting functions:
+/// - sorting.points-by-distace(points, reference: (0, 0, 0))
+/// - sorting.points-by-angle(points, reference: (0, 0, 0))
+#let intersections(name, ..elements, samples: 10, sort: none) = {
+ samples = calc.clamp(samples, 2, 2500)
+
+ assert(type(name) == str and name != "",
+ message: "Intersection must have a name, got:" + repr(name))
+ assert(elements.pos() != (),
+ message: "You must at least give one element to intersections.")
+
+ return (ctx => {
+ let ctx = ctx
+
+ // List of drawables to calc intersections for;
+ // grouped by element.
+ let named-drawables = ()
+ // List of drawables passed as elements to calc intersections for;
+ // grouped by element.
+ let drawables = ()
+
+ for elem in elements.pos() {
+ if type(elem) == str {
+ assert(elem in ctx.nodes,
+ message: "No such element '" + elem + "' in elements " + repr(ctx.nodes.keys()))
+ named-drawables.push(ctx.nodes.at(elem).drawables)
+ } else {
+ for sub in elem {
+ let sub-drawables = ()
+ (ctx: ctx, drawables: sub-drawables, ..) = process.element(ctx, sub)
+ if sub-drawables != none and sub-drawables != () {
+ drawables.push(sub-drawables)
+ }
+ }
+ }
+ }
+
+ let elems = named-drawables + drawables
+ let pts = ()
+ if elems.len() > 1 {
+ for (i, elem-1) in elems.enumerate() {
+ for j in range(i + 1, elems.len()) {
+ let elem-2 = elems.at(j)
+ for path-1 in elem-1 {
+ for path-2 in elem-2 {
+ for pt in intersection.path-path(
+ path-1,
+ path-2,
+ samples: samples
+ ) {
+ if pt not in pts { pts.push(pt) }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ if sort != none {
+ pts = (sort)(ctx, pts)
+ }
+
+ let anchors = (:)
+ for (i, pt) in pts.enumerate() {
+ anchors.insert(str(i), pt)
+ }
+
+ return (
+ ctx: ctx,
+ name: name,
+ anchors: anchor_.setup(
+ anchor => {
+ anchors.at(anchor)
+ },
+ anchors.keys(),
+ transform: none,
+ name: name
+ ).last(),
+ drawables: drawables.flatten()
+ )
+ },)
+}
+
+/// Groups one or more elements together. This element acts as a scope, all state changes such as transformations and styling only affect the elements in the group. Elements after the group are not affected by the changes inside the group.
+///
+/// ```typc example
+/// // Create group
+/// group({
+/// stroke(5pt)
+/// scale(.5); rotate(45deg)
+/// rect((-1,-1),(1,1))
+/// })
+/// rect((-1,-1),(1,1))
+/// ```
+///
+/// - body (elements, function): Elements to group together. A least one is required. A function that accepts `ctx` and returns elements is also accepted.
+/// - anchor (none, str): Anchor to position the group and it's children relative to. For translation the difference between the groups `"default"` anchor and the passed anchor is used.
+/// - name (none, str):
+/// - ..style (style):
+///
+/// ## Styling
+/// *Root:* `group`
+///
+/// - padding (none, number, array, dictionary) = none: How much padding to add around the group's bounding box. `none` applies no padding. A number applies padding to all sides equally. A dictionary applies padding following Typst's `pad` function: https://typst.app/docs/reference/layout/pad/. An array follows CSS like padding: `(y, x)`, `(top, x, bottom)` or `(top, right, bottom, left)`.
+///
+/// ## Anchors
+/// Supports border and path anchors of the axis aligned bounding box of all the child elements of the group.
+///
+/// You can add custom named anchors to the group by using the [anchor](./anchor) element while in the scope of said group, see [anchor](./anchor) for more details.
+///
+/// The default anchor is `"center"` but this can be overridden by using [anchor](./anchor) to place a new anchor called `"default"`.
+///
+/// When using named elements within a group, you can access the element's anchors outside of the group by using the implicit anchor coordinate. e.g. `"a.b.north"`
+/// ```typc example
+/// group(name: "a", {
+/// circle((), name: "b")
+/// })
+/// circle("a.b.south", radius: 0.2)
+/// circle((name: "a", anchor: "b.north"), radius: 0.2)
+/// ```
+#let group(body, name: none, anchor: none, ..style) = {
+ // No extra positional arguments from the style sink
+ assert.eq(style.pos(), (),
+ message: "Unexpected positional arguments: " + repr(style.pos()),)
+ util.assert-body(body)
+
+ (ctx => {
+ let style = styles.resolve(ctx.style, merge: style.named(), root: "group")
+
+ let bounds = none
+ let drawables = ()
+ let group-ctx = ctx
+ group-ctx.groups.push(())
+
+ (ctx: group-ctx, drawables, bounds) = process.many(group-ctx, util.resolve-body(group-ctx, body))
+
+ // Apply bounds padding
+ bounds = if bounds != none {
+ let padding = util.as-padding-dict(style.padding)
+ padding = padding.pairs().map(
+ ((k, v)) => (
+ (k): util.resolve-number(ctx, v)
+ )
+ ).join()
+
+ aabb.padded(bounds, padding)
+ }
+
+ // Calculate a bounding box path used for border
+ // anchor calculation.
+ let (center, width, height, path) = if bounds != none {
+ (bounds.low.at(1), bounds.high.at(1)) = (bounds.high.at(1), bounds.low.at(1))
+ let center = aabb.mid(bounds)
+ let (width, height, _) = aabb.size(bounds)
+ let path = drawable.path(
+ path-util.line-segment((
+ (bounds.low.at(0), bounds.high.at(1)),
+ bounds.high,
+ (bounds.high.at(0), bounds.low.at(1)),
+ bounds.low,
+ )), close: true)
+ (center, width, height, path)
+ } else { (none,) * 4 }
+
+ let children = group-ctx.groups.last().map(name => ((name): group-ctx.nodes.at(name))).join()
+
+ // Children can be none if the groups array is empty
+ let anchors = if children != none {
+ children.pairs().map(((name, child)) => {
+ if "anchors" in child {
+ ((name): child.anchors)
+ }
+ }).join()
+ } else {
+ (:)
+ }
+
+ let (transform, anchors) = anchor_.setup(
+ anchor => {
+ let (name, ..nested-anchors) = if type(anchor) == array {
+ anchor
+ } else {
+ (anchor,)
+ }
+ anchor = (
+ if bounds != none {
+ (default: center, center: center)
+ } + anchors
+ ).at(name)
+ if type(anchor) == function {
+ anchor(if nested-anchors == () { "default" } else { nested-anchors })
+ } else {
+ anchor
+ }
+ },
+ (anchors.keys() + if bounds != none { ("center",) }).dedup(),
+ name: name,
+ default: if bounds != none or "default" in anchors { "default" },
+ offset-anchor: anchor,
+ path-anchors: bounds != none,
+ border-anchors: bounds != none,
+ radii: (width, height),
+ path: path,
+ nested-anchors: true
+ )
+
+ return (
+ ctx: ctx,
+ name: name,
+ anchors: anchors,
+ drawables: drawable.apply-transform(transform, drawables),
+ )
+ },)
+}
+
+/// This element acts as a scope, all state changes such as transformations and styling only affect the elements in the group. Elements after the scope are not affected by the changes inside the scope.
+/// In contrast to `group`, the `scope` element does not create a named element itself and "leaks" body element to the outside.
+///
+/// - body (elements, function): Elements to group together. A least one is required. A function that accepts `ctx` and returns elements is also accepted.
+#let scope(body) = (ctx => {
+ let bounds = none
+ let drawables = ()
+ let group-ctx = ctx
+ group-ctx.groups.push(())
+
+ (ctx: group-ctx, drawables, bounds) = process.many(group-ctx, util.resolve-body(group-ctx, body))
+
+ // Leak nodes
+ ctx.nodes += group-ctx.nodes
+
+ return (
+ ctx: ctx,
+ drawables: drawables,
+ )
+},)
+
+/// Creates a new anchor for the current group. The new anchor will be accessible from inside the group by using just the anchor's name as a coordinate.
+///
+/// ```typc example
+/// // Inside a group
+/// group(name: "g", {
+/// circle((0,0))
+/// anchor("x", (.4, .1))
+/// circle("x", radius: .2)
+/// })
+/// circle("g.x", radius: .1)
+/// ```
+
+/// ```typc example
+/// // At the root scope
+/// anchor("x", (1, 1))
+/// // ...
+/// circle("x", radius: .1)
+/// ```
+///
+/// - name (str): The name of the anchor
+/// - position (coordinate): The position of the anchor
+#let anchor(name, position) = {
+ assert(name != none and name != "" and not name.starts-with("."),
+ message: "Anchors must not be none, \"\" or start with \".\"!")
+
+ coordinate.resolve-system(position)
+ return (ctx => {
+ let (ctx, position) = coordinate.resolve(ctx, position)
+ position = util.apply-transform(ctx.transform, position)
+ return (
+ ctx: ctx,
+ name: name,
+ anchors: anchor_.setup(
+ anchor => position,
+ ("default",),
+ default: "default",
+ name: name,
+ transform: none
+ ).last()
+ )
+ },)
+}
+
+/// Copies multiple anchors from one element into the current group. Panics when used outside of a group. Copied anchors will be accessible in the same way anchors created by the `anchor` element are.
+///
+/// - element (str): The name of the element to copy anchors from.
+/// - filter (auto,array): When set to `auto` all anchors will be copied to the group. An array of anchor names can instead be given so only the anchors that are in the element and the list will be copied over.
+#let copy-anchors(element, filter: auto) = {
+ (ctx => {
+ assert(
+ ctx.groups.len() > 0,
+ message: "copy-anchors cannot be used outside of a group.",
+ )
+ assert(
+ element in ctx.nodes,
+ message: "copy-anchors: Could not find element '" + element + "'",
+ )
+
+ let calc-anchors = ctx.nodes.at(element).anchors
+ let anchors = calc-anchors(())
+ if filter != auto {
+ anchors = anchors.filter(a => a in filter)
+ }
+
+ // Add each anchor as own element
+ for anchor in anchors {
+ ctx.nodes.insert(
+ anchor,
+ (anchors: name => {
+ if name == "default" {
+ calc-anchors(anchor)
+ } else if name == () {
+ ("default",)
+ } else {
+ calc-anchors((anchor,) + name)
+ }
+ })
+ )
+ ctx.groups.last().push(anchor)
+ }
+
+ return (ctx: ctx)
+ },)
+}
+
+/// An advanced element that allows you to modify the current canvas {{context}}.
+/// Note: The transformation matrix (`transform`) is rounded after calling the `callback` function and therefore might be not exactly the matrix specified. This is due to rounding errors and should not cause any problems.
+///
+/// ```typc example
+/// // Setting a custom transformation matrix
+/// set-ctx(ctx => {
+/// let mat = ((1, 0, .5, 0),
+/// (0, 1, 0, 0),
+/// (0, 0, 1, 0),
+/// (0, 0, 0, 1))
+/// ctx.transform = mat
+/// return ctx
+/// })
+/// circle((z: 0), fill: red)
+/// circle((z: 1), fill: blue)
+/// circle((z: 2), fill: green)
+/// ```
+///
+/// - callback (function): A function that accepts the context dictionary and only returns a new one.
+#let set-ctx(callback) = {
+ assert(type(callback) == function)
+ return (ctx => {
+ let new-ctx = callback(ctx)
+ assert(new-ctx != none, message: "set-ctx must return a context!")
+
+ if new-ctx.transform != ctx.transform {
+ // User supplied matrices can cause rounding issues
+ new-ctx.transform = matrix.round(new-ctx.transform)
+ }
+ (ctx: new-ctx)
+ },)
+}
+
+/// An advanced element that allows you to read the current {{context}} through a callback and return {{element}}s based on it.
+///
+/// ```typc example
+/// // Print the transformation matrix
+/// get-ctx(ctx => {
+/// content((), [#repr(ctx.transform)])
+/// })
+/// ```
+///
+/// - callback (function): A function that accepts the {{context}} and can return elements.
+#let get-ctx(callback) = {
+ assert(type(callback) == function)
+ (ctx => {
+ let body = callback(ctx)
+ if body != none {
+ let (ctx, drawables) = process.many(ctx, callback(ctx))
+ return (ctx: ctx, drawables: drawables)
+ }
+ return (ctx: ctx)
+ },)
+}
+
+/// Iterates through all named anchors of an element and calls a callback for each one.
+///
+/// ```typc example
+/// // Label nodes anchors
+/// rect((0, 0), (2,2), name: "my-rect")
+/// for-each-anchor("my-rect", exclude: ("start", "mid", "end"), (name) => {
+/// content((), box(inset: 1pt, fill: white, text(8pt, [#name])), angle: -30deg)
+/// })
+/// ```
+///
+/// - name (str): The name of the element with the anchors to loop through.
+/// - callback (function): A function that takes the anchor name and can return elements.
+/// - exclude (array): An array of anchor names to not include in the loop.
+#let for-each-anchor(name, callback, exclude: ()) = {
+ get-ctx(ctx => {
+ assert(
+ name in ctx.nodes,
+ message: strfmt("Unknown element {} in elements {}", name, repr(ctx.nodes.keys()))
+ )
+ for anchor in (ctx.nodes.at(name).anchors)(()) {
+ if anchor == none or (anchor in exclude) { continue }
+ move-to(name + "." + anchor)
+ callback(anchor)
+ }
+ })
+}
+
+/// Places elements on a specific layer.
+///
+/// A layer determines the position of an element in the draw queue. A lower layer is drawn before a higher layer.
+///
+/// Layers can be used to draw behind or in front of other elements, even if the other elements were created before or after. An example would be drawing a background behind a text, but using the text's calculated bounding box for positioning the background.
+///
+/// ```typc example
+/// // Draw something behind text
+/// set-style(stroke: none)
+/// content((0, 0), [This is an example.], name: "text")
+/// on-layer(-1, {
+/// circle("text.north-east", radius: .3, fill: red)
+/// circle("text.south", radius: .4, fill: green)
+/// circle("text.north-west", radius: .2, fill: blue)
+/// })
+/// ```
+///
+/// - layer (float, int): The layer to place the elements on. Elements placed without `on-layer` are always placed on layer 0.
+/// - body (elements, function): Elements to draw on the layer specified. A function that accepts `ctx` and returns elements is also accepted.
+#let on-layer(layer, body) = {
+ util.assert-body(body)
+ assert(type(layer) in (int, float),
+ message: "Layer must be a float or integer, 0 being the default layer. Got: " + repr(layer))
+
+ return (ctx => {
+ let (ctx, drawables, ..) = process.many(ctx, util.resolve-body(ctx, body))
+ drawables = drawables.map(d => {
+ if d.at("z-index", default: none) == none {
+ d.z-index = layer
+ }
+ return d
+ })
+
+ return (
+ ctx: ctx,
+ drawables: drawables
+ )
+ },)
+}
diff --git a/render/packages/preview/cetz/0.3.4/src/draw/projection.typ b/render/packages/preview/cetz/0.3.4/src/draw/projection.typ
new file mode 100644
index 0000000..beb182d
--- /dev/null
+++ b/render/packages/preview/cetz/0.3.4/src/draw/projection.typ
@@ -0,0 +1,190 @@
+#import "grouping.typ": group, get-ctx, set-ctx, scope
+#import "transformations.typ": set-transform
+#import "/src/process.typ"
+#import "/src/matrix.typ"
+#import "/src/drawable.typ"
+#import "/src/util.typ"
+#import "/src/polygon.typ"
+
+// Get an orthographic view matrix for 3 angles
+#let ortho-matrix(x, y, z) = matrix.mul-mat(
+ matrix.ident(4),
+ matrix.transform-rotate-x(x),
+ matrix.transform-rotate-y(y),
+ matrix.transform-rotate-z(z),
+)
+
+#let ortho-projection-matrix = (
+ (1, 0, 0, 0),
+ (0, 1, 0, 0),
+ (0, 0, 0, 0),
+ (0, 0, 0, 1),
+)
+
+#let _sort-by-distance(drawables) = {
+ return drawables.sorted(key: d => {
+ let z = none
+ for ((kind, ..pts)) in d.segments {
+ pts = pts.map(p => p.at(2))
+ z = if z == none {
+ calc.max(..pts)
+ } else {
+ calc.max(z, ..pts)
+ }
+ }
+ return z
+ })
+}
+
+// Filter out all clock-wise polygons, or if `invert` is true,
+// all counter clock-wise ones.
+#let _filter-cw-faces(drawables, mode: "cw") = {
+ return drawables.filter(d => {
+ let poly = polygon.from-segments(d.segments)
+ poly.first() != poly.last() or polygon.winding-order(poly) == mode
+ })
+}
+
+// Sets up a view matrix to transform all `body` elements. The current context
+// transform is not modified.
+//
+// - body (element): Elements
+// - view-matrix (matrix): View matrix
+// - projection-matrix (matrix): Projection matrix
+// - reset-transform (bool): Ignore the current transformation matrix
+// - sorted (bool): Sort drawables by maximum distance (front to back)
+// - cull-face (none,str): Enable back-face culling if set to `"cw"` for clockwise
+// or `"ccw"` for counter-clockwise. Polygons of the specified order will not get drawn.
+#let _projection(body, view-matrix, projection-matrix, reset-transform: true, sorted: true, cull-face: "cw") = {
+ (ctx => {
+ let transform = ctx.transform
+ ctx.transform = view-matrix
+
+ let (ctx, drawables, bounds) = process.many(ctx, util.resolve-body(ctx, body))
+
+ if cull-face != none {
+ assert(cull-face in ("cw", "ccw"),
+ message: "cull-face must be none, cw or ccw.")
+ drawables = _filter-cw-faces(drawables, mode: cull-face)
+ }
+ if sorted {
+ drawables = _sort-by-distance(drawables)
+ }
+
+ if projection-matrix != none {
+ drawables = drawable.apply-transform(projection-matrix, drawables)
+ }
+
+ ctx.transform = transform
+ if not reset-transform {
+ drawables = drawable.apply-transform(ctx.transform, drawables)
+ }
+
+ return (
+ ctx: ctx,
+ bounds: bounds,
+ drawables: drawables,
+ )
+ },)
+}
+
+// Apply function `fn` to all vertices of all
+// elements in `body`.
+//
+// - body (element): Elements
+// - ..mat (matrix): Transformation matrices
+#let scoped-transform(body, ..mat) = {
+ scope({
+ set-ctx(ctx => {
+ ctx.transform = matrix.mul-mat(ctx.transform, ..mat.pos().filter(m => m != none))
+ return ctx
+ })
+ body
+ })
+}
+
+/// Set-up an orthographic projection environment.
+///
+/// This is a transformation matrix that rotates elements around the x, the y and the z axis by the parameters given.
+///
+/// By default an isometric projection (x ≈ 35.264°, y = 45°) is set.
+///
+/// ```typc example
+/// ortho({
+/// on-xz({
+/// rect((-1,-1), (1,1))
+/// })
+/// })
+/// ```
+///
+/// - x (angle): X-axis rotation angle
+/// - y (angle): Y-axis rotation angle
+/// - z (angle): Z-axis rotation angle
+/// - sorted (bool): Sort drawables by maximum distance (front to back)
+/// - cull-face (none,str): Enable back-face culling if set to `"cw"` for clockwise
+/// or `"ccw"` for counter-clockwise. Polygons of the specified order will not get drawn.
+/// - reset-transform (bool): Ignore the current transformation matrix
+/// - body (element): Elements to draw
+#let ortho(x: 35.264deg, y: 45deg, z: 0deg, sorted: true, cull-face: none, reset-transform: false, body, name: none) = group(name: name, ctx => {
+ _projection(body, ortho-matrix(x, y, z), ortho-projection-matrix,
+ sorted: sorted,
+ cull-face: cull-face,
+ reset-transform: reset-transform)
+})
+
+/// Draw elements on the xy-plane with optional z offset.
+///
+/// All vertices of all elements will be changed in the following way: $\begin{pmatrix} x \\ y \\ z_\text{argument}\end{pmatrix}$, where $z_\text{argument}$ is the z-value given as argument.
+///
+/// ```typc example
+/// on-xy({
+/// rect((-1, -1), (1, 1))
+/// })
+/// ```
+///
+/// - z (number): Z offset for all coordinates
+/// - body (element): Elements to draw
+#let on-xy(z: 0, body) = get-ctx(ctx => {
+ let z = util.resolve-number(ctx, z)
+ scoped-transform(body, if z != 0 {
+ matrix.transform-translate(0, 0, z)
+ }, matrix.ident(4))
+})
+
+/// Draw elements on the xz-plane with optional y offset.
+///
+/// All vertices of all elements will be changed in the following way: $\begin{pmatrix} x \\ y_\text{argument} \\ y \end{pmatrix}$, where $y_\text{argument}$ is the y-value given as argument.
+///
+/// ```typc example
+/// on-xz({
+/// rect((-1, -1), (1, 1))
+/// })
+/// ```
+///
+/// - y (number): Y offset for all coordinates
+/// - body (element): Elements to draw
+#let on-xz(y: 0, body) = get-ctx(ctx => {
+ let y = util.resolve-number(ctx, y)
+ scoped-transform(body, if y != 0 {
+ matrix.transform-translate(0, y, 0)
+ }, matrix.transform-rotate-x(90deg))
+})
+
+/// Draw elements on the yz-plane with optional x offset.
+///
+/// All vertices of all elements will be changed in the following way: $\begin{pmatrix} x_\text{argument} \\ x \\ y \end{pmatrix}$, where $x_\text{argument}$ is the x-value given as argument.
+///
+/// ```typc example
+/// on-yz({
+/// rect((-1, -1), (1, 1))
+/// })
+/// ```
+///
+/// - x (number): X offset for all coordinates
+/// - body (element): Elements to draw
+#let on-yz(x: 0, body) = get-ctx(ctx => {
+ let x = util.resolve-number(ctx, x)
+ scoped-transform(body, if x != 0 {
+ matrix.transform-translate(x, 0, 0)
+ }, matrix.transform-rotate-y(90deg))
+})
diff --git a/render/packages/preview/cetz/0.3.4/src/draw/shapes.typ b/render/packages/preview/cetz/0.3.4/src/draw/shapes.typ
new file mode 100644
index 0000000..299340c
--- /dev/null
+++ b/render/packages/preview/cetz/0.3.4/src/draw/shapes.typ
@@ -0,0 +1,1637 @@
+#let typst-angle = angle
+#let typst-rotate = rotate
+
+#import "/src/coordinate.typ"
+#import "/src/drawable.typ"
+#import "/src/styles.typ"
+#import "/src/path-util.typ"
+#import "/src/util.typ"
+#import "/src/vector.typ"
+#import "/src/matrix.typ"
+#import "/src/process.typ"
+#import "/src/bezier.typ" as bezier_
+#import "/src/hobby.typ" as hobby_
+#import "/src/anchor.typ" as anchor_
+#import "/src/mark.typ" as mark_
+#import "/src/mark-shapes.typ" as mark-shapes_
+#import "/src/polygon.typ" as polygon_
+#import "/src/aabb.typ"
+
+#import "transformations.typ": *
+#import "styling.typ": *
+#import "grouping.typ": *
+
+/// Draws a circle or ellipse.
+///
+/// ```typc example
+/// circle((0,0))
+/// // Draws an ellipse
+/// circle((0,-2), radius: (0.75, 0.5))
+/// // Draws a circle at (0, 2) through point (1, 3)
+/// circle((0,2), (rel: (1,1)))
+/// ```
+///
+/// - ..points-style (coordinate, style): The position to place the circle on.
+/// If given two coordinates, the distance between them is used as radius.
+/// If given a single coordinate, the radius can be set via the `radius` (style)
+/// argument.
+/// - name (none,str):
+/// - anchor (none, str):
+///
+/// ### Styling
+/// *Root*: `circle`
+///
+/// - radius (number, array) = 1: A number that defines the size of the circle's radius. Can also be set to a tuple of two numbers to define the radii of an ellipse, the first number is the `x` radius and the second is the `y` radius.
+///
+/// ### Anchors
+/// Supports border and path anchors. The `"center"` anchor is the default.
+///
+#let circle(..points-style, name: none, anchor: none) = {
+ let style = points-style.named()
+ let points = points-style.pos()
+ assert(points.len() in (1, 2),
+ message: "circle expects one or two points, got " + repr(points))
+ assert(points.len() != 2 or "radius" not in style,
+ message: "unexpected radius for circle constructed by two points")
+
+ (ctx => {
+ let (center, outer) = if points.len() == 1 {
+ (points.at(0), none)
+ } else {
+ points
+ }
+
+ let (ctx, center) = coordinate.resolve(ctx, center)
+ let style = styles.resolve(ctx.style, merge: style, root: "circle")
+
+ // If we got two points, use the second one to calculate
+ // the radius.
+ let (rx, ry) = if outer != none {
+ (ctx, outer) = coordinate.resolve(ctx, outer, update: false)
+ (vector.dist(center, outer),) * 2
+ } else {
+ util.resolve-radius(style.radius).map(util.resolve-number.with(ctx))
+ }
+ let (cx, cy, cz) = center
+
+ let drawables = drawable.ellipse(
+ cx, cy, cz,
+ rx, ry,
+ fill: style.fill,
+ stroke: style.stroke
+ )
+
+ let (transform, anchors) = anchor_.setup(
+ (_) => center,
+ ("center",),
+ default: "center",
+ name: name,
+ offset-anchor: anchor,
+ transform: ctx.transform,
+ border-anchors: true,
+ path-anchors: true,
+ radii: (rx*2, ry*2),
+ path: drawables,
+ )
+
+ return (
+ ctx: ctx,
+ name: name,
+ anchors: anchors,
+ drawables: drawable.apply-transform(transform, drawables),
+ )
+ },)
+}
+
+/// Draws a circle through three coordinates.
+///
+/// ```typc example
+/// let (a, b, c) = ((0,0), (2,-.5), (1,1))
+/// line(a, b, c, close: true, stroke: gray)
+/// circle-through(a, b, c, name: "c")
+/// circle("c.center", radius: .05, fill: red)
+/// ```
+///
+/// - a (coordinate): Coordinate a.
+/// - b (coordinate): Coordinate b.
+/// - c (coordinate): Coordinate c.
+/// - name (none,str):
+/// - anchor (none,str):
+/// - ..style (style):
+///
+/// ### Styling
+/// *Root*: `circle`
+///
+/// `circle-through` has the same styling as [circle](./circle#styling) except for `radius` as the circle's radius is calculated by the given coordinates.
+///
+/// ### Anchors
+/// Supports the same anchors as [circle](./circle#anchors) as well as:
+/// - **a**: Coordinate a
+/// - **b**: Coordinate b
+/// - **c**: Coordinate c
+#let circle-through(a, b, c, name: none, anchor: none, ..style) = {
+ assert.eq(style.pos(), (), message: "Unexpected positional arguments: " + repr(style.pos()))
+ style = style.named()
+
+ (a, b, c).map(coordinate.resolve-system)
+
+ return (ctx => {
+ let (ctx, a, b, c) = coordinate.resolve(ctx, a, b, c)
+
+ let center = util.calculate-circle-center-3pt(a, b, c)
+
+ let style = styles.resolve(ctx.style, merge: style, root: "circle")
+ let (cx, cy, cz) = center
+ let r = vector.dist(a, (cx, cy))
+
+ let drawables = drawable.ellipse(
+ cx, cy, 0,
+ r, r,
+ fill: style.fill,
+ stroke: style.stroke
+ )
+
+ let (transform, anchors) = anchor_.setup(
+ (anchor) => (
+ center: center,
+ a: a,
+ b: b,
+ c: c
+ ).at(anchor),
+ ("center", "a", "b", "c"),
+ default: "center",
+ name: name,
+ offset-anchor: anchor,
+ transform: ctx.transform,
+ border-anchors: true,
+ path-anchors: true,
+ radii: (r*2, r*2),
+ path: drawables,
+ )
+
+ return (
+ ctx: ctx,
+ name: name,
+ anchors: anchors,
+ drawables: drawable.apply-transform(
+ transform,
+ drawables
+ )
+ )
+ },)
+}
+
+/// Draws a circular segment.
+///
+/// ```typc example
+/// arc((0,0), start: 45deg, stop: 135deg)
+/// arc((0,-0.5), start: 45deg, delta: 90deg, mode: "CLOSE")
+/// arc((0,-1), stop: 135deg, delta: 90deg, mode: "PIE")
+/// ```
+///
+/// Note that two of the three angle arguments (`start`, `stop` and `delta`) must be set.
+/// The current position `()` gets updated to the arc's end coordinate (anchor `arc-end`).
+///
+/// - position (coordinate): Position to place the arc at.
+/// - start (auto,angle): The angle at which the arc should start. Remember that `0deg` points directly towards the right and `90deg` points up.
+/// - stop (auto,angle): The angle at which the arc should stop.
+/// - delta (auto,angle): The change in angle away start or stop.
+/// - name (none,str):
+/// - anchor (none, str):
+/// - ..style (style):
+///
+/// ## Styling
+/// *Root*: `arc`\
+/// - radius (number, array) = 1: The radius of the arc. An elliptical arc can be created by passing a tuple of numbers where the first element is the x radius and the second element is the y radius.
+/// - mode (str) = "OPEN": The options are: `"OPEN"` no additional lines are drawn so just the arc is shown; `"CLOSE"` a line is drawn from the start to the end of the arc creating a circular segment; `"PIE"` lines are drawn from the start and end of the arc to the origin creating a circular sector.
+/// - update-position (bool) = true: Update the current canvas position to the arc's end point (anchor `"arc-end"`). This overrides the default of `true`, that allows chaining of (arc) elements.
+///
+/// ## Anchors
+/// Supports border and path anchors.
+/// - **arc-start**: The position at which the arc's curve starts, this is the default.
+/// - **arc-end**: The position of the arc's curve end.
+/// - **arc-center**: The midpoint of the arc's curve.
+/// - **center**: The center of the arc, this position changes depending on if the arc is closed or not.
+/// - **chord-center**: Center of chord of the arc drawn between the start and end point.
+/// - **origin**: The origin of the arc's circle.
+#let arc(
+ position,
+ start: auto,
+ stop: auto,
+ delta: auto,
+ name: none,
+ anchor: none,
+ ..style,
+) = {
+ // Start, stop, delta check
+ assert(
+ (start, stop, delta).filter(it => { it == auto }).len() == 1,
+ message: "Exactly two of three options start, stop and delta should be defined.",
+ )
+
+ // No extra positional arguments from the style sink
+ assert.eq(
+ style.pos(),
+ (),
+ message: "Unexpected positional arguments: " + repr(style.pos()),
+ )
+ let style = style.named()
+
+ // Coordinate check
+ let t = coordinate.resolve-system(position)
+
+ let start-angle = if start == auto { stop - delta } else { start }
+ let stop-angle = if stop == auto { start + delta } else { stop }
+ // Border angles can break if the angle is 0.
+ assert.ne(start-angle, stop-angle, message: "Angle must be greater than 0deg")
+
+ return (ctx => {
+ let style = styles.resolve(ctx.style, merge: style, root: "arc")
+ assert(style.mode in ("OPEN", "PIE", "CLOSE"))
+
+ let (ctx, arc-start) = coordinate.resolve(ctx, position)
+ let (rx, ry) = util.resolve-radius(style.radius).map(util.resolve-number.with(ctx))
+
+ let (x, y, z) = arc-start
+ let drawables = drawable.arc(
+ ..arc-start,
+ start-angle,
+ stop-angle,
+ rx,
+ ry,
+ stroke: style.stroke,
+ fill: style.fill,
+ mode: style.mode
+ )
+
+ let sector-center = (
+ x - rx * calc.cos(start-angle),
+ y - ry * calc.sin(start-angle),
+ z
+ )
+ let arc-end = (
+ sector-center.first() + rx * calc.cos(stop-angle),
+ sector-center.at(1) + ry * calc.sin(stop-angle),
+ z
+ )
+ let chord-center = vector.lerp(arc-start, arc-end, 0.5)
+ let arc-center = (
+ sector-center.first() + rx * calc.cos((stop-angle + start-angle)/2),
+ sector-center.at(1) + ry * calc.sin((stop-angle + start-angle)/2),
+ z
+ )
+
+ // Set the last position to arc-end
+ if style.update-position {
+ ctx.prev.pt = arc-end
+ }
+
+ // Center is calculated based on observations of tikz's circular sector and semi circle shapes.
+ let center = if style.mode != "CLOSE" {
+ // A circular sector's center anchor is placed half way between the sector-center and arc-center when the angle is 180deg. At 60deg it is placed 1/3 of the way between, this is mirrored at 300deg.
+ vector.lerp(
+ arc-center,
+ sector-center,
+ if (stop-angle + start-angle) > 180deg { (stop-angle + start-angle) } else { (stop-angle + start-angle) + 180deg } / 720deg
+ )
+ } else {
+ // A semi circle's center anchor is placed half way between the sector-center and arc-center, so that is always `center` when the arc is closed. Otherwise the point at which compass anchors are calculated from will be outside the lines.
+ vector.lerp(
+ arc-center,
+ chord-center,
+ 0.5
+ )
+ }
+
+ let (transform, anchors) = anchor_.setup(
+ anchor => (
+ arc-start: arc-start,
+ origin: sector-center,
+ arc-end: arc-end,
+ arc-center: arc-center,
+ chord-center: chord-center,
+ center: center,
+ ).at(anchor),
+ ("arc-center", "chord-center", "origin", "arc-start", "arc-end", "center"),
+ default: "arc-start",
+ name: name,
+ offset-anchor: anchor,
+ transform: ctx.transform,
+ border-anchors: true,
+ path-anchors: true,
+ radii: (rx, ry), // Don't multiply as its not from the arc's center
+ path: drawables
+ )
+
+ if mark_.check-mark(style.mark) {
+ drawables = mark_.place-marks-along-path(ctx, style.mark, transform, drawables)
+ } else {
+ drawables = drawable.apply-transform(transform, drawables)
+ }
+
+ return (
+ ctx: ctx,
+ name: name,
+ anchors: anchors,
+ drawables: drawables,
+ )
+ },)
+}
+
+/// Draws an arc that passes through three points a, b and c.
+///
+/// Note that all three points must not lie on a straight line, otherwise
+/// the function fails.
+///
+/// ```typc example
+/// arc-through((0,1), (1,1), (1,0))
+/// ```
+///
+/// - a (coordinate): Start position of the arc
+/// - b (coordinate): Position the arc passes through
+/// - c (coordinate): End position of the arc
+/// - name (none, str):
+/// - ..style (style):
+///
+/// ### Styling
+/// *Root*: `arc`
+///
+/// Uses the same styling as [arc](./arc#styling)
+///
+/// ### Anchors
+/// For anchors see [arc](./arc#anchors).
+///
+#let arc-through(
+ a,
+ b,
+ c,
+ name: none,
+ ..style,
+) = get-ctx(ctx => {
+ let (ctx, a, b, c) = coordinate.resolve(ctx, a, b, c)
+ assert(a.at(2) == b.at(2) and b.at(2) == c.at(2),
+ message: "The z coordinate of all points must be equal, but is: " + repr((a, b, c).map(v => v.at(2))))
+
+ // Calculate the circle center from three points or fails if all
+ // three points are on one straight line.
+ let center = util.calculate-circle-center-3pt(a, b, c)
+ let radius = vector.dist(center, a)
+
+ // Find the start and inner angle between a-center-c
+ let start = vector.angle2(center, a)
+ let delta = vector.angle(a, center, c)
+
+ // Returns a negative number if pt is left of the line a-b,
+ // if pt is right to a-b, a positive number is returned,
+ // otherwise zero.
+ let side-on-line(a, b, pt) = {
+ let (x1, y1, ..) = a
+ let (x2, y2, ..) = b
+ let (x, y, ..) = pt
+ return (x - x1) * (y2 - y1) - (y - y1) * (x2 - x1)
+ }
+
+ // Center & b b is left,
+ // are left center not
+ //
+ // +-b-+ +-b-+
+ // / \ / \
+ // | C | --a-------c--
+ // \ / \ C /
+ // ---a---c--- +---+
+ //
+ // If b and C are on the same side of a-c, the arcs radius is >= 180deg,
+ // otherwise the radius is < 180deg.
+ let center-is-left = side-on-line(a, c, center) < 0
+ let b-is-left = side-on-line(a, c, b) < 0
+
+ // If the center and point b are on the same side of a-c,
+ // the arcs delta must be > 180deg. Note, that delta is
+ // the inner angle between a-center-c, so we need to calculate
+ // the outer angle by subtracting from 360deg.
+ if center-is-left == b-is-left {
+ delta = 360deg - delta
+ }
+
+ // If b is left of a-c, swap a-c to c-a by using a negative delta
+ if b-is-left {
+ delta *= -1
+ }
+
+ return arc(
+ a,
+ start: start,
+ delta: delta,
+ radius: radius,
+ anchor: "arc-start",
+ name: name,
+ ..style
+ )
+})
+
+/// Draws a single mark pointing towards a target coordinate.
+///
+/// ```typc example
+/// mark((0,0), (1,0), symbol: ">", fill: black)
+/// mark((0,0), (1,1), symbol: "stealth", scale: 3, fill: black)
+/// ```
+///
+/// Note: To place a mark centered at the first coodinate (`from`) use
+/// the marks `anchor: "center"` style.
+///
+/// - from (coordinate): The position to place the mark.
+/// - to (coordinate,angle): The position or angle the mark should point towards.
+/// - ..style (style):
+///
+/// ## Styling
+/// *Root*: `mark`
+///
+/// You can directly use the styling from [Mark Styling](/docs/basics/marks).
+#let mark(from, to, ..style) = {
+ assert.eq(
+ style.pos(),
+ (),
+ message: "Unexpected positional arguments: " + repr(style.pos()),
+ )
+
+ let style = style.named()
+
+ if type(to) == angle {
+ // Construct a coordinate pointing (+1, 0) away from
+ // `from`, rotated by the angle given.
+ to = ((rel: (to, 1), to: from))
+ }
+
+ (from, to).map(coordinate.resolve-system)
+
+ return (ctx => {
+ let (ctx, ..pts) = coordinate.resolve(ctx, from, to)
+ let style = styles.resolve(ctx.style, merge: style, root: "mark")
+
+ if style.end == none {
+ style.end = style.symbol
+ }
+ style.start = none
+ style.symbol = none
+
+ let (to, from) = (..pts)
+ from = vector.sub(to, vector.sub(from, to))
+
+ let drawables = drawable.path((path-util.line-segment((from, to)),))
+ drawables = mark_.place-marks-along-path(ctx, style, none, drawables, add-path: false)
+ return (
+ ctx: ctx,
+ drawables: drawable.apply-transform(ctx.transform, drawables)
+ )
+ },)
+}
+
+/// Draws a line, more than two points can be given to create a line-strip.
+///
+/// ```typc example
+/// line((-1.5, 0), (1.5, 0))
+/// line((0, -1.5), (0, 1.5))
+/// line((-1, -1), (-0.5, 0.5), (0.5, 0.5), (1, -1), close: true)
+/// ```
+///
+/// If the first or last coordinates are given as the name of an element,
+/// that has a `"default"` anchor, the intersection of that element's border
+/// and a line from the first or last two coordinates given is used as coordinate.
+/// This is useful to span a line between the borders of two elements.
+///
+/// ```typc example
+/// circle((1,2), radius: .5, name: "a")
+/// rect((2,1), (rel: (1,1)), name: "b")
+/// line("a", "b")
+/// ```
+/// - ..pts-style (coordinate,style): Positional two or more coordinates to draw lines between. Accepts style key-value pairs.
+/// - close (bool): If true, the line-strip gets closed to form a polygon
+/// - name (none,str):
+///
+/// ## Styling
+/// *Root:* `line`
+///
+/// Supports mark styling.
+///
+/// ## Anchors
+/// Supports path anchors.
+/// - **centroid**: The centroid anchor is calculated for _closed non self-intersecting_ polygons if all vertices share the same z value.
+#let line(..pts-style, close: false, name: none) = {
+ // Extra positional arguments from the pts-style sink are interpreted as coordinates.
+ let pts = pts-style.pos()
+ let style = pts-style.named()
+
+ assert(pts.len() >= 2, message: "Line must have a minimum of two points")
+
+ // Coordinate check
+ let pts-system = pts.map(coordinate.resolve-system)
+
+ // Find the intersection between line a-b next to b
+ // if no intersection could be found, return a.
+ let element-line-intersection(ctx, elem, a, b) = {
+ // Vectors a and b are not transformed yet, but the vectors of the
+ // drawable are.
+ let (ta, tb) = util.apply-transform(ctx.transform, a, b)
+
+ let pts = ()
+ for drawable in elem.at("drawables", default: ()).filter(d => d.type == "path") {
+ pts += intersection.line-path(ta, tb, drawable)
+ }
+ return if pts == () {
+ a
+ } else {
+ // Find the nearest point
+ let pt = util.sort-points-by-distance(tb, pts).first()
+
+ // Reverse the transformation
+ return util.revert-transform(ctx.transform, pt)
+ }
+ }
+
+ return (ctx => {
+ let first-elem = pts.first()
+ let last-elem = pts.last()
+ let (ctx, ..pts) = coordinate.resolve(ctx, ..pts)
+
+ // If the first/last element, test for intersection
+ // of that element and a line from the two first/last coordinates of this
+ // line strip.
+ if pts-system.first() == "element" {
+ let elem = ctx.nodes.at(first-elem)
+ pts.first() = element-line-intersection(ctx, elem, ..pts.slice(0, 2))
+ }
+ if pts-system.last() == "element" {
+ let elem = ctx.nodes.at(last-elem)
+ pts.last() = element-line-intersection(ctx, elem, ..pts.slice(-2).rev())
+ }
+
+ let style = styles.resolve(ctx.style, merge: style, root: "line")
+
+ let drawables = drawable.path(
+ (path-util.line-segment(pts),),
+ fill: style.fill,
+ fill-rule: style.fill-rule,
+ stroke: style.stroke,
+ close: close
+ )
+
+ // Get bounds
+ let (transform, anchors) = anchor_.setup(
+ name => {
+ if name == "centroid" {
+ return polygon_.simple-centroid(pts)
+ }
+ },
+ if close != none { ("centroid",) } else { () },
+ default: if close != none { "centroid" },
+ name: name,
+ transform: ctx.transform,
+ path-anchors: true,
+ path: drawables
+ )
+
+ // Place marks and adjust segments
+ if mark_.check-mark(style.mark) {
+ drawables = mark_.place-marks-along-path(ctx, style.mark, transform, drawables)
+ } else {
+ drawables = drawable.apply-transform(transform, drawables)
+ }
+
+ return (
+ ctx: ctx,
+ name: name,
+ anchors: anchors,
+ drawables: drawables,
+ )
+ },)
+}
+
+/// Draws a regular polygon.
+///
+/// ```typc example
+/// polygon((0,0), 3, angle: 90deg)
+/// polygon((2,0), 5)
+/// polygon((4,0), 7)
+/// ```
+///
+/// - origin (coordinate): Coordinate to draw the polygon at
+/// - sides (int): Number of sides of the polygon (>= 3)
+/// - angle (angle) = 0deg: Angle angle to rotate the polygon arround its origin
+/// - name (none, str):
+///
+/// ## Styling
+/// *Root*: `polygon`
+/// - radius (number) = 1: Radius of the polygon
+#let polygon(origin, sides, angle: 0deg, name: none, anchor: none, ..style) = {
+ coordinate.resolve-system(origin)
+
+ assert(type(sides) == int and sides >= 3,
+ message: "Invalid number of sides: " + repr(sides))
+
+ let style = style.named()
+ return (ctx => {
+ let anchors = ()
+
+ let style = styles.resolve(ctx.style, merge: style, root: "polygon")
+
+ let (ctx, origin) = coordinate.resolve(ctx, origin)
+ let (rx, ry) = util.resolve-radius(style.radius)
+
+ let points = range(0, sides).map(i => {
+ let alpha = angle + 360deg / sides * i
+ vector.add(origin, (calc.cos(alpha) * rx, calc.sin(alpha) * ry, 0))
+ })
+
+ let drawables = drawable.path(
+ (path-util.line-segment(points),),
+ fill: style.fill,
+ stroke: style.stroke,
+ close: true)
+
+ let edge-anchors = range(0, sides).map(i => "edge-" + str(i))
+ let corner-anchors = range(0, sides).map(i => "corner-" + str(i))
+
+ let (transform, anchors) = anchor_.setup(
+ name => {
+ return if name == "center" or name == "default" {
+ origin
+ } else if name in edge-anchors {
+ let idx = edge-anchors.position(item => item == name)
+ vector.lerp(
+ points.at(idx),
+ points.at(idx + 1, default: points.first()),
+ .5)
+ } else if name in corner-anchors {
+ let idx = corner-anchors.position(item => item == name)
+ points.at(idx)
+ }
+ },
+ ("center",) + edge-anchors + corner-anchors,
+ name: name,
+ transform: ctx.transform,
+ path-anchors: false,
+ border-anchors: true,
+ radii: (rx*2, ry*2),
+ path: drawables,
+ offset-anchor: anchor,
+ default: "center",
+ )
+
+ return (
+ ctx: ctx,
+ name: name,
+ anchors: anchors,
+ drawables: drawable.apply-transform(transform, drawables),
+ )
+ },)
+}
+
+/// Draws a grid between two coordinates
+///
+/// ```typc example
+/// // Draw a grid
+/// grid((0,0), (2,2))
+///
+/// // Draw a smaller blue grid
+/// grid((1,1), (2,2), stroke: blue, step: .25)
+/// ```
+///
+/// - from (coordinate): The top left of the grid
+/// - to (coordinate): The bottom right of the grid
+/// - name (none,str):
+/// - ..style (style):
+///
+/// ## Styling
+/// *Root*: `grid`
+/// - step (number, array, dictionary) = 1: Distance between grid lines. A distance of $1$ means to draw a grid line every $1$ length units in x- and y-direction. If given a dictionary with `x` and `y` keys or a tuple, the step is set per axis.
+/// - help-lines (bool) = false: If true, force the stroke style to `gray + 0.2pt`
+///
+/// ## Anchors
+/// Supports border anchors.
+#let grid(from, to, name: none, ..style) = {
+ (from, to).map(coordinate.resolve-system)
+
+ assert.eq(style.pos(), (), message: "Unexpected positional arguments: " + repr(style.pos()))
+ style = style.named()
+
+ return (ctx => {
+ let (ctx, from, to) = coordinate.resolve(ctx, from, to)
+
+ (from, to) = {
+ let pairs = ((from.at(0), to.at(0)), (from.at(1), to.at(1)), (from.at(2), from.at(2)))
+ (
+ pairs.map(e => calc.min(..e)),
+ pairs.map(e => calc.max(..e))
+ )
+ }
+
+ let style = styles.resolve(ctx.style, merge: style, root: "grid", base: (
+ step: 1,
+ stroke: auto,
+ help-lines: false,
+ ))
+ if style.help-lines {
+ style.stroke = 0.2pt + gray
+ }
+
+ let (x-step, y-step) = if type(style.step) == dictionary {
+ (style.step.at("x", default: 1), style.step.at("y", default: 1))
+ } else if type(style.step) == array {
+ style.step
+ } else {
+ (style.step, style.step)
+ }.map(util.resolve-number.with(ctx))
+
+ let drawables = {
+ if x-step != 0 {
+ range(int((to.at(0) - from.at(0)) / x-step)+1).map(x => {
+ x *= x-step
+ x += from.at(0)
+ drawable.path(
+ path-util.line-segment(((x, from.at(1)), (x, to.at(1)))),
+ stroke: style.stroke
+ )
+ })
+ } else {
+ ()
+ }
+ if y-step != 0 {
+ range(int((to.at(1) - from.at(1)) / y-step)+1).map(y => {
+ y *= y-step
+ y += from.at(1)
+ drawable.path(
+ path-util.line-segment(((from.at(0), y), (to.at(0), y))),
+ stroke: style.stroke
+ )
+ })
+ } else {
+ ()
+ }
+ }
+
+ let center = vector.lerp(from, to, .5)
+ let (transform, anchors) = anchor_.setup(
+ _ => center,
+ ("center",),
+ name: name,
+ transform: ctx.transform,
+ border-anchors: true,
+ radii: (vector.dist(center, from) * 2,) * 2,
+ path: drawable.path(
+ path-util.line-segment((
+ from,
+ (from.first(), to.at(1), 0),
+ to,
+ (to.first(), from.at(1), 0)
+ )),
+ close: true
+ )
+ )
+
+ return (
+ ctx: ctx,
+ name: name,
+ anchors: anchors,
+ drawables: drawable.apply-transform(
+ transform,
+ drawables
+ )
+ )
+ },)
+}
+
+/// Positions Typst content in the canvas. Note that the content itself is not transformed only its position is.
+///
+/// ```typc example
+/// content((0,0), [Hello World!])
+/// ```
+/// To put text on a line you can let the function calculate the angle between its position and a second coordinate by passing it to `angle`:
+///
+/// ```typc example
+/// line((0, 0), (3, 1), name: "line")
+/// content(
+/// ("line.start", 50%, "line.end"),
+/// angle: "line.end",
+/// padding: .1,
+/// anchor: "south",
+/// [Text on a line]
+/// )
+/// ```
+///
+/// ```typc example
+/// // Place content in a rect between two coordinates
+/// content(
+/// (0, 0),
+/// (2, 2),
+/// box(
+/// par(justify: false)[This is a long text.],
+/// stroke: 1pt,
+/// width: 100%,
+/// height: 100%,
+/// inset: 1em
+/// )
+/// )
+/// ```
+///
+/// - ..args-style (coordinate, content, style): When one coordinate is given as a positional argument, the content will be placed at that position. When two coordinates are given as positional arguments, the content will be placed inside a rectangle between the two positions. All named arguments are styling and any additional positional arguments will panic.
+/// - angle (angle,coordinate): Rotates the content by the given angle. A coordinate can be given to rotate the content by the angle between it and the first coordinate given in `args`. This effectively points the right hand side of the content towards the coordinate. This currently exists because Typst's rotate function does not change the width and height of content.
+/// - anchor (none, str):
+/// - name (none, str):
+///
+/// ## Styling
+/// *Root*: `content`
+/// - padding (number, dictionary) = 0: Sets the spacing around content. Can be a single number to set padding on all sides or a dictionary to specify each side specifically. The dictionary follows Typst's `pad` function: https://typst.app/docs/reference/layout/pad/
+/// - frame (str, none) = none: Sets the frame style. Can be {{none}}, `"rect"` or `"circle"` and inherits the `stroke` and `fill` style.
+/// - auto-scale (bool): If `true`, apply current canvas scaling to the content. Defaults to `false`.
+///
+/// ## Anchors
+/// Supports border anchors, the default anchor is set to **center**.
+/// - **mid**: Content center, from baseline to top bounds
+/// - **mid-east**: Content center extended to the east
+/// - **mid-west**: Content center extended to the west
+/// - **base**: Horizontally centered baseline of the content
+/// - **base-east**: Baseline height extended to the east
+/// - **base-west**: Baseline height extended to the west
+/// - **text**: Position at the content start on the baseline of the content
+#let content(
+ ..args-style,
+ angle: 0deg,
+ anchor: none,
+ name: none,
+ ) = {
+ let (args, style) = (args-style.pos(), args-style.named())
+
+ let (a, b, body) = if args.len() == 2 {
+ args.insert(1, auto)
+ args
+ } else if args.len() == 3 {
+ args
+ } else {
+ panic("Expected 2 or 3 positional arguments, got " + str(args.len()))
+ }
+
+ coordinate.resolve-system(a)
+
+ if b != auto {
+ coordinate.resolve-system(b)
+ }
+
+ if type(angle) != typst-angle {
+ coordinate.resolve-system(angle)
+ }
+
+ return (ctx => {
+ let body = body
+ let style = styles.resolve(ctx.style, merge: style, root: "content")
+ let padding = util.as-padding-dict(style.padding)
+ for (k, v) in padding {
+ padding.insert(k, util.resolve-number(ctx, v))
+ }
+
+ let (ctx, a) = coordinate.resolve(ctx, a)
+ let b = b
+ let auto-size = b == auto
+ if not auto-size {
+ (ctx, b) = coordinate.resolve(ctx, b)
+ }
+
+ let angle = if type(angle) != typst-angle {
+ let c
+ (ctx, c) = coordinate.resolve(ctx, angle)
+ vector.angle2(a, c)
+ } else {
+ angle
+ }
+
+ // Typst's `rotate` function is clockwise relative to x-axis, which is backwards from us
+ angle = angle * -1
+
+ // Optionally scale content with current canvas scaling
+ if style.auto-scale == true {
+ let sx = vector.len(matrix.column(ctx.transform, 0))
+ let sy = vector.len(matrix.column(ctx.transform, 1))
+
+ body = std.scale(x: sx * 100%, y: sy * 100%, body, reflow: true)
+ }
+
+ // Height from the baseline to content-north
+ let (content-width, baseline-height) = util.measure(ctx, text(top-edge: "cap-height", bottom-edge: "baseline", body))
+
+ // Size of the bounding box
+ let (width, height, ..) = if auto-size {
+ util.measure(ctx, text(top-edge: "cap-height", bottom-edge: "bounds", body))
+ } else {
+ vector.sub(b, a)
+ }
+
+ let bounds-width = calc.abs(width)
+ let bounds-height = calc.abs(height)
+ baseline-height = bounds-height - baseline-height
+
+ width = calc.max(0, bounds-width + padding.left + padding.right)
+ height = calc.max(0, bounds-height + padding.top + padding.bottom)
+
+ let anchors = {
+ let w = width / 2
+ let h = height / 2
+ let bh = (baseline-height - padding.top - padding.bottom) / 2
+
+ let bounds-center = if auto-size {
+ a
+ } else {
+ vector.lerp(a, b, .5)
+ }
+
+ // Only the center anchor gets transformed. All other anchors
+ // must be calculated relative to the transformed center!
+ bounds-center = matrix.mul4x4-vec3(ctx.transform,
+ vector.as-vec(bounds-center, init: (0,0,0)))
+
+ let east-dir = vector.rotate-z((1, 0, 0), angle)
+ let north-dir = vector.rotate-z((-1, 0, 0), angle + 90deg)
+ let east-scaled = vector.scale(east-dir, +w)
+ let west-scaled = vector.scale(east-dir, -w)
+ let north-scaled = vector.scale(north-dir, +h)
+ let south-scaled = vector.scale(north-dir, -h)
+
+ let north = vector.add(bounds-center, north-scaled)
+ let south = vector.add(bounds-center, south-scaled)
+ let east = vector.add(bounds-center, east-scaled)
+ let west = vector.add(bounds-center, west-scaled)
+ let north-east = vector.add(bounds-center, vector.add(north-scaled, east-scaled))
+ let north-west = vector.sub(bounds-center, vector.add(south-scaled, east-scaled))
+ let south-east = vector.add(bounds-center, vector.add(south-scaled, east-scaled))
+ let south-west = vector.sub(bounds-center, vector.add(north-scaled, east-scaled))
+
+ let base = vector.add(south,
+ vector.scale(north-dir, padding.bottom + baseline-height))
+ let mid = vector.lerp(
+ vector.sub(north, vector.scale(north-dir, padding.top)),
+ base,
+ 0.5)
+ let base-east = vector.add(base, east-scaled)
+ let base-west = vector.add(base, west-scaled)
+ let text = vector.add(base, vector.scale(east-dir, -content-width / 2))
+ let mid-east = vector.add(mid, east-scaled)
+ let mid-west = vector.add(mid, west-scaled)
+
+ (
+ center: bounds-center,
+ mid: mid,
+ mid-east: mid-east,
+ mid-west: mid-west,
+ base: base,
+ base-east: base-east,
+ base-west: base-west,
+ text: text,
+ north: north,
+ north-east: north-east,
+ north-west: north-west,
+ south: south,
+ south-east: south-east,
+ south-west: south-west,
+ east: east,
+ west: west,
+ )
+ }
+
+ let frame-stroke = if style.frame != none {
+ style.stroke
+ }
+ let frame-fill = if style.frame != none {
+ style.fill
+ }
+ let frame-shape = if style.frame in (none, "rect") {
+ drawable.path(
+ path-util.line-segment((
+ anchors.north-west,
+ anchors.north-east,
+ anchors.south-east,
+ anchors.south-west
+ )),
+ close: true,
+ stroke: frame-stroke,
+ fill: frame-fill,)
+ } else if style.frame == "circle" {
+ let (x, y, z) = util.calculate-circle-center-3pt(anchors.north-west, anchors.south-west, anchors.south-east)
+ let r = vector.dist((x, y, z), anchors.north-west)
+ drawable.ellipse(
+ x, y, z,
+ r, r,
+ stroke: frame-stroke,
+ fill: frame-fill,)
+ }
+
+ let (aabb-width, aabb-height, ..) = aabb.size(aabb.aabb(
+ (anchors.north-west, anchors.north-east,
+ anchors.south-west, anchors.south-east)))
+
+ let drawables = ()
+ if frame-shape != none {
+ drawables.push(frame-shape)
+ }
+
+ // Because of precision problems with some fonts (e.g. "Source Sans 3")
+ // we need to round the block sizes up. Otherwise, unwanted hyphenation
+ // gets introduced.
+ let round-up(v, digits: 8) = {
+ calc.ceil(v * calc.pow(10, digits)) / calc.pow(10, digits)
+ }
+
+ drawables.push(
+ drawable.content(
+ anchors.center,
+ aabb-width,
+ aabb-height,
+ frame-shape.segments,
+ typst-rotate(angle,
+ reflow: true,
+ origin: center + horizon,
+ block(
+ width: round-up(width) * ctx.length,
+ height: round-up(height) * ctx.length,
+ inset: (
+ top: padding.at("top", default: 0) * ctx.length,
+ left: padding.at("left", default: 0) * ctx.length,
+ bottom: padding.at("bottom", default: 0) * ctx.length,
+ right: padding.at("right", default: 0) * ctx.length,
+ ),
+ text(top-edge: "cap-height", bottom-edge: "baseline", body)
+ )
+ )
+ )
+ )
+
+ let (transform, anchors) = anchor_.setup(
+ anchor => {
+ if type(anchor) == str {
+ anchors.at(anchor)
+ }
+ },
+ anchors.keys(),
+ default: if auto-size { "center" } else { "north-west" },
+ offset-anchor: anchor,
+ transform: none, // Content does not get transformed, see the calculation of anchors.
+ name: name,
+ )
+
+ return (
+ ctx: ctx,
+ name: name,
+ anchors: anchors,
+ drawables: drawable.apply-transform(
+ transform,
+ drawables
+ )
+ )
+ },)
+}
+
+/// Draws a rectangle between two coordinates.
+/// ```typc example
+/// rect((0,0), (1,1))
+/// rect(
+/// (-.5, -.5),
+/// (rel: (2, 2)),
+/// radius: (
+/// north-east: (100%, .5),
+/// south-west: (100%, .5),
+/// rest: .2
+/// ),
+/// stroke: red
+/// )
+/// rect((-1, -1), (rel: (3, 3)), radius: .5, stroke: blue)
+/// ```
+///
+/// - a (coordinate): Coordinate of the bottom left corner of the rectangle.
+/// - b (coordinate): Coordinate of the top right corner of the rectangle. You can draw a rectangle with a specified width and height by using relative coordinates for this parameter `(rel: (width, height))`.
+/// - name (none,str):
+/// - anchor (none, str):
+/// - ..style (style):
+///
+/// ## Styling
+/// *Root*: `rect`
+/// <Parameter name="radius" types="number,ratio,dictionary" default_value="0">
+/// The rectangle's corner radius. If set to a single number, that radius is applied to all four corners of the rectangle. If passed a dictionary you can set the radii per corner. The following keys support either a <Type>number</Type>, <Type>ratio</Type> or an array of <Type>number</Type> or <Type>ratio</Type> for specifying a different x- and y-radius: `north`, `east`, `south`, `west`, `north-west`, `north-east`, `south-west` and `south-east`. To set a default value for remaining corners, the `rest` key can be used.
+///
+/// Ratio values are relative to the rectangle's width and height.
+///
+/// ```typc example vertical
+/// rect((0,0), (rel: (1,1)), radius: 0)
+/// rect((2,0), (rel: (1,1)), radius: 25%)
+/// rect((4,0), (rel: (1,1)), radius: (north: 50%))
+/// rect((6,0), (rel: (1,1)), radius: (north-east: 50%))
+/// rect((8,0), (rel: (1,1)), radius: (south-west: 0, rest: 50%))
+/// rect((10,0), (rel: (1,1)), radius: (rest: (20%, 50%)))
+/// ```
+/// </Parameter>
+///
+/// ## Anchors
+/// Supports border and path anchors. It's default is the `"center"` anchor.
+///
+#let rect(a, b, name: none, anchor: none, ..style) = {
+ // Coordinate check
+ let t = (a, b).map(coordinate.resolve-system)
+
+ // No extra positional arguments from the style sink
+ assert.eq(
+ style.pos(),
+ (),
+ message: "Unexpected positional arguments: " + repr(style.pos()),
+ )
+ let style = style.named()
+
+ return (
+ ctx => {
+ let ctx = ctx
+ let (ctx, a, b) = coordinate.resolve(ctx, a, b)
+ assert(a.at(2) == b.at(2),
+ message: "Both rectangle points must have the same z value.")
+ (a, b) = {
+ let lo = (
+ calc.min(a.at(0), b.at(0)),
+ calc.min(a.at(1), b.at(1)),
+ calc.min(a.at(2), b.at(2)),
+ )
+ let hi = (
+ calc.max(a.at(0), b.at(0)),
+ calc.max(a.at(1), b.at(1)),
+ calc.max(a.at(2), b.at(2)),
+ )
+ (lo, hi)
+ }
+
+ let style = styles.resolve(ctx.style, merge: style, root: "rect")
+ let (x1, y1, z1) = a
+ let (x2, y2, z2) = b
+
+ let size = (calc.abs(x2 - x1), calc.abs(y2 - y1))
+ let (north-west: nw, north-east: ne,
+ south-west: sw, south-east: se) = util.as-corner-radius-dict(ctx, style.radius, size)
+
+ let drawables = {
+ let z = z1
+
+ // Compute two corner points offset by radius from origin pt.
+ //
+ // x radius * a
+ // |----|
+ // --p1←--pt ---
+ // | | y radius * b
+ // ↓ |
+ // p2 ---
+ // |
+ //
+ // parameters a and b function as direction vectors in which
+ // direction the resulting points p1 and p2 should get offset to.
+ //
+ // The point pt is the corner point of the non-rounded rectangle.
+ // If the radius is zero, we can just return that point for both
+ // new corners.
+ let get-corner-pts(radius, pt, a, b) = {
+ let (rx, ry) = radius
+ if rx > 0 or ry > 0 {
+ let (xa, ya) = a
+ let (xb, yb) = b
+ (vector.add(pt, (xa * rx, ya * ry)),
+ vector.add(pt, (xb * rx, yb * ry)))
+ } else {
+ (pt, pt)
+ }
+ }
+
+ // Get segments for arc between start- and stop angle, starting
+ // at point. If radius is zero for both axes, x and y, nothing
+ // gets returned.
+ //
+ // s----p0/
+ // p1
+ // |
+ // e
+ //
+ // Returns a cubic bezier curve between s and e
+ // with the control points pointing from s in direction
+ // p0 * radius and from e in direction p1 * radius.
+ // The bezier approximates a 90 degree arc.
+ let corner-arc(radius, s, e, p0, p1) = {
+ let (rx, ry) = radius
+ if rx > 0 or ry > 0 {
+ let m = 0.551784
+ let p0 = (p0.at(0) * m * rx,
+ p0.at(1) * m * ry)
+ let p1 = (p1.at(0) * m * rx,
+ p1.at(1) * m * ry)
+ (path-util.cubic-segment(s, e,
+ vector.add(s, p0),
+ vector.add(e, p1)),)
+ }
+ }
+
+ // Compute all eight corner points:
+ //
+ // p1-------p2
+ // / | | \
+ // p0--+ +--p3
+ // | |
+ // p7--+ +--p4
+ // \ | | /
+ // p6-------p5
+ //
+ // If a corner has radius (0,0), both of its
+ // corner points are the same. See the comment on get-corner-pts
+ // on how the corners get computed.
+ let (p0, p1) = get-corner-pts(nw, (x1, y2, z), ( 0,-1), ( 1, 0))
+ let (p2, p3) = get-corner-pts(ne, (x2, y2, z), (-1, 0), ( 0,-1))
+ let (p4, p5) = get-corner-pts(se, (x2, y1, z), ( 0, 1), (-1, 0))
+ let (p6, p7) = get-corner-pts(sw, (x1, y1, z), ( 1, 0), ( 0, 1))
+
+ let segments = ()
+ segments += corner-arc(nw, p1, p0, (-1,0), (0, 1))
+ if p0 != p7 { segments += (path-util.line-segment((p0, p7)),) }
+ segments += corner-arc(sw, p7, p6, (0,-1), (-1,0))
+ if p6 != p5 { segments += (path-util.line-segment((p6, p5)),) }
+ segments += corner-arc(se, p5, p4, (1, 0), (0,-1))
+ if p4 != p3 { segments += (path-util.line-segment((p4, p3)),) }
+ segments += corner-arc(ne, p3, p2, (0, 1), (1, 0))
+ if p2 != p1 { segments += (path-util.line-segment((p2, p1)),) }
+
+ drawable.path(segments, fill: style.fill, stroke: style.stroke, close: true)
+ }
+
+ // Calculate border anchors
+ let center = vector.lerp(a, b, .5)
+ let (width, height, ..) = size
+ let (transform, anchors) = anchor_.setup(
+ _ => center,
+ ("center",),
+ default: "center",
+ name: name,
+ offset-anchor: anchor,
+ transform: ctx.transform,
+ border-anchors: true,
+ path-anchors: true,
+ radii: (width, height),
+ path: drawables,
+ )
+
+ return (
+ ctx: ctx,
+ name: name,
+ anchors: anchors,
+ drawables: drawable.apply-transform(transform, drawables),
+ )
+ },
+ )
+}
+
+/// Draws a quadratic or cubic bezier curve
+///
+/// ```typc example
+/// let (a, b, c) = ((0, 0), (2, 0), (1, 1))
+/// line(a, c, b, stroke: gray)
+/// bezier(a, b, c)
+///
+/// let (a, b, c, d) = ((0, -1), (2, -1), (.5, -2), (1.5, 0))
+/// line(a, c, d, b, stroke: gray)
+/// bezier(a, b, c, d)
+/// ```
+///
+/// - start (coordinate): Start position
+/// - end (coordinate): End position (last coordinate)
+/// - name (none,str):
+/// - ..ctrl-style (coordinate,style): The first two positional arguments are taken as cubic bezier control points, where the first is the start control point and the second is the end control point. One control point can be given for a quadratic bezier curve instead. Named arguments are for styling.
+///
+/// ## Styling
+/// *Root* `bezier`
+///
+/// Supports marks.
+///
+/// ## Anchors
+/// Supports path anchors.
+/// - **ctrl-n**: nth control point where n is an integer starting at 0
+///
+#let bezier(start, end, ..ctrl-style, name: none) = {
+ // Extra positional arguments are treated like control points.
+ let (ctrl, style) = (ctrl-style.pos(), ctrl-style.named())
+
+ // Control point check
+ let len = ctrl.len()
+ assert(
+ len in (1, 2),
+ message: "Bezier curve expects 1 or 2 control points. Got " + str(len),
+ )
+ let coordinates = (start, ..ctrl, end)
+
+ // Coordinates check
+ let t = coordinates.map(coordinate.resolve-system)
+
+ return (
+ ctx => {
+ let (ctx, start, ..ctrl, end) = coordinate.resolve(ctx, ..coordinates)
+
+ if ctrl.len() == 1 {
+ (start, end, ..ctrl) = bezier_.quadratic-to-cubic(start, end, ..ctrl)
+ }
+
+ let style = styles.resolve(ctx.style, merge: style, root: "bezier")
+ let drawables = drawable.path(
+ (path-util.cubic-segment(start, end, ..ctrl),),
+ fill: style.fill,
+ fill-rule: style.fill-rule,
+ stroke: style.stroke,
+ )
+
+ let (transform, anchors) = anchor_.setup(
+ anchor => (
+ ctrl-0: ctrl.at(0),
+ ctrl-1: ctrl.at(1),
+ ).at(anchor),
+ ("ctrl-0", "ctrl-1"),
+ default: "start",
+ name: name,
+ transform: ctx.transform,
+ path-anchors: true,
+ path: drawables,
+ )
+
+ if mark_.check-mark(style.mark) {
+ drawables = mark_.place-marks-along-path(ctx, style.mark, transform, drawables)
+ } else {
+ drawables = drawable.apply-transform(transform, drawables)
+ }
+
+ return (
+ ctx: ctx,
+ name: name,
+ anchors: anchors,
+ drawables: drawables,
+ )
+ },
+ )
+}
+
+/// Draws a cubic bezier curve through a set of three points. See [bezier](./bezier) for style and anchor details.
+///
+/// ```typc example
+/// let (a, b, c) = ((0, 0), (1, 1), (2, -1))
+/// line(a, b, c, stroke: gray)
+/// bezier-through(a, b, c, name: "b")
+///
+/// // Show calculated control points
+/// line(a, "b.ctrl-0", "b.ctrl-1", c, stroke: gray)
+/// ```
+///
+/// - start (coordinate): The position to start the curve.
+/// - pass-through (coordinate): The position to pass the curve through.
+/// - end (coordinate): The position to end the curve.
+/// - name (none,str):
+/// - ..style (style):
+#let bezier-through(start, pass-through, end, name: none, ..style) = {
+ assert.eq(style.pos(), (), message: "Unexpected positional arguments: " + repr(style.pos()))
+ style = style.named()
+
+ return (ctx => {
+ let (ctx, start, pass-through, end) = coordinate.resolve(ctx, start, pass-through, end)
+
+ let (start, end, ..control) = bezier_.cubic-through-3points(start, pass-through, end)
+
+ return bezier(start, end, ..control, ..style, name: name).first()(ctx)
+ },)
+}
+
+/// Draws a Catmull-Rom curve through a set of points.
+///
+/// ```typc example
+/// catmull((0,0), (1,1), (2,-1), (3,0), tension: .4, stroke: blue)
+/// catmull((0,0), (1,1), (2,-1), (3,0), tension: .5, stroke: red)
+/// ```
+///
+/// - ..pts-style (coordinate,style): Positional arguments should be coordinates that the curve should pass through. Named arguments are for styling.
+/// - close (bool): Closes the curve with a straight line between the start and end of the curve.
+/// - name (none,str):
+///
+/// ## Styling
+/// *Root*: `catmull`
+///
+/// Supports marks.
+///
+/// - tension (float) = 0.5: How tight the curve should fit to the points. The higher the tension the less curvy the curve.
+///
+/// ## Anchors
+/// Supports path anchors.
+/// - **pt-n**: The nth given position (0 indexed so "pt-0" is equal to "start")
+#let catmull(..pts-style, close: false, name: none) = {
+ let (pts, style) = (pts-style.pos(), pts-style.named())
+
+ assert(pts.len() >= 2, message: "Catmull-rom curve requires at least two points. Got " + repr(pts.len()) + "instead.")
+
+ pts.map(coordinate.resolve-system)
+
+ return (ctx => {
+ let (ctx, ..pts) = coordinate.resolve(ctx, ..pts)
+ let style = styles.resolve(ctx.style, merge: style, root: "catmull")
+
+ let curves = bezier_.catmull-to-cubic(
+ pts,
+ style.tension,
+ close: close)
+
+ let segments = curves.map(c => path-util.cubic-segment(..c))
+ let drawables = drawable.path(
+ segments,
+ fill: style.fill,
+ fill-rule: style.fill-rule,
+ stroke: style.stroke,
+ close: close)
+
+ let (transform, anchors) = {
+ let a = for (i, pt) in pts.enumerate() {
+ (("pt-" + str(i)): pt)
+ }
+ anchor_.setup(
+ anchor => a.at(anchor), // Would like to return just `a.at` but Typst is mean :<
+ a.keys(),
+ name: name,
+ default: "start",
+ transform: ctx.transform,
+ path-anchors: true,
+ path: drawables,
+ )
+ }
+
+ if mark_.check-mark(style.mark) {
+ drawables = mark_.place-marks-along-path(ctx, style.mark, transform, drawables)
+ } else {
+ drawables = drawable.apply-transform(transform, drawables)
+ }
+
+ return (
+ ctx: ctx,
+ name: name,
+ anchors: anchors,
+ drawables: drawables,
+ )
+ },)
+}
+
+/// Draws a Hobby curve through a set of points.
+///
+/// ```typc example
+/// hobby((0, 0), (1, 1), (2, -1), (3, 0), omega: 0, stroke: blue)
+/// hobby((0, 0), (1, 1), (2, -1), (3, 0), omega: 1, stroke: red)
+/// ```
+///
+/// - ..pts-style (coordinate,style): Positional arguments are the coordinates to use to draw the curve with, a minimum of two is required. Named arguments are for styling.
+/// - tb (auto,array): Incoming tension at `pts.at(n+1)` from `pts.at(n)` to `pts.at(n+1)`. The number given must be one less than the number of points.
+/// - ta (auto, array): Outgoing tension at `pts.at(n)` from `pts.at(n)` to `pts.at(n+1)`. The number given must be one less than the number of points.
+/// - close (bool): Closes the curve with a proper smooth curve between the start and end of the curve.
+/// - name (none,str):
+///
+/// ## Styling
+/// *Root* `hobby`
+///
+/// Supports marks.
+/// - omega (array) = (1, 1): A tuple of floats that describe how curly the curve should be at each endpoint. When the curl is close to zero, the spline approaches a straight line near the endpoints. When the curl is close to one, it approaches a circular arc.
+///
+/// ## Anchors
+/// Supports path anchors.
+/// - **pt-n**: The nth given position (0 indexed, so "pt-0" is equal to "start")
+#let hobby(..pts-style, ta: auto, tb: auto, close: false, name: none) = {
+ let (pts, style) = (pts-style.pos(), pts-style.named())
+
+ assert(pts.len() >= 2, message: "Hobby curve requires at least two points. Got " + repr(pts.len()) + "instead.")
+
+ pts.map(coordinate.resolve-system)
+
+ return (ctx => {
+ let (ctx, ..pts) = coordinate.resolve(ctx, ..pts)
+ let style = styles.resolve(ctx.style, merge: style, root: "hobby")
+
+ let curves = hobby_.hobby-to-cubic(
+ pts,
+ ta: ta,
+ tb: tb,
+ omega: style.omega,
+ close: close)
+
+ let segments = curves.map(c => path-util.cubic-segment(..c))
+ let drawables = drawable.path(
+ segments,
+ fill: style.fill,
+ fill-rule: style.fill-rule,
+ stroke: style.stroke,
+ close: close)
+
+ let (transform, anchors) = {
+ let a = for (i, pt) in pts.enumerate() {
+ (("pt-" + str(i)): pt)
+ }
+ anchor_.setup(
+ anchor => {
+ if type(anchor) == str and anchor in a {
+ return a.at(anchor)
+ }
+ },
+ a.keys(),
+ name: name,
+ default: "start",
+ transform: ctx.transform,
+ path-anchors: true,
+ path: drawables,
+ )
+ }
+
+ if mark_.check-mark(style.mark) {
+ drawables = mark_.place-marks-along-path(ctx, style.mark, transform, drawables)
+ } else {
+ drawables = drawable.apply-transform(transform, drawables)
+ }
+
+ return (
+ ctx: ctx,
+ name: name,
+ anchors: anchors,
+ drawables: drawables,
+ )
+ },)
+}
+
+/// Merges two or more paths by concattenating their elements. Anchors and visual styling, such as `stroke` and `fill`, are not preserved. When an element's path does not start at the same position the previous element's path ended, a straight line is drawn between them so that the final path is continuous. You must then pay attention to the direction in which element paths are drawn.
+///
+/// ```typc example
+/// merge-path(fill: white, {
+/// line((0, 0), (1, 0))
+/// bezier((), (0, 0), (1,1), (0,1))
+/// })
+/// ```
+///
+/// Elements hidden via @@hide() are ignored.
+///
+/// ## Anchors
+/// **centroid**: Centroid of the _closed and non self-intersecting_ shape. Only exists if `close` is true.
+/// Supports path anchors and shapes where all vertices share the same z-value.
+///
+/// - body (elements): Elements with paths to be merged together.
+/// - close (bool): Close the path with a straight line from the start of the path to its end.
+/// - name (none,str):
+/// - ..style (style):
+#let merge-path(body, close: false, name: none, ..style) = {
+ // No extra positional arguments from the style sink
+ assert.eq(
+ style.pos(),
+ (),
+ message: "Unexpected positional arguments: " + repr(style.pos()),
+ )
+ let style = style.named()
+
+ return (
+ ctx => {
+ let ctx = ctx
+ let segments = ()
+ for element in body {
+ let r = process.element(ctx, element)
+ if r != none {
+ ctx = r.ctx
+ if segments != () and r.drawables != () {
+ assert.eq(r.drawables.first().type, "path")
+ let start = path-util.segment-end(segments.last())
+ let end = path-util.segment-start(r.drawables.first().segments.first())
+ if vector.dist(start, end) > 0 {
+ segments.push(path-util.line-segment((start, end,)))
+ }
+ }
+ for drawable in r.drawables {
+ if drawable.hidden { continue }
+ assert.eq(drawable.type, "path")
+ segments += drawable.segments
+ }
+ }
+ }
+
+ let style = styles.resolve(ctx.style, merge: style)
+ let drawables = drawable.path(fill: style.fill, fill-rule: style.fill-rule, stroke: style.stroke, close: close, segments)
+
+ let (transform, anchors) = anchor_.setup(
+ name => {
+ if name == "centroid" {
+ // Try finding a closed shapes center by
+ // Sampling it to a polygon.
+ return polygon_.simple-centroid(polygon_.from-segments(drawables.segments))
+ }
+ },
+ if close != none { ("centroid",) } else { () },
+ name: name,
+ transform: none,
+ path-anchors: true,
+ path: drawables,
+ )
+
+ return (
+ ctx: ctx,
+ name: name,
+ anchors: anchors,
+ drawables: drawables,
+ )
+ },
+ )
+}
diff --git a/render/packages/preview/cetz/0.3.4/src/draw/styling.typ b/render/packages/preview/cetz/0.3.4/src/draw/styling.typ
new file mode 100644
index 0000000..2783ede
--- /dev/null
+++ b/render/packages/preview/cetz/0.3.4/src/draw/styling.typ
@@ -0,0 +1,69 @@
+#import "/src/util.typ"
+
+/// Set current style
+///
+/// - ..style (style): Style key-value pairs
+#let set-style(..style) = {
+ assert.eq(
+ style.pos().len(),
+ 0,
+ message: "set-style takes no positional arguments",
+ )
+
+ (ctx => {
+ ctx.style = util.merge-dictionary(ctx.style, style.named())
+
+ return (ctx: ctx)
+ },)
+}
+
+/// Set current fill style
+///
+/// Shorthand for `set-style(fill: <fill>)`
+///
+/// - fill (paint): Fill style
+#let fill(fill) = set-style(fill: fill)
+
+/// Set current stroke style
+///
+/// Shorthand for `set-style(stroke: <fill>)`
+///
+/// - stroke (stroke): Stroke style
+#let stroke(stroke) = set-style(stroke: stroke)
+
+/// Register a custom mark to the canvas
+///
+/// The mark should contain both anchors called **tip** and **base** that are used to determine the marks orientation. If unset both default to `(0, 0)`.
+/// An anchor named **center** is used as center of the mark, if present. Otherwise the mid between **tip** and **base** is used.
+///
+/// ```typc example
+/// register-mark(":)", style => {
+/// circle((0,0), radius: .5, fill: yellow)
+/// arc((0,0), start: 180deg + 30deg, delta: 180deg - 60deg, anchor: "origin", radius: .3)
+/// circle((-0.15, 0.15), radius: .1, fill: white)
+/// circle((-0.10, 0.10), radius: .025, fill: black)
+/// circle(( 0.15, 0.15), radius: .1, fill: white)
+/// circle(( 0.20, 0.10), radius: .025, fill: black)
+///
+/// anchor("tip", ( 0.5, 0))
+/// anchor("base", (-0.5, 0))
+/// })
+///
+/// line((0,0), (3,0), mark: (end: ":)"))
+/// ```
+///
+/// - symbol (str): Mark name
+/// - mnemonic (none,str): Mark short name
+/// - body (function): Mark drawing callback, receiving the mark style as argument and returning elements. Format `(styles) => elements`.
+#let register-mark(symbol, body, mnemonic: none) = {
+ assert(type(symbol) == str)
+ assert(type(body) == function)
+
+ (ctx => {
+ ctx.marks.marks.insert(symbol, body)
+ if type(mnemonic) == str and mnemonic.len() > 0 {
+ ctx.marks.mnemonics.insert(mnemonic, symbol)
+ }
+ return (ctx: ctx)
+ },)
+}
diff --git a/render/packages/preview/cetz/0.3.4/src/draw/transformations.typ b/render/packages/preview/cetz/0.3.4/src/draw/transformations.typ
new file mode 100644
index 0000000..d8e3f04
--- /dev/null
+++ b/render/packages/preview/cetz/0.3.4/src/draw/transformations.typ
@@ -0,0 +1,273 @@
+#import "/src/coordinate.typ"
+#import "/src/matrix.typ"
+#import "/src/vector.typ"
+#import "/src/util.typ"
+
+// Utility for applying translation to and from
+// the origin to apply a transformation matrix to.
+//
+// - ctx (context): Context
+// - transform (matrix): Transformation matrix
+// - origin (coordinate): Origin coordinate or none
+#let _transform-around-origin(ctx, transform, origin) = {
+ if origin != none {
+ let (_, origin) = coordinate.resolve(ctx, origin, update: false)
+ let a = matrix.transform-translate(..origin)
+ let b = matrix.transform-translate(..vector.scale(origin, -1))
+
+ matrix.mul-mat(a, matrix.mul-mat(transform, b))
+ } else {
+ transform
+ }
+}
+
+/// Sets the transformation matrix.
+///
+/// - mat (none, matrix): The 4x4 transformation matrix to set. If `none` is passed, the transformation matrix is set to the identity matrix (`matrix.ident()`).
+#let set-transform(mat) = {
+ let mat = if mat == none {
+ matrix.ident(4)
+ } else {
+ matrix.round(mat)
+ }
+
+ assert(
+ type(mat) == array,
+ message: "Transformtion matrix must be of type array, got: " + repr(mat)
+ )
+ assert.eq(
+ mat.len(),
+ 4,
+ message: "Transformation matrix must be of size 4x4, got: " + repr(mat)
+ )
+
+ (ctx => {
+ ctx.transform = mat
+ return (ctx: ctx)
+ },)
+}
+
+/// Rotates the transformation matrix on the z-axis by a given angle or other axes when specified.
+///
+/// ```typc example
+/// // Rotate on z-axis
+/// rotate(z: 45deg)
+/// rect((-1,-1), (1,1))
+/// // Rotate on y-axis
+/// rotate(y: 80deg)
+/// circle((0,0))
+/// ```
+///
+/// - ..angles (angle): A single angle as a positional argument to rotate on the z-axis by.
+/// Named arguments of `x`, `y` or `z` can be given to rotate on their respective axis.
+/// You can give named arguments of `yaw`, `pitch` or `roll`, too.
+/// - origin (none,coordinate): Origin to rotate around, or (0, 0, 0) if set to `none`.
+#let rotate(..angles, origin: none) = {
+ assert(angles.pos().len() == 1 or angles.named().len() > 0,
+ message: "Rotate takes a single z-angle or angles " +
+ "(x, y, z or yaw, pitch, roll) as named arguments, got: " + repr(angles))
+
+ let named = angles.named()
+ let names = named.keys()
+
+ let mat = if angles.pos().len() == 1 {
+ matrix.transform-rotate-z(angles.pos().at(0))
+ } else if names.all(n => n in ("x", "y", "z")) {
+ matrix.transform-rotate-xyz(named.at("x", default: 0deg),
+ named.at("y", default: 0deg),
+ named.at("z", default: 0deg))
+ } else if names.all(n => n in ("yaw", "pitch", "roll")) {
+ matrix.transform-rotate-ypr(named.at("yaw", default: 0deg),
+ named.at("pitch", default: 0deg),
+ named.at("roll", default: 0deg))
+ } else {
+ panic("Invalid rotate arguments." +
+ "Rotate expects: A single (z-axis) angle or any combination of x, y,z or any combination of yaw, pitch, roll. " +
+ "Got: " + repr(named))
+ }
+
+ (ctx => {
+ ctx.transform = matrix.mul-mat(ctx.transform,
+ _transform-around-origin(ctx, mat, origin))
+ return (ctx: ctx)
+ },)
+}
+
+/// Translates the transformation matrix by the given vector or dictionary.
+///
+/// ```typc example
+/// // Outer rect
+/// rect((0, 0), (2, 2))
+/// // Inner rect
+/// translate(x: .5, y: .5)
+/// rect((0, 0), (1, 1))
+/// ```
+///
+/// - ..args (vector, float, length): A single vector or any combination of the named arguments `x`, `y` and `z` to translate by.
+/// A translation matrix with the given offsets gets multiplied with the current transformation depending on the value of `pre`.
+/// - pre (bool): Specify matrix multiplication order
+/// - false: `World = World * Translate`
+/// - true: `World = Translate * World`
+#let translate(..args, pre: false) = {
+ assert((args.pos().len() == 1 and args.named() == (:)) or
+ (args.pos() == () and args.named() != (:)),
+ message: "Expected a single positional argument or one or more named arguments, got: " + repr(args))
+
+ let pos = args.pos()
+ let named = args.named()
+
+ let vec = if named != (:) {
+ (named.at("x", default: 0), named.at("y", default: 0), named.at("z", default: 0))
+ } else {
+ vector.as-vec(pos.at(0), init: (0, 0, 0))
+ }
+
+ (ctx => {
+ // Allow translating by length values
+ let vec = vec.map(v => if type(v) == length {
+ util.resolve-number(ctx, v)
+ } else {
+ v
+ })
+
+ let t = matrix.transform-translate(..vec)
+ if pre {
+ ctx.transform = matrix.mul-mat(t, ctx.transform)
+ } else {
+ ctx.transform = matrix.mul-mat(ctx.transform, t)
+ }
+ return (ctx: ctx)
+ },)
+}
+
+/// Scales the transformation matrix by the given factor(s).
+///
+/// ```typc example
+/// // Scale the y-axis
+/// scale(y: 50%)
+/// circle((0,0))
+/// ```
+///
+/// Note that content like text does not scale automatically. See `auto-scale` styling of content for that.
+///
+/// - ..args (float, ratio): A single value to scale the transformation matrix by or per axis
+/// scaling factors. Accepts a single float or ratio value or any combination of the named arguments
+/// `x`, `y` and `z` to set per axis scaling factors. A ratio of 100% is the same as the value $1$.
+/// - origin (none,coordinate): Origin to rotate around, or (0, 0, 0) if set to `none`.
+#let scale(..args, origin: none) = {
+ assert((args.pos().len() == 1 and args.named() == (:)) or
+ (args.pos() == () and args.named() != (:)),
+ message: "Expected a single positional argument or one or more named arguments, got: " + repr(args))
+
+ let pos = args.pos()
+ let named = args.named()
+
+ let vec = if args.named() != (:) {
+ (named.at("x", default: 1), named.at("y", default: 1), named.at("z", default: 1))
+ } else if type(pos.at(0)) == array {
+ vector.as-vec(pos, init: (1, 1, 1))
+ } else {
+ let factor = pos.at(0)
+ (factor, factor, factor)
+ }
+
+ // Allow scaling using ratio values
+ vec = vec.map(v => if type(v) == ratio {
+ v / 100%
+ } else {
+ v
+ })
+
+ (ctx => {
+ let mat = matrix.transform-scale(vec)
+ ctx.transform = matrix.mul-mat(ctx.transform,
+ _transform-around-origin(ctx, mat, origin))
+ return (ctx: ctx)
+ },)
+}
+
+/// Sets the given position as the new origin `(0, 0, 0)`
+///
+/// ```typc example
+/// // Outer rect
+/// rect((0,0), (2,2), name: "r")
+/// // Move origin to top edge
+/// set-origin("r.north")
+/// circle((0, 0), radius: .1)
+/// ```
+///
+/// - origin (coordinate): Coordinate to set as new origin `(0,0,0)`
+#let set-origin(origin) = {
+ (
+ ctx => {
+ let (ctx, c) = coordinate.resolve(ctx, origin)
+ let (x, y, z) = vector.sub(
+ util.apply-transform(ctx.transform, c),
+ util.apply-transform(ctx.transform, (0, 0, 0)),
+ )
+ ctx.transform = matrix.mul-mat(matrix.transform-translate(x, y, z), ctx.transform)
+ return (ctx: ctx)
+ },
+ )
+}
+
+/// Sets the previous coordinate.
+///
+/// The previous coordinate can be used via `()` (empty coordinate).
+/// It is also used as base for relative coordinates if not specified
+/// otherwise.
+///
+/// ```typc example
+/// circle((), radius: .25)
+/// move-to((1,0))
+/// circle((), radius: .15)
+/// ```
+///
+/// - pt (coordinate): The coordinate to move to.
+#let move-to(pt) = {
+ let t = coordinate.resolve-system(pt)
+
+ return (ctx => {
+ let (ctx, pt) = coordinate.resolve(ctx, pt)
+ return (ctx: ctx)
+ },)
+}
+
+/// Span viewport between two coordinates and set-up scaling and translation
+///
+/// ```typc example
+/// rect((0,0), (2,2))
+/// set-viewport((0,0), (2,2), bounds: (10, 10))
+/// circle((5,5))
+/// ```
+///
+/// - from (coordinate): Bottom left corner coordinate
+/// - to (coordinate): Top right corner coordinate
+/// - bounds (vector): Viewport bounds vector that describes the inner width,
+/// height and depth of the viewport
+#let set-viewport(from, to, bounds: (1, 1, 1)) = {
+ (from, to).map(coordinate.resolve-system)
+
+ return (ctx => {
+ let bounds = vector.as-vec(bounds, init: (1, 1, 1))
+
+ let (ctx, from, to) = coordinate.resolve(ctx, from, to)
+ let (fx, fy, fz) = from
+ let (tx, ty, tz) = to
+
+ // Compute scaling
+ let (sx, sy, sz) = vector.sub((tx, ty, tz),
+ (fx, fy, fz)).enumerate().map(((i, v)) => if bounds.at(i) == 0 {
+ 0
+ } else {
+ v / bounds.at(i)
+ })
+
+ ctx.transform = matrix.mul-mat(ctx.transform,
+ matrix.transform-translate(fx, fy, fz))
+ ctx.transform = matrix.mul-mat(ctx.transform,
+ matrix.transform-scale((sx, sy, sz)))
+ return (ctx: ctx)
+ },)
+}
+
diff --git a/render/packages/preview/cetz/0.3.4/src/draw/util.typ b/render/packages/preview/cetz/0.3.4/src/draw/util.typ
new file mode 100644
index 0000000..3f2c0d1
--- /dev/null
+++ b/render/packages/preview/cetz/0.3.4/src/draw/util.typ
@@ -0,0 +1,20 @@
+/// Assert that the cetz version of the canvas matches the given version (range).
+///
+/// min (version): Minimum version (current >= min)
+/// max (none, version): First unsupported version (current < max)
+/// hint (string): Name of the function/module this assert is called from
+#let assert-version(min, max: none, hint: "") = {
+ if hint != "" { hint = " by " + hint }
+ (ctx => {
+ /* Default to 2.0.0, as this is the first version that had elements as single functions. */
+ let v = ctx.at("version", default: version(0,2,0))
+ assert(min <= v,
+ message: "CeTZ canvas version is " + str(v) + ", but the minimum required version" + hint + " is " + str(min))
+ if max != none {
+ assert(max > v,
+ message: "CeTZ canvas version is " + str(v) + ", but the maximum supported version" + hint + " is " + str(min))
+ }
+
+ return (ctx: ctx)
+ },)
+}
diff --git a/render/packages/preview/cetz/0.3.4/src/drawable.typ b/render/packages/preview/cetz/0.3.4/src/drawable.typ
new file mode 100644
index 0000000..615bde3
--- /dev/null
+++ b/render/packages/preview/cetz/0.3.4/src/drawable.typ
@@ -0,0 +1,205 @@
+#import "vector.typ"
+#import "util.typ"
+#import "path-util.typ"
+
+/// Applies a transform to drawables. If a single drawable is given it will be returned in a single element <Type>array</Type>.
+/// - transform (matrix): The transformation matrix.
+/// - drawables (drawable): The drawables to transform.
+/// -> drawable
+#let apply-transform(transform, drawables) = {
+ if type(drawables) == dictionary {
+ drawables = (drawables,)
+ }
+ if drawables.len() == 0 {
+ return ()
+ }
+ if transform == none {
+ return drawables
+ }
+ for drawable in drawables {
+ assert(type(drawable) != array,
+ message: "Expected drawable, got array: " + repr(drawable))
+ if drawable.type == "path" {
+ drawable.segments = drawable.segments.map(((kind, ..pts)) => {
+ return (kind,) + util.apply-transform(transform, ..pts)
+ })
+ } else if drawable.type == "content" {
+ drawable.pos = util.apply-transform(transform, drawable.pos)
+ } else {
+ panic()
+ }
+ (drawable,)
+ }
+}
+
+/// Creates a path drawable from path segements.
+/// - segments (array): The segments to create the path from.
+/// - close (bool): If `true` the path will be closed.
+/// - fill (color,none): The color to fill the path with.
+/// - fill-rule (string): One of "even-odd" or "non-zero".
+/// - stroke (stroke): The stroke of the path.
+/// -> drawable
+#let path(close: false, fill: none, stroke: none, fill-rule: "non-zero", segments) = {
+ let segments = segments
+ // Handle case where only one segment has been passed
+ if type(segments.first()) == str {
+ segments = (segments,)
+ }
+
+ segments = path-util.normalize(segments)
+ if close and path-util.segment-end(segments.last()) != path-util.segment-start(segments.first()) {
+ segments.push(path-util.line-segment((
+ path-util.segment-end(segments.last()),
+ path-util.segment-start(segments.first()),
+ )))
+ }
+
+ return (
+ type: "path",
+ close: close,
+ segments: segments,
+ fill: fill,
+ fill-rule: fill-rule,
+ stroke: stroke,
+ hidden: false,
+ bounds: true,
+ )
+}
+
+
+/// Creates a content drawable.
+/// - pos (vector): The position of the drawable.
+/// - width (float): The width of the drawable.
+/// - height (float): The height of the drawable.
+/// - border (segment): A segment to define the border of the drawable with.
+/// - body (content): The content of the drawable.
+/// -> drawable
+#let content(pos, width, height, border, body) = {
+ return (
+ type: "content",
+ pos: pos,
+ width: width,
+ height: height,
+ segments: border,
+ body: body,
+ hidden: false,
+ bounds: true,
+ )
+}
+
+/// Creates a path drawable in the shape of an ellipse.
+/// - x (float): The $x$ position of the ellipse.
+/// - y (float): The $y$ position of the ellipse.
+/// - z (float): The $z$ position of the ellipse.
+/// - rx (float): The radius of the ellipse in the $x$ axis.
+/// - ry (float): The radius of the ellipse in the $y$ axis.
+/// - fill (color,none): The color to fill the ellipse with.
+/// - stroke (stroke): The stroke of the ellipse's path.
+/// -> drawable
+#let ellipse(x, y, z, rx, ry, fill: none, stroke: none) = {
+ let m = 0.551784
+ let mx = m * rx
+ let my = m * ry
+ let left = x - rx
+ let right = x + rx
+ let top = y + ry
+ let bottom = y - ry
+
+ path(
+ (
+ path-util.cubic-segment(
+ (x, top, z),
+ (left, y, z),
+ (x - m * rx, top, z),
+ (left, y + m * ry, z),
+ ),
+ path-util.cubic-segment(
+ (left, y, z),
+ (x, bottom, z),
+ (left, y - m * ry, z),
+ (x - m * rx, bottom, z),
+ ),
+ path-util.cubic-segment(
+ (x, bottom, z),
+ (right, y, z),
+ (x + m * rx, bottom, z),
+ (right, y - m * ry, z),
+ ),
+ path-util.cubic-segment(
+ (right, y, z),
+ (x, top, z),
+ (right, y + m * ry, z),
+ (x + m * rx, top, z)
+ ),
+ ),
+ stroke: stroke,
+ fill: fill,
+ close: true,
+ )
+}
+
+/// Creates a path drawable in the shape of an arc.
+/// - x (float): The $x$ position of the start of the arc.
+/// - y (float): The $y$ position of the start of the arc.
+/// - z (float): The $z$ position of the start of the arc.
+/// - start (angle): The angle along an ellipse to start drawing the arc from.
+/// - stop (angle): The angle along an ellipse to stop drawing the arc at.
+/// - rx (float): The radius of the arc in the $x$ axis.
+/// - ry (float): The radius of the arc in the $y$ axis.
+/// - mode (str): How to draw the arc: `"OPEN"` leaves the path open, `"CLOSED"` closes the arc by drawing a straight line between the end of the arc and its start, `"PIE"` also closes the arc by drawing a line from its end to its origin then to its start.
+/// - fill (color,none): The color to fill the arc with.
+/// - stroke (stroke): The stroke of the arc's path.
+/// -> drawable
+#let arc(x, y, z, start, stop, rx, ry, mode: "OPEN", fill: none, stroke: none) = {
+ let delta = calc.max(-360deg, calc.min(stop - start, 360deg))
+ let num-curves = calc.max(1, calc.min(calc.ceil(calc.abs(delta) / 90deg), 4))
+
+ // Move x/y to the center
+ x -= rx * calc.cos(start)
+ y -= ry * calc.sin(start)
+
+ // Calculation of control points is based on the method described here:
+ // https://pomax.github.io/bezierinfo/#circles_cubic
+ let segments = ()
+ for n in range(0, num-curves) {
+ let start = start + delta / num-curves * n
+ let stop = start + delta / num-curves
+
+ let d = delta / num-curves
+ let k = 4 / 3 * calc.tan(d / 4)
+
+ let sx = x + rx * calc.cos(start)
+ let sy = y + ry * calc.sin(start)
+ let ex = x + rx * calc.cos(stop)
+ let ey = y + ry * calc.sin(stop)
+
+ let s = (sx, sy, z)
+ let c1 = (
+ x + rx * (calc.cos(start) - k * calc.sin(start)),
+ y + ry * (calc.sin(start) + k * calc.cos(start)),
+ z,
+ )
+ let c2 = (
+ x + rx * (calc.cos(stop) + k * calc.sin(stop)),
+ y + ry * (calc.sin(stop) - k * calc.cos(stop)),
+ z,
+ )
+ let e = (ex, ey, z)
+
+ segments.push(path-util.cubic-segment(s, e, c1, c2))
+ }
+
+ if mode == "PIE" and calc.abs(delta) < 360deg {
+ segments.push(path-util.line-segment((
+ path-util.segment-end(segments.last()),
+ (x, y, z),
+ path-util.segment-start(segments.first()))))
+ }
+
+ return path(
+ fill: fill,
+ stroke: stroke,
+ close: mode != "OPEN",
+ segments
+ )
+}
diff --git a/render/packages/preview/cetz/0.3.4/src/hobby.typ b/render/packages/preview/cetz/0.3.4/src/hobby.typ
new file mode 100644
index 0000000..9fa2863
--- /dev/null
+++ b/render/packages/preview/cetz/0.3.4/src/hobby.typ
@@ -0,0 +1,284 @@
+#import "/src/vector.typ"
+#import "/src/complex.typ"
+
+// Implementation by @Enivex
+//
+// Notation comes from https://tug.org/TUGboat/tb34-2/tb107jackowski.pdf
+//
+// points = (P_0, P_1, ... , P_n)
+//
+// ta = (tau_(a,0),tau_(a,1), ... , tau_(a,n-1))
+// ta(i) = tau_(a,i) is the outgoing tension at P_i on the curve from P_i to P_(i+1)
+//
+// tb = (tau_(b,0),tau(b,1), ..., tau_(b,n-1))
+// tb(i) = tau_(b,i) is the incoming tension at P_(i+1) on the curve from P_i to P_(i+1)
+//
+// omega = (omega_0,omega_n)
+// curl at the start and end of curve (size of mock curvature relative to nearest point)
+//
+// v(i) = P_(i+1) - P_i
+// vector pointing from point i to point i + 1 (direction of ith chord)
+//
+// d(i) = |v(i)|
+// length of the ith chord
+//
+// gamma(i) = signed angle from v(i - 1) to v(i) (change in angle at P_i)
+// Note: gamma(0) = gamma(n) = 0
+//
+// ca(i) = first control point on chord i
+// cb(i) = second control point on chord i
+//
+// alpha(i) = signed angle from v(i) to ca(i) - P(i)
+// beta(i) = signed angle from P(i + 1) - cb(i) to v(i)
+
+// Solve tridiagonal system
+//
+// - a,b,c,d have the same length, n + 1
+// - a(0) and c(n) are not used
+//
+// Solves Ax=d
+// where A=
+// [ b_0 c_0
+// a_1 b_1 c_1
+// ......
+// a_(n-1) b_(n-1) c_(n-1)
+// a_n b_n ]
+#let thomas(a, b, c, d) = {
+ let n = a.len() - 1
+
+ for i in range(1,n + 1) {
+ let w = a.at(i) / b.at(i - 1)
+ b.at(i) = b.at(i) - w*c.at(i - 1)
+ d.at(i) = d.at(i) - w*d.at(i - 1)
+ }
+
+ let x = (0,)*(n + 1)
+ x.last() = d.last() / b.last()
+ for i in range(n - 1, -1 , step: -1) {
+ x.at(i) = (d.at(i) - c.at(i)*x.at(i + 1)) / b.at(i)
+ }
+ return x
+}
+
+// Solve cyclic tridiagonal system
+//
+// - a,b,c,d have the same length, n+1
+//
+// Solves Ax=d
+// where A=
+// [ b_0 c_0 a_0
+// a_1 b_1 c_1
+// ......
+// a_(n-1) b_(n-1) c_(n-1)
+// c_n a_n b_n ]
+#let thomas-cyclic(a, b, c, d) = {
+ let n = a.len() - 1
+
+ let u = (a.first(),) + (0,)*(n - 1) + (c.last(),)
+ let v = (1,) + (0,)*(n - 1) + (1,)
+
+ let bp = array.zip(b,u).map(((s,t)) => s - t)
+ let y = thomas(a, bp, c, d)
+ let z = thomas(a, bp, c, u)
+
+ // Sherman-Morrison formula
+ return vector.sub(y, vector.scale(z, vector.dot(v,y) / (1 + vector.dot(v, z))))
+}
+
+/// Calculates a bezier spline for an open Hobby curve through a list of points. Returns an {{array}} of {{bezier}}s
+///
+/// - points (array): List of points
+/// - ta (auto,array): Outgoing tension per point
+/// - tb (auto,array): Incoming tension per point
+/// - rho (auto,function): The rho function of the form `(float, float) => float`
+/// - omega (auto,array): Tuple of the curl at the start end end of the curve `(start, end)` as floats
+///
+/// -> array
+#let hobby-to-cubic-open(points, ta: auto, tb: auto, rho: auto, omega: auto) = {
+ let n = points.len() - 1
+
+ if ta == auto {
+ ta = (1,)*n
+ } else {
+ assert.eq(type(ta), array, message: "ta must be an array")
+ assert.eq(ta.len(), n, message: "ta must have length n for n + 1 points")
+ assert(ta.all(x => x > 0), message: "ta must contain only positive numbers")
+ }
+ if tb == auto {
+ tb = (1,)*n
+ } else {
+ assert.eq(type(tb), array, message: "tb must be an array")
+ assert.eq(tb.len(), n, message: "tb must have length n for n + 1 points")
+ assert(tb.all(x => x > 0), message: "tb must contain only positive numbers")
+ }
+ if rho == auto {
+ rho = (a,b) => {
+ (2 + calc.sqrt(2)*(calc.sin(a) - calc.sin(b)/16)*(calc.sin(b)-calc.sin(a)/16)*(calc.cos(a)-calc.cos(b)))/(1 + calc.cos(a)*(calc.sqrt(5)-1)/2 + calc.cos(b)*(3-calc.sqrt(5))/2)
+ }
+ } else {
+ assert.eq(type(rho), function,
+ message: "rho must be a function")
+ }
+
+ let v = range(n).map(i => complex.sub(points.at(i + 1),points.at(i)))
+ let d = v.map(complex.norm)
+
+ let gamma = (0,) + range(n - 1).map(i => complex.ang(v.at(i),v.at(i + 1))) + (0,)
+
+ let ita = ta.map(x => 1/x)
+ let itasq = ita.map(x => x*x)
+
+ let itb = tb.map(x => 1/x)
+ let itbsq = itb.map(x => x*x)
+
+ let (omega0, omegan) = omega
+
+ let A = (0,) * (n + 1); let B = A; let C = A; let D = A; let E = A
+
+ C.at(0) = omega0 * ita.at(0) * itasq.at(0) / itbsq.at(0) + 3 - itb.at(0)
+ D.at(0) = omega0 * itasq.at(0) / itbsq.at(0) * (3 - ita.at(0)) + itb.at(0)
+ E.at(0) = - D.at(0) * gamma.at(1)
+
+ for i in range(1, n) {
+ A.at(i) = ita.at(i - 1) / (d.at(i - 1) * itbsq.at(i - 1))
+ B.at(i) = (3 - ita.at(i - 1))/(d.at(i - 1) * itbsq.at(i - 1))
+ C.at(i) = (3 - itb.at(i))/(d.at(i) * itasq.at(i))
+ D.at(i) = itb.at(i) / (d.at(i) * itasq.at(i))
+ E.at(i) = - B.at(i) * gamma.at(i) - D.at(i) * gamma.at(i + 1)
+ }
+
+ A.at(n) = omegan * itbsq.at(n - 1) / itasq.at(n - 1) * ( 3 - itb.at(n - 1)) + ita.at(n - 1)
+ B.at(n) = omegan * itb.at(n - 1) * itbsq.at(n - 1) / itasq.at(n - 1) + 3 - ita.at(n - 1)
+
+ let alpha = thomas(A,vector.add(B,C), D, E)
+ let beta = vector.scale(vector.add(alpha,gamma).slice(1), -1)
+
+ let ca = (0,)*n; let cb = ca
+ for i in range(n) {
+ let a = rho(alpha.at(i),beta.at(i)) * d.at(i) / 3
+ let b = rho(beta.at(i),alpha.at(i)) * d.at(i) / 3
+ ca.at(i) = complex.add(points.at(i), complex.scale(complex.unit(complex.rot(v.at(i),alpha.at(i))), a))
+ cb.at(i) = complex.sub(points.at(i + 1), complex.scale(complex.unit(complex.rot(v.at(i),-beta.at(i))), b))
+ }
+ return range(n).map(i => (points.at(i), points.at(i+1), ca.at(i), cb.at(i)))
+}
+
+/// Calculates a bezier spline for a closed Hobby curve through a list of points. Returns an {{array}} of {{bezier}}s.
+///
+/// - points (array): List of points
+/// - ta (auto,array): Outgoing tension per point
+/// - tb (auto,array): Incoming tension per point
+/// - rho (auto,array): The rho function of the form `(float, b) => float`
+///
+/// -> array
+#let hobby-to-cubic-closed(points, ta: auto, tb: auto, rho: auto) = {
+ if points.first() != points.last() {
+ points.push(points.first())
+ }
+
+ let n = points.len() - 1
+ points.push(points.at(1))
+
+ if ta == auto {
+ ta = (1,)*n
+ } else {
+ assert.eq(type(ta), array, message: "ta must be an array")
+ assert.eq(ta.len(), n, message: "ta must have length n for n + 1 points")
+ assert(ta.all(x => x > 0), message: "ta must contain only positive numbers")
+ }
+ if tb == auto {
+ tb = (1,)*n
+ } else {
+ assert.eq(type(tb), array, message: "tb must be an array")
+ assert.eq(tb.len(), n, message: "tb must have length n for n + 1 points")
+ assert(tb.all(x => x > 0), message: "tb must contain only positive numbers")
+ }
+ if rho == auto {
+ rho = (a,b) => {
+ (2 + calc.sqrt(2)*(calc.sin(a) - calc.sin(b)/16)*(calc.sin(b)-calc.sin(a)/16)*(calc.cos(a)-calc.cos(b)))/(1 + calc.cos(a)*(calc.sqrt(5)-1)/2 + calc.cos(b)*(3-calc.sqrt(5))/2)
+ }
+ } else {
+ assert.eq(type(rho), function,
+ message: "rho must be a function")
+ }
+
+ let v = range(n + 1).map(i => complex.sub(points.at(i + 1),points.at(i)))
+ let d = v.map(complex.norm)
+
+ let gamma = range(n).map(i => complex.ang(v.at(i),v.at(i + 1)))
+ gamma = (gamma.last(),..gamma)
+
+ let ita = ta.map(x => 1/x)
+ let itasq = ita.map(x => x*x)
+
+ let itb = tb.map(x => 1/x)
+ let itbsq = itb.map(x => x*x)
+
+ let A = (0,) * n; let B = A; let C = A; let D = A; let E = A
+
+ A.at(0) = ita.at(n - 1) / (d.at(n - 1) * itbsq.at(n - 1))
+ B.at(0) = (3 - ita.at(n - 1))/(d.at(n - 1) * itbsq.at(n - 1))
+ C.at(0) = (3 - itb.at(0))/(d.at(0) * itasq.at(0))
+ D.at(0) = itb.at(0) / (d.at(0) * itasq.at(0))
+ E.at(0) = - B.at(0) * gamma.at(0) - D.at(0) * gamma.at(1)
+
+ for i in range(1, n) {
+ A.at(i) = ita.at(i - 1) / (d.at(i - 1) * itbsq.at(i - 1))
+ B.at(i) = (3 - ita.at(i - 1))/(d.at(i - 1) * itbsq.at(i - 1))
+ C.at(i) = (3 - itb.at(i))/(d.at(i) * itasq.at(i))
+ D.at(i) = itb.at(i) / (d.at(i) * itasq.at(i))
+ E.at(i) = - B.at(i) * gamma.at(i) - D.at(i) * gamma.at(i + 1)
+ }
+
+ let alpha = thomas-cyclic(A,vector.add(B,C), D, E)
+ alpha.push(alpha.at(0))
+ let beta = vector.scale(vector.add(alpha,gamma), -1)
+ beta = (..beta.slice(1),beta.at(0))
+
+ let ca = (0,) * n; let cb = ca
+ for i in range(n) {
+ let a = rho(alpha.at(i),beta.at(i)) * d.at(i) / 3
+ let b = rho(beta.at(i),alpha.at(i)) * d.at(i) / 3
+ ca.at(i) = complex.add(points.at(i), complex.scale(complex.unit(complex.rot(v.at(i),alpha.at(i))), a))
+ cb.at(i) = complex.sub(points.at(i + 1), complex.scale(complex.unit(complex.rot(v.at(i),-beta.at(i))), b))
+ }
+
+ return range(n).map(i => (points.at(i), points.at(i+1), ca.at(i), cb.at(i)))
+}
+
+/// Calculates a bezier spline for a Hobby curve through a list of points. Returns an {{array}} of {{bezier}}s.
+///
+/// - points (array): List of points
+/// - ta (auto,array): Outgoing tension per point
+/// - tb (auto,array): Incoming tension per point
+/// - rho (auto,array): The rho function of the form `(float, float) => float`
+/// - omega (auto,array): Tuple of the curl at the start end end of the curve `(start, end)` as floats
+/// - close (bool): Close the curve
+///
+/// -> array
+#let hobby-to-cubic(points, ta: auto, tb: auto, rho: auto, omega: auto, close: false) = {
+ let omega = if omega == auto {
+ (1, 1)
+ } else if type(omega) == array {
+ omega
+ } else {
+ (omega, omega)
+ }
+ assert.eq(type(omega), array,
+ message: "Omega must be of type array")
+ assert.eq(omega.len(), 2,
+ message: "Omega must be of length 2")
+ assert(omega.all(x => x >= 0),
+ message: "Omega must contain positive values only")
+
+ if not close and points.len() == 2 {
+ let (a, b) = points
+ return ((a, b, a, b),)
+ }
+
+ return if close {
+ hobby-to-cubic-closed(points, ta: ta, tb: tb, rho: rho)
+ } else {
+ hobby-to-cubic-open(points, ta: ta, tb: tb, rho: rho, omega: omega)
+ }
+}
diff --git a/render/packages/preview/cetz/0.3.4/src/intersection.typ b/render/packages/preview/cetz/0.3.4/src/intersection.typ
new file mode 100644
index 0000000..ff79ed0
--- /dev/null
+++ b/render/packages/preview/cetz/0.3.4/src/intersection.typ
@@ -0,0 +1,125 @@
+#import "vector.typ"
+#import "util.typ"
+
+/// Checks for a line-line intersection between the given points and returns its position, otherwise {{none}}.
+///
+/// - a (vector): Line 1 point 1
+/// - b (vector): Line 1 point 2
+/// - c (vector): Line 2 point 1
+/// - d (vector): Line 2 point 2
+/// - ray (bool): When `true`, intersections will be found for the whole line instead of inbetween the given points.
+/// -> vector,none
+#let line-line(a, b, c, d, ray: false) = {
+ let lli8(x1, y1, x2, y2, x3, y3, x4, y4) = {
+ let nx = (x1*y2 - y1*x2)*(x3 - x4)-(x1 - x2)*(x3*y4 - y3*x4)
+ let ny = (x1*y2 - y1*x2)*(y3 - y4)-(y1 - y2)*(x3*y4 - y3*x4)
+ let d = (x1 - x2)*(y3 - y4)-(y1 - y2)*(x3 - x4)
+ if d == 0 {
+ return none
+ }
+ return (nx / d, ny / d, 0)
+ }
+ let pt = lli8(a.at(0), a.at(1), b.at(0), b.at(1),
+ c.at(0), c.at(1), d.at(0), d.at(1))
+ if pt != none {
+ let on-line(pt, a, b) = {
+ let (x, y, ..) = pt
+ let epsilon = util.float-epsilon
+ let mx = calc.min(a.at(0), b.at(0)) - epsilon
+ let my = calc.min(a.at(1), b.at(1)) - epsilon
+ let Mx = calc.max(a.at(0), b.at(0)) + epsilon
+ let My = calc.max(a.at(1), b.at(1)) + epsilon
+ return mx <= x and Mx >= x and my <= y and My >= y
+ }
+ if ray or (on-line(pt, a, b) and on-line(pt, c, d)) {
+ return pt
+ }
+ }
+}
+
+/// Finds the intersections of a line and cubic bezier.
+///
+/// - s (vector): Bezier start point
+/// - e (vector): Bezier end point
+/// - c1 (vector): Bezier control point 1
+/// - c2 (vector): Bezier control point 2
+/// - la (vector): Line start point
+/// - lb (vector): Line end point
+/// - ray (bool): When `true`, intersections will be found for the whole line instead of inbetween the given points.
+/// -> array
+#let line-cubic(la, lb, s, e, c1, c2) = {
+ import "/src/bezier.typ": line-cubic-intersections as line-cubic
+ return line-cubic(la, lb, s, e, c1, c2)
+}
+
+/// Finds the intersections of a line and linestrip.
+/// - la (vector): Line start point.
+/// - lb (vector): Line end point.
+/// - v (array): An {{array}} of {{vector}}s that define each point on the linestrip.
+/// -> array
+#let line-linestrip(la, lb, v) = {
+ let pts = ()
+ for i in range(0, v.len() - 1) {
+ let pt = line-line(la, lb, v.at(i), v.at(i + 1))
+ if pt != none {
+ pts.push(pt)
+ }
+ }
+ return pts
+}
+
+/// Finds the intersections of a line and path in 2D. The path should be given as a {{drawable}} of type `path`.
+///
+/// - la (vector): Line start
+/// - lb (vector): Line end
+/// - path (drawable): The path.
+/// -> array
+#let line-path(la, lb, path) = {
+ let segment(s) = {
+ let (k, ..v) = s
+ if k == "line" {
+ return line-linestrip(la, lb, v)
+ } else if k == "cubic" {
+ return line-cubic(la, lb, ..v)
+ } else {
+ return ()
+ }
+ }
+
+ let pts = ()
+ for s in path.at("segments", default: ()) {
+ pts += segment(s)
+ }
+ return pts
+}
+
+/// Finds the intersections between two path {{drawable}}s in 2D.
+///
+/// - a (path): Path a
+/// - b (path): Path b
+/// - samples (int): Number of samples to use for bezier curves
+/// -> array
+#let path-path(a, b, samples: 8) = {
+ import "bezier.typ": cubic-point
+
+ // Convert segment to vertices by sampling curves
+ let linearize-segment(s) = {
+ let t = s.at(0)
+ if t == "line" {
+ return s.slice(1)
+ } else if t == "cubic" {
+ return range(samples + 1).map(
+ t => cubic-point(..s.slice(1), t/samples)
+ )
+ }
+ }
+
+ let pts = ()
+ for s in a.at("segments", default: ()) {
+ let sv = linearize-segment(s)
+ for ai in range(0, sv.len() - 1) {
+ pts += line-path(sv.at(ai), sv.at(ai + 1), b)
+ }
+ }
+ return pts
+}
diff --git a/render/packages/preview/cetz/0.3.4/src/lib.typ b/render/packages/preview/cetz/0.3.4/src/lib.typ
new file mode 100644
index 0000000..7bd9072
--- /dev/null
+++ b/render/packages/preview/cetz/0.3.4/src/lib.typ
@@ -0,0 +1,24 @@
+#import "version.typ": version
+
+#import "canvas.typ": canvas
+#import "draw.typ"
+
+// Expose utilities
+#import "vector.typ"
+#import "matrix.typ"
+#import "styles.typ"
+#import "coordinate.typ"
+#import "intersection.typ"
+#import "drawable.typ"
+#import "process.typ"
+#import "util.typ"
+#import "path-util.typ"
+#import "mark.typ"
+#import "mark-shapes.typ"
+#import "sorting.typ"
+
+// Libraries
+#import "lib/palette.typ"
+#import "lib/angle.typ"
+#import "lib/tree.typ"
+#import "lib/decorations.typ"
diff --git a/render/packages/preview/cetz/0.3.4/src/lib/angle.typ b/render/packages/preview/cetz/0.3.4/src/lib/angle.typ
new file mode 100644
index 0000000..00da0b3
--- /dev/null
+++ b/render/packages/preview/cetz/0.3.4/src/lib/angle.typ
@@ -0,0 +1,207 @@
+#import "/src/drawable.typ"
+#import "/src/styles.typ"
+#import "/src/vector.typ"
+#import "/src/util.typ"
+#import "/src/coordinate.typ"
+#import "/src/anchor.typ" as anchor_
+#import "/src/draw.typ"
+
+// Angle default-style
+#let default-style = (
+ fill: none,
+ stroke: auto,
+ radius: .5,
+ label-radius: 50%,
+ mark: auto,
+)
+
+/// Draw an angle counter-clock-wise between `a` and `b` through origin `origin`
+///
+/// ```typc example
+/// line((0,0), (1,1.5), name: "a")
+/// line((0,0), (2,-1), name: "b")
+///
+/// // Draw an angle between the two lines
+/// cetz.angle.angle("a.start", "a.end", "b.end", label: $ alpha $,
+/// mark: (end: ">"), radius: 1.5)
+/// cetz.angle.angle("a.start", "b.end", "a.end", label: $ alpha' $,
+/// radius: 50%, direction: "cw")
+/// ```
+///
+/// - origin (coordinate): Angle origin
+/// - a (coordinate): Coordinate of side `a`, containing an angle between `origin` and `b`.
+/// - b (coordinate): Coordinate of side `b`, containing an angle between `origin` and `a`.
+/// - direction (string): Direction of the angle. Accepts "cw" (clockwise) and "ccw" (counter-clockwise), the latter being the default.
+/// - label (none,content,function): Draw a label at the angles "label" anchor. If label is a function, it gets the angle value passed as argument. The function must be of the format `angle => content`.
+/// - name (none,str): Element name, used for querying anchors.
+/// - ..style (style): Style key-value pairs.
+///
+/// ## Styling
+/// *Root:* `angle` \
+///
+/// - radius (number) = 0.5: The radius of the angles arc. If of type `ratio`, it is relative to the smaller distance of either origin to a or origin to b.
+/// - label-radius (number, ratio) = 50%: The radius of the angles label origin. If of type `ratio`, it is relative to `radius`.
+///
+/// ## Anchors
+/// - **a** Point a
+/// - **b** Point b
+/// - **origin** Origin
+/// - **label** Label center
+/// - **start** Arc start
+/// - **end** Arc end
+#let angle(
+ origin,
+ a,
+ b,
+ direction: "ccw",
+ label: none,
+ name: none,
+ ..style
+) = draw.group(name: name, ctx => {
+ let style = styles.resolve(ctx.style, merge: style.named(), base: default-style, root: "angle")
+ let radius = util.resolve-number(ctx, style.radius)
+ let label-radius = util.resolve-number(ctx, style.label-radius)
+
+ let (ctx, origin) = coordinate.resolve(ctx, origin)
+ let (ctx, a, b) = coordinate.resolve(ctx, a, b, update: false)
+
+ assert(origin.at(2) == a.at(2) and a.at(2) == b.at(2),
+ message: "Angle z coordinates of all three points must be equal")
+
+ assert(direction in ("cw", "ccw"),
+ message: "Invalid angle direction " + repr(direction))
+
+ let (start, delta, ccw) = {
+ let ccw = direction == "ccw"
+
+ let s = vector.angle2(origin, a)
+ if s < 0deg { s += 360deg }
+
+ let e = vector.angle2(origin, b)
+ if e < 0deg { e += 360deg }
+
+ if e < s {
+ e += 360deg
+ }
+
+ if ccw {
+ (s, (e - s), ccw)
+ } else {
+ (s, -(360deg - (e - s)), ccw)
+ }
+ }
+
+ let mid = start + delta / 2
+
+ // Radius can be relative to the min-distance between origin-a and origin-b
+ if type(radius) == ratio {
+ radius = radius * calc.min(vector.dist(origin, a), vector.dist(origin, b)) / 100%
+ }
+
+ // Label radius can be relative to radius
+ if type(label-radius) == ratio {
+ label-radius = label-radius * radius / 100%
+ }
+
+ let label-pt = vector.add(origin, (calc.cos(mid) * label-radius, calc.sin(mid) * label-radius, 0))
+ let start-pt = vector.add(origin, (calc.cos(start) * radius, calc.sin(start) * radius, 0))
+ let end-pt = vector.add(origin, (calc.cos(start + delta) * radius, calc.sin(start + delta) * radius, 0))
+ draw.anchor("origin", origin)
+ draw.anchor("label", label-pt)
+ draw.anchor("start", start-pt)
+ draw.anchor("end", end-pt)
+ draw.anchor("a", a)
+ draw.anchor("b", b)
+
+ if delta != 0deg {
+ if style.fill != none {
+ draw.arc(origin, start: start, delta: delta, anchor: "origin",
+ name: "arc", ..style, radius: radius, mode: "PIE", mark: none, stroke: none)
+ }
+ if style.stroke != none {
+ draw.arc(origin, start: start, delta: delta, anchor: "origin",
+ name: "arc", ..style, radius: radius, fill: none)
+ }
+ }
+
+ let label = if type(label) == function { label(calc.abs(delta)) } else { label }
+ if label != none {
+ draw.content(label-pt, label)
+ }
+})
+
+/// Draw a right angle between `a` and `b` through origin `origin`
+///
+/// ```typc example
+/// line((0,0), (1,2), name: "a")
+/// line((0,0), (2,-1), name: "b")
+///
+/// // Draw an angle between the two lines
+/// cetz.angle.right-angle(
+/// "a.start",
+/// "a.end",
+/// "b.end",
+/// radius: 1.5
+/// )
+/// ```
+///
+/// - origin (coordinate): Angle origin
+/// - a (coordinate): Coordinate of side `a`, containing an angle between `origin` and `b`.
+/// - b (coordinate): Coordinate of side `b`, containing an angle between `origin` and `a`.
+/// - label (none,content): Draw a label at the angles "label" anchor.
+/// - name (none,str): Element name, used for querying anchors.
+/// - ..style (style): Style key-value pairs.
+///
+/// ## Styling
+/// Styling is the same as the `angle` function.
+///
+/// ## Anchors
+/// Anchors are the same as the `angle` function
+///
+#let right-angle(
+ origin,
+ a,
+ b,
+ label: "•",
+ name: none,
+ ..style
+) = draw.group(name: name, ctx => {
+ let style = styles.resolve(ctx.style, merge: style.named(), base: default-style, root: "angle")
+ let (ctx, origin) = coordinate.resolve(ctx, origin)
+ let (ctx, a, b) = coordinate.resolve(ctx, a, b, update: false)
+ let vo = origin; let va = a; let vb = b
+
+ // Radius can be relative to the min-distance between origin-a and origin-b
+ if type(style.radius) == ratio {
+ style.radius = style.radius * calc.min(vector.dist(vo, va), vector.dist(vo, vb)) / 100%
+ }
+ let (r, _) = util.resolve-radius(style.radius).map(util.resolve-number.with(ctx))
+
+ let va = vector.add(vo, vector.scale(vector.norm(vector.sub(va, vo)), r))
+ let vb = vector.add(vo, vector.scale(vector.norm(vector.sub(vb, vo)), r))
+ let angle-b = vector.angle2(vo, vb)
+ let vm = vector.add(va, (calc.cos(angle-b) * r, calc.sin(angle-b) * r, 0))
+
+ // Label radius can be relative to the distance between origin and the
+ // angle corner
+ if type(style.label-radius) == ratio {
+ style.label-radius = style.label-radius * vector.dist(vm, vo) / 100%
+ }
+ let (ra, _) = util.resolve-radius(style.label-radius).map(util.resolve-number.with(ctx))
+
+ if style.fill != none {
+ draw.line(vo, va, vm, vb, close: true, stroke: none, fill: style.fill)
+ }
+ draw.line(va, vm, vb, ..style, fill: none)
+
+ let label-pt = vector.add(vo, vector.scale(vector.norm(vector.sub(vm, vo)), ra))
+ if label != none {
+ draw.content(label-pt, label)
+ }
+
+ draw.anchor("a", a)
+ draw.anchor("b", b)
+ draw.anchor("origin", origin)
+ draw.anchor("corner", vm)
+ draw.anchor("label", label-pt)
+})
diff --git a/render/packages/preview/cetz/0.3.4/src/lib/decorations.typ b/render/packages/preview/cetz/0.3.4/src/lib/decorations.typ
new file mode 100644
index 0000000..f91786c
--- /dev/null
+++ b/render/packages/preview/cetz/0.3.4/src/lib/decorations.typ
@@ -0,0 +1,2 @@
+#import "decorations/brace.typ": brace, brace-default-style, flat-brace, flat-brace-default-style
+#import "decorations/path.typ": zigzag, wave, coil, square
diff --git a/render/packages/preview/cetz/0.3.4/src/lib/decorations/brace.typ b/render/packages/preview/cetz/0.3.4/src/lib/decorations/brace.typ
new file mode 100644
index 0000000..6829a95
--- /dev/null
+++ b/render/packages/preview/cetz/0.3.4/src/lib/decorations/brace.typ
@@ -0,0 +1,353 @@
+#import "/src/vector.typ"
+#import "/src/matrix.typ"
+#import "/src/util.typ"
+#import "/src/draw.typ": *
+#import "/src/coordinate.typ"
+#import "/src/styles.typ"
+
+// Rotates the vector 'ab' around 'a' and scales it to 'len', returns the absolute point 'c'.
+#let _rotate-around(a, b, angle: 90deg, len: auto) = {
+ let rel = vector.sub(b, a)
+ let rotated = util.apply-transform(matrix.transform-rotate-z(angle), rel)
+ let scaled = if len == auto {
+ rotated
+ } else {
+ vector.scale(vector.norm(rotated), len)
+ }
+ return vector.add(a, scaled)
+}
+
+#let brace-default-style = (
+ amplitude: .5,
+ pointiness: 15deg,
+ outer-pointiness: 0deg,
+ content-offset: .3,
+ flip: false,
+ stroke: auto,
+ fill: none,
+)
+
+/// Draw a curly brace between two points.
+///
+/// ```typc example
+/// cetz.decorations.brace((0,1),(2,1))
+///
+/// cetz.decorations.brace((0,0),(2,0),
+/// pointiness: 45deg, outer-pointiness: 45deg)
+/// cetz.decorations.brace((0,-1),(2,-1),
+/// pointiness: 90deg, outer-pointiness: 90deg)
+/// ```
+///
+/// - start (coordinate): Start point
+/// - end (coordinate): End point
+/// - name (string, none): Element name used for querying anchors
+/// - ..style (style): Style key-value pairs
+///
+/// ## Styling
+///
+/// *Root:* `brace`
+/// - amplitude (number) = 0.5: Sets the height of the brace, from its baseline to its middle tip.
+/// - pointiness (ratio, angle) = 15deg: How pointy the spike should be. `0deg` or `100%` for maximum pointiness, `90deg` or `0%` for minimum.
+/// - outer-pointiness (ratio, angle) = 15deg: How pointy the outer edges should be. `0deg` or `100%` for maximum pointiness (allowing for a smooth transition to a straight line), `90deg` or `0%` for minimum. Setting this to <Type>auto</Type> will use the value set for `pointiness`.
+/// - content-offset (number) = 0.3: Offset of the `"content"` anchor from the spike of the brace.
+/// - flip (bool) = false: Mirror the brace along the line between start and end.
+///
+/// ## Anchors
+/// - **start** Where the brace starts, same as the `start` parameter.
+/// - **end** Where the brace end, same as the `end` parameter.
+/// - **spike** Point of the spike, halfway between `start` and `end` and shifted by `amplitude` towards the pointing direction.
+/// - **content** Point to place content/text at, in front of the spike.
+/// - **center** Center of the enclosing rectangle.
+#let brace(start, end, ..style, name: none) = {
+ assert.eq(style.pos().len(), 0,
+ message: "Brace takes no additional positional arugments.")
+
+ // Validate coordinates
+ let _ = (start, end).map(coordinate.resolve-system)
+
+ group(name: name, ctx => {
+ // Resolve all coordinates
+ let (ctx, start, end) = coordinate.resolve(ctx, start, end)
+
+ // Query and resolve style
+ let style = styles.resolve(ctx.style, root: "brace", base: brace-default-style, merge: style.named())
+
+ let amplitude = util.resolve-number(ctx, style.amplitude)
+ let content-offset = util.resolve-number(ctx, style.content-offset)
+ let pointiness = if type(style.pointiness) == ratio {
+ (1 - style.pointiness / 100%) * 90deg
+ } else { style.pointiness }
+ pointiness = calc.max(0deg, calc.min(pointiness, 90deg))
+
+ let outer-pointiness = if type(style.outer-pointiness) == ratio {
+ (1 - style.outer-pointiness / 100%) * 90deg
+ } else { style.outer-pointiness }
+ outer-pointiness = calc.max(0deg, calc.min(outer-pointiness, 90deg)) * -1
+
+ let up = (0, 0, -1)
+ let mid = vector.lerp(start, end, .5)
+
+ let dir = vector.norm(vector.sub(end, start))
+ let normal = vector.cross(dir, up)
+ if style.flip {
+ normal = vector.scale(normal, -1)
+ pointiness *= -1
+ outer-pointiness *= -1
+ }
+
+ // Compute tip coordinate
+ let tip = vector.add(mid, vector.scale(normal, calc.abs(amplitude)))
+
+ // Measure distance between midpoint on start-end and tip
+ let amplitude = vector.dist(mid, tip)
+
+ // Add anchors
+ anchor("start", start)
+ anchor("end", end)
+ anchor("default", mid)
+ anchor("spike", tip)
+
+ // Offset content anchor
+ anchor("content", vector.add(tip, vector.scale(normal, content-offset)))
+
+ merge-path({
+ let scale-amplitude(v) = {
+ let max = vector.dist(start, end) / 2
+ vector.scale(v, calc.min(amplitude, max))
+ }
+
+ let rotate-inner(factor) = {
+ vector.rotate-z(normal, pointiness * factor)
+ }
+
+ let rotate-outer(factor) = {
+ vector.rotate-z(normal, outer-pointiness * factor)
+ }
+
+ let dist = vector.dist(start, tip) + vector.dist(tip, end)
+ let ratio = vector.dist(start, tip) / dist
+ let b = vector.dist(end, tip) / dist
+
+ bezier(start, tip,
+ vector.add(start, scale-amplitude(rotate-outer(+1))),
+ vector.sub(tip, scale-amplitude(rotate-inner(-1))))
+ bezier(tip, end,
+ vector.sub(tip, scale-amplitude(rotate-inner(+1))),
+ vector.add(end, scale-amplitude(rotate-outer(-1))))
+ }, stroke: style.stroke, fill: style.fill)
+
+ move-to(end)
+ })
+}
+
+
+#let flat-brace-default-style = (
+ stroke: auto,
+ fill: none,
+ amplitude: .3,
+ aspect: 50%,
+ curves: (1, .5, .6, .15),
+ outer-curves: auto,
+ content-offset: .3,
+ debug-text-size: 6pt,
+)
+
+/// Draw a flat curly brace between two points.
+///
+/// ```typc example
+/// cetz.decorations.flat-brace((0,1),(2,1))
+///
+/// cetz.decorations.flat-brace((0,0),(2,0),
+/// curves: .2,
+/// aspect: 25%)
+/// cetz.decorations.flat-brace((0,-1),(2,-1),
+/// outer-curves: 0,
+/// aspect: 75%)
+/// ```
+///
+/// This mimics the braces from TikZ's [`decorations.pathreplacing` library](https://github.com/pgf-tikz/pgf/blob/6e5fd71581ab04351a89553a259b57988bc28140/tex/generic/pgf/libraries/decorations/pgflibrarydecorations.pathreplacing.code.tex#L136-L185).
+/// In contrast to the `brace` function, these braces use straight line segments, resulting in better looks for long braces with a small amplitude.
+///
+/// - start (coordinate): Start point
+/// - end (coordinate): End point
+/// - flip (bool): Flip the brace around
+/// - name (str, none): Element name for querying anchors
+/// - debug (bool):
+/// - ..style (style): Style key-value pairs
+///
+/// ## Styling
+///
+/// *Root:* `flat-brace`
+/// - amplitude (number) = 0.3: Determines how much the brace rises above the base line.
+/// - aspect (ratio) = 50% Determines the fraction of the total length where the spike will be placed.
+/// - curves (number, auto, array) = auto: Curviness factor of the brace, a factor of 0 means no curves.
+/// - outer-curves (number, auto, array) = auto: Curviness factor of the outer curves of the brace. A factor of 0 means no curves.
+///
+/// ## Anchors
+/// - **start** Where the brace starts, same as the `start` parameter.
+/// - **end** Where the brace end, same as the `end` parameter.
+/// - **spike** Point of the spike's top.
+/// - **content** Point to place content/text at, in front of the spike.
+/// - **center** Center of the enclosing rectangle.
+#let flat-brace(
+ start,
+ end,
+ flip: false,
+ debug: false,
+ name: none,
+ ..style,
+) = {
+ // Validate coordinates
+ let _ = (start, end).map(coordinate.resolve-system)
+
+ group(name: name, ctx => {
+ // Get styles and validate their types and values
+ let style = styles.resolve(ctx.style, merge: style.named(),
+ root: "flat-brace", base: flat-brace-default-style)
+
+ let amplitude = style.amplitude
+ assert(
+ type(amplitude) in (int, float),
+ message: "amplitude must be a number, got " + repr(amplitude),
+ )
+
+ let aspect = style.aspect
+ assert(
+ (type(aspect) == ratio
+ and aspect >= 0% and aspect <= 100%)
+ or (type(aspect) in (int, float)
+ and aspect >= 0 and aspect <= 1),
+ message: "aspect must be a ratio between 0% and 100%, got " + repr(aspect),
+ )
+ if type(aspect) == ratio { aspect /= 100% }
+
+ let inner-curves = style.curves
+ assert(
+ type(inner-curves) in (int, float)
+ or type(inner-curves) == array
+ and inner-curves.all(v => type(v) in (int, float, type(auto))),
+ message: "curves must be a number, or an array of numbers or auto, got " + repr(inner-curves),
+ )
+ if type(inner-curves) in (int, float) { inner-curves = (inner-curves,) }
+ while inner-curves.len() < flat-brace-default-style.curves.len() {
+ inner-curves.push(auto)
+ }
+ inner-curves = inner-curves.enumerate().map(((idx, v)) => if v == auto {
+ flat-brace-default-style.curves.at(idx)
+ } else { v })
+
+ let outer-curves = style.outer-curves
+ assert(
+ type(outer-curves) in (int, float, type(auto))
+ or type(outer-curves) == array
+ and outer-curves.all(v => type(v) in (int, float, type(auto))),
+ message: "outer-curves must be auto, a number, or an array of numbers or auto, got " + repr(outer-curves),
+ )
+ if outer-curves == auto {
+ outer-curves = inner-curves
+ } else {
+ if type(outer-curves) in (int, float) { outer-curves = (outer-curves,) }
+ while outer-curves.len() < inner-curves.len() { outer-curves.push(auto) }
+ outer-curves = outer-curves.enumerate()
+ .map(((idx, v)) => if v == auto { inner-curves.at(idx) } else { v })
+ }
+
+ let content-offset = style.content-offset
+ assert(
+ type(content-offset) in (int, float),
+ message: "content-offset must be a number, got " + repr(content-offset),
+ )
+
+ // all the following code assumes the brace to start at (0, 0), growing to the right,
+ // pointing upwards, so we set the origin and rotate the entire group accordingly
+ let (_, start, end) = coordinate.resolve(ctx, start, end)
+ set-origin(start)
+ rotate(vector.angle2(start, end))
+
+ // we achieve flipping by inverting the amplitude
+ if flip {
+ amplitude *= -1
+ content-offset *= -1
+ }
+
+ let length = vector.dist(start, end)
+ let middle = aspect * length
+ let horizon = amplitude / 2
+
+ let normal-outer = calc.abs(amplitude * outer-curves.at(0))
+ let normal-inner = calc.abs(amplitude * inner-curves.at(0))
+ let length-left = middle
+ let length-right = length - middle
+
+ // width of left-outer, left-inner, right-inner, right-outer curve segments
+ let lo = if 2 * normal-outer > length-left { length-left / 2 } else { normal-outer }
+ let li = if 2 * normal-inner > length-left { length-left / 2 } else { normal-inner }
+ let ri = if 2 * normal-inner > length-right { length-right / 2 } else { normal-inner }
+ let ro = if 2 * normal-outer > length-right { length-right / 2 } else { normal-outer }
+
+ // 'a' and 'b' are start and end
+ let a = ( 0, 0)
+ let b = (length, 0)
+ // 'c' is the spike's top
+ let c = (middle, amplitude)
+ // 'de' is the left line, 'fg' is the right line
+ let d = ( lo, horizon)
+ let e = (middle - li, horizon)
+ let f = (middle + ri, horizon)
+ let g = (length - ro, horizon)
+ // 'h' is where to place content, above the spike
+ let h = (middle, amplitude + content-offset)
+
+ // list of all named points to show in debug mode
+ let points = (a: a, b: b, c: c, d: d, e: e, f: f, g: g, h: h)
+
+ // bezier control points: in 'dlc' 'd' stands for the point 'd' where the control point is used,
+ // 'l' stands for left of spike, 'c' stands for control point
+ let dlc = ( (1 - outer-curves.at(1)) * lo, horizon)
+ let elc = (middle - (1 - inner-curves.at(1)) * li, horizon)
+ let frc = (middle + (1 - inner-curves.at(1)) * ri, horizon)
+ let grc = (length - (1 - outer-curves.at(1)) * ro, horizon)
+ let alc = ( outer-curves.at(3) * lo, outer-curves.at(2) / 2 * amplitude)
+ let clc = (middle - inner-curves.at(3) * li, (1 - inner-curves.at(2) / 2) * amplitude)
+ let crc = (middle + inner-curves.at(3) * ri, (1 - inner-curves.at(2) / 2) * amplitude)
+ let brc = (length - outer-curves.at(3) * ro, outer-curves.at(2) / 2 * amplitude)
+
+ merge-path({
+ bezier(a, d, alc, dlc)
+ bezier(e, c, elc, clc)
+ bezier(c, f, crc, frc)
+ bezier(g, b, grc, brc)
+ }, stroke: style.stroke, fill: style.fill)
+
+ // Define some named anchors
+ anchor("spike", c)
+ anchor("content", h)
+ anchor("start", a)
+ anchor("end", b)
+ anchor("default", (d, 50%, g))
+
+ // Define anchors for all points
+ for (name, point) in points {
+ anchor(name, point)
+ }
+
+ if debug {
+ // Show bezier control points using colored lines
+ line(stroke: purple, a, alc)
+ line(stroke: blue, d, dlc)
+ line(stroke: olive, e, elc)
+ line(stroke: red, c, clc)
+ line(stroke: red, c, crc)
+ line(stroke: olive, f, frc)
+ line(stroke: blue, g, grc)
+ line(stroke: purple, b, brc)
+ // Show all named points
+ for (name, point) in points {
+ content(point, box(fill: luma(240), inset: .5pt, text(style.debug-text-size, raw(name))))
+ }
+ }
+ })
+
+ // Move to end point so the current position after this is the end position
+ move-to(end)
+}
diff --git a/render/packages/preview/cetz/0.3.4/src/lib/decorations/path.typ b/render/packages/preview/cetz/0.3.4/src/lib/decorations/path.typ
new file mode 100644
index 0000000..fe32b4c
--- /dev/null
+++ b/render/packages/preview/cetz/0.3.4/src/lib/decorations/path.typ
@@ -0,0 +1,501 @@
+// Library for drawing springs
+#import "/src/draw.typ"
+#import "/src/styles.typ"
+#import "/src/coordinate.typ"
+#import "/src/vector.typ"
+#import "/src/process.typ"
+#import "/src/path-util.typ"
+#import "/src/util.typ"
+#import "/src/bezier.typ"
+
+#let default-style = (
+ /// Number of segments
+ segments: 10,
+ /// Length of a single segments
+ segment-length: none,
+
+ /// Amplitude of a segment in the direction of the segments normal.
+ /// The following types are supported:
+ /// - float
+ /// - function ratio -> float (the segment ratio is given as argument)
+ /// - array of floats (the rounded down segment number is used as index modulo the array length)
+ amplitude: 1,
+ /// Decoration start
+ start: 0%,
+ /// Decoration stop
+ stop: 100%,
+ /// Decoration alignment on the target path
+ align: "START",
+ /// Draw remaining space as line ("LINE") or none
+ rest: "LINE",
+
+ /// Up-vector for 3D lines
+ z-up: (0, 1, 0),
+ /// Up-vector for 2D lines
+ xy-up: (0, 0, -1),
+
+ stroke: auto,
+ fill: none,
+ mark: auto,
+)
+
+// Zig-Zag default style
+#let zigzag-default-style = (
+ ..default-style,
+ /// Midpoint factor
+ /// 0%: Sawtooth (up-down)
+ /// 50%: Triangle
+ /// 100%: Sawtooth (down-up)
+ factor: 50%,
+)
+
+// Wave default style
+#let wave-default-style = (
+ ..default-style,
+ /// Wave (catmull-rom) tension
+ tension: .5,
+)
+
+// Coil default style
+#let coil-default-style = (
+ ..default-style,
+ /// Coil "overshoot" factor
+ factor: 150%,
+)
+
+// Square default style
+#let square-default-style = (
+ ..default-style,
+ /// Midpoint factor
+ factor: 50%,
+)
+
+#let resolve-amplitude(ctx, amplitude, segment, num-segments) = {
+ segment = calc.max(0, calc.min(segment, num-segments))
+ let amp = if type(amplitude) == function {
+ (amplitude)(segment / num-segments * 100%)
+ } else if type(amplitude) == array {
+ amplitude.at(calc.rem(int(2*segment), amplitude.len()), default: 0)
+ } else {
+ amplitude
+ }
+ return util.resolve-number(ctx, amp)
+}
+
+#let resolve-style(ctx, segments, style) = {
+ assert(not (style.segments == none and style.segment-length == none),
+ message: "Only one of segments or segment-length must be set, while the other must be auto")
+ assert(style.segments != none or style.segment-length != none,
+ message: "Either segments or segment-length must be not equal to none")
+
+ // Calculate absolute start/stop distances
+ let len = path-util.length(segments)
+ if type(style.start) == ratio {
+ style.start = len * style.start / 100%
+ }
+ style.start = calc.max(0, calc.min(style.start, len))
+ if type(style.stop) == ratio {
+ style.stop = len * style.stop / 100%
+ }
+ style.stop = calc.max(0, calc.min(style.stop, len))
+
+ if style.segment-length != none {
+ // Calculate number of divisions
+ let n = (style.stop - style.start) / style.segment-length
+ style.segments = calc.floor(n)
+
+ // Divides the rest between start, stop or both
+ let r = (n - calc.floor(n)) * style.segment-length
+ if style.align == "MID" {
+ let m = (style.start + style.stop) / 2
+ style.start = m - n * style.segment-length / 2
+ style.stop = m + n * style.segment-length / 2
+ } else if style.align == "STOP" {
+ style.start = style.stop - n * style.segment-length
+ } else if style.align == "START" {
+ style.stop = style.start + n * style.segment-length
+ }
+ }
+
+ return style
+}
+
+#let get-segments(ctx, target) = {
+ if type(target) == array {
+ assert.eq(target.len(), 1,
+ message: "Expected a single element, got " + str(target.len()))
+ target = target.first()
+ }
+
+ let (ctx, drawables, ..) = process.element(ctx, target)
+ if drawables == none or drawables == () {
+ return ()
+ }
+
+ let first = drawables.first()
+ return (segments: first.segments, close: first.close)
+}
+
+// Add optional line elements from segments start to mid-path start
+// and mid-path end to sgements end
+#let finalize-path(ctx, segments, style, mid-path, close: false) = {
+ let add = style.rest == "LINE" and not close
+
+ let (ctx, drawables, ..) = process.many(ctx, mid-path)
+ let mid-first = drawables.first().segments.first()
+ let mid-last = drawables.last().segments.last()
+
+ if add {
+ let start = path-util.segment-start(segments.first())
+ start = util.revert-transform(ctx.transform, start)
+
+ let mid-start = path-util.segment-start(mid-first)
+ mid-start = util.revert-transform(ctx.transform, mid-start)
+ draw.line(start, mid-start, mark: none)
+ }
+ mid-path;
+ if add {
+ let end = path-util.segment-end(segments.last())
+ end = util.revert-transform(ctx.transform, end)
+
+ let mid-end = path-util.segment-end(mid-last)
+ mid-end = util.revert-transform(ctx.transform, mid-end)
+ draw.line(mid-end, end, mark: none)
+ }
+ // TODO: Add marks on path.
+}
+
+// Call callback `fn` for each decoration segment
+// on path `segments`.
+//
+// The callback gets called with the following arguments:
+// - i Segment index
+// - start Segment start point
+// - end Segment end point
+// - norm Normal vector (length 1)
+// Result values get returned as an array
+#let _path-effect(ctx, segments, fn, close: false, style) = {
+ let n = style.segments
+ assert(n > 0,
+ message: "Number of segments must be greater than 0")
+
+ let (start, stop) = (style.start, style.stop)
+ let inc = (stop - start) / n
+ let pts = ()
+ let len = path-util.length(segments)
+ for i in range(0, n) {
+ let p0 = path-util.point-on-path(segments, calc.max(start,
+ start + inc * i))
+ let p1 = path-util.point-on-path(segments, calc.min(stop,
+ start + inc * (i + 1)))
+ if p0 == p1 { continue }
+
+ (p0, p1) = util.revert-transform(ctx.transform, p0, p1)
+
+ let dir = vector.norm(vector.sub(p1, p0))
+ let norm = vector.cross(dir, if p0.at(2) != p1.at(2) {
+ style.z-up
+ } else {
+ style.xy-up
+ })
+
+ pts += fn(i, p0, p1, norm)
+ }
+ return pts
+}
+
+/// Draw a zig-zag or saw-tooth wave along a path.
+///
+/// The number of tooths can be controlled via the `segments` or `segment-length` style key, and the width via `amplitude`.
+///
+/// ```typc example
+/// line((0,0), (2,1), stroke: gray)
+/// cetz.decorations.zigzag(line((0,0), (2,1)), amplitude: .25, start: 10%, stop: 90%)
+/// ```
+///
+/// - target (drawable): Target path
+/// - close (auto,bool): Close the path
+/// - name (none,string): Element name
+/// - ..style (style): Style
+///
+/// ## Styling
+/// *Root*: `zigzag`
+/// - factor (ratio) = 100%: Triangle mid between its start and end. Setting this to 0% leads to a falling sawtooth shape, while 100% results in a raising sawtooth.
+#let zigzag(target, name: none, close: auto, ..style) = draw.get-ctx(ctx => {
+ let style = styles.resolve(ctx, merge: style.named(),
+ base: zigzag-default-style, root: "zigzag")
+
+ let (segments, close) = get-segments(ctx, target)
+ let style = resolve-style(ctx, segments, style)
+ let num-segments = style.segments
+
+ // Return points for a zigzag line
+ //
+ // m1 ▲
+ // / \ │ Up
+ // ..a....\....b.. '
+ // \ /
+ // m2
+ // |--|
+ // q-dir (quarter length between a and b)
+ //
+ // For the first/last segment, a/b get added. For all
+ // other segments we only have to add m1 and m2 to the
+ // list of points for the line-strip.
+ let fn(i, a, b, norm) = {
+ let ab = vector.sub(b, a)
+ let f = .25 - (50% - style.factor) / 50% * .25
+ let q-dir = vector.scale(ab, f)
+ let up = vector.scale(norm, resolve-amplitude(ctx, style.amplitude, i + .25, num-segments) / 2)
+ let down = vector.scale(norm, -resolve-amplitude(ctx, style.amplitude, i + .75, num-segments) / 2)
+
+ let m1 = vector.add(vector.add(a, q-dir), up)
+ let m2 = vector.add(vector.sub(b, q-dir), down)
+
+ return if not close and i == 0 {
+ (a, m1, m2) // First segment: add a
+ } else if not close and i == num-segments - 1 {
+ (m1, m2, b) // Last segment: add b
+ } else {
+ (m1, m2)
+ }
+ }
+
+ let pts = _path-effect(ctx, segments, fn, close: close, style)
+ return draw.merge-path(
+ finalize-path(ctx, segments, style,
+ draw.line(..pts, name: name, ..style, mark: none),
+ close: close),
+ close: close,
+ ..style)
+})
+
+/// Draw a stretched coil/loop spring along a path
+///
+/// The number of windings can be controlled via the `segments` or `segment-length` style key, and the width via `amplitude`.
+///
+/// ```typc example
+/// line((0,0), (2,1), stroke: gray)
+/// cetz.decorations.coil(line((0,0), (2,1)), amplitude: .25, start: 10%, stop: 90%)
+/// ```
+/// - target (drawable): Target path
+/// - close (auto,bool): Close the path
+/// - name (none,string): Element name
+/// - ..style (style): Style
+///
+/// ## Styling
+/// *Root*: `coil`
+/// - factor (ratio) = 150%: Factor of how much the coil overextends its length to form a curl.
+#let coil(target, close: auto, name: none, ..style) = draw.get-ctx(ctx => {
+ let style = styles.resolve(ctx, merge: style.named(),
+ base: coil-default-style, root: "coil")
+
+ let (segments, close) = get-segments(ctx, target)
+ let style = resolve-style(ctx, segments, style)
+
+ let num-segments = calc.max(style.segments, 1)
+ let length = path-util.length(segments)
+ let phase-length = length / num-segments
+ let overshoot = calc.max(0, (style.factor - 100%) / 100% * phase-length)
+
+ // Offset both control points so the curve approximates
+ // an elliptic arc
+ let ellipsize-cubic(s, e, c1, c2) = {
+ let m = vector.scale(vector.add(c1, c2), .5)
+ let d = vector.sub(e, s)
+
+ c1 = vector.sub(m, vector.scale(d, .5))
+ c2 = vector.add(m, vector.scale(d, .5))
+
+ return (s, e, c1, c2)
+ }
+
+ // Return a list of drawables to form a coil-like loop
+ //
+ // ____ ┐
+ // / \ │ Upper curve
+ // | | ┘
+ // ..a...b..|.. ┐ Lower curve
+ // \_/ ┘
+ //
+ // └──┘
+ // Overshoot
+ //
+ let fn(i, a, b, norm) = {
+ let ab = vector.sub(b, a)
+ let amplitude = resolve-amplitude(ctx, style.amplitude, i, num-segments)
+ let up = vector.scale(norm, amplitude / 2)
+ let dist = vector.dist(a, b)
+
+ let d = vector.norm(ab)
+ let overshoot-at(i) = if num-segments <= 1 {
+ 0
+ } else if close {
+ overshoot / 2
+ } else {
+ i / (num-segments - 1) * overshoot
+ }
+
+ let next-a = vector.sub(b, vector.scale(d, overshoot-at(i + 1)))
+ let a = vector.sub(a, vector.scale(d, overshoot-at(i)))
+ let b = vector.add(b, vector.scale(d, overshoot-at(num-segments - i)))
+ let m = vector.scale(vector.add(a, b), .5)
+ let m-up = vector.add(m, up)
+ let m-down = vector.sub(vector.scale(vector.add(next-a, b), .5), up)
+
+ let upper = bezier.cubic-through-3points(a, m-up, b)
+ upper = ellipsize-cubic(..upper)
+
+ let lower = bezier.cubic-through-3points(b, m-down, next-a)
+ lower = ellipsize-cubic(..lower)
+
+ if i < num-segments - 1 or close {
+ return (
+ draw.bezier(..upper, mark: none),
+ draw.bezier(..lower, mark: none),
+ )
+ } else {
+ return (draw.bezier(..upper, mark: none),)
+ }
+ }
+
+ return draw.merge-path(
+ finalize-path(ctx, segments, style,
+ _path-effect(ctx, segments, fn, close: close, style).flatten(),
+ close: close),
+ ..style,
+ name: name,
+ close: close)
+})
+
+/// Draw a wave along a path using a catmull-rom curve
+///
+/// The number of phases can be controlled via the `segments` or `segment-length` style key, and the width via `amplitude`.
+///
+/// ```typc example
+/// line((0,0), (2,1), stroke: gray)
+/// cetz.decorations.wave(line((0,0), (2,1)), amplitude: .25, start: 10%, stop: 90%)
+/// ```
+///
+/// - target (drawable): Target path
+/// - close (auto,bool): Close the path
+/// - name (none,string): Element name
+/// - ..style (style): Style
+///
+/// ## Styling
+/// *Root*: `wave`
+///
+/// - tension (float) = 0.5 Catmull-Rom curve tension, see [Catmull](/api/draw-functions/shapes/catmull)
+#let wave(target, close: auto, name: none, ..style) = draw.get-ctx(ctx => {
+ let style = styles.resolve(ctx, merge: style.named(),
+ base: wave-default-style, root: "wave")
+
+ let (segments, close) = get-segments(ctx, target)
+ let style = resolve-style(ctx, segments, style)
+ let num-segments = style.segments
+
+ // Return a list of points for the catmull-rom curve
+ //
+ // ╭ ma ╮ ▲
+ // │ │ │ Up
+ // ..a....m....b.. '
+ // │ │
+ // ╰ mb ╯
+ //
+ let fn(i, a, b, norm) = {
+ let ab = vector.sub(b, a)
+ let up = vector.scale(norm, +resolve-amplitude(ctx, style.amplitude, i + .25, num-segments) / 2)
+ let down = vector.scale(norm, -resolve-amplitude(ctx, style.amplitude, i + .75, num-segments) / 2)
+
+ let ma = vector.add(vector.add(a, vector.scale(ab, .25)), up)
+ let m = vector.add(a, vector.scale(ab, .50))
+ let mb = vector.add(vector.sub(b, vector.scale(ab, .25)), down)
+
+ if not close {
+ if num-segments == 1 {
+ return (a, ma, mb, b)
+ } else if i == 0 {
+ return (a, ma, mb)
+ } else if i == num-segments - 1 {
+ return (ma, mb, b,)
+ }
+ }
+
+ return (ma, mb)
+ }
+
+ return draw.merge-path(
+ finalize-path(ctx, segments, style, draw.catmull(
+ .._path-effect(ctx, segments, fn, close: close, style),
+ close: close), close: close) ,
+ name: name,
+ close: close,
+ ..style)
+})
+
+/// Draw a square-wave along a path using a line-strip
+///
+/// The number of phases can be controlled via the `segments` or `segment-length` style key, and the width via `amplitude`.
+///
+/// ```typc example
+/// line((0,0), (2,1), stroke: gray)
+/// cetz.decorations.square(line((0,0), (2,1)), amplitude: .25, start: 10%, stop: 90%)
+/// ```
+///
+/// - target (drawable): Target path
+/// - close (auto,bool): Close the path
+/// - name (none,string): Element name
+/// - ..style (style): Style
+///
+/// ## Styling
+/// *Root*: `squre`
+///
+/// - factor (ratio) = 50% Square-Wave midpoint
+#let square(target, close: auto, name: none, ..style) = draw.get-ctx(ctx => {
+ let style = styles.resolve(ctx, merge: style.named(),
+ base: square-default-style, root: "square")
+
+ let (segments, close) = get-segments(ctx, target)
+ let style = resolve-style(ctx, segments, style)
+ let num-segments = style.segments
+ let factor = calc.max(0, calc.min(style.factor / 100%, 1))
+
+ // Return a list of points for the line-strip
+ //
+ // +----+ ▲
+ // | | │ Up
+ // ..a....m....b.. '
+ // | |
+ // +----+
+ //
+ let fn(i, a, b, norm) = {
+ let ab = vector.sub(b, a)
+ let up = vector.scale(norm, +resolve-amplitude(ctx, style.amplitude, i + .25, num-segments) / 2)
+ let down = vector.scale(norm, -resolve-amplitude(ctx, style.amplitude, i + .75, num-segments) / 2)
+ let m = vector.add(a, vector.scale(ab, factor))
+
+ if not close {
+ if i == 0 {
+ return (a, vector.add(a, up),
+ vector.add(m, up), vector.add(m, down),
+ vector.add(b, down))
+ } else if i == num-segments - 1 {
+ return (vector.add(a, up),
+ vector.add(m, up), vector.add(m, down),
+ vector.add(b, down), b)
+ }
+ }
+
+ return (vector.add(a, up),
+ vector.add(m, up), vector.add(m, down),
+ vector.add(b, down))
+ }
+
+ return draw.merge-path(
+ finalize-path(ctx, segments, style, draw.line(
+ .._path-effect(ctx, segments, fn, close: close, style),
+ close: close), close: close) ,
+ name: name,
+ close: close,
+ ..style)
+})
diff --git a/render/packages/preview/cetz/0.3.4/src/lib/palette.typ b/render/packages/preview/cetz/0.3.4/src/lib/palette.typ
new file mode 100644
index 0000000..9792fd7
--- /dev/null
+++ b/render/packages/preview/cetz/0.3.4/src/lib/palette.typ
@@ -0,0 +1,125 @@
+#let base-style = (stroke: (paint: black), fill: none)
+
+/// Create a new palette based on a base style
+///
+/// ```typc example
+/// let p = cetz.palette.new(colors: (red, blue, green))
+/// for i in range(0, p("len")) {
+/// set-style(..p(i))
+/// circle((0,0), radius: .5)
+/// set-origin((1.1, 0))
+/// }
+/// ```
+///
+/// The functions returned by this function have the following named arguments:
+/// - fill (bool) = true: If true, the returned fill color is one of the colors from the `colors` list, otherwise the base styles fill is used.
+/// - stroke (bool) = false: If true, the returned stroke color is one of the colors from the `colors` list, otherwise the base styles stroke color is used.
+///
+/// You can use a palette for stroking via: `red.with(stroke: true)`.
+///
+/// - base (style): Style dictionary to use as base style for the styles generated per color
+/// - colors (none, array): List of colors the returned palette should return styles with.
+/// - dash (none, array): List of stroke dash patterns the returned palette should return styles with.
+/// -> function
+#let new(base: base-style, colors: (), dash: ()) = {
+ if not "stroke" in base { base.stroke = (paint: black, thickness: 1pt, dash: "solid") }
+ if not "fill" in base { base.fill = none }
+
+ let color-n = colors.len()
+ let pattern-n = dash.len()
+ return (index, fill: true, stroke: false) => {
+ if index == "len" { return calc.max(color-n, pattern-n, 1) }
+
+ let style = base
+ if pattern-n > 0 {
+ style.stroke.dash = dash.at(calc.rem(index, pattern-n))
+ }
+ if color-n > 0 {
+ if stroke {
+ style.stroke.paint = colors.at(calc.rem(index, color-n))
+ }
+ if fill {
+ style.fill = colors.at(calc.rem(index, color-n))
+ }
+ }
+ return style
+ }
+}
+
+// Predefined color themes
+#let tango-colors = (
+ "edd400", "f57900", "c17d11",
+ "73d216", "3465a4", "75507b",
+ "cc0000", "d3d7cf", "555753").map(rgb)
+#let tango-light-colors = (
+ "fce94f", "fcaf3e", "e9b96e",
+ "8ae234", "729fcf", "ad7fa8",
+ "ef2929", "eeeeec", "888a85").map(rgb)
+#let tango-dark-colors = (
+ "c4a000", "ce5c00", "8f5902",
+ "4e9a06", "204a87", "5c3566",
+ "a40000", "babdb6", "2e3436").map(rgb)
+#let rainbow-colors = (
+ "#9400D4", "#4B0082", "#0000FF",
+ "#00FF00", "#FFFF00", "#FF7F00",
+ "#FF0000").map(rgb)
+
+#let red-colors = (
+ "#FFCCCC", "#FF9999", "#FF6666",
+ "#FF3333", "#CC0000").map(rgb)
+#let orange-colors = (
+ "#FFE5CC", "#FFCC99", "#FFB266",
+ "#FF9933", "#FF8000").map(rgb)
+#let light-green-colors = (
+ "#E5FFCC", "#CCFF99", "#B2FF66",
+ "#99FF33", "#72E300", "#66CC00",
+ "#55A800", "#478F00", "#3A7300",
+ "#326300").map(rgb)
+#let dark-green-colors = (
+ "#80E874", "#5DD45D", "#3CC23C",
+ "#009900", "#006E00").map(rgb)
+#let turquoise-colors = (
+ "#C0FFD3", "#99FFCC", "#66FFB2",
+ "#33FF99", "#4BD691").map(rgb)
+#let cyan-colors = (
+ "#CCFFFF", "#99FFFF", "#66FFFF",
+ "#00F3F3", "#00DADA").map(rgb)
+#let blue-colors = (
+ "#BABAFF", "#9999FF", "#6666FF",
+ "#3333FF", "#0000CC").map(rgb)
+#let indigo-colors = (
+ "#BABAFF", "#9999FF", "#6666FF",
+ "#3333FF", "#0000CC").map(rgb)
+#let purple-colors = (
+ "#E0C2FF", "#CC99FF", "#B266FF",
+ "#9933FF", "#7F00FF").map(rgb)
+#let magenta-colors = (
+ "#FFD4FF", "#FF99FF", "#FF66FF",
+ "#F331F3", "#DA00DA").map(rgb)
+#let pink-colors = (
+ "#FFCCE5", "#FF99CC", "#FF66B2",
+ "#FF3399", "#F20C7F", "#DB006B",
+ "#C30061", "#99004C", "#800040",
+ "#660033").map(rgb)
+
+
+// Predefined palettes
+#let gray = new(colors: range(90, 40, step: -12).map(v => luma(v * 1%)))
+
+#let red = new(colors: red-colors)
+#let orange = new(colors: orange-colors)
+#let light-green = new(colors: light-green-colors)
+#let dark-green = new(colors: dark-green-colors)
+#let turquoise = new(colors: turquoise-colors)
+#let cyan = new(colors: cyan-colors)
+#let blue = new(colors: blue-colors)
+#let indigo = new(colors: indigo-colors)
+#let purple = new(colors: purple-colors)
+#let magenta = new(colors: magenta-colors)
+#let pink = new(colors: pink-colors)
+
+#let rainbow = new(colors: rainbow-colors)
+
+#let tango = new(colors: tango-colors)
+#let tango-light = new(colors: tango-light-colors)
+#let tango-dark = new(colors: tango-dark-colors)
diff --git a/render/packages/preview/cetz/0.3.4/src/lib/pin.typ b/render/packages/preview/cetz/0.3.4/src/lib/pin.typ
new file mode 100644
index 0000000..6273219
--- /dev/null
+++ b/render/packages/preview/cetz/0.3.4/src/lib/pin.typ
@@ -0,0 +1,17 @@
+#let _pin-name(name) = "cetz-pin-" + name
+
+/// Place a pin aka. cetz anchor in the document
+#let pin(name) = [ #metadata("cetz-pin-tracker") #label(_pin-name(name)) ]
+
+/// Returns all pins
+#let get-pin() = context {
+ let result = ()
+ for item in locate(metadata) {
+ if item.value.starts-with("cetz-pin-") {
+ let name = item.value.slice(9)
+
+ result.insert(name, item)
+ }
+ }
+ panic(result)
+}
diff --git a/render/packages/preview/cetz/0.3.4/src/lib/tree.typ b/render/packages/preview/cetz/0.3.4/src/lib/tree.typ
new file mode 100644
index 0000000..279a4c6
--- /dev/null
+++ b/render/packages/preview/cetz/0.3.4/src/lib/tree.typ
@@ -0,0 +1,243 @@
+// CeTZ Library for Layouting Tree-Nodes
+#import "/src/util.typ"
+#import "/src/draw.typ"
+#import "/src/coordinate.typ"
+#import "/src/vector.typ"
+#import "/src/matrix.typ"
+#import "/src/process.typ"
+#import "/src/anchor.typ" as anchor_
+
+#let typst-content = content
+
+// Default edge draw callback
+//
+// - from (string): Source element name
+// - to (string): Target element name
+// - parent (node): Parent (source) tree node
+// - child (node): Child (target) tree node
+#let default-draw-edge(from, to, parent, child) = {
+ draw.line(from, to)
+}
+
+// Default node draw callback
+//
+// - node (node): The node to draw
+#let default-draw-node(node, _) = {
+ let text = if type(node) in (content, str, int, float) {
+ [#node]
+ } else if type(node) == dictionary {
+ node.content
+ }
+
+ draw.get-ctx(ctx => {
+ draw.content((), text)
+ })
+}
+
+/// Lays out and renders tree nodes.
+///
+/// For each node, the `tree` function creates an anchor of the format `"node-<depth>-<child-index>"` that can be used to query a nodes position on the canvas.
+///
+/// ```typc example
+/// import cetz.tree
+/// set-style(content: (padding: .1))
+/// tree.tree(([Root], ([A], [A.A], [A.B]), ([B], [B.A])))
+/// ```
+///
+/// - root (array): A nested array of content that describes the structure the tree should take. Example: `([root], [child 1], ([child 2], [grandchild 1]))`
+/// - draw-node (auto,function): The function to call to draw a node. The function will be passed two positional arguments, the node to draw and the node's parent, and is expected to return elements (`(node, parent-node) => elements`). The node's position is accessible through the "center" anchor or by using the previous position coordinate `()`. If `auto` is given, just the node's value will be drawn as content. The following predefined styles can be used:
+/// - draw-edge (none,auto,function): The function to call draw an edge between two nodes. The function will be passed the name of the starting node, the name of the ending node, the start node, the end node, and is expected to return elements (`(source-name, target-name, parent-node, child-node) => elements`). If `auto` is given, a straight line will be drawn between nodes.
+/// - direction (str): A string describing the direction the tree should grow in ("up", "down", "left", "right")
+/// - parent-position (str): Positioning of parent nodes (begin, center, end)
+/// - grow (float): Depth grow factor
+/// - spread (float): Sibling spread factor
+/// - name (none,str): The tree element's name
+/// - node-layer (int): Layer to draw nodes on
+/// - edge-layer (int): Layer to draw edges on
+#let tree(
+ root,
+ draw-node: auto,
+ draw-edge: auto,
+ direction: "down",
+ parent-position: "center",
+ grow: 1,
+ spread: 1,
+ name: none,
+ node-layer: 1,
+ edge-layer: 0
+ ) = {
+ assert(parent-position in ("begin", "center","end", "after-end"))
+ assert(grow > 0)
+ assert(spread > 0)
+
+ direction = (
+ up: "north",
+ down: "south",
+ right: "east",
+ left: "west"
+ ).at(direction)
+
+ if draw-edge == auto {
+ draw-edge = default-draw-edge
+ } else if draw-edge == none {
+ draw-edge = (..) => ()
+ }
+
+ if draw-node == auto {
+ draw-node = default-draw-node
+ }
+ assert(draw-node != none, message: "Node draw callback must be set!")
+
+ let build-node(tree, depth: 0, sibling: 0) = {
+ let children = ()
+ let content = none
+ if type(tree) == array {
+ children = tree.slice(1).enumerate().map(
+ ((n, c)) => build-node(c, depth: depth + 1, sibling: n)
+ )
+ content = tree.at(0)
+ } else {
+ content = tree
+ }
+
+ return (
+ x: 0,
+ y: depth * grow,
+ n: sibling,
+ depth: depth,
+ children: children,
+ content: content
+ )
+ }
+
+ // Layout node recursive
+ //
+ // return:
+ // (node, left-x, right-x)
+ let layout-node(node, shift-x) = {
+ if node.children.len() == 0 {
+ node.x = shift-x
+ return (node, node.x, node.x)
+ } else {
+ let (min-x, max-x) = (none, none)
+ let (left, right) = (none, none)
+
+ let n-children = node.children.len()
+ for i in range(0, n-children) {
+ let child = node.children.at(i)
+ let (child-min-x, child-max-x) = (none, none)
+
+ (child, child-min-x, child-max-x) = layout-node(child, shift-x)
+ node.children.at(i) = child
+
+ left = util.min(child.x, left)
+ right = util.max(child.x, right)
+
+ min-x = util.min(min-x, child-min-x)
+ max-x = util.max(max-x, child-max-x)
+
+ shift-x = child-max-x + spread
+ }
+
+ if parent-position == "begin" {
+ node.x = left
+ } else if parent-position == "center" {
+ node.x = left + (right - left) / 2
+ } else if parent-position == "end" {
+ node.x = right
+ } else { //after-end
+ node.x = right+spread
+ max-x = max-x + spread
+ }
+
+ node.direct-min-x = left
+ node.direct-max-x = right
+ node.min-x = min-x
+ node.max-x = max-x
+
+ return (node, min-x, max-x)
+ }
+ }
+
+ let node-position(node) = {
+ if direction == "south" {
+ return (node.x, -node.y)
+ } else if direction == "north" {
+ return (node.x, node.y)
+ } else if direction == "west" {
+ return (-node.y, node.x)
+ } else if direction == "east" {
+ return (node.y, node.x)
+ } else {
+ panic(message: "Invalid tree direction.")
+ }
+ }
+
+ let anchors(node, parent-path) = {
+ if parent-path != none {
+ parent-path += "-"
+ } else {
+ parent-path = ""
+ }
+
+ let d = (:)
+ d.insert(parent-path + str(node.n), node-position(node))
+ for child in node.children {
+ d += anchors(child, parent-path + str(node.n))
+ }
+ return d
+ }
+
+ let build-element(node, parent-name) = {
+ let name = if parent-name != none {
+ parent-name + "-" + str(node.n)
+ } else {
+ "0"
+ }
+
+ // Render element
+ node.name = name
+ node.group-name = "g" + name
+ node.element = {
+ draw.anchor(node.name, node-position(node))
+ draw.group(name: node.group-name, {
+ draw.move-to(node-position(node))
+ draw.anchor("default", ())
+ draw-node(node, parent-name)
+ })
+ }
+
+ // Render children
+ node.children = node.children.map(c => build-element(c, name))
+
+ // Render edges
+ node.edges = if node.children != () {
+ draw.group({
+ for child in node.children {
+ draw-edge(node.group-name, child.group-name, node, child)
+ }
+ })
+ } else { () }
+
+ return node
+ }
+
+ let root = build-node(root)
+ let (nodes, ..) = layout-node(root, 0)
+ let node = build-element(nodes, none)
+
+ // Render node recursive
+ let render(node) = {
+ if node.element != none {
+ draw.on-layer(node-layer, node.element)
+ if "children" in node {
+ for child in node.children {
+ render(child)
+ }
+ }
+ draw.on-layer(edge-layer, node.edges)
+ }
+ }
+
+ draw.group(name: name, render(node))
+}
diff --git a/render/packages/preview/cetz/0.3.4/src/mark-shapes.typ b/render/packages/preview/cetz/0.3.4/src/mark-shapes.typ
new file mode 100644
index 0000000..aad9b22
--- /dev/null
+++ b/render/packages/preview/cetz/0.3.4/src/mark-shapes.typ
@@ -0,0 +1,315 @@
+#import "drawable.typ"
+#import "path-util.typ"
+#import "vector.typ"
+
+// Calculate triangular tip offset, depending on the strokes
+// join type.
+//
+// The angle is calculated for an isosceles triangle of base style.widh
+// and height style.length
+#let _calculate-tip-offset(style) = {
+ if style.stroke.join == "round" {
+ return style.stroke.thickness / 2
+ }
+
+ if style.length == 0 {
+ return 0
+ }
+
+ let angle = calc.atan(style.width / (2 * style.length) / if style.harpoon { 2 } else { 1 } ) * 2
+ // If the miter length divided by the stroke width exceeds
+ // the stroke miter limit then the miter join is converted to a bevel.
+ // See: https://svgwg.org/svg2-draft/painting.html#LineJoin
+ if style.stroke.join == "miter" {
+ let angle = calc.abs(angle)
+ if angle > 0deg {
+ let miter-limit = 1 / calc.sin(angle / 2)
+ if miter-limit <= style.stroke.miter-limit {
+ return miter-limit * (style.stroke.thickness / 2)
+ }
+ }
+ }
+
+ // style.stroke.join must be "bevel"
+ return calc.sin(angle/2) * (style.stroke.thickness / 2)
+}
+
+#let create-tip-and-base-anchor(style, tip, base, center: none) = {
+ if base == tip { base = vector.add(tip, (1e-8, 0, 0)) }
+ let dir = vector.norm(vector.sub(tip, base))
+
+ import "/src/draw.typ": *
+ anchor("tip", vector.add(tip, vector.scale(dir, style.stroke.thickness / 2)))
+ anchor("base", vector.sub(base, vector.scale(dir, style.stroke.thickness / 2)))
+}
+
+#let create-triangle-tip-and-base-anchor(style, tip, base, center: none) = {
+ if base == tip { base = vector.add(tip, (1e-8, 0, 0)) }
+ let dir = vector.norm(vector.sub(tip, base))
+
+ import "/src/draw.typ": *
+ if style.reverse {
+ // Since tip and base are now "swapped", we add the stroke thickness to the triangle
+ // base. To get smooth looking connections between the triangle tip and a connecting line,
+ // we do not add the tip-offset.
+ anchor("tip", vector.add(tip, vector.scale(dir, style.stroke.thickness / 2)))
+ anchor("base", base)
+ } else {
+ anchor("tip", vector.add(tip, vector.scale(dir, _calculate-tip-offset(style))))
+ anchor("base", vector.sub(base, vector.scale(dir, style.stroke.thickness / 2)))
+ }
+}
+
+#let create-diamond-tip-and-base-anchor(style, tip, base, center: none, ratio: 50%) = {
+ if base == tip { base = vector.add(tip, (1e-8, 0, 0)) }
+ let dir = vector.norm(vector.sub(tip, base))
+
+ import "/src/draw.typ": *
+
+ let tip-style = style
+ tip-style.length = style.length * (ratio / 100%)
+ if style.reverse {
+ anchor("tip", tip)
+ } else {
+ anchor("tip", vector.add(tip, vector.scale(dir, _calculate-tip-offset(tip-style))))
+ }
+ if style.reverse {
+ anchor("base", vector.sub(base, vector.scale(dir, _calculate-tip-offset(tip-style))))
+ } else {
+ anchor("base", base)
+ }
+}
+
+// Dictionary of built-in mark styles
+//
+// (style) => (<elements..>)
+#let marks = (
+ triangle: (style) => {
+ import "/src/draw.typ": *
+
+ if style.harpoon {
+ line((0,0), (style.length, 0), (style.length, +style.width / 2), close: true)
+ } else {
+ line((0,0), (style.length, -style.width / 2), (style.length, +style.width / 2), close: true)
+ }
+
+ create-triangle-tip-and-base-anchor(style, (0, 0), (style.length, 0))
+ },
+ // A mark in the shape of an arrow tip.
+ stealth: (style) => {
+ import "/src/draw.typ": *
+
+ let (l, w, i) = (style.length, style.width, style.inset)
+
+ if style.harpoon {
+ line((0,0), (l, w / 2), (l - i, 0), close: true)
+ } else {
+ line((0,0), (l, w / 2), (l - i, 0), (l, -w / 2), close: true)
+ }
+
+ create-triangle-tip-and-base-anchor(style, (0, 0), (l - i, 0))
+ },
+ bar: (style) => {
+ import "/src/draw.typ": *
+
+ let w = style.width
+
+ if style.harpoon {
+ line((0, w / 2), (0, 0))
+ } else {
+ line((0, w / 2), (0, -w / 2))
+ }
+
+ create-tip-and-base-anchor(style, (0, 0), (0, 0))
+ },
+ ellipse: (style) => {
+ import "/src/draw.typ": *
+
+ let r = (style.length / 2, style.width / 2)
+
+ if style.harpoon {
+ arc((0, 0), delta: -180deg, start: 0deg, radius: r, anchor: "origin", mode: "PIE")
+ } else {
+ circle((0, 0), radius: r)
+ }
+
+ create-tip-and-base-anchor(style, (r.at(0), 0), (-r.at(0), 0))
+ },
+ circle: (style) => {
+ import "/src/draw.typ": *
+
+ let r = calc.min(style.length, style.width) / 2
+
+ if style.harpoon {
+ arc((0, 0), delta: -180deg, start: 0deg, radius: r, anchor: "origin", mode: "PIE")
+ } else {
+ circle((0, 0), radius: r)
+ }
+
+ create-tip-and-base-anchor(style, (r, 0), (-r, 0))
+ },
+ bracket: (style) => {
+ import "/src/draw.typ": *
+
+ let (l, w, i) = (style.length, style.width, style.inset)
+
+ if style.harpoon {
+ line((-l - i, w / 2), (0, w / 2), (0, 0), fill: none)
+ } else {
+ line((-l - i, w / 2), (0, w / 2), (0, -w / 2), (-l - i, -w / 2), fill: none)
+ }
+
+ create-tip-and-base-anchor(style, (0, 0), (-1e-8, 0), center: ((-l - i) / 2, 0))
+ },
+ diamond: (style) => {
+ import "/src/draw.typ": *
+
+ let (l, w) = (style.length, style.width)
+
+ if style.harpoon {
+ line((0,0), (l / 2, w / 2), (l, 0), close: true)
+ } else {
+ line((0,0), (l / 2, w / 2), (l, 0), (l / 2, -w / 2), close: true)
+ }
+
+ create-diamond-tip-and-base-anchor(style, (0, 0), (l, 0))
+ },
+ rect: (style) => {
+ import "/src/draw.typ": *
+
+ let (l, w) = (style.length, style.width)
+
+ if style.harpoon {
+ rect((0, -w / 2), (-l, +w / 2))
+ } else {
+ rect((0, -w / 2), (-l, +w / 2))
+ }
+
+ create-tip-and-base-anchor(style, (0, 0), (-l, 0))
+ },
+ hook: (style) => {
+ import "/src/draw.typ": *
+
+ let r = calc.min(style.length, style.width / 2) / 2
+ let (l, i) = (style.length, style.inset)
+
+ merge-path({
+ line((i, -2 * r), (0, -2 * r))
+ arc((0, 0), delta: -180deg, start: -90deg, radius: r, anchor: "end")
+ if not style.harpoon {
+ arc((0, 0), delta: -180deg, start: -90deg, radius: r, anchor: "start")
+ line((i, +2 * r), (0, +2 * r))
+ }
+ }, fill: none)
+
+ line((0, 0), (l - r, 0))
+
+ create-tip-and-base-anchor(style, (-r, 0), (l - r, 0), center: ((-r + i) / 2, 0))
+ },
+ // An unfilled mark in the shape of an angle bracket (>).
+ straight: (style) => {
+ import "/src/draw.typ": *
+
+ let (l, w) = (style.length, style.width)
+
+ if style.harpoon {
+ line((l, w / 2), (0, 0), fill: none)
+ } else {
+ line((l, w / 2), (0, 0), (l, -w / 2), fill: none)
+ }
+
+ create-triangle-tip-and-base-anchor(style, (0, 0), (0, 0))
+ },
+ barbed: (style) => {
+ import "/src/draw.typ": *
+
+ let style = style
+ style.stroke.join = "round"
+
+ let (l, w) = (style.length, style.width)
+
+ let ctrl-a = (l, 0)
+ let ctrl-b = (0, 0)
+
+ merge-path({
+ bezier((l, w / 2), (0, 0), ctrl-a, ctrl-b)
+ if not style.harpoon {
+ bezier((0, 0), (l, -w / 2), ctrl-b, ctrl-a)
+ }
+ }, ..style)
+
+ create-tip-and-base-anchor(style, (0, 0), (1e-6, 0))
+ },
+ plus: (style) => {
+ import "/src/draw.typ": *
+
+ let style = style
+ style.stroke.join = "round"
+
+ let (l, w) = (style.length, style.width)
+
+ line((-l / 2, 0), (+l / 2, 0))
+ line((0, -w / 2), (0, +w / 2))
+
+ create-tip-and-base-anchor(style, (0, 0), (l / 2, 0))
+ },
+ x: (style) => {
+ import "/src/draw.typ": *
+
+ let style = style
+ style.stroke.join = "round"
+
+ let (l, w) = (style.length, style.width)
+
+ line((-l / 2, w / 2), (+l / 2, -w / 2))
+ line((-l / 2, -w / 2), (+l / 2, +w / 2))
+
+ create-tip-and-base-anchor(style, (0, 0), (0, 0))
+ },
+ star: (style) => {
+ import "/src/draw.typ": *
+
+ let (l, w) = (style.length, style.width)
+
+ let n = 5
+ for i in range(0, n) {
+ let a = 360deg / n * i
+ line((0, 0), (calc.cos(a) * l / 2, calc.sin(a) * w / 2))
+ }
+
+ create-tip-and-base-anchor(style, (0, 0), (l / 2, 0))
+ },
+)
+#let names = marks.keys()
+
+// Mark mnemonics
+// Each mnemonic maps to a dictionary of:
+// - reverse (bool)
+// - flip (bool)
+// - harpoon (bool)
+// TODO: Resolve mark styles at a later point, to support all style keys here
+#let mnemonics = (
+ ">": ("triangle", (:)),
+ "<": ("triangle", (reverse: true)),
+ "<>": ("diamond", (:)),
+ "[]": ("rect", (:)),
+ "]": ("bracket", (:)),
+ "[": ("bracket", (reverse: true)),
+ "|": ("bar", (:)),
+ "o": ("circle", (:)),
+ "+": ("plus", (:)),
+ "x": ("x", (:)),
+ "*": ("star", (:)),
+)
+
+// Get a mark shape + reverse tuple for a mark name
+#let get-mark(ctx, symbol) = {
+ symbol = ctx.marks.mnemonics.at(symbol, default: symbol)
+ if symbol in ctx.marks.marks {
+ return (ctx.marks.marks.at(symbol), (:))
+ }
+
+ let (symbol, defaults) = mnemonics.at(symbol, default: (symbol, (:)))
+ assert(symbol in marks, message: "Unknown mark '" + symbol + "'")
+ return (marks.at(symbol), defaults)
+}
diff --git a/render/packages/preview/cetz/0.3.4/src/mark.typ b/render/packages/preview/cetz/0.3.4/src/mark.typ
new file mode 100644
index 0000000..463c33e
--- /dev/null
+++ b/render/packages/preview/cetz/0.3.4/src/mark.typ
@@ -0,0 +1,449 @@
+#import "drawable.typ"
+#import "vector.typ"
+#import "matrix.typ"
+#import "util.typ"
+#import "path-util.typ"
+#import "styles.typ"
+#import "mark-shapes.typ": get-mark
+#import "process.typ"
+
+/// Checks if a mark should be drawn according to the current style.
+/// - style (style): The current style.
+/// -> bool
+#let check-mark(style) = {
+ style != none and ("start", "end", "symbol").any(key =>
+ style.at(key, default: none) != none)
+}
+
+/// Processes the mark styling.
+/// TODO: remember what is actually going on here.
+///
+/// - ctx (context): The context object.
+/// - style (style): The current style.
+/// - root (str): Where the mark is being placed, normally either `"start"` or `"end"`. Allows different styling for marks in different directions.
+/// - path-length (float): The length of the path. This is used for relative offsets.
+#let process-style(ctx, style, root, path-length) = {
+ let base-style = (
+ symbol: auto,
+ fill: auto,
+ stroke: auto,
+ slant: auto,
+ harpoon: auto,
+ flip: auto,
+ reverse: auto,
+ inset: auto,
+ width: auto,
+ scale: auto,
+ length: auto,
+ sep: auto,
+ pos: auto,
+ offset: auto,
+ flex: auto,
+ xy-up: auto,
+ z-up: auto,
+ shorten-to: auto,
+ position-samples: auto,
+ anchor: auto,
+ )
+
+ if type(style.at(root)) != array {
+ style.at(root) = (style.at(root),)
+ }
+ if type(style.symbol) != array {
+ style.symbol = (style.symbol,)
+ }
+
+ let out = ()
+ for i in range(calc.max(style.at(root).len(), style.symbol.len())) {
+ let style = style
+ style.symbol = style.symbol.at(i, default: auto)
+ style.at(root) = style.at(root).at(i, default: auto)
+
+ if type(style.symbol) == dictionary {
+ style = styles.resolve(style, merge: style.symbol)
+ }
+
+ if type(style.at(root)) == str {
+ style.symbol = style.at(root)
+ } else if type(style.at(root)) == dictionary {
+ style = styles.resolve(style, root: root, base: base-style)
+ }
+
+ style.stroke = util.resolve-stroke(style.stroke)
+ style.stroke.thickness = util.resolve-number(ctx, style.stroke.thickness)
+
+ if "angle" in style and type(style.angle) == angle {
+ style.width = calc.tan(style.angle / 2) * style.length * 2
+ }
+
+ // Stroke thickness relative attributes
+ for (k, v) in style {
+ if k in ("length", "width", "inset", "sep") {
+ style.insert(k, if type(v) == ratio {
+ style.stroke.thickness * v / 100%
+ } else {
+ util.resolve-number(ctx, v)
+ } * style.scale)
+ }
+ }
+
+ // Path length relative attributes
+ for k in ("offset", "pos",) {
+ let v = style.at(k)
+ if v != none and v != auto {
+ style.insert(k, if type(v) == ratio {
+ v * path-length / 100%
+ } else {
+ util.resolve-number(ctx, v)
+ })
+ }
+ }
+
+ out.push(style)
+ }
+ return out
+}
+
+#let transform-mark(style, mark, pos, dir, flip: false, reverse: false, slant: none, harpoon: false) = {
+ let up = style.xy-up
+ if dir.at(2) != 0 {
+ up = style.z-up
+ }
+
+ assert(style.anchor in ("tip", "base", "center"))
+ let tip = mark.tip
+ let base = mark.base
+ let origin = mark.at(style.anchor)
+
+ // Mirror anchors on mark center
+ if reverse {
+ (tip, base) = (base, tip)
+ origin = vector.sub(mark.center, vector.sub(origin, mark.center))
+ }
+
+ mark.offset = vector.dist(origin, tip)
+
+ let t = (
+ // Translate & rotate to the target coordinate & direction
+ matrix.transform-translate(..pos),
+ matrix.transform-rotate-dir(dir, up),
+ matrix.transform-rotate-z(-90deg),
+
+ // Rotate mark to have base->tip on the x-axis
+ matrix.transform-rotate-z(if reverse {
+ vector.angle2(tip, base)
+ } else {
+ vector.angle2(base, tip)
+ }),
+
+ // Translate mark to have its anchor (tip, base, center) at (0,0)
+ matrix.transform-translate(..vector.scale(origin, if reverse {1} else {-1})),
+
+ // Mirror on x and/or y axis
+ if flip or reverse {
+ matrix.transform-scale({
+ if flip {
+ (y: -1)
+ }
+ if reverse {
+ (x: -1)
+ }
+ })
+ },
+
+ // Slant on x axis
+ if slant not in (none, 0%) {
+ if type(slant) == ratio {
+ slant /= 100%
+ }
+ matrix.transform-shear-x(slant)
+ },
+ )
+
+ mark.drawables = drawable.apply-transform(
+ matrix.mul-mat(..t.filter(m => m != none)),
+ mark.drawables
+ )
+
+ return mark
+}
+
+#let _eval-mark-shape-and-anchors(ctx, mark, style) = {
+ if "eval-mark-guard" in ctx {
+ panic("Recursive mark drawing is not allowed")
+ }
+ ctx.eval-mark-guard = true
+
+ ctx.groups = ()
+ ctx.nodes = (:)
+ ctx.transform = matrix.ident(4)
+
+ import "/src/draw.typ"
+ let body = draw.group({
+ draw.set-style(
+ stroke: style.at("stroke", default: none),
+ fill: style.at("fill", default: none),
+ mark: none,
+ line: (mark: none),
+ bezier: (mark: none),
+ arc: (mark: none),
+ )
+ mark
+ }, name: "mark")
+ let (ctx: ctx, bounds: bounds, drawables: drawables) = process.many(ctx, body)
+ let anchor-fn = ctx.nodes.at("mark").anchors
+
+ // Check if the mark has named anchor
+ let has-anchor(name) = {
+ return name in (anchor-fn)(())
+ }
+
+ // Fetch special mark anchors
+ let get-anchor(name, default: none) = {
+ if default != none {
+ if not has-anchor(name) {
+ return default
+ }
+ }
+ return (anchor-fn)(name)
+ }
+
+ let tip = get-anchor("tip", default: (0, 0, 0))
+ let base = get-anchor("base", default: tip)
+ let center = get-anchor("center", default: vector.lerp(tip, base, .5))
+
+ return (
+ tip: tip,
+ base: base,
+ center: center,
+ length: vector.dist(tip, base),
+ drawables: drawables,
+ )
+}
+
+/// Places a mark on the given path. Returns a {{dictionary}} with the following keys:
+/// - drawables (drawable): The mark drawables.
+/// - distance (float): The length to shorten the path by.
+/// - pos (float): The position of the mark, can be used to snap the end of the path to after shortening.
+///
+/// ---
+///
+/// - ctx (context): The canvas context object.
+/// - styles (style): A processed mark styling.
+/// - segments (drawable): The path to place the mark on.
+/// - is-end (bool): TODO
+/// -> dictionary
+#let place-mark-on-path(ctx, styles, segments, is-end: false) = {
+ if type(styles) != array {
+ styles = (styles,)
+ }
+ let distance = 0
+ let shorten-distance = 0
+ let shorten-pos = none
+ let drawables = ()
+ for (i, style) in styles.enumerate() {
+ let is-last = i + 1 == styles.len()
+ if style.symbol == none {
+ continue
+ }
+
+ // Override position, if set
+ if style.pos != none {
+ distance = style.pos
+ }
+
+ // Apply mark offset
+ distance += style.offset
+
+ let (mark-fn, defaults) = get-mark(ctx, style.symbol)
+
+ let merge-flag(style, key, default: false) = {
+ let old = style.at(key)
+ let def = defaults.at(key, default: default)
+ style.insert(key, (old or def) and not (old and def))
+ return style
+ }
+
+ style = merge-flag(style, "reverse")
+ style = merge-flag(style, "flip")
+ style = merge-flag(style, "harpoon")
+
+ let mark = _eval-mark-shape-and-anchors(ctx, mark-fn(style), style)
+
+ let pos = if style.flex {
+ path-util.point-on-path(
+ segments,
+ if distance != 0 {
+ distance * if is-end { -1 } else { 1 }
+ } else {
+ if is-end {
+ 100%
+ } else {
+ 0%
+ }
+ }, extrapolate: true)
+ } else {
+ let (_, dir) = path-util.direction(
+ segments,
+ if is-end {
+ 100%
+ } else {
+ 0%
+ },
+ clamp: true)
+ let pt = if is-end {
+ path-util.segment-end(segments.last())
+ } else {
+ path-util.segment-start(segments.first())
+ }
+ vector.sub(pt, vector.scale(vector.norm(dir), distance * if is-end { 1 } else { -1 }))
+ }
+ assert.ne(pos, none,
+ message: "Could not determine mark position")
+
+ let dir = if style.flex {
+ let a = pos
+ let b = path-util.point-on-path(
+ segments,
+ (mark.length + distance) * if is-end { -1 } else { 1 },
+ samples: style.position-samples,
+ extrapolate: true)
+ if b != none and a != b {
+ vector.sub(b, a)
+ } else {
+ let (_, dir) = path-util.direction(
+ segments,
+ distance,
+ clamp: true)
+ vector.scale(dir, if is-end { -1 } else { 1 })
+ }
+ } else {
+ let (_, dir) = path-util.direction(
+ segments,
+ if is-end {
+ 100%
+ } else {
+ 0%
+ },
+ clamp: true)
+ if dir != none {
+ vector.scale(dir, if is-end { -1 } else { 1 })
+ }
+ }
+ assert.ne(pos, none,
+ message: "Could not determine mark direction")
+
+ mark = transform-mark(
+ style,
+ mark,
+ pos,
+ dir,
+ reverse: style.reverse,
+ slant: style.slant,
+ flip: style.flip,
+ harpoon: style.harpoon,
+ )
+
+ // Shorten path to this mark
+ let inset = mark.at("inset", default: 0)
+ if style.shorten-to != none and (style.shorten-to == auto or i <= style.shorten-to) {
+ let offset = mark.offset
+ inset += offset
+
+ shorten-distance = distance + mark.length - inset
+ shorten-pos = vector.add(pos,
+ vector.scale(vector.norm(dir), mark.length - inset))
+ }
+
+ drawables += mark.drawables
+ distance += mark.length
+
+ // Add separator
+ distance += style.sep
+ }
+
+ return (
+ drawables: drawables,
+ distance: shorten-distance,
+ pos: shorten-pos
+ )
+}
+
+/// Places marks along a path. Returns them as an {{array}} of {{drawable}}.
+///
+/// - ctx (context): The context object.
+/// - style (style): The current mark styling.
+/// - transform (matrix): The current transformation matrix.
+/// - path (drawable): The path to place the marks on.
+/// - add-path (bool): When `true` the shortened path will returned as the first {{drawable}} in the {{array}}
+/// -> array
+#let place-marks-along-path(ctx, style, transform, path, add-path: true) = {
+ let distance = (0, 0)
+ let snap-to = (none, none)
+ let drawables = ()
+
+ if style == none {
+ style = (start: none, end: none, symbol: none)
+ }
+ let both-symbol = style.at("symbol", default: none)
+ let start-symbol = style.at("start",
+ default: both-symbol)
+ if start-symbol == none {
+ start-symbol = both-symbol
+ }
+ let end-symbol = style.at("end",
+ default: both-symbol)
+ if end-symbol == none {
+ end-symbol = both-symbol
+ }
+
+ let (path, is-transformed) = if not style.at("transform-shape", default: true) and transform != none {
+ (drawable.apply-transform(transform, path).first(), true)
+ } else {
+ (path, false)
+ }
+
+ let segments = path.segments
+ if start-symbol != none {
+ let (drawables: start-drawables, distance: start-distance, pos: pt) = place-mark-on-path(
+ ctx,
+ process-style(ctx, style, "start", path-util.length(segments)),
+ segments
+ )
+ drawables += start-drawables
+ distance.first() = start-distance
+ snap-to.first() = pt
+ }
+ if end-symbol != none {
+ let (drawables: end-drawables, distance: end-distance, pos: pt) = place-mark-on-path(
+ ctx,
+ process-style(ctx, style, "end", path-util.length(segments)),
+ segments,
+ is-end: true
+ )
+ drawables += end-drawables
+ distance.last() = end-distance
+ snap-to.last() = pt
+ }
+ if distance != (0, 0) {
+ segments = path-util.shorten-path(
+ segments,
+ ..distance,
+ mode: if style.flex { "CURVED" } else { "LINEAR" },
+ samples: style.position-samples,
+ snap-to: snap-to)
+ }
+
+ if add-path {
+ path.segments = segments
+ drawables.insert(0, path)
+ }
+
+ // If not transformed pre mark placement,
+ // transform everything after mark placement.
+ if not is-transformed {
+ drawables = drawable.apply-transform(transform, drawables)
+ }
+
+ return drawables
+}
diff --git a/render/packages/preview/cetz/0.3.4/src/matrix.typ b/render/packages/preview/cetz/0.3.4/src/matrix.typ
new file mode 100644
index 0000000..1117482
--- /dev/null
+++ b/render/packages/preview/cetz/0.3.4/src/matrix.typ
@@ -0,0 +1,363 @@
+#import "vector.typ"
+
+// Global rounding precision
+#let precision = 8
+
+#let _round = calc.round.with(digits: precision)
+
+#let cos(x) = {
+ _round(calc.cos(x))
+}
+
+#let sin(x) = {
+ _round(calc.sin(x))
+}
+
+#let pi = calc.pi
+
+/// Create a (square) identity matrix with dimensions $size \times size$
+///
+/// - size (int): Size of the matrix
+/// -> matrix
+#let ident(size) = {
+ assert(size >= 1, message: "Invalid dimension")
+
+ range(0, size).map(j => range(0, size).map(k => {
+ if j == k { 1 } else { 0 }
+ }))
+}
+
+/// Create a square matrix with the diagonal set to the
+/// given values
+///
+/// - ..diag (float): Diagonal values
+/// -> matrix
+#let diag(..diag) = {
+ assert(diag.pos().len() >= 1, message: "Invalid dimension")
+ assert.eq(diag.named(), (), messaged: "Unexpected named argument")
+
+ let diag = diag.pos()
+ range(0, diag.len()).map(m => range(0, diag.len()).map(n => {
+ if n == m { diag.at(m) } else { 0 }
+ }))
+}
+
+/// Returns the dimension of the given matrix as `(m, n)`
+/// - m (matrix): The matrix
+/// -> array
+#let dim(m) = {
+ return (m.len(), if m.len() > 0 {m.at(0).len()} else {0})
+}
+
+/// Returns the nth column of a matrix as a {{vector}}
+/// - mat (matrix): Input matrix
+/// - n (int): The column's index
+/// -> vector
+#let column(mat, n) = {
+ range(0, mat.len()).map(m => mat.at(m).at(n))
+}
+
+/// Replaces the nth column of a matrix with the given vector.
+/// - mat (matrix): Input matrix.
+/// - n (int): The index of the column to replace
+/// - vec (vector): The column data to insert.
+/// -> matrix
+#let set-column(mat, n, vec) = {
+ assert(vec.len() == matrix.len())
+ for m in range(0, mat.len()) {
+ mat.at(m).at(n) = vec.at(n)
+ }
+}
+
+/// Rounds each value in the matrix to a precision.
+/// - mat (matrix): Input matrix
+/// - precision (int) = 8: Rounding precision (digits)
+/// -> matrix
+#let round(mat, precision: precision) = {
+ mat.map(r => r.map(v => _round(v, digits: precision)))
+}
+
+/// Returns a $4 \times 4$ translation matrix
+/// - x (float): The translation in the $x$ direction.
+/// - y (float): The translation in the $y$ direction.
+/// - z (float): The translation in the $x$ direction.
+/// -> matrix
+#let transform-translate(x, y, z) = {
+ ((1, 0, 0, x),
+ (0, 1, 0, y),
+ (0, 0, 1, z),
+ (0, 0, 0, 1))
+}
+
+/// Returns a $4 \times 4$ x-shear matrix
+/// - factor (float): The shear in the $x$ direction.
+/// -> matrix
+#let transform-shear-x(factor) = {
+ ((1, factor, 0, 0),
+ (0, 1, 0, 0),
+ (0, 0, 1, 0),
+ (0, 0, 0, 1))
+}
+
+
+/// Returns a $4 \times 4$ z-shear matrix
+/// - factor (float): The shear in the $z$ direction.
+/// -> matrix
+#let transform-shear-z(factor) = {
+ ((1, 0, factor, 0),
+ (0, 1,-factor, 0),
+ (0, 0, 1, 0),
+ (0, 0, 0, 1))
+}
+
+/// Returns a $4 \times 4$ scale matrix
+/// - f (float,array,dictionary): The scale factor(s) of the matrix. An {{array}} of at least 3 {{float}}s sets the x, y and z scale factors. A {{dictionary}} sets the scale in the direction of the corresponding x, y and z keys. A single {{float}} sets the scale for all directions.
+/// -> matrix
+#let transform-scale(f) = {
+ let (x, y, z) = if type(f) == array {
+ vector.as-vec(f, init: (1, 1, 1))
+ } else if type(f) == dictionary {
+ (f.at("x", default: 1),
+ f.at("y", default: 1),
+ f.at("z", default: 1))
+ } else {
+ (f, f, f)
+ }
+ return(
+ (x, 0, 0, 0),
+ (0, y, 0, 0),
+ (0, 0, z, 0),
+ (0, 0, 0, 1))
+}
+
+/// Returns a $4 \times 4$ rotation xyz matrix for a direction and up vector
+/// - dir (vector): idk
+/// - up (vector): idk
+/// -> matrix
+#let transform-rotate-dir(dir, up) = {
+ dir = vector.norm(dir)
+ up = vector.norm(up)
+
+ let (dx, dy, dz) = dir
+ let (ux, uy, uz) = up
+ let (rx, ry, rz) = vector.norm(vector.cross(dir, up))
+
+ ((rx, dx, ux, 0),
+ (ry, dy, uy, 0),
+ (rz, dz, uz, 0),
+ (0, 0, 0, 1))
+}
+
+// Return 4x4 rotate x matrix
+/// Returns a $4 \times 4$ $x$ rotation matrix
+/// - angle (angle): The angle to rotate around the $x$ axis
+/// -> matrix
+#let transform-rotate-x(angle) = {
+ ((1, 0, 0, 0),
+ (0, cos(angle), -sin(angle), 0),
+ (0, sin(angle), cos(angle), 0),
+ (0, 0, 0, 1))
+}
+
+// Return 4x4 rotate y matrix
+/// Returns a $4 \times 4$ $y$ rotation matrix
+/// - angle (angle): The angle to rotate around the $y$ axis
+/// -> matrix
+#let transform-rotate-y(angle) = {
+ ((cos(angle), 0, -sin(angle), 0),
+ (0, 1, 0, 0),
+ (sin(angle), 0, cos(angle), 0),
+ (0, 0, 0, 1))
+}
+
+// Return 4x4 rotate z matrix
+/// Returns a $4 \times 4$ $z$ rotation matrix
+/// - angle (angle): The angle to rotate around the $z$ axis
+/// -> matrix
+#let transform-rotate-z(angle) = {
+ ((cos(angle), -sin(angle), 0, 0),
+ (sin(angle), cos(angle), 0, 0),
+ (0, 0, 1, 0),
+ (0, 0, 0, 1))
+}
+
+// Return 4x4 rotate xz matrix
+/// Returns a $4 \times 4$ $x z$ rotation matrix
+/// - x (angle): The angle to rotate around the $x$ axis
+/// - z (angle): The angle to rotate around the $z$ axis
+/// -> matrix
+#let transform-rotate-xz(x, z) = {
+ ((cos(z), sin(z), 0, 0),
+ (-cos(x)*sin(z), cos(x)*cos(z), -sin(x), 0),
+ (sin(x)*sin(z), -sin(x)*cos(z), cos(x), 1),
+ (0, 0, 0, 1))
+}
+
+/// Returns a $4 \times 4$ rotation matrix - yaw-pitch-roll
+///
+/// Calculates the product of the three rotation matrices
+/// $R = Rz(a) Ry(b) Rx(c)$
+///
+/// - a (angle): Yaw
+/// - b (angle): Pitch
+/// - c (angle): Roll
+/// -> matrix
+#let transform-rotate-ypr(a, b, c) = {
+ ((cos(a)*cos(b), cos(a)*sin(b)*sin(c) - sin(a)*cos(c), cos(a)*sin(b)*cos(c) + sin(a)*sin(c), 0),
+ (sin(a)*cos(b), sin(a)*sin(b)*sin(c) + cos(a)*cos(c), sin(a)*sin(b)*cos(c) - cos(a)*sin(c), 0),
+ (-sin(b), cos(b)*sin(c), cos(b)*cos(c), 1),
+ (0,0,0,1))
+}
+
+/// Returns a $4 \times 4$ rotation matrix - euler angles
+///
+/// Calculates the product of the three rotation matrices
+/// $R = Rz(z) Ry(y) Rx(x)$
+///
+/// - x (angle): Rotation about x
+/// - y (angle): Rotation about y
+/// - z (angle): Rotation about z
+/// -> matrix
+#let transform-rotate-xyz(x, y, z) = {
+ ((cos(y)*cos(z), sin(x)*sin(y)*cos(z) - cos(x)*sin(z), cos(x)*sin(y)*cos(z) + sin(x)*sin(z), 0),
+ (cos(y)*sin(z), sin(x)*sin(y)*sin(z) + cos(x)*cos(z), cos(x)*sin(y)*sin(z) - sin(x)*cos(z), 0),
+ (-sin(y), sin(x)*cos(y), cos(x)*cos(y), 0),
+ (0,0,0,1))
+}
+
+/// Multiplies matrices on top of each other.
+/// - ..matrices (matrix): The matrices to multiply from left to right.
+/// -> matrix
+#let mul-mat(..matrices) = {
+ matrices = matrices.pos()
+ let out = matrices.remove(0)
+ for matrix in matrices {
+ let (m, n, p) = (
+ ..dim(out),
+ dim(matrix).last()
+ )
+ out = (
+ for i in range(m) {
+ (
+ for j in range(p) {
+ (_round(range(n).map(k => out.at(i).at(k) * matrix.at(k).at(j)).sum(), digits: precision),)
+ }
+ ,)
+ }
+ )
+ }
+ return out
+}
+
+// Multiply 4x4 matrix with vector of size 3 or 4.
+// The value of vec_4 defaults to w (1).
+//
+// The resulting vector is of dimension 3
+/// Multiplies a $4 \times 4$ matrix with a vector of size 3 or 4. The resulting is three dimensional
+/// - mat (matrix): The matrix to multiply
+/// - vec (vector): The vector to multiply
+/// - w (float): The default value for the fourth element of the vector if it is three dimensional.
+/// -> vector
+#let mul4x4-vec3(mat, vec, w: 1) = {
+ assert(vec.len() <= 4)
+
+ let x = vec.at(0)
+ let y = vec.at(1)
+ let z = vec.at(2, default: 0)
+ let w = vec.at(3, default: w)
+
+ let ((a1,a2,a3,a4), (b1,b2,b3,b4), (c1,c2,c3,c4), _) = mat
+ return (
+ a1 * x + a2 * y + a3 * z + a4 * w,
+ b1 * x + b2 * y + b3 * z + b4 * w,
+ c1 * x + c2 * y + c3 * z + c4 * w)
+}
+
+// Multiply matrix with vector
+/// Multiplies an $m \times n$ matrix with an $m$th dimensional vector where $m \lte 4$. Prefer the use of `mul4x4-vec3` when possible as it does not use loops.
+/// - mat (matrix): The matrix to multiply
+/// - vec (vector): The vector to multiply
+/// -> vector
+#let mul-vec(mat, vec) = {
+ let m = mat.len()
+ let n = mat.at(0).len()
+ assert(n == vec.len(), message: "Matrix columns must be equal to vector rows")
+
+ let new = (0,) * m
+ for i in range(0, m) {
+ for j in range(0, n) {
+ new.at(i) = new.at(i) + mat.at(i).at(j) * vec.at(j)
+ }
+ }
+ return new
+}
+
+/// Calculates the inverse matrix of any size.
+/// - matrix (matrix): The matrix to inverse.
+/// -> matrix
+#let inverse(matrix) = {
+ let n = {
+ let size = dim(matrix)
+ assert.eq(size.first(), size.last(), message: "Matrix must be square to perform inversion.")
+ size.first()
+ }
+
+ let N = range(n)
+ let inverted = ident(n)
+ let p
+ for j in N {
+ for i in range(j, n) {
+ if matrix.at(i).at(j) != 0 {
+ (matrix.at(j), matrix.at(i)) = (matrix.at(i), matrix.at(j))
+ (inverted.at(j), inverted.at(i)) = (inverted.at(i), inverted.at(j))
+
+ p = 1 / matrix.at(j).at(j)
+ for k in N {
+ matrix.at(j).at(k) *= p
+ inverted.at(j).at(k) *= p
+ }
+
+ for L in N {
+ if L != j {
+ p = -matrix.at(L).at(j)
+ for k in N {
+ matrix.at(L).at(k) += _round(p * matrix.at(j).at(k))
+ inverted.at(L).at(k) += _round(p * inverted.at(j).at(k))
+ }
+ }
+ }
+ }
+ }
+ }
+
+ return inverted
+}
+
+/// Swaps the a-th column with the b-th column.
+///
+/// - mat (matrix): Matrix
+/// - a (int): The index of column a.
+/// - b (int): The index of column b.
+/// -> matrix
+#let swap-cols(mat, a, b) = {
+ let new = mat
+ for m in range(mat.len()) {
+ new.at(m).at(a) = mat.at(m).at(b)
+ new.at(m).at(b) = mat.at(m).at(a)
+ }
+ return new
+}
+
+/// Translates a matrix by a vector.
+/// - mat (matrix): The matrix to translate
+/// - vec (vector): The vector to translate by.
+#let translate(mat, vec) = {
+ return mul-mat(
+ mat,
+ transform-translate(
+ vec.at(0),
+ -vec.at(1),
+ vec.at(2),
+ ),
+ )
+}
diff --git a/render/packages/preview/cetz/0.3.4/src/path-util.typ b/render/packages/preview/cetz/0.3.4/src/path-util.typ
new file mode 100644
index 0000000..886f553
--- /dev/null
+++ b/render/packages/preview/cetz/0.3.4/src/path-util.typ
@@ -0,0 +1,452 @@
+// This file contains utility functions for path calculation
+#import "util.typ"
+#import "vector.typ"
+#import "bezier.typ"
+#import "deps.typ"
+#import deps.oxifmt: strfmt
+
+#let default-samples = 25
+
+/// Returns the first position vector of a path segment.
+///
+/// - s (segment): Path segment
+/// -> vector
+#let segment-start(s) = {
+ return s.at(1)
+}
+
+/// Returns the last position vector of a path segment
+///
+/// - s (segment): Path segment
+/// -> vector
+#let segment-end(s) = {
+ if s.at(0) == "line" {
+ return s.last()
+ }
+ return s.at(2)
+}
+
+/// Calculates the bounding points for a list of path segments
+///
+/// - segments (array): List of path segments
+/// -> array
+#let bounds(segments) = {
+ let bounds = ()
+
+ for s in segments {
+ let (kind, ..pts) = s
+ if kind == "line" {
+ bounds += pts
+ } else if kind == "cubic" {
+ bounds.push(pts.at(0))
+ bounds.push(pts.at(1))
+ bounds += bezier.cubic-extrema(..pts)
+ }
+ }
+ return bounds
+}
+
+/// Calculates the length of a single path segment
+///
+/// - s (array): Path segment
+/// -> float
+#let _segment-length(s, samples: default-samples) = {
+ let (kind, ..pts) = s
+ if kind == "line" {
+ let len = 0
+ for i in range(1, pts.len()) {
+ len += vector.len(vector.sub(pts.at(i - 1), pts.at(i)))
+ }
+ return len
+ } else if kind == "cubic" {
+ return bezier.cubic-arclen(..pts, samples: samples)
+ } else {
+ panic("Invalid segment: " + kind, s)
+ }
+}
+
+/// Calculates the length of a path
+///
+/// - segments (array): List of path segments
+/// -> float
+#let length(segments) = {
+ return segments.map(_segment-length).sum()
+}
+
+/// Finds the two points that enclose a distance along a line segment.
+///
+/// Returns a {{dictionary}} with the following key values:
+/// - start (int): The index of the point that is before the distance.
+/// - end (int): The index of the point that is after the distance.
+/// - distance (float): The distance along the line segment to the point with the `start` index.
+/// - length (float): The distance between the found points.
+///
+/// ---
+///
+/// - pts (array): The array of points of a line segment.
+/// - distance (float): The distance along the line segment.
+/// -> dictionary
+#let _points-between-distance(pts, distance) = {
+ let travelled = 0
+ let length = 0
+ for i in range(1, pts.len()) {
+ length = vector.dist(pts.at(i - 1), pts.at(i))
+ if travelled <= distance and distance <= travelled + length {
+ return (
+ start: i - 1,
+ end: i,
+ distance: distance - travelled,
+ length: length
+ )
+ }
+ travelled += length
+ }
+ return (
+ start: pts.len() - 2,
+ end: pts.len() - 1,
+ distance: length,
+ length: length
+ )
+}
+
+/// Finds the point at a given distance from the start of a line segment. Distances greater than the length of the segment return the end of the line segment. Distances less than zero return the start of the segment.
+///
+/// - segment (array): The line segment
+/// - distance (float): The distance along the line segment to find the point
+/// -> vector
+#let _point-on-line-segment(segment, distance) = {
+ let pts = segment.slice(1)
+
+ let (start, end, distance, length) = _points-between-distance(pts, distance)
+ return if length == 0 {
+ // length can be zero if start and end are at the same position
+ // this can occur for several reasons, user input, group has zero width or height (not both)
+ pts.at(end)
+ } else {
+ vector.lerp(pts.at(start), pts.at(end), distance / length)
+ }
+}
+
+/// Finds the point at a given distance from the start of a path segment. Distances greater than the length of the segment return the end of the path segment. Distances less than zero return the start of the segment.
+///
+/// - segment (segment): Path segment
+/// - distance (float): The distance along the path segment to find the point
+/// - extrapolate (bool): If true, use linear extrapolation for distances outsides the path
+/// -> vector
+#let _point-on-segment(segment, distance, samples: default-samples, extrapolate: false) = {
+ let (kind, ..pts) = segment
+ if kind == "line" {
+ return _point-on-line-segment(segment, distance)
+ } else if kind == "cubic" {
+ return bezier.cubic-point(
+ ..pts,
+ bezier.cubic-t-for-distance(
+ ..pts,
+ distance,
+ samples: samples
+ )
+ )
+ }
+}
+
+/// Finds the segment that contains a point that is distance `t` from the start of a path.
+/// - segments (array): The array of segments that make up the path.
+/// - t (float,ratio): The distance to find the segment with. A {{float}} will be in absolute distance along the path. A {{ratio}} will be relative to the length of the path. Will panic if the distance is greater than the length of the path.
+/// - rev (bool): When true the path will be reversed, effectively looking for the segment from the end of the path.
+/// - samples (int): The number of samples to use when calculating the length of a cubic segment.
+/// - clamp (bool): Clamps the distance to the length of the path, so the function won't panic.
+/// -> dictionary
+/// ---
+/// Returns a {{dictionary}} with the folloing key-value pairs:
+/// - index (int): The index of the segment in the given array of segments.
+/// - segment (segment): The found segment.
+/// - travelled (float): The absolute distance travelled along the path to find the segment.
+/// - distance (float): The distance left to travel along the path.
+/// - length (float): The length of the returned segment.
+#let segment-at-t(segments, t, rev: false, samples: default-samples, clamp: false) = {
+ let lengths = segments.map(_segment-length.with(samples: samples))
+ let total = lengths.sum()
+
+ if type(t) == ratio {
+ t = total * t / 100%
+ }
+ if not clamp {
+ assert(t >= 0 and t <= total,
+ message: strfmt("t is expected to be between 0 and the length of the path ({}), got: {}", total, t))
+ }
+
+ if rev {
+ segments = segments.rev()
+ lengths = lengths.rev()
+ }
+ let travelled = 0
+ for (i, segment-length) in segments.zip(lengths).enumerate() {
+ let (segment, length) = segment-length
+ if travelled <= t and t <= travelled + length {
+ return (
+ index: if rev { segments.len() - i } else { i },
+ segment: segment,
+ // Distance travelled
+ travelled: travelled,
+ // Distance left
+ distance: t - travelled,
+ // The length of the segment
+ length: length
+ )
+ }
+ travelled += length
+ }
+ return (index: if rev { 0 } else { segments.len() - 1 },
+ segment: segments.last(),
+ travelled: total,
+ distance: t,
+ length: lengths.last())
+}
+
+/// Extrapolates a point from a segment. It finds the direction the end of the segment is pointing and scales the normalised vector from the end of the segment. Returns {{none}} if the segment has no direction.
+/// - segment (segment): The segment to extrapolate from.
+/// - distance (float): The distance to extrapolate the point to.
+/// - rev (bool): If `true` the segment will be reversed, effectively extrapolating the point from its start.
+/// - samples (int): This isn't used.
+#let _extrapolated-point-on-segment(segment, distance, rev: false, samples: 100) = {
+ let (kind, ..pts) = segment
+ let (pt, dir) = if kind == "line" {
+ let (a, b) = if rev {
+ (pts.at(0), pts.at(1))
+ } else {
+ (pts.at(-2), pts.at(-1))
+ }
+ (if rev {a} else {b}, vector.sub(b, a))
+ } else {
+ let dir = bezier.cubic-derivative(..pts, if rev { 0 } else { 1 })
+ if vector.len(dir) == 0 {
+ dir = vector.sub(pts.at(1), pts.at(0))
+ }
+ (if rev {pts.at(0)} else {pts.at(1)}, dir)
+ }
+
+ if vector.len(dir) != 0 {
+ return vector.add(pt, vector.scale(vector.norm(dir), distance * if rev { -1 } else { 1 }))
+ }
+ return none
+}
+
+/// Finds the position of a point a distance from the start of a path. If the path is empty {{none}} will be returned.
+///
+/// - segments (array): List of path segments
+/// - t (int,float,ratio): Absolute position on the path if given an float or integer, or relative position if given a ratio from 0% to 100%. When this value is negative, the point will be found from the end of the path instaed of the start.
+/// - extrapolate (bool): If true, use linear extrapolation if distance is outsides the path's range
+/// -> none,vector
+#let point-on-path(segments, t, samples: default-samples, extrapolate: false) = {
+ assert(
+ type(t) in (int, float, ratio),
+ message: "Distance t must be of type int, float or ratio"
+ )
+ let rev = if type(t) == ratio and t < 0% or type(t) in (int, float) and t < 0 {
+ true
+ } else {
+ false
+ }
+ if rev {
+ t *= -1
+ }
+
+ // Extrapolate at path boundaries if enabled
+ if extrapolate {
+ let total = length(segments)
+ let absolute-t = if type(t) == ratio { t / 100% * total } else { t }
+ if absolute-t > total {
+ return _extrapolated-point-on-segment(segments.first(), absolute-t - total, rev: rev, samples: samples)
+ }
+ }
+
+ let segment = segment-at-t(segments, t, samples: samples, rev: rev)
+ return if segment != none {
+ let (distance, segment, length, ..) = segment
+ _point-on-segment(segment, if rev { length - distance } else { distance }, samples: samples, extrapolate: extrapolate)
+ }
+}
+
+/// Finds the position and direction of a point a distance along from the start of a path. Returns an {{array}} of two vectors where the first is the position, and the second is the direction.
+///
+/// - segments (array): List of path segments
+/// - t (int,float,ratio): Absolute position on the path if given an float or integer, or relative position if given a ratio from 0% to 100%. When this value is negative, the point will be found from the end of the path instaed of the start.
+/// - extrapolate (bool): If true, use linear extrapolation if distance is outsides the path's range
+/// - clamp (bool): Clamps the distance between the start and end of a path.
+/// -> array
+#let direction(segments, t, samples: default-samples, clamp: false) = {
+ let (segment, distance, length, ..) = segment-at-t(segments, t, samples: samples, clamp: clamp)
+ let (kind, ..pts) = segment
+ return (
+ _point-on-segment(segment, distance, samples: samples),
+ if kind == "line" {
+ let (start, end, distance, length) = _points-between-distance(pts, distance)
+ vector.norm(vector.sub(segment.at(end+1), segment.at(start+1)))
+ } else {
+ let t = bezier.cubic-t-for-distance(..pts, distance, samples: samples)
+ let dir = bezier.cubic-derivative(..pts, t)
+ if vector.len(dir) == 0 {
+ vector.norm(vector.sub(pts.at(1), pts.at(0)))
+ } else {
+ dir
+ }
+ }
+ )
+}
+
+/// Creates a line segment with points
+///
+/// - points (array): List of points
+/// -> segment
+#let line-segment(points) = {
+ ("line",) + points
+}
+
+/// Creates a cubic bezier segment
+///
+/// - a (vector): Start
+/// - b (vector): End
+/// - ctrl-a (vector): Control point a
+/// - ctrl-b (vector): Control point b
+/// -> segment
+#let cubic-segment(a, b, ctrl-a, ctrl-b) = {
+ ("cubic", a, b, ctrl-a, ctrl-b)
+}
+
+/// Normalize segments by connecting gaps via straight line segments and merging multiple line segments into a single one.
+///
+/// - segments (array): The path segments to normalize.
+/// -> array
+#let normalize(segments) = {
+ let new = ()
+ for s in segments {
+ if new == () {
+ new.push(s)
+ } else {
+ let head = new.last()
+ let (kind, ..pts) = s
+
+ if kind == "line" and head.at(0) == kind {
+ // Merge consecutive line segments
+ if new.last().len() > 0 and new.last().last() == pts.first() {
+ new.last() += pts.slice(1)
+ } else {
+ new.last() += pts
+ }
+ } else if segment-start(s) != segment-end(head) {
+ // Push a new line or line point if the current segment
+ // does not start where the previous segment ended
+ if head.at(0) == "line" {
+ new.last().push(pts.first())
+ } else {
+ new.push(line-segment((segment-end(head), segment-start(s))))
+ }
+ // Push the segment
+ new.push(s)
+ } else {
+ new.push(s)
+ }
+ }
+ }
+ return new
+}
+
+/// Shortens a segment by a given distance.
+/// - segment (segment): The segment to shorten.
+/// - distance (float): The distance to move the start of the segment towards the end of the segment. If this value is negative, the end of the segment will be moved towards the start.
+/// - snap-to (none, vector): Shortening bezier curves suffers from rounding and precision errors so a position can be given to "snap" a curve's start/end point to.
+/// - mode (str): How cubic segments should be shortned. Can be `"LINEAR"` to use `bezier.cubic-shorten-linear` or `"CURVED"` to use `bezier.cubic-shorten`.
+/// - samples (int): The number of samples to use when shortening a cubic segment.
+/// -> segment
+#let shorten-segment(segment, distance, snap-to: none, mode: "CURVED", samples: default-samples) = {
+ let rev = distance < 0
+ if distance >= _segment-length(segment) {
+ return line-segment(if rev {
+ (segment-start(segment), segment-start(segment))
+ } else {
+ (segment-end(segment), segment-end(segment))
+ })
+ }
+
+ let (kind, ..s) = segment
+ if kind == "line" {
+ if rev {
+ distance *= -1
+ s = s.rev()
+ }
+ let (start, end, distance, length) = _points-between-distance(s, distance)
+ if length != 0 {
+ s = (vector.lerp(s.at(start), s.at(end), distance / length),) + s.slice(end)
+ }
+
+ if rev {
+ s = s.rev()
+ }
+ } else {
+ s = if mode == "LINEAR" {
+ bezier.cubic-shorten-linear(..s, distance)
+ } else {
+ bezier.cubic-shorten(..s, distance, samples: samples)
+ }
+
+ // Shortening beziers suffers from rounding or precision errors
+ // so we "snap" the curve start/end to the snap-points, if provided.
+ if snap-to != none {
+ if rev { s.at(1) = snap-to } else { s.at(0) = snap-to }
+ }
+ }
+ return (kind,) + s
+}
+
+/// Shortens a path's segments by the given distances. The start of the path is shortened first by moving the point along the path towards the end. The end of the path is then shortened in the same way. When a distance is 0 no other calculations are made.
+///
+/// - segments (segments): The segments of the path to shorten.
+/// - start-distance (int, float): The distance to shorten from the start of the path.
+/// - end-distance (int, float): The distance to shorten from the end of the path
+/// - pos (none, tuple): Tuple of points to "snap" the path ends to
+/// -> segments Segments of the path that have been shortened
+#let shorten-path(segments, start-distance, end-distance, snap-to: none, mode: "CURVED", samples: default-samples) = {
+ let total = length(segments)
+ let (snap-start, snap-end) = if snap-to == none {
+ (none, none)
+ } else {
+ snap-to
+ }
+
+ if start-distance > 0 {
+ let (segment, distance, index, ..) = segment-at-t(
+ segments,
+ start-distance,
+ clamp: true,
+ )
+ segments = segments.slice(index + 1)
+ segments.insert(0,
+ shorten-segment(
+ segment,
+ distance,
+ mode: mode,
+ samples: samples,
+ snap-to: snap-start
+ )
+ )
+ }
+ if end-distance > 0 {
+ let (segment, distance, index, ..) = segment-at-t(
+ segments,
+ end-distance,
+ rev: true,
+ clamp: true,
+ )
+ segments = segments.slice(0, index - 1)
+ segments.push(
+ shorten-segment(
+ segment,
+ -distance,
+ mode: mode,
+ samples: samples,
+ snap-to: snap-end
+ )
+ )
+ }
+ return segments
+}
diff --git a/render/packages/preview/cetz/0.3.4/src/polygon.typ b/render/packages/preview/cetz/0.3.4/src/polygon.typ
new file mode 100644
index 0000000..fa25241
--- /dev/null
+++ b/render/packages/preview/cetz/0.3.4/src/polygon.typ
@@ -0,0 +1,108 @@
+#import "/src/vector.typ"
+
+/// Returns a list of polygon points from
+/// a list of segments.
+///
+/// Cubic segments get linearized by sampling.
+///
+/// - segment (array): List of segments
+/// - samples (int): Number of samples
+/// -> array
+#let from-segments(segments, samples: 10) = {
+ import "/src/bezier.typ": cubic-point
+ let poly = ()
+ for ((kind, ..pts)) in segments {
+ if kind == "cubic" {
+ poly += range(0, samples).map(t => {
+ cubic-point(..pts, t / (samples - 1))
+ })
+ } else {
+ poly += pts
+ }
+ }
+ return poly
+}
+
+/// Computes the signed area of a 2D polygon.
+///
+/// The formula used is the following:
+/// $ 1/2 \sum_{i}=0^{n-1} x_i*y_i+1 - x_i+1*y_i $
+///
+/// - points (array): List of Vectors of dimension >= 2
+/// -> float
+#let signed-area(points) = {
+ let a = 0
+ let n = points.len()
+ let (cx, cy) = (0, 0)
+ for i in range(0, n) {
+ let (x0, y0, ..) = points.at(i)
+ let (x1, y1, ..) = points.at(calc.rem(i + 1, n))
+ cx += (x0 + x1) * (x0 * y1 - x1 * y0)
+ cy += (y0 + y1) * (x0 * y1 - x1 * y0)
+ a += x0 * y1 - x1 * y0
+ }
+ return .5 * a
+}
+
+/// Returns the winding order of a 2D polygon
+/// by using it's signed area.
+///
+/// Returns either "ccw" (counter clock-wise) or "cw" (clock-wise) or none.
+///
+/// - point (array): List of polygon points
+/// -> str,none
+#let winding-order(points) = {
+ let area = signed-area(points)
+ if area > 0 {
+ "cw"
+ } else if area < 0 {
+ "ccw"
+ } else {
+ none
+ }
+}
+
+// Calculate triangle centroid
+#let triangle-centroid(points) = {
+ assert.eq(points.len(), 3)
+
+ let (mx, my, mz) = (0, 0, 0)
+ for p in points {
+ let (x, y, z) = p
+ mx += x
+ my += y
+ mz += z
+ }
+ return (mx / 3, my / 3, mz / 3)
+}
+
+// Calculate the centroid of a line, triangle or simple polygon
+// Formulas:
+// https://en.wikipedia.org/wiki/Centroid
+#let simple-centroid(points) = {
+ return if points.len() <= 1 {
+ none
+ } else if points.len() == 2 {
+ vector.lerp(..points, .5)
+ } else if points.len() == 3 {
+ triangle-centroid(points)
+ } else if points.len() >= 3 {
+ // Skip polygons with multiple z values
+ let z = points.first().at(2, default: 0)
+ if points.any(p => p.at(2) != z) {
+ return none
+ }
+
+ let a = 0
+ let n = points.len()
+ let (cx, cy) = (0, 0)
+ for i in range(0, n) {
+ let (x0, y0, ..) = points.at(i)
+ let (x1, y1, ..) = points.at(calc.rem(i + 1, n))
+ cx += (x0 + x1) * (x0 * y1 - x1 * y0)
+ cy += (y0 + y1) * (x0 * y1 - x1 * y0)
+ a += x0 * y1 - x1 * y0
+ }
+ return (cx/(3*a), cy/(3*a), z)
+ }
+}
diff --git a/render/packages/preview/cetz/0.3.4/src/process.typ b/render/packages/preview/cetz/0.3.4/src/process.typ
new file mode 100644
index 0000000..47ffb41
--- /dev/null
+++ b/render/packages/preview/cetz/0.3.4/src/process.typ
@@ -0,0 +1,91 @@
+#import "util.typ"
+#import "path-util.typ"
+#import "aabb.typ"
+#import "drawable.typ"
+#import "vector.typ"
+
+
+/// Processes an element's function to get its drawables and bounds. Returns a {{dictionary}} with the key-values: `ctx` The modified context object, `bounds` The {{aabb}} of the element's drawables, `drawables` An {{array}} of the element's {{drawable}}s.
+///
+/// - ctx (ctx): The current context object.
+/// - element-func (function): A function that when passed {{ctx}}, it should return an element dictionary.
+#let element(ctx, element-func) = {
+ let bounds = none
+ let element
+ let anchors = (:)
+
+ (ctx, ..element,) = element-func(ctx)
+ if "drawables" in element {
+ if type(element.drawables) == dictionary {
+ element.drawables = (element.drawables,)
+ }
+ for drawable in element.drawables {
+ if drawable.bounds {
+ bounds = aabb.aabb(
+ if drawable.type == "path" {
+ path-util.bounds(drawable.segments)
+ } else if drawable.type == "content" {
+ let (x, y, _, w, h,) = drawable.pos + (drawable.width, drawable.height)
+ ((x + w / 2, y - h / 2, 0), (x - w / 2, y + h / 2, 0))
+ },
+ init: bounds
+ )
+ }
+ }
+ }
+
+ let name = element.at("name", default: none)
+ if name != none {
+ assert.eq(type(name), str,
+ message: "Element name must be a string")
+ assert(not name.contains("."),
+ message: "Invalid name for element '" + element.name + "'; name must not contain '.'")
+
+ if "anchors" in element {
+ ctx.nodes.insert(name, element)
+ if ctx.groups.len() > 0 {
+ ctx.groups.last().push(name)
+ }
+ }
+ }
+
+ if ctx.debug and bounds != none {
+ element.drawables.push(drawable.path(
+ path-util.line-segment((
+ bounds.low,
+ (bounds.high.at(0), bounds.low.at(1), 0),
+ bounds.high,
+ (bounds.low.at(0), bounds.high.at(1), 0)
+ )),
+ stroke: red,
+ close: true
+ ))
+ }
+
+ return (
+ ctx: ctx,
+ bounds: bounds,
+ drawables: element.at("drawables", default: ()),
+ )
+}
+
+/// Runs the `element` function for a list of element functions and aggregates the results.
+/// - ctx (ctx): The current context object.
+/// - body (array): The array of element functions to process.
+/// -> dictionary
+#let many(ctx, body) = {
+ let drawables = ()
+ let bounds = none
+
+ for el in body {
+ let r = element(ctx, el)
+ if r != none {
+ if r.bounds != none {
+ bounds = aabb.aabb(r.bounds, init: bounds)
+ }
+ ctx = r.ctx
+ drawables += r.drawables
+ }
+ }
+ return (ctx: ctx, bounds: bounds, drawables: drawables)
+}
diff --git a/render/packages/preview/cetz/0.3.4/src/sorting.typ b/render/packages/preview/cetz/0.3.4/src/sorting.typ
new file mode 100644
index 0000000..3778b8c
--- /dev/null
+++ b/render/packages/preview/cetz/0.3.4/src/sorting.typ
@@ -0,0 +1,29 @@
+#import "/src/vector.typ"
+#import "/src/util.typ"
+
+/// Sort list of points by distance to a
+/// reference point.
+///
+/// - points (array): List of points to sort
+/// - reference (vec): Reference point
+/// -> List of points
+#let points-by-distance(ctx, points, reference: (0, 0, 0)) = {
+ let reference = util.apply-transform(ctx.transform, reference)
+ return points.sorted(key: pt => {
+ vector.dist(pt, reference)
+ })
+}
+
+/// Sort list of 2D points by angle to a
+/// reference 2D point in CCW order.
+/// Z component is ignored.
+///
+/// - points (array): List of points to sort
+/// - reference (vec): Reference point
+/// -> List of points
+#let points-by-angle(ctx, points, reference: (0, 0, 0)) = {
+ let (rx, ry, ..) = util.apply-transform(ctx.transform, reference)
+ return points.sorted(key: ((px, py, ..)) => {
+ 360deg - calc.atan2(rx - px, ry - py)
+ })
+}
diff --git a/render/packages/preview/cetz/0.3.4/src/styles.typ b/render/packages/preview/cetz/0.3.4/src/styles.typ
new file mode 100644
index 0000000..a64a8fd
--- /dev/null
+++ b/render/packages/preview/cetz/0.3.4/src/styles.typ
@@ -0,0 +1,232 @@
+#import "util.typ"
+
+#let default = (
+ fill: none,
+ fill-rule: "non-zero",
+ stroke: black + 1pt,
+ radius: 1,
+ /// Bezier shortening mode:
+ /// - "LINEAR" Moving the affected point and it's next control point (like TikZ "quick" key)
+ /// - "CURVED" Preserving the bezier curve by calculating new control points
+ shorten: "LINEAR",
+
+ // Allowed values:
+ // - none
+ // - Number
+ // - Array: (y, x), (top, y, bottom), (top, right, bottom, left)
+ // - Dictionary: (top:, right:, bottom:, left:)
+ padding: none,
+ mark: (
+ scale: 1, // A factor that is applied to length, width, and inset.
+ length: .2cm, // The size of the mark along its direction
+ width: 0.15cm, // The size of the mark along the normal of its direction
+ inset: .05cm, // The inner length of some mark shapes, like triangles and brackets
+ sep: .1cm, // The distance between multiple marks along their path
+ pos: none, // Position override on the path (none, number or path-length ratio)
+ offset: 0, // Mark extra offset (number or path-length ratio)
+ start: none, // Mark start symbol(s)
+ end: none, // Mark end symbol(s)
+ symbol: none, // Mark symbol
+ xy-up: (0, 0, 1), // Up vector for 2D marks
+ z-up: (0, 1, 0), // Up vector for 3D marks
+ stroke: auto,
+ fill: auto,
+ slant: none, // Slant factor - 0%: no slant, 100%: 45 degree slant
+ harpoon: false,
+ flip: false,
+ reverse: false,
+ /// If false, the mark points in the direction of the paths start/end direction.
+ /// Curved paths get shortened linearly.
+ flex: true,
+ /// Max. number of samples to use for calculating curve positions
+ /// a higher number gives better results but may slow down compilation.
+ position-samples: 30,
+ /// Index of the mark the path should get shortened to, or auto
+ /// to shorten to the last mark. To apply different values per side,
+ /// set the default to `0` and to `auto` for the mark you want to
+ /// shorten the path to. Set to `none` to disable path shortening.
+ shorten-to: auto,
+ /// Apply shape transforms for marks. This is not honored per mark, but
+ /// for all marks on a path. If set to false, marks get placed after the
+ /// shape they are placed on got transformed.
+ transform-shape: true,
+ /// Mark anchor used for placement
+ /// Possible values are:
+ /// - "tip"
+ /// - "center"
+ /// - "base"
+ anchor: "tip",
+ ),
+ circle: (
+ radius: auto,
+ stroke: auto,
+ fill: auto
+ ),
+ group: (
+ padding: auto,
+ fill: auto,
+ stroke: auto
+ ),
+ line: (
+ mark: auto,
+ fill: auto,
+ fill-rule: auto,
+ stroke: auto,
+ ),
+ bezier: (
+ stroke: auto,
+ fill: auto,
+ fill-rule: auto,
+ mark: auto,
+ shorten: auto,
+ ),
+ catmull: (
+ tension: .5,
+ mark: auto,
+ shorten: auto,
+ stroke: auto,
+ fill: auto,
+ fill-rule: auto,
+ ),
+ hobby: (
+ /// Curve start and end omega (curlyness)
+ omega: (0,0),
+ mark: auto,
+ shorten: auto,
+ stroke: auto,
+ fill: auto,
+ fill-rule: auto,
+ ),
+ rect: (
+ /// Rect corner radius that supports the following types:
+ /// - <radius>: Same x and y radius for all corners
+ /// - (west: <radius>, east: <radius>, north: <radius>, south: <radius>,
+ /// north-west: <radius>, north-east: <radius>, south-west: <radius>, south-east: <radius>,
+ /// rest: <radius: 0>)
+ ///
+ /// A radius can be either a number, a ratio or a tuple of numbers or ratios.
+ /// Ratios represent a value relative to the rects height or width.
+ /// E.g. the radius `50%` is equal to `(50%, 50%)` and represents a x and y radius
+ /// of 50% of the rects width/height.
+ radius: 0,
+ stroke: auto,
+ fill: auto,
+ ),
+ arc: (
+ // Supported values:
+ // - "OPEN"
+ // - "CLOSE"
+ // - "PIE"
+ mode: "OPEN",
+ update-position: true,
+ mark: auto,
+ stroke: auto,
+ fill: auto,
+ radius: auto
+ ),
+ polygon: (
+ radius: auto,
+ stroke: auto,
+ fill: auto,
+ ),
+ content: (
+ padding: auto,
+ // Supported values
+ // - none
+ // - "rect"
+ // - "circle"
+ frame: none,
+ fill: auto,
+ stroke: auto,
+ // Apply canvas scaling to content
+ auto-scale: false,
+ ),
+)
+
+/// You can use this to combine the style in `ctx`, the style given by a user for a single element and an element's default style.
+///
+/// `base` is first merged onto `dict` without overwriting existing values, and if `root` is given it is merged onto that key of `dict`. `merge` is then merged onto `dict` but does overwrite existing entries, if `root` is given it is merged onto that key of `dict`. Then entries in `dict` that are {{auto}} inherit values from their nearest ancestor and entries of type {{dictionary}} are merged with their closest ancestor.
+/// ```typ example
+/// #let dict = (
+/// stroke: "black",
+/// fill: none,
+/// mark: (stroke: auto, fill: "blue"),
+/// line: (stroke: auto, mark: auto, fill: "red")
+/// )
+/// #cetz.styles.resolve(dict, merge: (mark: (stroke: "yellow")), root: "line")
+/// ```
+/// The following is a more detailed explanation of how the algorithm works to use as a reference if needed. It should be updated whenever changes are made.
+/// Remember that dictionaries are recursively merged, if an entry is any other type it is simply updated. (dict + dict = merged dict, value + dict = dict, dict + value = value)
+/// First if `base` is given, it will be merged without overwriting values onto `dict`. If `root` is given it will be merged onto that key of `dict`.
+/// Each level of `dict` is then processed with these steps. If `root` is given the level with that key will be the first, otherwise the whole of `dict` is processed.
+/// + Values on the corresponding level of `merge` are inserted into the level if the key does not exist on the level or if they are not both dictionaries. If they are both dictionaries their values will be inserted in the same stage at a lower level.
+/// + If an entry is `auto` or a dictionary, the tree is travelled back up until an entry with the same key is found. If the current entry is `auto` the value of the ancestor's entry is copied. Or if the current entry and ancestor entry is a dictionary, they are merged with the current entry overwriting any values in it's ancestors.
+/// + Each entry that is a dictionary is then resolved from step 1.
+///
+/// ```typc example
+/// get-ctx(ctx => {
+/// // Get the current "mark" style
+/// content((0,0), [#cetz.styles.resolve(ctx.style, root: "mark")])
+/// })
+/// ```
+///
+/// - dict (style): Current context style from `ctx.style`.
+/// - merge (style): Style values overwriting the current style. I.e. inline styles passed with an element: `line(.., stroke: red)`.
+/// - root (none, str): Style root element name.
+/// - base (none, style): Style values to merge into `dict` without overwriting it.
+/// -> style
+#let resolve(dict, root: none, merge: (:), base: (:)) = {
+ let resolve(dict, ancestors, merge) = {
+ // Merge. If both values are dictionaries, merge's values will be inserted at a lower level in this step.
+ for (k, v) in merge {
+ if k not in dict or not (type(v) == dictionary and type(dict.at(k)) == dictionary) {
+ dict.insert(k, v)
+ }
+ }
+
+ // For each entry that is a dictionary or `auto`, travel back up the tree until it finds an entry with the same key.
+ for (k, v) in dict {
+ let is-dict = type(v) == dictionary
+ if is-dict or v == auto {
+ for ancestor in ancestors {
+ if k in ancestor {
+ // If v is auto and the ancestor's value is not auto, update v.
+ if ancestor.at(k) != auto and v == auto {
+ v = ancestor.at(k)
+ // If both values are dictionaries, merge them. Values in v overwrite its ancestor's value.
+ } else if is-dict and type(ancestor.at(k)) == dictionary {
+ v = util.merge-dictionary(ancestor.at(k), v)
+ }
+ // Retain the updated value. Because all of the ancestors have already been processed even if a v is still auto that just means the key at the highest level either is auto or doesn't exist.
+ dict.insert(k, v)
+ break
+ }
+ }
+ }
+ }
+
+ // Record history here so it doesn't change.
+ ancestors = (dict,) + ancestors
+ // Because only keys on this level have been processed, process all children of this level.
+ for (k, v) in dict {
+ if type(v) == dictionary {
+ dict.insert(k, resolve(v, ancestors, merge.at(k, default: (:))))
+ }
+ }
+ return dict
+ }
+
+ if base != (:) {
+ if root != none {
+ let a = (:)
+ a.insert(root, base)
+ base = a
+ }
+ dict = util.merge-dictionary(dict, base, overwrite: false)
+ }
+ return resolve(
+ if root != none { dict.at(root) } else { dict },
+ if root != none {(dict,)} else {()},
+ merge
+ )
+}
diff --git a/render/packages/preview/cetz/0.3.4/src/util.typ b/render/packages/preview/cetz/0.3.4/src/util.typ
new file mode 100644
index 0000000..2b4175f
--- /dev/null
+++ b/render/packages/preview/cetz/0.3.4/src/util.typ
@@ -0,0 +1,401 @@
+#import "deps.typ"
+#import deps.oxifmt: strfmt
+
+#import "matrix.typ"
+#import "vector.typ"
+#import "bezier.typ"
+
+/// Constant to be used as float rounding error
+#let float-epsilon = 0.000001
+
+/// Multiplies vectors by a transformation matrix. If multiple vectors are given they are returned as an array, if only one vector is given only one will be returned, if a dictionary is given they will be returned in the dictionary with the same keys.
+///
+/// - transform (matrix,function): The $4 \times 4$ transformation matrix or a function that accepts and returns a vector.
+/// - ..vecs (vector): Vectors to get transformed. Only the positional part of the sink is used. A dictionary of vectors can also be passed and all will be transformed.
+/// -> vector,array,dictionary
+#let apply-transform(transform, ..vecs) = {
+ let t = if type(transform) != function {
+ matrix.mul4x4-vec3.with(transform)
+ } else {
+ transform
+ }
+ if type(vecs.pos().first()) == dictionary {
+ vecs = vecs.pos().first()
+ for (k, vec) in vecs {
+ vecs.insert(k, t(vec))
+ }
+ } else {
+ vecs = vecs.pos().map(t)
+ if vecs.len() == 1 {
+ return vecs.first()
+ }
+ }
+ return vecs
+}
+
+/// Reverts the transform of the given vector
+///
+/// - transform (matrix): Transformation matrix
+/// - vec (vector): Vector to be transformed
+/// -> vector
+#let revert-transform(transform, ..vecs) = {
+ apply-transform(matrix.inverse(transform), ..vecs)
+}
+
+/// Linearly interpolates between two points and returns its position
+///
+/// - a (vector): Start point
+/// - b (vector): End point
+/// - t (float): Position on the line $[0, 1]$
+/// -> vector
+#let line-pt(a, b, t) = {
+ return vector.add(a, vector.scale(vector.sub(b, a), t))
+}
+
+/// Get orthogonal vector to line
+///
+/// - a (vector): Start point
+/// - b (vector): End point
+/// -> vector
+#let line-normal(a, b) = {
+ let v = vector.norm(vector.sub(b, a))
+ return (0 - v.at(1), v.at(0), v.at(2, default: 0))
+}
+
+/// Calculates the arc-length of a circle or arc
+///
+/// - radius (float): Circle or arc radius
+/// - angle (angle): The angle of the arc.
+/// -> float
+#let circle-arclen(radius, angle: 360deg) = {
+ calc.abs(angle / 360deg * 2 * calc.pi)
+}
+
+/// Get point on an ellipse for an angle
+///
+/// - center (vector): Center
+/// - radius (float,array): Radius or tuple of x/y radii
+/// - angled (angle): Angle to get the point at
+/// -> vector
+#let ellipse-point(center, radius, angle) = {
+ let (rx, ry) = if type(radius) == array {
+ radius
+ } else {
+ (radius, radius)
+ }
+
+ let (x, y, z) = center
+ return (calc.cos(angle) * rx + x, calc.sin(angle) * ry + y, z)
+}
+
+/// Calculates the center of a circle from 3 points. The z coordinate is taken from point a.
+///
+/// - a (vector): Point 1
+/// - b (vector): Point 2
+/// - c (vector): Point 3
+/// -> vector
+#let calculate-circle-center-3pt(a, b, c) = {
+ let m-ab = line-pt(a, b, .5)
+ let m-bc = line-pt(b, c, .5)
+ let m-cd = line-pt(c, a, .5)
+
+ let args = () // a, c, b, d
+ for i in range(0, 3) {
+ let (p1, p2) = ((a,b,c).at(calc.rem(i,3)),
+ (b,c,a).at(calc.rem(i,3)))
+ let m = line-pt(p1, p2, .5)
+ let n = line-normal(p1, p2)
+
+ // Find a line with a non upwards normal
+ if n.at(0) == 0 { continue }
+
+ let la = n.at(1) / n.at(0)
+ args.push(la)
+ args.push(m.at(1) - la * m.at(0))
+
+ // We need only 2 lines
+ if args.len() == 4 { break }
+ }
+
+ // Find intersection point of two 2d lines
+ // L1: a*x + c
+ // L2: b*x + d
+ let line-intersection-2d(a, c, b, d) = {
+ if a - b == 0 {
+ if c == d {
+ return (0, c, 0)
+ }
+ return none
+ }
+ let x = (d - c)/(a - b)
+ let y = a * x + c
+ return (x, y)
+ }
+
+ assert(args.len() == 4, message: "Could not find circle center")
+ return vector.as-vec(line-intersection-2d(..args), init: (0, 0, a.at(2)))
+}
+
+/// Converts a {{number}} to "canvas units"
+/// - ctx (context): The current context object.
+/// - num (number): The number to resolve.
+/// -> float
+#let resolve-number(ctx, num) = {
+ return if type(num) == length {
+ float(num.to-absolute() / ctx.length)
+ } else if type(num) == ratio {
+ num
+ } else {
+ float(num)
+ }
+}
+
+/// Ensures that a radius has an `x` and `y` component.
+/// - radius (number, array):
+/// -> array
+#let resolve-radius(radius) = {
+ return if type(radius) == array {radius} else {(radius, radius)}
+}
+
+/// Finds the minimum of a set of values while ignoring {{none}} values.
+/// - a (float,none):
+/// -> float
+#let min(..a) = {
+ let a = a.pos().filter(v => v != none)
+ return calc.min(..a)
+}
+
+/// Finds the maximum of a set of values while ignoring {{none}} values.
+/// - ..a (float,none):
+/// -> float
+#let max(..a) = {
+ let a = a.pos().filter(v => v != none)
+ return calc.max(..a)
+}
+
+/// Merges dictionary `b` onto dictionary `a`. If a key does not exist in `a` but does in `b`, it is inserted into `a` with `b`'s value. If a key does exist in `a` and `b`, the value in `b` is only inserted into `a` if the `overwrite` argument is `true`. If a key does exist both in `a` and `b` and both values are of type {{dictionary}} they will be recursively merged with this same function.
+///
+/// - a (dictionary): Dictionary a
+/// - b (dictionary): Dictionary b
+/// - overwrite (bool): Whether to override an entry in `a` that also exists in `b` with the value in `b`.
+/// -> dictionary
+#let merge-dictionary(a, b, overwrite: true) = {
+ for (k, v) in b {
+ if type(a) == dictionary and k in a and type(v) == dictionary and type(a.at(k)) == dictionary {
+ a.insert(k, merge-dictionary(a.at(k), v, overwrite: overwrite))
+ } else if overwrite or k not in a {
+ a.insert(k, v)
+ }
+ }
+ return a
+}
+
+/// Measures the size of some {{content}} in canvas coordinates.
+/// - ctx (context): The current context object.
+/// - cnt (content): The content to measure.
+/// -> vector
+#let measure(ctx, cnt) = {
+ let size = std.measure(cnt)
+ return (
+ calc.abs(size.width / ctx.length),
+ calc.abs(size.height / ctx.length)
+ )
+}
+
+/// Get a padding/margin dictionary with keys `(top, left, bottom, right)` from a padding value.
+///
+///
+/// Type of `padding`:
+/// - {{none}}: All sides padded by 0
+/// - {{number}}: All sides are padded by the same value
+/// - {{array}}: CSS like padding: `(y, x)`, `(top, x, bottom)` or `(top, right, bottom, left)`
+/// - {{dictionary}}: Converts a Typst padding dictionary (top, left, bottom, right, x, y, rest) to a dictionary containing top, left, bottom and right.
+///
+/// - padding (none, number, array, dictionary): Padding specification
+///
+/// -> dictionary
+#let as-padding-dict(padding) = {
+ if padding == none {
+ padding = 0
+ }
+
+ if type(padding) == array {
+ // Allow CSS like padding array
+ assert(padding.len() in (2, 3, 4),
+ message: "Padding array formats are: (y, x), (top, x, bottom), (top, right, bottom, left)")
+ if padding.len() == 2 {
+ let (y, x) = padding
+ return (top: y, right: x, bottom: y, left: x)
+ } else if padding.len() == 3 {
+ let (top, x, bottom) = padding
+ return (top: top, right: x, bottom: bottom, left: x)
+ } else if padding.len() == 4 {
+ let (top, right, bottom, left) = padding
+ return (top: top, right: right, bottom: bottom, left: left)
+ }
+ } else if type(padding) == dictionary {
+ // Support typst padding dictionary
+ let rest = padding.at("rest", default: 0)
+ let x = padding.at("x", default: rest)
+ let y = padding.at("y", default: rest)
+ if not "left" in padding { padding.left = x }
+ if not "right" in padding { padding.right = x }
+ if not "top" in padding { padding.top = y }
+ if not "bottom" in padding { padding.bottom = y }
+
+ return padding
+ } else {
+ return (top: padding, left: padding, bottom: padding, right: padding)
+ }
+}
+
+/// Creates a corner-radius dictionary with keys `north-east`, `north-west`, `south-east` and `south-west` with values of a two element {{array}} of the radius in the `x` and `y` direction. Returns none if all radii are zero or none.
+///
+/// - ctx (context): The current canvas context object
+/// - radii (none, number, dictionary): The radius specification. A {{number}} will cause all corners to have the same radius. An {{array}} with two items will cause all corners to have the same rx and ry radius. A {{dictionary}} can be given where the key specifies the corner and the value specifies the radius. The value can be either {{number}} for a circle radius or {{array}} for an x and y radius. The keys `north`, `south`, `east` and `west` targets both corners in that cardinal direction e.g. `south` sets the south west and south east corners. The keys `north-east`, `north-west`, `south-east` and `south-west` targets the corresponding corner. The key `rest` targets all other corners that have not been target by other keys.
+/// - size (???): I'm not sure what this does.
+///
+/// -> dictionary
+#let as-corner-radius-dict(ctx, radii, size) = {
+ if radii == none or radii == 0 {
+ return (north-west: (0,0), north-east: (0,0),
+ south-west: (0,0), south-east: (0,0))
+ }
+
+ let radii = (if type(radii) == dictionary {
+ let rest = radii.at("rest", default: (0,0))
+ let north = radii.at("north", default: auto)
+ let south = radii.at("south", default: auto)
+ let west = radii.at("west", default: auto)
+ let east = radii.at("east", default: auto)
+
+ if north != auto or south != auto {
+ assert(west == auto and east == auto,
+ message: "Corner radius north/south and west/east are mutually exclusive! Use per corner radii: north-west, .. instead.")
+ }
+ if west != auto or east != auto {
+ assert(north == auto and south == auto,
+ message: "Corner radius north/south and west/east are mutually exclusive! Use per corner radii: north-west, .. instead.")
+ }
+
+ let north-east = if north != auto { north } else if east != auto { east } else {rest}
+ let north-west = if north != auto { north } else if west != auto { west } else {rest}
+ let south-east = if south != auto { south } else if east != auto { east } else {rest}
+ let south-west = if south != auto { south } else if west != auto { west } else {rest}
+
+ (radii.at("north-west", default: north-west),
+ radii.at("north-east", default: north-east),
+ radii.at("south-west", default: south-west),
+ radii.at("south-east", default: south-east))
+ } else if type(radii) == array {
+ panic("Invalid corner radius type: " + type(radii))
+ } else {
+ (radii, radii, radii, radii)
+ }).map(v => if type(v) != array { (v, v) } else { v })
+
+ // Resolve lengths to floats
+ radii = radii.map(t => t.map(resolve-number.with(ctx)))
+
+ // Clamp radii to half the size
+ radii = radii.map(t => t.enumerate().map(((i, v)) => {
+ calc.max(0, calc.min(if type(v) == ratio {
+ v * size.at(i) / 100%
+ } else { v }, size.at(i) / 2))
+ }))
+
+ let (nw, ne, sw, se) = radii
+ return (
+ north-west: nw,
+ north-east: ne,
+ south-west: sw,
+ south-east: se,
+ )
+}
+
+/// Sorts an array of vectors by distance to a common position.
+/// - base (vector): The position to measure the distance of the other vectors from.
+/// - pts (array): The array of vectors to sort.
+/// -> array
+#let sort-points-by-distance(base, pts) = {
+ if pts.len() == 1 {
+ return pts
+ }
+
+ // Sort by transforming points into tuples of (point, distance),
+ // sorting them by key 1 and then transforming them back to points.
+ return pts.map(p => {
+ return (p, vector.dist(p, base))
+ })
+ .sorted(key: t => t.at(1))
+ .map(t => t.at(0))
+}
+
+/// Resolves a stroke into a usable dictionary with all fields that are missing or auto set to their Typst defaults.
+/// - stroke (none, stroke): The stroke to resolve.
+/// -> dictionary
+#let resolve-stroke(stroke) = {
+ if stroke == none {
+ return (paint: none, thickness: 0pt, join: none, cap: none, miter-limit: 4)
+ }
+
+ let default = (
+ paint: black,
+ thickness: 1pt,
+ join: "miter",
+ cap: "butt",
+ miter-limit: 4
+ )
+ let s = line(stroke: stroke).stroke
+ let stroke = (:)
+ for (k, v) in (paint: s.paint, thickness: s.thickness, join: s.join, cap: s.cap, miter-limit: s.miter-limit) {
+ if v == auto {
+ stroke.insert(k, default.at(k))
+ } else {
+ stroke.insert(k, v)
+ }
+ }
+ return stroke
+}
+
+/// Asserts whether a "body" has the correct type.
+#let assert-body(body) = {
+ assert(body == none or type(body) in (array, function),
+ message: "Body must be of type none, array or function")
+}
+
+// Returns body if of type array, an
+// empty array if body is none or
+// the result of body called with ctx if of type
+// function. A function result of none will return
+// an empty array.
+#let resolve-body(ctx, body) = {
+ if type(body) == function {
+ body = body(ctx)
+ }
+ if body == none {
+ body = ()
+ }
+ return body
+}
+
+
+#let str-to-number-regex = regex("^(-?\d*\.?\d+)(cm|mm|pt|em|in|%|deg|rad)?$")
+#let number-units = (
+ "%": 1%,
+ "cm": 1cm,
+ "mm": 1mm,
+ "pt": 1pt,
+ "em": 1em,
+ "in": 1in,
+ "deg": 1deg,
+ "rad": 1rad
+)
+#let str-is-number(string) = string.match(str-to-number-regex) != none
+#let str-to-number(string) = {
+ let (num, unit) = string.match(str-to-number-regex).captures
+ num = float(num)
+ if unit != none and unit in number-units {
+ num *= number-units.at(unit)
+ }
+ return num
+}
diff --git a/render/packages/preview/cetz/0.3.4/src/vector.typ b/render/packages/preview/cetz/0.3.4/src/vector.typ
new file mode 100644
index 0000000..d8fb607
--- /dev/null
+++ b/render/packages/preview/cetz/0.3.4/src/vector.typ
@@ -0,0 +1,169 @@
+/// Converts a vector to a row or column matrix.
+///
+/// - v (vector): The vector to convert.
+/// - mode (str): The type of matrix to convert into. Must be one of `"row"` or `"column"`.
+/// -> matrix
+#let as-mat(v, mode: "row") = {
+ if mode == "column" {
+ return (v,)
+ } else if mode == "row" {
+ return (for c in v { (c,) }, )
+ } else {
+ panic("Invalid mode " + mode)
+ }
+}
+
+/// Ensures a vector has an exact number of components. This is done by passing another vector `init` that has the required dimension. If the original vector does not have enough dimensions, the values from `init` will be inserted. It is recommended to use a zero vector for `init`.
+///
+/// - v (vector): The vector to ensure.
+/// - init (vector): The vector to check the dimension against.
+/// -> vector
+#let as-vec(v, init: (0, 0, 0)) = {
+ for i in range(0, calc.min(v.len(), init.len())) {
+ init.at(i) = v.at(i)
+ }
+ return init
+}
+
+
+/// Return length/magnitude of a vector.
+///
+/// - v (vector): The vector to find the magnitude of.
+/// -> float
+#let len(v) = {
+ return calc.sqrt(v.fold(0, (s, c) => s + c * c))
+}
+
+/// Adds two vectors of the same dimension
+///
+/// - v1 (vector): The vector on the left hand side.
+/// - v2 (vector): The vector on the right hand side.
+/// -> vector
+#let add(v1, v2) = {
+ range(0, calc.max(v1.len(), v2.len())).map(i => {
+ v1.at(i, default: 0) + v2.at(i, default: 0)
+ })
+}
+
+/// Subtracts two vectors of the same dimension
+///
+/// - v1 (vector): The vector on the left hand side.
+/// - v2 (vector): The vector on the right hand side.
+/// -> vector
+#let sub(v1, v2) = {
+ range(0, calc.max(v1.len(), v2.len())).map(i => {
+ v1.at(i, default: 0) - v2.at(i, default: 0)
+ })
+}
+
+/// Calculates the distance between two vectors by subtracting the length of vector `a` from vector `b`.
+///
+/// - a (vector): Vector a
+/// - b (vector): Vector b
+/// -> float
+#let dist(a, b) = len(sub(b, a))
+
+/// Multiplys a vector with scalar `x`
+/// - v (vector): The vector to scale.
+/// - x (float): The scale factor.
+/// -> vector
+#let scale(v, x) = v.map(s => s * x)
+
+/// Divides a vector by scalar `x`
+/// - v (vector): The vector to be divded.
+/// - x (float): The inverse scale factor.
+#let div(v, x) = v.map(s => s / x)
+
+/// Negates each value in a vector
+/// - v (vector): The vector to negate.
+/// -> vector
+#let neg(v) = scale(v, -1)
+
+/// Normalizes a vector (divide by its length)
+/// - v (vector): The vector to normalize.
+/// -> vector
+#let norm(v) = div(v, len(v))
+
+/// Multiply two vectors component-wise
+/// - a (vector): First vector.
+/// - b (vector): Second vector.
+#let element-product(a, b) = a.enumerate().map(((i, v)) => v * b.at(i))
+
+/// Calculates the dot product between two vectors.
+/// - v1 (vector): The vector on the left hand side.
+/// - v2 (vector): The vector on the right hand side.
+/// -> float
+#let dot(v1, v2) = {
+ assert(v1.len() == v2.len())
+ return v1.enumerate().fold(0, (s, t) => s + t.at(1) * v2.at(t.at(0)))
+}
+
+/// Calculates the cross product of two vectors with a dimension of three.
+/// - v1 (vector): The vector on the left hand side.
+/// - v2 (vector): The vector on the right hand side.
+/// -> vector
+#let cross(v1, v2) = {
+ assert(v1.len() == 3 and v2.len() == 3)
+
+ let (x1, y1, z1) = v1
+ let (x2, y2, z2) = v2
+
+ return (y1 * z2 - z1 * y2,
+ z1 * x2 - x1 * z2,
+ x1 * y2 - y1 * x2)
+}
+
+/// Calculates the angle between two vectors and the x-axis in 2d space
+/// - a (vector): The vector to measure the angle from.
+/// - b (vector): The vector to measure the angle to.
+/// -> angle
+#let angle2(a, b) = {
+ // Typst's atan2 is (x, y) order, not (y, x)
+ return calc.atan2(b.at(0) - a.at(0), b.at(1) - a.at(1))
+}
+
+/// Calculates the angle between three vectors
+/// - v1 (vector): The vector to measure the angle from.
+/// - c (vector): The vector to measure the angle at.
+/// - v2 (vector): The vector to measure the angle to.
+#let angle(v1, c, v2) = {
+ assert(v1.len() == v2.len(),
+ message: "Vectors " + repr(v1) + " and " + repr(v2) + " do not have the same dimensions.")
+ if v1.len() == 2 or v1.len() == 3 {
+ v1 = sub(v1, c)
+ v2 = sub(v2, c)
+ return calc.acos(dot(norm(v1), norm(v2)))
+ } else {
+ panic("Invalid vector dimension")
+ }
+}
+
+/// Linear interpolation between two vectors.
+/// - v1 (vector): The vector to interpolate from.
+/// - v2 (vector): The vector to interpolate to.
+/// - t (float): The factor to interpolate by. A value of `0` is `v1` and a value of `1` is `v2`.
+#let lerp(v1, v2, t) = {
+ return add(
+ v1,
+ scale(
+ sub(
+ v2,
+ v1
+ ),
+ t,
+ )
+ )
+}
+
+/// Rotates a vector of dimension 2 or 3 around the z-axis by an angle.
+/// - v (vector): The vector to rotate.
+/// - angle (angle): The angle to rotate by.
+/// -> vector
+#let rotate-z(v, angle) = {
+ assert(v.len() >= 2,
+ message: "Vector size must be >= 2")
+ let (x, y, ..) = v
+ v.at(0) = x * calc.cos(angle) - y * calc.sin(angle)
+ v.at(1) = x * calc.sin(angle) + y * calc.cos(angle)
+ return v
+}
diff --git a/render/packages/preview/cetz/0.3.4/src/version.typ b/render/packages/preview/cetz/0.3.4/src/version.typ
new file mode 100644
index 0000000..9c9b1a4
--- /dev/null
+++ b/render/packages/preview/cetz/0.3.4/src/version.typ
@@ -0,0 +1 @@
+#let version = version(0,3,3)
diff --git a/render/packages/preview/cetz/0.3.4/typst.toml b/render/packages/preview/cetz/0.3.4/typst.toml
new file mode 100644
index 0000000..8abcdd4
--- /dev/null
+++ b/render/packages/preview/cetz/0.3.4/typst.toml
@@ -0,0 +1,16 @@
+[package]
+name = "cetz"
+version = "0.3.4"
+compiler = "0.13.0"
+repository = "https://github.com/cetz-package/cetz"
+homepage = "https://cetz-package.github.io/"
+entrypoint = "src/lib.typ"
+authors = [
+ "Johannes Wolf <https://github.com/johannes-wolf>",
+ "fenjalien <https://github.com/fenjalien>"
+]
+categories = [ "visualization" ]
+license = "LGPL-3.0-or-later"
+description = "Drawing with Typst made easy, providing an API inspired by TikZ and Processing. Includes modules for plotting, charts and tree layout."
+keywords = [ "draw", "canvas", "tree" ]
+exclude = [ "/gallery/*", "manual.pdf", "manual.typ" ]
diff --git a/render/packages/preview/cetz/0.5.2/LICENSE b/render/packages/preview/cetz/0.5.2/LICENSE
new file mode 100644
index 0000000..65c5ca8
--- /dev/null
+++ b/render/packages/preview/cetz/0.5.2/LICENSE
@@ -0,0 +1,165 @@
+ GNU LESSER GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+
+ This version of the GNU Lesser General Public License incorporates
+the terms and conditions of version 3 of the GNU General Public
+License, supplemented by the additional permissions listed below.
+
+ 0. Additional Definitions.
+
+ As used herein, "this License" refers to version 3 of the GNU Lesser
+General Public License, and the "GNU GPL" refers to version 3 of the GNU
+General Public License.
+
+ "The Library" refers to a covered work governed by this License,
+other than an Application or a Combined Work as defined below.
+
+ An "Application" is any work that makes use of an interface provided
+by the Library, but which is not otherwise based on the Library.
+Defining a subclass of a class defined by the Library is deemed a mode
+of using an interface provided by the Library.
+
+ A "Combined Work" is a work produced by combining or linking an
+Application with the Library. The particular version of the Library
+with which the Combined Work was made is also called the "Linked
+Version".
+
+ The "Minimal Corresponding Source" for a Combined Work means the
+Corresponding Source for the Combined Work, excluding any source code
+for portions of the Combined Work that, considered in isolation, are
+based on the Application, and not on the Linked Version.
+
+ The "Corresponding Application Code" for a Combined Work means the
+object code and/or source code for the Application, including any data
+and utility programs needed for reproducing the Combined Work from the
+Application, but excluding the System Libraries of the Combined Work.
+
+ 1. Exception to Section 3 of the GNU GPL.
+
+ You may convey a covered work under sections 3 and 4 of this License
+without being bound by section 3 of the GNU GPL.
+
+ 2. Conveying Modified Versions.
+
+ If you modify a copy of the Library, and, in your modifications, a
+facility refers to a function or data to be supplied by an Application
+that uses the facility (other than as an argument passed when the
+facility is invoked), then you may convey a copy of the modified
+version:
+
+ a) under this License, provided that you make a good faith effort to
+ ensure that, in the event an Application does not supply the
+ function or data, the facility still operates, and performs
+ whatever part of its purpose remains meaningful, or
+
+ b) under the GNU GPL, with none of the additional permissions of
+ this License applicable to that copy.
+
+ 3. Object Code Incorporating Material from Library Header Files.
+
+ The object code form of an Application may incorporate material from
+a header file that is part of the Library. You may convey such object
+code under terms of your choice, provided that, if the incorporated
+material is not limited to numerical parameters, data structure
+layouts and accessors, or small macros, inline functions and templates
+(ten or fewer lines in length), you do both of the following:
+
+ a) Give prominent notice with each copy of the object code that the
+ Library is used in it and that the Library and its use are
+ covered by this License.
+
+ b) Accompany the object code with a copy of the GNU GPL and this license
+ document.
+
+ 4. Combined Works.
+
+ You may convey a Combined Work under terms of your choice that,
+taken together, effectively do not restrict modification of the
+portions of the Library contained in the Combined Work and reverse
+engineering for debugging such modifications, if you also do each of
+the following:
+
+ a) Give prominent notice with each copy of the Combined Work that
+ the Library is used in it and that the Library and its use are
+ covered by this License.
+
+ b) Accompany the Combined Work with a copy of the GNU GPL and this license
+ document.
+
+ c) For a Combined Work that displays copyright notices during
+ execution, include the copyright notice for the Library among
+ these notices, as well as a reference directing the user to the
+ copies of the GNU GPL and this license document.
+
+ d) Do one of the following:
+
+ 0) Convey the Minimal Corresponding Source under the terms of this
+ License, and the Corresponding Application Code in a form
+ suitable for, and under terms that permit, the user to
+ recombine or relink the Application with a modified version of
+ the Linked Version to produce a modified Combined Work, in the
+ manner specified by section 6 of the GNU GPL for conveying
+ Corresponding Source.
+
+ 1) Use a suitable shared library mechanism for linking with the
+ Library. A suitable mechanism is one that (a) uses at run time
+ a copy of the Library already present on the user's computer
+ system, and (b) will operate properly with a modified version
+ of the Library that is interface-compatible with the Linked
+ Version.
+
+ e) Provide Installation Information, but only if you would otherwise
+ be required to provide such information under section 6 of the
+ GNU GPL, and only to the extent that such information is
+ necessary to install and execute a modified version of the
+ Combined Work produced by recombining or relinking the
+ Application with a modified version of the Linked Version. (If
+ you use option 4d0, the Installation Information must accompany
+ the Minimal Corresponding Source and Corresponding Application
+ Code. If you use option 4d1, you must provide the Installation
+ Information in the manner specified by section 6 of the GNU GPL
+ for conveying Corresponding Source.)
+
+ 5. Combined Libraries.
+
+ You may place library facilities that are a work based on the
+Library side by side in a single library together with other library
+facilities that are not Applications and are not covered by this
+License, and convey such a combined library under terms of your
+choice, if you do both of the following:
+
+ a) Accompany the combined library with a copy of the same work based
+ on the Library, uncombined with any other library facilities,
+ conveyed under the terms of this License.
+
+ b) Give prominent notice with the combined library that part of it
+ is a work based on the Library, and explaining where to find the
+ accompanying uncombined form of the same work.
+
+ 6. Revised Versions of the GNU Lesser General Public License.
+
+ The Free Software Foundation may publish revised and/or new versions
+of the GNU Lesser General Public License from time to time. Such new
+versions will be similar in spirit to the present version, but may
+differ in detail to address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Library as you received it specifies that a certain numbered version
+of the GNU Lesser General Public License "or any later version"
+applies to it, you have the option of following the terms and
+conditions either of that published version or of any later version
+published by the Free Software Foundation. If the Library as you
+received it does not specify a version number of the GNU Lesser
+General Public License, you may choose any version of the GNU Lesser
+General Public License ever published by the Free Software Foundation.
+
+ If the Library as you received it specifies that a proxy can decide
+whether future versions of the GNU Lesser General Public License shall
+apply, that proxy's public statement of acceptance of any version is
+permanent authorization for you to choose that version for the
+Library.
diff --git a/render/packages/preview/cetz/0.5.2/README.md b/render/packages/preview/cetz/0.5.2/README.md
new file mode 100644
index 0000000..6e7c604
--- /dev/null
+++ b/render/packages/preview/cetz/0.5.2/README.md
@@ -0,0 +1,165 @@
+# CeTZ
+
+CeTZ (CeTZ, ein Typst Zeichenpaket) is a library for drawing with [Typst](https://typst.app) with an API inspired by TikZ and [Processing](https://processing.org/).
+
+## Examples
+
+<!-- img width is set so the table gets evenly spaced by GitHub's css -->
+<table>
+<tr>
+ <td>
+ <a href="gallery/karls-picture.typ">
+ <img src="gallery/karls-picture.png" width="250px" alt="Right triangle on the unit circle illustrating sine and cosine">
+ </a>
+ </td>
+ <td>
+ <a href="gallery/paciolis.typ">
+ <img src="gallery/paciolis.png" width="250px" alt="Pacioli's construction of the icosahedron">
+ </a>
+ </td>
+ <td>
+ <a href="gallery/plate-capacitor.typ">
+ <img src="gallery/plate-capacitor.png" width="250px" alt="Plate capacitor">
+ </a>
+ </td>
+</tr>
+<tr>
+ <td>Karl's Picture</td>
+ <td>Pacioli's construction of the icosahedron</td>
+ <td>Plate Capacitor</td>
+</tr>
+<tr>
+ <td>
+ <a href="gallery/tree.typ">
+ <img src="gallery/tree.png" width="250px" alt="Simple tree graph">
+ </a>
+ </td>
+ <td>
+ <a href="gallery/periodic-table.typ">
+ <img src="gallery/periodic-table.png" width="250px" alt="Periodic table of elements">
+ </a>
+ </td>
+ <td>
+ <a href="gallery/waves.typ">
+ <img src="gallery/waves.png" width="250px" alt="3D diagram showing two sine waves">
+ </a>
+ </td>
+</tr>
+<tr>
+ <td>Tree Layout</td>
+ <td>Periodic Table of Elements</td>
+ <td>Waves</td>
+</tr>
+<tr>
+ <td>
+ <a href="gallery/torus.typ">
+ <img src="gallery/torus.png" width="250px" alt="3D torus figure">
+ </a>
+ </td>
+ <td>
+ </td>
+ <td>
+ </td>
+</tr>
+<tr>
+ <td>Torus</td>
+ <td></td>
+ <td></td>
+</tr>
+</table>
+
+_Click on the example image to jump to the code._
+
+You can explore an example gallery of scientific diagrams at [janosh.github.io/diagrams](https://janosh.github.io/diagrams).
+
+## Usage
+
+For information, see the [API Reference (PDF)](./manual.pdf?raw=true) or the [online manual](https://cetz-package.github.io/docs).
+
+To use this package, simply add the following code to your document:
+
+```typ
+#import "@preview/cetz:0.5.2"
+
+#cetz.canvas({
+ import cetz.draw: *
+ // Your drawing code goes here
+})
+```
+
+## CeTZ Libraries
+
+- [cetz-plot - Plotting and Charts Library](https://github.com/cetz-package/cetz-plot)
+- [cetz-venn - Simple two- or three-set Venn diagrams](https://github.com/cetz-package/cetz-venn)
+
+## Installing
+
+To install the CeTZ package under [your local typst package dir](https://github.com/typst/packages?tab=readme-ov-file#local-packages) you can use the `install` script from the repository.
+
+Make sure to first perform a recursive git clone
+
+```bash
+# to fetch a clean clone:
+git clone --recursive https://github.com/cetz-package/cetz.git
+# or if you forgot the `--recursive` flag before:
+git submodule update --init
+```
+
+and also ensure you have `just` and `cargo` installed.
+
+<details>
+ <summary>For nix users</summary>
+
+After enabling flakes, use:
+
+```bash
+nix --extra-experimental-features 'nix-command flakes' develop
+```
+
+</details>
+
+Now use the installation script:
+
+```bash
+just install
+```
+
+The installed version can be imported by prefixing the package name with `@local`.
+
+```typ
+#import "@local/cetz:0.5.2"
+
+#cetz.canvas({
+ import cetz.draw: *
+ // Your drawing code goes here
+})
+```
+
+### Just
+
+This project uses [just](https://github.com/casey/just), a handy command runner.
+
+You can run all commands without having `just` installed, just have a look into the `justfile`.
+To install `just` on your system, use your systems package manager. On Windows, [Cargo](https://doc.rust-lang.org/cargo/) (`cargo install just`), [Chocolatey](https://chocolatey.org/) (`choco install just`) and [some other sources](https://just.systems/man/en/packages.html) can be used. You need to run it from a `sh` compatible shell on Windows (e.g git-bash).
+
+## Testing
+
+This package comes with some unit tests under the `tests` directory.
+To run all tests you can run the `just test` target. You need to have
+[`tytanic`](https://github.com/tingerrr/tytanic/) in your `PATH`: `cargo install tytanic`.
+
+## Projects using CeTZ
+
+- [finite](https://github.com/jneug/typst-finite) Finite is a Typst package for rendering finite automata.
+- [fletcher](https://github.com/Jollywatt/typst-fletcher) Package for drawing commutative diagrams and figures with arrows.
+- [chronos](https://git.kb28.ch/HEL/chronos) Package for drawing sequence diagrams.
+- [circuiteria](https://git.kb28.ch/HEL/circuiteria) Package for drawing circuits.
+- [zap](https://codeberg.org/grangelouis/zap) Package for drawing standard electronic circuits.
+- [bone](https://codeberg.org/grangelouis/bone) Package to draw structural analysis and kinematic diagrams
+- [rivet](https://git.kb28.ch/HEL/rivet-typst) Package for drawing instruction / register diagrams.
+- [plotsy-3d](https://github.com/misskacie/plotsy-3d) Package for rendering 3D objects & plots.
+- [alchemist](https://github.com/Typsium/alchemist) A package to render skeletal formulae using a human-readable format using cetz.
+- [deckz](https://github.com/micheledusi/Deckz) Render Poker-Style playing cards.
+- [neural-netz](https://github.com/edgaremy/neural-netz) Visualize neural network architectures.
+- [energy-dia](https://github.com/Typsium/energy-dia) Library for creating professional energy diagrams in chemistry and physics.
+- [conchord](https://github.com/sitandr/conchord) Package for writing lyrics with chords that generates fretboard diagrams.
diff --git a/render/packages/preview/cetz/0.5.2/cetz-core/cetz_core.wasm b/render/packages/preview/cetz/0.5.2/cetz-core/cetz_core.wasm
new file mode 100755
index 0000000..fb40dfb
Binary files /dev/null and b/render/packages/preview/cetz/0.5.2/cetz-core/cetz_core.wasm differ
diff --git a/render/packages/preview/cetz/0.5.2/src/aabb.typ b/render/packages/preview/cetz/0.5.2/src/aabb.typ
new file mode 100644
index 0000000..a5e6ff2
--- /dev/null
+++ b/render/packages/preview/cetz/0.5.2/src/aabb.typ
@@ -0,0 +1,81 @@
+#import "vector.typ"
+#import "wasm.typ": call_wasm
+#let cetz-core = plugin("../cetz-core/cetz_core.wasm")
+
+/// Compute an axis aligned bounding box (aabb) for a list of <Type>vectors</Type>.
+///
+/// - pts (array): List of <Type>vector</Type>s.
+/// - init (aabb): Initial aabb
+/// -> aabb
+#let aabb(pts, init: none) = {
+ return call_wasm(cetz-core.aabb_func, (pts: pts, init: init))
+}
+
+#let merge(a, b) = {
+ if a == none { return b }
+ if b == none { return a }
+
+ import calc: min, max
+ let (alx, aly, alz) = a.low
+ let (ahx, ahy, ahz) = a.high
+ let (blx, bly, blz) = b.low
+ let (bhx, bhy, bhz) = b.high
+
+ (low: (min(alx, blx), min(aly, bly), min(alz, blz)),
+ high: (max(ahx, bhx), max(ahy, bhy), max(ahz, bhz)))
+}
+
+/// Get the mid-point of an AABB as vector.
+///
+/// - bounds (aabb): The AABB to get the mid-point of.
+/// -> vector
+#let mid(bounds) = {
+ return vector.scale(vector.add(bounds.low, bounds.high), .5)
+}
+
+/// Get four corner points of the AABB as vectors.
+///
+/// - bounds (aabb): The AABB
+/// - fron (bool): Return the corner points for the high z component
+/// -> array of vectors
+#let corner-points(bounds, front: true) = {
+ let z = if front {
+ bounds.high.at(2, default: 0)
+ } else {
+ bounds.low.at(2, default: 0)
+ }
+
+ let (hx, hy, hz) = bounds.high
+ let (lx, ly, lz) = bounds.low
+
+ return (
+ (hx, hy, z),
+ (hx, ly, z),
+ (lx, ly, z),
+ (lx, hy, z),
+ )
+}
+
+/// Get the size of an aabb as vector. This is a vector from the aabb's low to high.
+///
+/// - bounds (aabb): The aabb to get the size of.
+/// -> vector
+#let size(bounds) = {
+ vector.sub(bounds.high, bounds.low).map(calc.abs)
+}
+
+/// Pad AABB with padding from dictionary with keys top, left, right and bottom.
+///
+/// - bounds (aabb): The AABB to pad.
+/// - padding (none, dictionary): Padding values
+///
+/// -> aabb
+#let padded(bounds, padding) = {
+ if padding != none {
+ bounds.low.at(0) -= padding.at("left", default: 0)
+ bounds.low.at(1) -= padding.at("top", default: 0)
+ bounds.high.at(0) += padding.at("right", default: 0)
+ bounds.high.at(1) += padding.at("bottom", default: 0)
+ }
+ return bounds
+}
diff --git a/render/packages/preview/cetz/0.5.2/src/anchor.typ b/render/packages/preview/cetz/0.5.2/src/anchor.typ
new file mode 100644
index 0000000..86650f1
--- /dev/null
+++ b/render/packages/preview/cetz/0.5.2/src/anchor.typ
@@ -0,0 +1,233 @@
+#import "deps.typ"
+#import deps.oxifmt: strfmt
+
+#import "util.typ"
+#import "intersection.typ"
+#import "drawable.typ"
+#import "path-util.typ"
+#import "matrix.typ"
+#import "vector.typ"
+
+// Compass direction to angle
+#let named-border-anchors = (
+ east: 0deg,
+ north-east: 45deg,
+ north: 90deg,
+ north-west: 135deg,
+ west: 180deg,
+ south-west: 225deg,
+ south: 270deg,
+ south-east: 315deg,
+)
+
+// Path anchors
+#let named-path-anchors = (
+ start: 0%,
+ mid: 50%,
+ end: 100%,
+)
+
+/// Calculates a border anchor at the given angle by testing for an intersection between a line and the given drawables. Returns `none` if no intersection is found for better error reporting.
+///
+/// - center (vector): The position from which to start the test line.
+/// - x-dist (number): The furthest distance the test line should go in the x direction.
+/// - y-dist (number): The furthest distance the test line should go in the y direction.
+/// - drawables (drawables): Drawables to test for an intersection against. Ideally should be of type path but all others are ignored.
+/// - angle (angle): The angle to check for a border anchor at.
+/// -> none
+/// -> vector
+#let shape-border(center, x-dist, y-dist, drawables, angle) = {
+ x-dist += util.float-epsilon
+ y-dist += util.float-epsilon
+
+ if type(drawables) == dictionary {
+ drawables = (drawables,)
+ }
+
+ let test-line = (
+ center,
+ (
+ center.at(0) + calc.abs(x-dist) * calc.cos(angle),
+ center.at(1) + calc.abs(y-dist) * calc.sin(angle),
+ center.at(2),
+ )
+ )
+
+ let pts = ()
+ for drawable in drawables {
+ if drawable.type != "path" {
+ continue
+ }
+ pts += intersection.line-path(..test-line, drawable)
+ }
+
+ if pts.len() == 1 {
+ return pts.first()
+ }
+
+ return if pts.len() == 1 {
+ pts.first()
+ } else if pts.len() > 1 {
+ // Find the furthest intersection point from center
+ util.sort-points-by-distance(center, pts).last()
+ }
+}
+
+
+/// Setup an anchor calculation and handling function for an element. Unifies anchor error checking and calculation of the offset transform.
+///
+/// A tuple of a transformation matrix and function will be returned.
+/// The transform is calculated by translating the given transform by the distance between the position of `offset-anchor` and `default`. It can then be used to correctly transform an element's drawables. If either are none the calculation won't happen but the transform will still be returned.
+/// The function can be used to get the transformed anchors of an element by passing it a string. An empty array can be passed to get the list of valid anchors.
+///
+/// - callback (function, auto): The function to call to get a named anchor's position. The anchor's name will be passed and it should return a <Type>vector</Type> (`str => vector`). If no named anchors exist on the element `auto` can be given instead of a function.
+/// - anchor-names (array): A list of valid anchor names. This list will be used to validate an anchor exists before `callback` is used.
+/// - default (str,none): The name of the default anchor, if one exists.
+/// - transform (matrix,none): The current transformation matrix to apply to an anchor's position before returning it. If `offset-anchor` and `default` is set, it will be first translated by the distance between them.
+/// - name (str, none): The name of the element, this is only used in the error message in the event an anchor is invalid.
+/// - offset-anchor (str, none): The name of an anchor to offset the transform by.
+/// - border-anchors (bool): If true, add border anchors.
+/// - path-anchors (bool): If true, add path anchors.
+/// - radii (none,array): Radius tuple used for border anchor calculation.
+/// - path (none,drawable): Path used for path and border anchor calculation.
+/// - path-anchor-callback (none,function): Callback of the form `(center, anchor) → vector`. If not `none`, this callback gets invoked for calculating path anchors.
+/// - border-anchor-callback (none,function): Callback of the form `(center, anchor) → vector`. If not `none`, this callback gets invoked for calculating border anchors.
+/// -> array
+#let setup(
+ callback,
+ anchor-names,
+ default: none,
+ transform: none,
+ name: none,
+ offset-anchor: none,
+ border-anchors: false,
+ path-anchors: false,
+ radii: none,
+ path: none,
+ nested-anchors: false,
+ path-anchor-callback: none, /* (center, anchor) -> vector */
+ border-anchor-callback: none, /* (center, anchor) -> vector */
+ ) = {
+ // Passing no callback is valid!
+ if callback == auto {
+ callback = (anchor) => {}
+ }
+
+ // Add enabled anchor names
+ if name != none or offset-anchor != none {
+ if border-anchors {
+ assert("center" in anchor-names and radii != none and path != none,
+ message: "Border anchors need a center anchor, radii and the path set!")
+ }
+ if path-anchors {
+ assert.ne(path, none,
+ message: "Path anchors need the path set!")
+ }
+ }
+
+ // Anchor callback
+ let calculate-anchor(anchor, transform: none) = {
+ if anchor == () {
+ return (anchor-names + if border-anchors { named-border-anchors.keys() } + if path-anchors { named-path-anchors.keys() }).dedup()
+ }
+
+ let out = none
+ let nested-anchors = if type(anchor) == array {
+ if not nested-anchors {
+ anchor = anchor.join(".")
+ } else {
+ if anchor.len() > 1 {
+ anchor
+ }
+ anchor = anchor.first()
+ }
+ } else if nested-anchors and type(anchor) == str {
+ anchor = anchor.split(".")
+ if anchor.len() > 1 {
+ anchor
+ }
+ anchor = anchor.first()
+ }
+
+ if type(anchor) == str {
+ if anchor in anchor-names or (anchor == "default" and default != none) {
+ if anchor == "default" {
+ anchor = default
+ }
+
+ out = callback(if nested-anchors != none { nested-anchors } else { anchor })
+ } else if path-anchors and anchor in named-path-anchors {
+ anchor = named-path-anchors.at(anchor)
+ } else if border-anchors and anchor in named-border-anchors {
+ anchor = named-border-anchors.at(anchor)
+ } else if util.str-is-number(anchor) {
+ anchor = util.str-to-number(if nested-anchors != none { nested-anchors.join(".") } else { anchor })
+ } else {
+ panic(
+ strfmt(
+ "Anchor '{}' not in anchors {} for element '{}'",
+ anchor,
+ repr(anchor-names),
+ name
+ )
+ )
+ }
+ }
+
+ if out == none {
+ if type(anchor) in (ratio, float, int) {
+ if not path-anchors {
+ panic(strfmt("Element '{}' does not support path anchors.", name))
+ }
+ out = if path-anchor-callback != none {
+ path-anchor-callback(callback("center"), anchor)
+ } else {
+ let info = path-util.point-at(path.segments, anchor)
+ assert.ne(info, none)
+ info.point
+ }
+ } else if type(anchor) == angle {
+ if not border-anchors {
+ panic(strfmt("Element '{}' does not support border anchors.", name))
+ }
+ out = if border-anchor-callback != none {
+ border-anchor-callback(callback("center"), anchor)
+ } else {
+ shape-border(callback("center"), ..radii, path, anchor)
+ }
+ if out == none {
+ panic(strfmt("Element '{}' does not have a border for anchor '{}'.", name, anchor))
+ }
+ } else {
+ panic(strfmt("Unknown anchor '{}' for element '{}'", repr(anchor), name))
+ }
+ }
+
+ return if transform != none {
+ util.apply-transform(
+ transform,
+ out
+ )
+ } else {
+ out
+ }
+ }
+
+ if default != none and offset-anchor != none {
+ let offset = matrix.transform-translate(
+ ..vector.sub(calculate-anchor(default), calculate-anchor(offset-anchor)).slice(0, 3)
+ )
+ transform = if transform != none {
+ matrix.mul-mat(
+ transform,
+ offset
+ )
+ } else {
+ offset
+ }
+ }
+
+ return (if transform == none { matrix.ident(4) } else { transform }, calculate-anchor.with(transform: transform))
+}
+
+
diff --git a/render/packages/preview/cetz/0.5.2/src/bezier.typ b/render/packages/preview/cetz/0.5.2/src/bezier.typ
new file mode 100644
index 0000000..bb55c9a
--- /dev/null
+++ b/render/packages/preview/cetz/0.5.2/src/bezier.typ
@@ -0,0 +1,591 @@
+// This file contains functions related to bezier curve calculation
+// Many functions are ports from https://github.com/Pomax/bezierjs
+#import "vector.typ"
+#import "aabb.typ"
+#import "wasm.typ": call_wasm
+
+#let cetz-core = plugin("../cetz-core/cetz_core.wasm")
+#let epsilon = 1e-6
+
+// Map number v from range (ds, de) to (ts, te)
+#let _map(v, ds, de, ts, te) = {
+ let d1 = de - ds
+ let d2 = te - ts
+ let v2 = v - ds
+ let r = v2 / d1
+ return ts + d2 * r
+}
+
+/// Get the point on quadratic bezier at position `t`.
+///
+/// - a (vector): Start point
+/// - b (vector): End point
+/// - c (vector): Control point
+/// - t (float): Position on curve $[0, 1]$
+/// -> vector
+#let quadratic-point(a, b, c, t) = {
+ // (1-t)^2 * a + 2 * (1-t) * t * c + t^2 b
+ return vector.add(
+ vector.add(
+ vector.scale(a, calc.pow(1-t, 2)),
+ vector.scale(c, 2 * (1-t) * t)
+ ),
+ vector.scale(b, calc.pow(t, 2))
+ )
+}
+
+/// Get the derivative (dx/dt) of a quadratic bezier at position `t`.
+///
+/// - a (vector): Start point
+/// - b (vector): End point
+/// - c (vector): Control point
+/// - t (float): Position on curve [0, 1]
+/// -> vector
+#let quadratic-derivative(a, b, c, t) = {
+ // 2(-a(1-t) + bt - 2ct + c)
+ return vector.scale(
+ vector.add(
+ vector.sub(
+ vector.add(
+ vector.scale(vector.neg(a), (1 - t)),
+ vector.scale(b, t)),
+ vector.scale(c, 2 * t)),
+ c)
+ , 2)
+}
+
+/// Get the point on a cubic bezier curve at position `t`.
+///
+/// - a (vector): Start point
+/// - b (vector): End point
+/// - c1 (vector): Control point 1
+/// - c2 (vector): Control point 2
+/// - t (float): Position on curve [0, 1]
+/// -> vector
+#let cubic-point(a, b, c1, c2, t) = {
+ // (1-t)^3*a + 3*(1-t)^2*t*c1 + 3*(1-t)*t^2*c2 + t^3*b
+ vector.add(
+ vector.add(
+ vector.scale(a, calc.pow(1-t, 3)),
+ vector.scale(c1, 3 * calc.pow(1-t, 2) * t)
+ ),
+ vector.add(
+ vector.scale(c2, 3*(1-t)*calc.pow(t,2)),
+ vector.scale(b, calc.pow(t, 3))
+ )
+ )
+}
+
+/// Get the derivative (dx/dt) of a cubic bezier at position `t`.
+///
+/// - a (vector): Start point
+/// - b (vector): End point
+/// - c1 (vector): Control point 1
+/// - c2 (vector): Control point 2
+/// - t (float): Position on curve [0, 1]
+/// -> vector
+#let cubic-derivative(a, b, c1, c2, t) = {
+ // -3(a(1-t)^2 + t(-2c2 - bt + 3 c2 t) + c1(-1 + 4t - 3t^2))
+ vector.scale(
+ vector.add(
+ vector.add(
+ vector.scale(a, calc.pow((1 - t), 2)),
+ vector.scale(
+ vector.sub(
+ vector.add(
+ vector.scale(b, -1 * t),
+ vector.scale(c2, 3 * t)
+ ),
+ vector.scale(c2, 2)
+ ),
+ t
+ )
+ ),
+ vector.scale(c1, -3 * calc.pow(t, 2) + 4 * t - 1)
+ ),
+ -3
+ )
+}
+
+/// Get a bezier curve's ABC coordinates. Returns them as a respective <Type>array</Type> of <Type>vector</Type>s.
+/// ```
+/// /A\ <-- Control point of quadratic bezier
+/// / | \
+/// / | \
+/// /_.-B-._\ <-- Point on curve
+/// ,' | ',
+/// / | \
+/// s------C------e <-- Point on line between s and e
+/// ```
+/// - s (vector): Curve start
+/// - e (vector): Curve end
+/// - B (vector): Point on curve
+/// - t (float): Position on curve $[0, 1]$
+/// - deg (int): Bezier degree (2 or 3)
+/// -> array
+#let to-abc(s, e, B, t, deg: 2) = {
+ let abc-ratio(t) = {
+ if t == 0 or t == 1 { return t }
+ let bottom = calc.pow(t, deg) + calc.pow(1 - t, deg)
+ let top = bottom - 1
+ return calc.abs(top / bottom)
+ }
+
+ let projection-ratio(t) = {
+ if t == 0 or t == 1 { return t }
+ let top = calc.pow(1 - t, deg)
+ let bottom = calc.pow(t, deg) + top
+ return top / bottom
+ }
+
+ let u = projection-ratio(t)
+ let um = 1 - u
+
+ let C = vector.add(
+ vector.scale(s, u),
+ vector.scale(e, um))
+
+ let s = abc-ratio(t)
+ let A = vector.add(
+ B,
+ vector.scale(vector.sub(B, C), 1/s))
+
+ return (A, B, C)
+}
+
+
+/// Compute the control points for a quadratic bezier through 3 points.
+///
+/// - s (vector): Curve start
+/// - e (vector): Curve end
+/// - B (vector): A point which the curve passes through
+/// -> bezier
+#let quadratic-through-3points(s, B, e) = {
+ let d1 = vector.dist(s, B)
+ let d2 = vector.dist(e, B)
+ let t = d1 / (d1 + d2)
+
+ let (A, B, C) = to-abc(s, e, B, t, deg: 2)
+
+ return (s, e, A)
+}
+
+
+/// Convert a quadratic bezier to a cubic bezier.
+///
+/// - s (vector): Curve start
+/// - e (vector): Curve end
+/// - c (vector): Control point
+/// -> bezier
+#let quadratic-to-cubic(s, e, c) = {
+ let c1 = vector.add(s, vector.scale(vector.sub(c, s), 2/3))
+ let c2 = vector.add(e, vector.scale(vector.sub(c, e), 2/3))
+ return (s, e, c1, c2)
+}
+
+/// Compute the control points for a cubic bezier through 3 points.
+///
+/// - s (vector): Curve start
+/// - e (vector): Curve end
+/// - B (vector): A point which the curve passes through
+/// -> bezier
+#let cubic-through-3points(s, B, e) = {
+ if s == B or e == B {
+ return (s, e, s, e)
+ }
+
+ let d1 = vector.dist(s, B)
+ let d2 = vector.dist(e, B)
+ let t = d1 / (d1 + d2)
+
+ let (A, _, C) = to-abc(s, e, B, t, deg: 3)
+
+ let angle = vector.angle2(s, e) - vector.angle2(s, B)
+ if angle == 0deg or calc.abs(angle) == 180deg {
+ let se = vector.dist(s, e)
+ let sB = vector.dist(s, B)
+ let eB = vector.dist(e, B)
+
+ if sB >= se and sB >= eB {
+ return (s, B, s, B)
+ } else if eB >= se and eB >= sB {
+ return (e, B, e, B)
+ }
+ return (s, e, s, e)
+ }
+
+ let bc = (if angle < 0deg or angle > 180deg { -1 } else { 1 }) * vector.dist(s, e) / 3
+ let de1 = t * bc
+ let de2 = (1 - t) * bc
+
+ let (ax, ay, az) = A
+ let (sx, sy, sz) = s
+ let (ex, ey, ez) = e
+ let (bx, by, bz) = B
+
+ import "/src/util.typ": calculate-circle-center-3pt
+ let (cx, cy, cz) = calculate-circle-center-3pt(s, B, e)
+ let tangent = (
+ (bx - (by - cy), by + (bx - cx), bz),
+ (bx + (by - cy), by - (bx - cx), bz))
+ let (dx, dy, dz) = vector.norm(vector.sub(tangent.at(1), tangent.at(0)))
+
+ let (e1x, e1y) = (
+ bx + de1 * dx,
+ by + de1 * dy)
+ let (e2x, e2y) = (
+ bx - de2 * dx,
+ by - de2 * dy)
+ let (v1x, v1y) = (
+ ax + (e1x - ax) / (1 - t),
+ ay + (e1y - ay) / (1 - t))
+ let (v2x, v2y) = (
+ ax + (e2x - ax) / t,
+ ay + (e2y - ay) / t)
+ let c1 = (
+ sx + (v1x - sx) / t,
+ sy + (v1y - sy) / t)
+ let c2 = (
+ ex + (v2x - ex) / (1 - t),
+ ey + (v2y - ey) / (1 - t))
+
+ return (s, e, c1, c2)
+}
+
+/// Split a cubic bezier into two cubic beziers at the point `t`. Returns an <Type>array</Type> of two <Type>bezier</Type>. The first holds the original curve start `s`, and the second holds the original curve end `e`.
+///
+/// - s (vector): Curve start
+/// - e (vector): Curve end
+/// - c1 (vector): Control point 1
+/// - c2 (vector): Control point 2
+/// - t (float): The point on the bezier to split, $[0, 1]$
+/// -> array
+#let split(s, e, c1, c2, t) = {
+ t = calc.max(0, calc.min(t, 1))
+
+ let split-rec(pts, t, left, right) = {
+ if pts.len() == 1 {
+ left.push(pts.at(0))
+ right.push(pts.at(0))
+ } else {
+ let new-pts = ()
+ for i in range(0, pts.len() - 1) {
+ if i == 0 {
+ left.push(pts.at(i))
+ }
+ if i == pts.len() - 2 {
+ right.push(pts.at(i + 1))
+ }
+ new-pts.push(vector.add(vector.scale(pts.at(i), (1 - t)),
+ vector.scale(pts.at(i + 1), t)))
+ }
+ (left, right) = split-rec(new-pts, t, left, right)
+ }
+ return (left, right)
+ }
+ let (left, right) = split-rec((s, c1, c2, e), t, (), ())
+
+ return ((left.at(0), left.at(3), left.at(1), left.at(2)),
+ (right.at(3), right.at(0), right.at(2), right.at(1)))
+}
+
+/// Get the approximate cubic curve length
+/// - s (vector): Curve start
+/// - e (vector): Curve end
+/// - c1 (vector): Control point 1
+/// - c2 (vector): Control point 2
+/// -> float
+#let cubic-arclen(s, e, c1, c2, samples: 20) = {
+ let d = 0
+ for i in range(1, samples + 1) {
+ let t0 = (i - 1) / samples
+ let t1 = i / samples
+ d += vector.dist(
+ cubic-point(s, e, c1, c2, t0),
+ cubic-point(s, e, c1, c2, t1))
+ }
+ return d
+}
+
+/// Shorten the curve by offsetting s and c1 or e and c2 by distance d. If d is positive the curve gets shortened by moving s and c1 closer to e, if d is negative, e and c2 get moved closer to s.
+///
+/// - s (vector): Curve start
+/// - e (vector): Curve end
+/// - c1 (vector): Control point 1
+/// - c2 (vector): Control point 2
+/// - d (float): Distance to shorten by
+/// -> bezier
+#let cubic-shorten-linear(s, e, c1, c2, d) = {
+ if d == 0 { return (s, e, c1, c2) }
+
+ let t = if d < 0 { 1 } else { 0 }
+ let sign = if d < 0 { -1 } else { 1 }
+
+ let a = cubic-point(s, e, c1, c2, t)
+ let b = cubic-point(s, e, c1, c2, t + sign * 0.01)
+ let offset = vector.scale(vector.norm(vector.sub(b, a)),
+ calc.abs(d))
+ if d > 0 {
+ s = vector.add(s, offset)
+ c1 = vector.add(c1, offset)
+ } else {
+ e = vector.add(e, offset)
+ c2 = vector.add(c2, offset)
+ }
+ return (s, e, c1, c2)
+}
+
+/// Approximate bezier interval `t` for a given distance `d`. If `d` is positive, the functions starts from the curve's start `s`, if `d` is negative, it starts form the curve's end `e`.
+/// - s (vector): Curve start
+/// - e (vector): Curve end
+/// - c1 (vector): Control point 1
+/// - c2 (vector): Control point 2
+/// - d (float): The distance along the bezier to find `t`.
+/// -> float
+#let cubic-t-for-distance(s, e, c1, c2, d, samples: 20) = {
+ let travel-forwards(s, e, c1, c2, d) = {
+ let sum = 0
+ for n in range(1, samples + 1) {
+ let t0 = (n - 1) / samples
+ let t1 = n / samples
+
+ let segment-dist = vector.dist(cubic-point(s, e, c1, c2, t0),
+ cubic-point(s, e, c1, c2, t1))
+ if sum <= d and d <= sum + segment-dist {
+ let lambda = (d - sum) / segment-dist
+ return (1 - lambda) * t0 + lambda * t1
+ }
+ sum += segment-dist
+ }
+ return 1
+ }
+
+ if d == 0 {
+ return 0
+ }
+
+ if d > 0 {
+ return travel-forwards(s, e, c1, c2, d)
+ } else {
+ return 1 - travel-forwards(e, s, c2, c1, -d)
+ }
+}
+
+/// Shorten curve by distance `d`. This keeps the curvature of the curve by finding new values along the original curve. If `d` is positive the curve gets shortened by moving `s` closer to `e`, if `d` is negative, `e` is moved closer to `s`. The points `s` and `e` are moved along the curve, keeping the curve's curvature the same (the control points get recalculated).
+///
+/// - s (vector): Curve start
+/// - e (vector): Curve end
+/// - c1 (vector): Control point 1
+/// - c2 (vector): Control point 2
+/// - d (float): Distance to shorten by
+/// - samples (int): Maximum of samples/steps to use
+/// -> bezier
+#let cubic-shorten(s, e, c1, c2, d, samples: 15) = {
+ if d == 0 { return (s, e, c1, c2) }
+
+ let (left, right) = split(s, e, c1, c2, cubic-t-for-distance(s, e, c1, c2, d, samples: samples))
+ return if d > 0 {
+ right
+ } else {
+ left
+ }
+}
+
+/// Find cubic curve extrema by calculating the roots of the curve's first derivative. Returns an <Type>array</Type> of <Type>vector</Type> ordered by distance along the curve from the start to its end.
+/// - s (vector): Curve start
+/// - e (vector): Curve end
+/// - c1 (vector): Control point 1
+/// - c2 (vector): Control point 2
+/// -> array
+#let cubic-extrema(s, e, c1, c2) = {
+ let args = (s: s, e: e, c1: c1, c2: c2)
+ return call_wasm(cetz-core.cubic_extrema_func, args)
+}
+
+/// Returns axis aligned bounding box coordinates `(bottom-left, top-right)` for a cubic bezier curve.
+///
+/// - s (vector): Curve start
+/// - e (vector): Curve end
+/// - c1 (vector): Control point 1
+/// - c2 (vector): Control point 2
+/// -> array
+#let cubic-aabb(s, e, c1, c2) = {
+ return aabb.aabb(cubic-extrema(s, e, c1, c2) + (s, e,)).bounds
+}
+
+/// Returns a cubic bezier between points `p2` and `p3` for a catmull-rom curve through all four points.
+///
+/// - p1 (vector): Point 1
+/// - p2 (vector): Point 2
+/// - p3 (vector): Point 3
+/// - p4 (vector): Point 4
+/// - k (float): The tension of the catmull-rom curve. Must be in the range $[0, 1]$
+/// -> bezier
+#let _catmull-section-to-cubic(p1, p2, p3, p4, k) = {
+ return (p2, p3,
+ vector.add(p2, vector.scale(vector.sub(p3, p1), 1/(k * 6))),
+ vector.sub(p3, vector.scale(vector.sub(p4, p2), 1/(k * 6))))
+}
+
+/// Returns an array of cubic <Type>bezier</Type> for a catmull curve through an array of points.
+///
+/// - points (array): Array of 2d points
+/// - k (float): Strength between 0 and 1
+/// - close (bool):
+/// -> array
+#let catmull-to-cubic(points, k, close: false) = {
+ k = calc.max(k, 0.1)
+ k = if k < .5 {
+ 1 / _map(k, .5, 0, 1, 10)
+ } else {
+ _map(k, .5, 1, 1, 10)
+ }
+
+ let len = points.len()
+ if len == 2 {
+ return ((points.at(0), points.at(1),
+ points.at(0), points.at(1)),)
+ } else if len > 2 {
+ let curves = ()
+
+ let (i0, iN) = if close {
+ (-1, 0)
+ } else {
+ (0, -1)
+ }
+
+ curves.push(_catmull-section-to-cubic(points.at(i0), points.at(0),
+ points.at(1), points.at(2), k))
+ for i in range(1, len - 2, step: 1) {
+ curves.push(_catmull-section-to-cubic(
+ ..range(i - 1, i + 3).map(i => points.at(i)), k))
+ }
+
+ curves.push(_catmull-section-to-cubic(
+ points.at(-3), points.at(-2), points.at(-1), points.at(iN), k))
+
+ if close {
+ curves.push(_catmull-section-to-cubic(
+ points.at(-2), points.at(-1), points.at(0), points.at(1), k))
+ }
+
+ return curves
+ }
+ return ()
+}
+
+/// Find the roots of a cubic polynomial with the coefficients a, b, c and d.
+///
+/// -> array Array of roots
+#let _cubic-roots(a, b, c, d, eps: epsilon) = {
+ if calc.abs(a) < eps {
+ if calc.abs(b) < eps {
+ // Constant
+ if calc.abs(c) < eps {
+ return ()
+ }
+
+ // Linear
+ let root = -1 * d / c
+ if root < -eps or root > 1 + eps {
+ return ()
+ }
+ return (root,)
+ }
+
+ // Quadratic
+ let dq = calc.pow(c, 2) - 4 * b * d
+ if dq >= 0 {
+ dq = calc.sqrt(dq)
+ let roots = (-1 * (dq + c) / (2 * b),
+ (dq - c) / (2 * b))
+ return roots.filter(t => t >= -eps and t <= 1 + eps)
+ } else {
+ // No real roots
+ return ()
+ }
+ }
+
+ let (A, B, C) = (b/a, c/a, d/a)
+ let Q = (3 * B - calc.pow(A, 2)) / 9
+ let R = (9 * A * B - 27 * C - 2 * calc.pow(A, 3)) / 54
+ let D = calc.pow(Q, 3) + calc.pow(R, 2)
+ let aa = -A / 3
+
+ let sgn = x => { if x < 0 { -1 } else { 1 } }
+ let roots = if D >= 0 {
+ let S = sgn(R + calc.sqrt(D)) * calc.pow(calc.abs(R + calc.sqrt(D)), 1/3)
+ let T = sgn(R - calc.sqrt(D)) * calc.pow(calc.abs(R - calc.sqrt(D)), 1/3)
+
+ if calc.abs(S - T) > eps {
+ // Roots 2 and 3 are complex
+ (aa + (S + T),)
+ } else {
+ (aa + (S + T), aa - (S + T) / 2)
+ }
+ } else {
+ let th = calc.acos(R / calc.sqrt(-calc.pow(Q, 3))) / 1rad
+ let qq = 2 * calc.sqrt(-Q)
+ (qq * calc.cos(th / 3) + aa,
+ qq * calc.cos((th + 2 * calc.pi) / 3) + aa,
+ qq * calc.cos((th + 4 * calc.pi) / 3) + aa)
+ }
+
+ return roots.filter(t => t >= -eps and t <= 1 + eps)
+}
+
+/// Calculate the intersection points between a 2D cubic-bezier and a straight line. Returns an array of <Type>vector</Type>
+///
+/// - s (vector): Bezier start point
+/// - e (vector): Bezier end point
+/// - c1 (vector): Bezier control point 1
+/// - c2 (vector): Bezier control point 2
+/// - la (vector): Line start point
+/// - lb (vector): Line end point
+/// - ray (bool): If set to true, ignore line length
+/// -> array
+#let line-cubic-intersections(la, lb, s, e, c1, c2, ray: false, eps: epsilon) = {
+ // Based on:
+ // http://www.particleincell.com/blog/2013/cubic-line-intersection/
+ // with some rounding improvements
+ let a = lb.at(1) - la.at(1)
+ let b = la.at(0) - lb.at(0)
+ let c = la.at(0) * (la.at(1) - lb.at(1)) + la.at(1) * (lb.at(0) - la.at(0))
+
+ /// Get cubic bezier function coefficients
+ let _cubic-coeff(a, b, c, d) = (
+ -a + 3*b - 3*c + d,
+ 3*a - 6*b + 3*c,
+ -3*a +3*b,
+ a)
+
+ let x-coeff = _cubic-coeff(s.at(0), c1.at(0), c2.at(0), e.at(0))
+ let y-coeff = _cubic-coeff(s.at(1), c1.at(1), c2.at(1), e.at(1))
+
+ let roots = _cubic-roots(a * x-coeff.at(0) + b * y-coeff.at(0),
+ a * x-coeff.at(1) + b * y-coeff.at(1),
+ a * x-coeff.at(2) + b * y-coeff.at(2),
+ a * x-coeff.at(3) + b * y-coeff.at(3) + c)
+
+ let pts = ()
+ for t in roots {
+ if t < -eps or t > 1 + eps {
+ continue
+ }
+
+ let pt = cubic-point(s, e, c1, c2, calc.clamp(t, 0, 1))
+ if ray {
+ pts.push(pt)
+ } else {
+ let s = if calc.abs(lb.at(0) - la.at(0)) >= eps {
+ (pt.at(0) - la.at(0)) / (lb.at(0) - la.at(0))
+ } else {
+ (pt.at(1) - la.at(1)) / (lb.at(1) - la.at(1))
+ }
+ if s > -eps and s <= 1 + eps {
+ pts.push(pt)
+ }
+ }
+ }
+ return pts
+}
diff --git a/render/packages/preview/cetz/0.5.2/src/canvas.typ b/render/packages/preview/cetz/0.5.2/src/canvas.typ
new file mode 100644
index 0000000..84d685c
--- /dev/null
+++ b/render/packages/preview/cetz/0.5.2/src/canvas.typ
@@ -0,0 +1,189 @@
+#import "version.typ"
+#import "drawable.typ"
+#import "vector.typ"
+#import "matrix.typ"
+#import "util.typ"
+#import "path-util.typ"
+#import "aabb.typ"
+#import "styles.typ"
+#import "process.typ"
+#import "coordinate.typ"
+
+/// Sets up a canvas for drawing on.
+///
+/// - length (length): Used to specify what 1 coordinate unit is. Note that ratios are no longer supported! You can wrap the canvas into a `layout(ly => canvas(length: ly.width * <ratio>, ...))`.
+/// - baseline (none,number,coordinate): Specifies the coordinate to use as the baseline. Setting this the canvas behaves like a `box` element instead of a `block`.
+/// - body (none, array, element): A code block in which functions from the `draw` module have been called.
+/// - background (none, color): A color to be used for the background of the canvas.
+/// - stroke (none, stroke): Stroke style to apply to the canvas top-level element (box or block)
+/// - padding (none, number, array, dictionary) = none: How much padding to add to the canvas. `none` applies no padding. A number applies padding to all sides equally. A dictionary applies padding following Typst's `pad` function: https://typst.app/docs/reference/layout/pad/. An array follows CSS like padding: `(y, x)`, `(top, x, bottom)` or `(top, right, bottom, left)`.
+/// - x (number, vector) = 1.0: Sets up the x vector of the coordinate system to `(x, 0, 0)` or to the given vector.
+/// - y (number, vector) = 1.0: Sets up the y vector of the coordinate system to `(0, y, 0)` or to the given vector.
+/// - z (number, vector) = 1.0: Sets up the z vector of the coordinate system to `(0, 0, z)` or to the given vector.
+/// - debug (bool): Shows the bounding boxes of each element when `true`.
+/// -> content
+#let canvas(length: 1cm, x: 1.0, y: 1.0, z: 1.0, baseline: none, debug: false, background: none, stroke: none, padding: none, body) = context {
+ if body == none {
+ return []
+ }
+ if type(body) != array {
+ panic("Incorrect type for body: " + repr(type(body)))
+ }
+ if type(length) != std.length {
+ panic("Expected `length` to be of type length, got " + repr(length))
+ }
+
+ let length = length.to-absolute()
+ assert(length / 1cm != 0,
+ message: "Canvas length must be != 0!")
+
+ // Prepare the coordinate system
+ let resolve-number(x) = {
+ return if type(x) == std.length {
+ x / length
+ } else {
+ float(x)
+ }
+ }
+ let x = (if type(x) != array { (x, 0.0, 0.0) } else { x }).map(resolve-number)
+ let y = (if type(y) != array { (0.0, y, 0.0) } else { y }).map(resolve-number)
+ let z = (if type(z) != array { (0.0, 0.0, z) } else { z }).map(resolve-number)
+
+ let ctx = (
+ version: version.version,
+ length: length,
+ debug: debug,
+ background: background,
+ // Previous element position & bbox
+ prev: (pt: (0.0, 0.0, 0.0)),
+ style: styles.default,
+ // Current transformation matrix
+ transform:
+ ((x.at(0, default: 1.0), y.at(0, default: 0.0), z.at(0, default: 0.0), 0.0),
+ (x.at(1, default: 0.0), y.at(1, default: 1.0), z.at(1, default: 0.0), 0.0),
+ (x.at(2, default: 0.0), y.at(2, default: 0.0), z.at(2, default: 1.0), 0.0),
+ (0.0, 0.0, 0.0, 1.0)),
+ // Nodes, stores anchors and paths
+ nodes: (:),
+ // Group stack
+ groups: (),
+ // User defined marks
+ marks: (
+ mnemonics: (:),
+ marks: (:),
+ ),
+ // coordinate resolver
+ resolve-coordinate: (),
+ // Shared state that is not scoped by group/scope elements.
+ // CeTZ itself does not use this dictionary for data.
+ shared-state: (:),
+ )
+
+ let (ctx, bounds, drawables) = process.many(ctx, body)
+ if bounds == none {
+ return []
+ }
+
+ // Filter hidden drawables
+ drawables = drawable.filter-tagged(drawables, drawable.TAG.hidden)
+
+ // Order draw commands by z-index
+ drawables = drawables.sorted(key: (cmd) => {
+ return cmd.at("z-index", default: 0)
+ })
+
+ // Apply padding
+ let padding = util.map-dict(util.as-padding-dict(padding), (_, v) => {
+ util.resolve-number(ctx, v)
+ })
+ let swapped-padding = padding
+ swapped-padding.top = padding.bottom
+ swapped-padding.bottom = padding.top
+ bounds = aabb.padded(bounds, swapped-padding)
+
+ // Final canvas size
+ let (width, height, ..) = vector.scale(aabb.size(bounds), length)
+
+ let (offset-x, offset-y, ..) = bounds.low
+ offset-y = -offset-y - height / length
+
+ // The top-level function the canvas gets wrapped in
+ let container-fn = block.with(breakable: false)
+
+ // Compute the baseline offset
+ let baseline-offset = 0cm
+ if baseline != none {
+ if type(baseline) in (int, float, length) {
+ baseline = (0, baseline)
+ }
+
+ let sub-ctx = ctx
+ sub-ctx.transform = matrix.ident(4)
+
+ let (_, (x, y, _)) = coordinate.resolve(sub-ctx, baseline)
+ baseline-offset = length * (-y - offset-y) - height
+
+ container-fn = box.with(baseline: -baseline-offset)
+ }
+
+ (container-fn)(width: width, height: height, stroke: stroke, fill: background, align(top, {
+ for drawable in drawables {
+ // Typst path elements have strange bounding boxes. We need to
+ // offset all paths to start at (0, 0) to make gradients work.
+ let (segment-x, segment-y, _) = if drawable.type == "path" {
+ let path-bounds = aabb.aabb(path-util.bounds(drawable.segments))
+ (path-bounds.low.at(0) - bounds.low.at(0),
+ bounds.high.at(1) - path-bounds.high.at(1),
+ 0)
+ } else {
+ (0, 0, 0)
+ }
+
+ place(top + left, float: false, if drawable.type == "path" {
+ let vertices = ()
+
+ let transform-point((x, y, ..)) = {
+ (( x - offset-x - segment-x) * length,
+ (-y - offset-y - segment-y) * length)
+ }
+
+ for ((origin, closed, segments)) in drawable.segments {
+ vertices.push(curve.move(transform-point(origin)))
+
+ for ((kind, ..args)) in segments {
+ if kind == "l" {
+ for pt in args {
+ vertices.push(curve.line(transform-point(pt)))
+ }
+ } else if kind == "c" {
+ vertices.push(curve.cubic(..args.map(transform-point)))
+ } else {
+ panic(kind, args)
+ }
+ }
+
+ if closed {
+ vertices.push(curve.close(mode: "straight"))
+ }
+ }
+
+ if type(drawable.stroke) == dictionary and "thickness" in drawable.stroke and type(drawable.stroke.thickness) != std.length {
+ drawable.stroke.thickness *= length
+ }
+ std.curve(
+ stroke: drawable.stroke,
+ fill: drawable.fill,
+ fill-rule: drawable.at("fill-rule", default: "non-zero"),
+ ..vertices,
+ )
+ } else if drawable.type == "content" {
+ let (width, height) = std.measure(drawable.body)
+ move(
+ dx: ( drawable.pos.at(0) - offset-x) * length - width / 2,
+ dy: (-drawable.pos.at(1) - offset-y) * length - height / 2,
+ drawable.body,
+ )
+ }, dx: segment-x * length, dy: segment-y * length)
+ }
+ }))
+}
diff --git a/render/packages/preview/cetz/0.5.2/src/complex.typ b/render/packages/preview/cetz/0.5.2/src/complex.typ
new file mode 100644
index 0000000..8e212a7
--- /dev/null
+++ b/render/packages/preview/cetz/0.5.2/src/complex.typ
@@ -0,0 +1,87 @@
+/// Returns the real part of a complex number.
+/// - V (complex): A complex number.
+/// -> float
+#let re(V) = V.at(0)
+
+/// Returns the imaginary part of a complex number.
+/// - V (complex): A complex number.
+/// -> float
+#let im(V) = V.at(1)
+
+
+/// Multiplies two complex numbers together and returns the result $V W$.
+/// - V (complex): The complex number on the left hand side.
+/// - W (complex): The complex number on the right hand side.
+#let mul(V, W) = (re(V) * re(W) - im(V) * im(W), im(V) * re(W) + re(V) * im(W))
+
+/// Calculates the conjugate of a complex number.
+/// - V (complex): A complex number.
+/// -> complex
+#let conj(V) = (re(V),-im(V))
+
+// TODO: check what "in R^2" means.
+/// Calculates the dot product of two complex numbers in R^2 $V \cdot W$.
+/// - V (complex): The complex number on the left hand side.
+/// - W (complex): The complex number on the right hand side.
+/// -> float
+#let dot(V,W) = re(mul(V,conj(W)))
+
+/// Calculates the squared normal of a complex number.
+/// - V (complex): The complex number.
+/// -> float
+#let normsq(V) = dot(V,V)
+
+
+/// Calculates the normal of a complex number
+/// - V (complex): The complex number.
+/// -> float
+#let norm(V) = calc.sqrt(normsq(V))
+
+/// Multiplies a complex number by a scale factor.
+/// - V (complex): The complex number to scale.
+/// - t (float): The scale factor.
+/// -> complex
+#let scale(V,t) = mul(V,(t,0))
+
+/// Returns a unit vector in the direction of a complex number.
+/// - V (complex): The complex number.
+/// -> vector
+#let unit(V) = scale(V, 1/norm(V))
+
+/// Inverts a complex number.
+/// - V (complex): The complex number
+/// -> complex
+#let inv(V) = scale(conj(V), 1/normsq(V))
+
+/// Divides two complex numbers.
+/// - V (complex): The complex number of the numerator.
+/// - W (complex): The complex number of the denominator.
+/// -> complex
+#let div(V,W) = mul(V,inv(W))
+
+/// Adds two complex numbers together.
+/// - V (complex): The complex number on the left hand side.
+/// - W (complex): The complex number on the right hand side.
+/// -> complex
+#let add(V,W) = (re(V) + re(W),im(V) + im(W))
+
+/// Subtracts two complex numbers together.
+/// - V (complex): The complex number on the left hand side.
+/// - W (complex): The complex number on the right hand side.
+/// -> complex
+#let sub(V,W) = (re(V) - re(W),im(V) - im(W))
+
+/// Calculates the argument of a complex number.
+/// - V (complex): The complex number.
+#let arg(V) = calc.atan2(..V) / 1rad
+
+/// Get the signed angle of two complex numbers from V to W.
+/// - V (complex): A complex number.
+/// - W (complex): A complex number.
+#let ang(V,W) = arg(div(W,V))
+
+// exp(i*a)
+#let expi(a) = (calc.cos(a),calc.sin(a))
+
+// Rotate by angle a
+#let rot(v,a) = mul(v,expi(a))
diff --git a/render/packages/preview/cetz/0.5.2/src/coordinate.typ b/render/packages/preview/cetz/0.5.2/src/coordinate.typ
new file mode 100644
index 0000000..03914ae
--- /dev/null
+++ b/render/packages/preview/cetz/0.5.2/src/coordinate.typ
@@ -0,0 +1,441 @@
+#import "vector.typ"
+#import "matrix.typ"
+#import "util.typ"
+#import "deps.typ"
+
+#let resolve-xyz(c) = {
+ // (x: <number> or <none>, y: <number> or <none>, z: <number> or <none>)
+ // (x, y)
+ // (x, y, z)
+
+ return if type(c) == array {
+ vector.as-vec(c)
+ } else {
+ (
+ c.at("x", default: 0),
+ c.at("y", default: 0),
+ c.at("z", default: 0),
+ )
+ }
+}
+
+
+#let resolve-polar(c) = {
+ // (angle: <angle>, radius: <number>)
+ // (angle: <angle>, radius: (x, y))
+ // (angle, radius)
+ // (angle, (x-radius, y-radius))
+
+ let (angle, xr, yr) = if type(c) == array {
+ (
+ c.first(),
+ ..if type(c.last()) == array {
+ c.last()
+ } else {
+ (c.last(), c.last())
+ }
+ )
+ } else {
+ (
+ c.angle,
+ ..if type(c.radius) == array {
+ c.radius
+ } else {
+ (c.radius, c.radius)
+ }
+ )
+ }
+ return (
+ xr * calc.cos(angle),
+ yr * calc.sin(angle),
+ 0
+ )
+}
+
+#let resolve-anchor(ctx, inverse, c) = {
+ // (name: <string>, anchor: <number, angle, string> or <none>)
+ // "name.anchor"
+ // "name"
+ let (name, anchor) = if type(c) == str {
+ if not c.contains(".") {
+ (c, "default")
+ } else {
+ let (name, ..anchor) = c.split(".")
+ (name, anchor)
+ }
+ } else {
+ (c.name, c.at("anchor", default: "default"))
+ }
+
+ // Check if node is known
+ let node = ctx.nodes.at(name, default: none)
+ if node == none {
+ panic("Unknown element '" + name + "' in elements " + repr(ctx.nodes.keys()))
+ }
+
+ // Resolve length anchors
+ if type(anchor) == length {
+ anchor = util.resolve-number(ctx, anchor)
+ }
+
+ return util.apply-transform(
+ inverse,
+ (node.anchors)(anchor)
+ )
+}
+
+#let resolve-barycentric(ctx, inverse, c) = {
+ // dictionary of numbers
+ return vector.scale(
+ c.bary.pairs().fold(
+ (0, 0, 0),
+ (vec, (k, v)) => {
+ vector.add(
+ vec,
+ vector.scale(
+ resolve-anchor(ctx, inverse, k),
+ v
+ )
+ )
+ }
+ ),
+ 1 / c.bary.values().sum()
+ )
+}
+
+#let resolve-relative(resolve, ctx, c) = {
+ // (rel: <coordinate>, update: <bool> or <none>, to: <coordinate>)
+ let update = c.at("update", default: true)
+ let (ctx, rel) = resolve(ctx, c.rel, update: false)
+ let (ctx, to) = if "to" in c {
+ resolve(ctx, c.to, update: false)
+ } else {
+ (ctx, ctx.prev.pt)
+ }
+ c = vector.add(
+ rel,
+ to,
+ )
+ c.insert(0, update)
+ return c
+}
+
+#let resolve-tangent(resolve, inverse, ctx, c) = {
+ // (element: <string>, point: <coordinate>, solution: <integer>)
+
+ // 1) center + query point
+ let C = resolve-anchor(ctx, inverse, c.element)
+ let (ctx, P) = resolve(ctx, c.point, update: false)
+
+ // 2) semi-axes a (east), b (north)
+ let a = vector.len(vector.sub(resolve-anchor(ctx, inverse, c.element + ".east"), C))
+ let b = vector.len(vector.sub(resolve-anchor(ctx, inverse, c.element + ".north"), C))
+
+ // 3) vector center→P
+ let D = vector.sub(P, C)
+
+ // 4) move into unit-circle coords
+ let Dscaled = (D.at(0)/a, D.at(1)/b)
+ let rho = vector.len(Dscaled)
+ if rho < 1 {
+ panic("No tangent solution for element " + c.element + " and point " + repr(c.point))
+ }
+
+ // 5) normalize & compute tangent parameters
+ let ux = Dscaled.at(0) / rho
+ let uy = Dscaled.at(1) / rho
+ let t = 1 / rho
+ let h = calc.sqrt(1 - t*t)
+
+ // 6) pick one of the two solutions on the unit circle
+ let (sx, sy) = if c.solution == 1 {
+ (
+ ux*t - uy*h,
+ uy*t + ux*h
+ )
+ } else {
+ (
+ ux*t + uy*h,
+ uy*t - ux*h
+ )
+ }
+
+ // 7) map back through the ellipse‐stretch and return
+ return (
+ C.at(0) + a * sx,
+ C.at(1) + b * sy,
+ 0
+ )
+}
+
+#let resolve-perpendicular(resolve, ctx, c) = {
+ // (horizontal: <coordinate>, vertical: <coordinate>)
+ // (horizontal, "-|", vertical)
+ // (vertical, "|-", horizontal)
+
+ let (ctx, horizontal, vertical) = resolve(ctx, ..if type(c) == array {
+ if c.at(1) == "|-" {
+ (c.first(), c.last())
+ } else {
+ // c.at(1) == "-|"
+ (c.last(), c.first())
+ }
+ } else {
+ (c.horizontal, c.vertical)
+ }, update: false)
+
+ return (
+ horizontal.at(0),
+ vertical.at(1),
+ 0
+ )
+}
+
+#let resolve-lerp(resolve, ctx, c) = {
+ // (a: <coordinate>, number: <number,ratio>,
+ // angle?: <angle>, b: <coordinate>)
+ // (a, <number, ratio>, b)
+ // (a, <number, ratio>, angle, b)
+
+ let (a, number, angle, b) = if type(c) == array {
+ if c.len() == 3 {
+ (
+ ..c.slice(0, 2),
+ none, // angle
+ c.last(),
+ )
+ } else {
+ c
+ }
+ } else {
+ (
+ c.a,
+ c.number,
+ c.at("angle", default: 0deg),
+ c.b
+ )
+ }
+
+ (ctx, a, b) = resolve(ctx, a, b)
+
+ if angle != none {
+ let (x, y, _) = vector.sub(b,a)
+ b = vector.add(
+ (
+ calc.cos(angle) * x - calc.sin(angle) * y,
+ calc.sin(angle) * x + calc.cos(angle) * y,
+ 0
+ ),
+ a,
+ )
+ }
+
+ let ab = vector.sub(b, a)
+
+ let is-absolute = type(number) != ratio
+ let distance = if is-absolute {
+ let dist = vector.len(ab)
+ if dist != 0 {
+ util.resolve-number(ctx, number) / dist
+ } else {
+ 0
+ }
+ } else {
+ number / 100%
+ }
+
+ return vector.add(a, vector.scale(ab, distance))
+}
+
+// Resolve a projection coordinate.
+//
+// (project: p, onto: (a, b))
+// (p, "_|_", a, b)
+// (p, "⟂", a, b)
+#let resolve-project-point-on-line(resolve, ctx, c) = {
+ let (ctx, a, b, p) = if type(c) == dictionary {
+ let (project: p, onto: (a, b)) = c
+ (_, a, b) = resolve(ctx, a, b)
+ (ctx, p) = resolve(ctx, p)
+ (ctx, a, b, p)
+ } else {
+ let (p, _, a, b) = c
+ (_, a, b) = resolve(ctx, a, b)
+ (ctx, p) = resolve(ctx, p)
+ (ctx, a, b, p)
+ }
+
+ let ap = vector.sub(p, a)
+ let ab = vector.sub(b, a)
+
+ return vector.add(a, vector.scale(ab, vector.dot(ap, ab) / vector.dot(ab, ab)))
+}
+
+#let resolve-function(resolve, ctx, c) = {
+ let (func, ..c) = c
+ (ctx, ..c) = resolve(ctx, ..c)
+ func(..c)
+}
+
+// Figures out what system a coordinate belongs to and returns the corresponding string.
+// - c (coordinate): The coordinate to find the system of.
+// -> str
+#let _resolve-system(c) = {
+ let t = if type(c) == dictionary {
+ let keys = c.keys()
+ let len = c.len()
+ if len in (1, 2, 3) and keys.all(k => k in ("x", "y", "z")) {
+ "xyz"
+ } else if len == 2 and keys.all(k => k in ("angle", "radius")) and {
+ let radius-type = type(c.radius)
+ radius-type in (int, float, length) or (radius-type == array and c.radius.len() == 2)
+ } {
+ "polar"
+ } else if len == 1 and keys == ("bary",) {
+ "barycentric"
+ } else if len in (1, 2) and keys.all(k => k in ("name", "anchor")) {
+ "anchor"
+ } else if len == 3 and keys.all(k => k in ("element", "point", "solution")) {
+ "tangent"
+ } else if len == 2 and keys.all(k => k in ("horizontal", "vertical")) {
+ "perpendicular"
+ } else if len in (1, 2, 3) and keys.all(k => k in ("rel", "to", "update")) {
+ "relative"
+ } else if len in (3, 4) and keys.all(k => k in ("a", "number", "angle", "abs", "b")) {
+ "lerp"
+ } else if len == 2 and keys.all(k => k in ("project", "onto")) {
+ "project"
+ }
+ } else if type(c) == array {
+ let len = c.len()
+ let t0 = if len > 0 { type(c.first()) }
+ let t1 = if len > 1 { type(c.at(1)) }
+ let t2 = if len > 2 { type(c.at(2)) }
+
+ if len == 0 {
+ "previous"
+ } else if len == 2 and t0 in (int, float, length) and t1 in (int, float, length) {
+ "xyz"
+ } else if len == 3 and t0 in (int, float, length) and t1 in (int, float, length) and t2 in (int, float, length) {
+ "xyz"
+ } else if len == 2 and t0 == angle {
+ "polar"
+ } else if len == 3 and c.at(1) in ("-|", "|-") {
+ "perpendicular"
+ } else if len == 3 and t1 in (int, float, length, ratio) {
+ "lerp"
+ } else if len == 4 and t1 in (int, float, length, ratio) and t2 == angle {
+ "lerp"
+ } else if len == 4 and c.at(1) in ("_|_", "⟂") {
+ "project"
+ } else if len >= 2 and t0 == function {
+ "function"
+ }
+ } else if type(c) == str {
+ if c.contains(".") {
+ "anchor"
+ } else {
+ "element"
+ }
+ }
+
+ if t == none {
+ panic("Failed to resolve coordinate system: " + repr(c))
+ }
+ return t
+}
+
+// Fast path for resolving 3 element vectors of numbers.
+#let _resolve-vec(ctx, v) = {
+ let (x, y, z, ..) = v
+ let t0 = type(x)
+ let t1 = type(y)
+ let t2 = type(z)
+ let int-float = (int, float)
+
+ if t0 in int-float and t1 in int-float and t2 in int-float {
+ return (float(x), float(y), float(z))
+ }
+
+ return (util.resolve-number(ctx, x),
+ util.resolve-number(ctx, y),
+ util.resolve-number(ctx, z))
+}
+
+/// Resolve a list of coordinates to absolute vectors. Returns an array of the new <Type>context</Type> then the resolved coordinate vectors.
+///
+/// ```example
+/// line((0,0), (1,1), name: "l")
+/// get-ctx(ctx => {
+/// // Get the vector of coordinate "l.start" and "l.end"
+/// let (ctx, a, b) = cetz.coordinate.resolve(ctx, "l.start", "l.end")
+/// content("l.start", [#a], frame: "rect", stroke: none, fill: white)
+/// content("l.end", [#b], frame: "rect", stroke: none, fill: white)
+/// })
+/// ```
+///
+/// - ctx (context): Canvas context object
+/// - ..coordinates (coordinate): List of coordinates
+/// - update (bool): Update the context's last position
+/// -> array
+#let resolve(ctx, ..coordinates, update: true) = {
+ let cached-inverse = none
+
+ let resolver = if type(ctx.resolve-coordinate) == array {
+ ctx.resolve-coordinate
+ } else {
+ ()
+ }
+
+ let result = ()
+ for c in coordinates.pos() {
+ for resolve-fn in resolver.rev() {
+ c = resolve-fn(ctx, c)
+ }
+
+ let t = _resolve-system(c)
+ c = _resolve-vec(ctx, if t == "xyz" {
+ resolve-xyz(c)
+ } else if t == "previous" {
+ ctx.prev.pt
+ } else if t == "polar" {
+ resolve-polar(c)
+ } else if t == "barycentric" {
+ if cached-inverse == none {
+ cached-inverse = matrix.inverse(ctx.transform)
+ }
+ resolve-barycentric(ctx, cached-inverse, c)
+ } else if t in ("element", "anchor") {
+ if cached-inverse == none {
+ cached-inverse = matrix.inverse(ctx.transform)
+ }
+ resolve-anchor(ctx, cached-inverse, c)
+ } else if t == "tangent" {
+ if cached-inverse == none {
+ cached-inverse = matrix.inverse(ctx.transform)
+ }
+ resolve-tangent(resolve, cached-inverse, ctx, c)
+ } else if t == "perpendicular" {
+ resolve-perpendicular(resolve, ctx, c)
+ } else if t == "relative" {
+ (update, ..c) = resolve-relative(resolve, ctx, c)
+ c
+ } else if t == "lerp" {
+ resolve-lerp(resolve, ctx, c)
+ } else if t == "project" {
+ resolve-project-point-on-line(resolve, ctx, c)
+ } else if t == "function" {
+ resolve-function(resolve, ctx, c)
+ } else {
+ panic("Failed to resolve coordinate of format: " + repr(c))
+ })
+
+ if update {
+ ctx.prev.pt = c
+ }
+
+ result.push(c)
+ }
+
+ return (ctx, ..result)
+}
diff --git a/render/packages/preview/cetz/0.5.2/src/deps.typ b/render/packages/preview/cetz/0.5.2/src/deps.typ
new file mode 100644
index 0000000..9957627
--- /dev/null
+++ b/render/packages/preview/cetz/0.5.2/src/deps.typ
@@ -0,0 +1 @@
+#import "@preview/oxifmt:1.0.0"
diff --git a/render/packages/preview/cetz/0.5.2/src/draw.typ b/render/packages/preview/cetz/0.5.2/src/draw.typ
new file mode 100644
index 0000000..8fa836d
--- /dev/null
+++ b/render/packages/preview/cetz/0.5.2/src/draw.typ
@@ -0,0 +1,7 @@
+#import "draw/grouping.typ": intersections, group, scope, anchor, copy-anchors, set-ctx, get-ctx, for-each-anchor, on-layer, hide, floating
+#import "draw/transformations.typ": set-transform, transform, rotate, translate, scale, set-origin, move-to, set-viewport
+#import "draw/styling.typ": set-style, fill, stroke, register-mark
+#import "draw/shapes.typ": circle, circle-through, arc, arc-through, mark, line, grid, content, rect, bezier, bezier-through, catmull, hobby, merge-path, polygon, compound-path, n-star, rect-around, svg-path
+#import "draw/boolean.typ": boolean
+#import "draw/projection.typ": ortho, perspective, on-xy, on-xz, on-zy
+#import "draw/util.typ": assert-version, register-coordinate-resolver
diff --git a/render/packages/preview/cetz/0.5.2/src/draw/boolean.typ b/render/packages/preview/cetz/0.5.2/src/draw/boolean.typ
new file mode 100644
index 0000000..44f54b6
--- /dev/null
+++ b/render/packages/preview/cetz/0.5.2/src/draw/boolean.typ
@@ -0,0 +1,288 @@
+#import "/src/drawable.typ"
+#import "/src/path-util.typ"
+#import "/src/process.typ"
+#import "/src/styles.typ"
+#import "/src/wasm.typ": call_wasm
+#import "/src/anchor.typ" as anchor_
+
+#let cetz-core = plugin("/cetz-core/cetz_core.wasm")
+
+// extract path subpaths and fill-rules from an array of resolved drawables
+#let _extract-paths(drawables, ignore-marks: true, ignore-hidden: true) = {
+ // exclude debug and content-frame drawables
+ let tags = (drawable.TAG.debug, drawable.TAG.content-frame)
+ if ignore-hidden { tags.push(drawable.TAG.hidden) }
+ if ignore-marks { tags.push(drawable.TAG.mark) }
+
+ let drawables = drawable.filter-tagged(drawables, ..tags)
+ let path-drawables = drawables.filter(d => d.type == "path")
+ let subpaths = path-drawables.map(d => d.segments).join(default: ())
+ let fill-rules = path-drawables.map(d => d.fill-rule)
+ return (subpaths, fill-rules)
+}
+
+// Resolves an operand into (subpaths, fill-rules). The operand can be:
+// - a string: the name of an existing element in `ctx.nodes`
+// - a CeTZ body
+#let _collect-path3d(ctx, operand, ignore-marks: true, ignore-hidden: true) = {
+ if type(operand) == str {
+ assert(
+ operand in ctx.nodes,
+ message: "boolean: no element named " + repr(operand),
+ )
+ let element = ctx.nodes.at(operand)
+ let raw = element.at("drawables", default: ())
+ let (subpaths, fill-rules) = _extract-paths(
+ raw,
+ ignore-marks: ignore-marks,
+ ignore-hidden: ignore-hidden,
+ )
+ return (subpaths, fill-rules)
+ }
+
+ let subpaths = ()
+ let fill-rules = ()
+ for element in operand {
+ let r = process.element(ctx, element)
+ if r != none {
+ ctx = r.ctx
+ let (extracted-subpaths, extracted-fill-rules) = _extract-paths(
+ r.drawables,
+ ignore-marks: ignore-marks,
+ ignore-hidden: ignore-hidden,
+ )
+ subpaths += extracted-subpaths
+ fill-rules += extracted-fill-rules
+ }
+ }
+ return (subpaths, fill-rules)
+}
+
+// Picks a fill-rule for one operand:
+// - If the user passed an explicit value (not `auto`), use it.
+// - Else if every contributing path drawable agrees on a single fill-rule, inherit that one.
+// - Else fall back to the style default.
+#let _infer-fill-rule(arg, observed, default) = {
+ if arg != auto {
+ return arg
+ }
+ let unique = observed.dedup()
+ if unique.len() == 1 {
+ return unique.first()
+ }
+ return default
+}
+
+// Projects a CeTZ 3D path to a 2D wire path, asserting all vertices share the
+// same z-plane (within `tol`) and all subpaths are closed.
+#let _path3d-to-wire2d(path3d, tol: 1e-6) = {
+ if path3d.len() == 0 {
+ return ((subpaths: ()), 0.0)
+ }
+
+ let (z0, same-z) = path-util.same-z-plane(path3d, tol: tol)
+ assert(same-z, message: "boolean: all input vertices must lie in a single z-plane.")
+
+ let drop-z(v) = (v.at(0), v.at(1))
+
+ let wire-subpaths = ()
+ for (origin, closed, segments) in path3d {
+ assert(closed, message: "boolean: every input subpath must be closed; got an open subpath")
+
+ let wire-segments = segments.map(seg => {
+ let (kind, ..args) = seg
+ if kind == "l" {
+ (kind: "l", to: drop-z(args.at(0)))
+ } else if kind == "c" {
+ let (c1, c2, to) = args
+ (kind: "c", c1: drop-z(c1), c2: drop-z(c2), to: drop-z(to))
+ } else {
+ panic("boolean: unsupported path segment kind " + repr(kind))
+ }
+ })
+
+ wire-subpaths.push((
+ origin: drop-z(origin),
+ closed: closed,
+ segments: wire-segments,
+ ))
+ }
+
+ return ((subpaths: wire-subpaths), z0)
+}
+
+// Injects z0 back into a 2D wire path to produce a CeTZ 3D path.
+#let _wire2d-to-path3d(wire, z0) = {
+ let inflate(v) = (v.at(0), v.at(1), z0)
+ return wire.subpaths.map(sp => {
+ let segments = sp.segments.map(seg => {
+ if seg.kind == "l" {
+ ("l", inflate(seg.to))
+ } else if seg.kind == "c" {
+ ("c", inflate(seg.c1), inflate(seg.c2), inflate(seg.to))
+ } else {
+ panic("boolean: unexpected wire segment kind " + repr(seg.kind))
+ }
+ })
+ (inflate(sp.origin), sp.closed, segments)
+ })
+}
+
+/// Performs a boolean operation on the paths produced by two CeTZ bodies.
+/// The supported operations are `"union"`, `"intersection"`, `"difference"`,
+/// and `"xor"`.
+///
+/// ```example
+/// boolean(
+/// { rect((-1, -1), (1, 0)) },
+/// { circle((0, 0), radius: 0.8) },
+/// op: "difference",
+/// fill: blue,
+/// )
+/// ```
+///
+/// Each operand can either be one or more type:elements or the name of an already-defined element (a string).
+///
+/// ```example
+/// rect((-1, -1), (1, 0), name: "r")
+/// circle((0, 0), radius: 0.8, name: "c")
+/// boolean("r", "c", op: "difference", fill: blue)
+/// ```
+///
+/// All input subpaths must be closed and lie in a single z-plane. The output
+/// is a single path drawable in the z-plane of the first input.
+///
+/// Each operand has its own fill-rule, which decides how its self-overlapping
+/// or nested subpaths are interpreted as a filled region *before* the
+/// boolean operation runs. By default (`auto`) the fill-rule is inferred
+/// from the operand: if every path drawable produced by the body agrees on
+/// one fill-rule (e.g. the body is a single `compound-path(..., fill-rule:
+/// "even-odd")`), that value is used; otherwise it falls back to
+/// `boolean`'s own resolved style.
+///
+/// - a (elements, str): First operand. Either an element body or the name
+/// of an existing element.
+/// - b (elements, str): Second operand. Either an element body or the name
+/// of an elementxisting element.
+/// - op (string): One of `"union"`, `"intersection"`, `"difference"`, `"xor"`.
+/// - fill-rule-a (auto, string): `"non-zero"` or `"even-odd"`, applied to `a`. If `auto`, inferred from `a`'s drawables
+/// - fill-rule-b (auto, string): `"non-zero"` or `"even-odd"`, applied to `b`. If `auto`, inferred from `b`'s drawables
+/// - eps (auto, float): Numerical accuracy. `auto` uses an automatically determined value.
+/// - ignore-marks (bool): Drop marks from the inputs (default: `true`).
+/// - ignore-hidden (bool): Drop hidden elements from the inputs (default: `true`).
+/// - name (none, string):
+/// - ..style (style):
+#let boolean(
+ a,
+ b,
+ op: "difference",
+ fill-rule-a: auto,
+ fill-rule-b: auto,
+ eps: auto,
+ ignore-marks: true,
+ ignore-hidden: true,
+ name: none,
+ ..style,
+) = {
+ let valid-op = ("union", "intersection", "difference", "xor")
+
+ assert.eq(
+ style.pos(),
+ (),
+ message: "boolean: unexpected positional arguments: " + repr(style.pos()),
+ )
+ let style = style.named()
+
+ assert(
+ op in valid-op,
+ message: "boolean: invalid op "
+ + repr(op)
+ + ". Expected one of: " + valid-op.join(", "),
+ )
+
+ let validate-fill-rule(name, value) = {
+ assert(
+ value == auto or value in ("non-zero", "even-odd"),
+ message: "boolean: invalid " + name + " " + repr(value) + ". Expected `auto`, \"non-zero\", or \"even-odd\".",
+ )
+ }
+ validate-fill-rule("fill-rule-a", fill-rule-a)
+ validate-fill-rule("fill-rule-b", fill-rule-b)
+
+ return (
+ ctx => {
+ let (a-path3d, a-fill-rules) = _collect-path3d(
+ ctx,
+ a,
+ ignore-marks: ignore-marks,
+ ignore-hidden: ignore-hidden,
+ )
+ let (b-path3d, b-fill-rules) = _collect-path3d(
+ ctx,
+ b,
+ ignore-marks: ignore-marks,
+ ignore-hidden: ignore-hidden,
+ )
+
+ let (a-wire, az) = _path3d-to-wire2d(a-path3d)
+ let (b-wire, bz) = _path3d-to-wire2d(b-path3d)
+
+ assert(
+ calc.abs(az - bz) < 1e-6,
+ message: "boolean: input paths must lie in the same z-plane; got z=" + repr(az) + " and z=" + repr(bz),
+ )
+
+ let resolved-style = styles.resolve(ctx.style, merge: style, root: "boolean")
+ let resolved-fill-rule-a = _infer-fill-rule(fill-rule-a, a-fill-rules, resolved-style.fill-rule)
+ let resolved-fill-rule-b = _infer-fill-rule(fill-rule-b, b-fill-rules, resolved-style.fill-rule)
+
+ let result = call_wasm(cetz-core.path_bool_func, (
+ a: a-wire,
+ b: b-wire,
+ op: op,
+ fill_rule_a: resolved-fill-rule-a,
+ fill_rule_b: resolved-fill-rule-b,
+ eps: if eps == auto { none } else { eps },
+ ))
+
+ let path3d = _wire2d-to-path3d(result.path, az)
+
+ // Empty result (e.g. difference of identical shapes): emit no drawables.
+ if path3d.len() == 0 {
+ return (
+ ctx: ctx,
+ name: name,
+ anchors: anchor => {
+ if anchor == () { () } else {
+ panic("boolean: result is empty; no anchor `" + repr(anchor) + "` available")
+ }
+ },
+ drawables: (),
+ )
+ }
+
+ let drawables = drawable.path(
+ fill: resolved-style.fill,
+ fill-rule: resolved-style.fill-rule,
+ stroke: resolved-style.stroke,
+ path3d,
+ )
+
+ let (_, anchors) = anchor_.setup(
+ auto,
+ (),
+ name: name,
+ transform: none,
+ path-anchors: true,
+ path: drawables,
+ )
+
+ return (
+ ctx: ctx,
+ name: name,
+ anchors: anchors,
+ drawables: drawables,
+ )
+ },
+ )
+}
diff --git a/render/packages/preview/cetz/0.5.2/src/draw/grouping.typ b/render/packages/preview/cetz/0.5.2/src/draw/grouping.typ
new file mode 100644
index 0000000..716079e
--- /dev/null
+++ b/render/packages/preview/cetz/0.5.2/src/draw/grouping.typ
@@ -0,0 +1,573 @@
+#import "/src/process.typ"
+#import "/src/intersection.typ"
+#import "/src/path-util.typ"
+#import "/src/styles.typ"
+#import "/src/drawable.typ"
+#import "/src/vector.typ"
+#import "/src/util.typ"
+#import "/src/coordinate.typ"
+#import "/src/aabb.typ"
+#import "/src/anchor.typ" as anchor_
+#import "/src/matrix.typ"
+#import "/src/deps.typ"
+#import deps.oxifmt: strfmt
+
+#import "transformations.typ": move-to
+
+/// Hides an element.
+///
+/// Hidden elements are not drawn to the canvas, are ignored when calculating bounding boxes and discarded by [`merge-path`](../shapes/merge-path). All other behaviours remain the same as a non-hidden element.
+///
+/// ```example
+/// set-style(radius: .5)
+/// intersections("i", {
+/// circle((0,0), name: "a")
+/// circle((1,2), name: "b")
+/// // Use a hidden line to find the border intersections
+/// hide(line("a.center", "b.center"))
+/// })
+/// line("i.0", "i.1")
+/// ```
+///
+/// - body (element): One or more elements to hide
+/// - bounds (bool): If true, respect the bounding box of the hidden elements for resizing the canvas
+#let hide(body, bounds: false) = {
+ if type(body) == array {
+ return body.map(f => {
+ (ctx) => {
+ let element = f(ctx)
+ if "drawables" in element {
+ element.drawables = drawable.apply-tags(element.drawables,
+ drawable.TAG.hidden, if not bounds { drawable.TAG.no-bounds })
+ }
+ return element
+ }
+ })
+ }
+ return body
+}
+
+/// Places an element without affecting bounding boxes.
+///
+/// Floating elements are drawn to the canvas but are ignored when calculating bounding boxes. All other behaviours remain the same.
+///
+/// ```example
+/// group(name: "g", {
+/// content((1,0), [Normal])
+/// content((0,1), [Normal])
+/// floating(content((.5,1.5), [Floating]))
+/// })
+/// set-style(stroke: red)
+/// rect("g.north-west", "g.south-east")
+/// ```
+///
+/// - body (element): One or more elements to place
+#let floating(body) = {
+ if type(body) == array {
+ return body.map(f => {
+ ctx => {
+ let element = f(ctx)
+ if "drawables" in element {
+ element.drawables = drawable.apply-tags(element.drawables, drawable.TAG.no-bounds)
+ }
+ return element
+ }
+ })
+ }
+ return body
+}
+
+/// This element acts as a scope, all state changes such as transformations and styling only affect the elements in the scope.
+/// Elements after the scope are not affected by the changes inside the scope.
+/// In contrast to `group`, the `scope` element does not create a named element itself and "leaks" body elements and anchors to the outside.
+///
+/// - body (elements, function): Elements to group together. At least one is required. A function that accepts `ctx` and returns elements is also accepted.
+#let scope(body) = (ctx => {
+ let drawables = ()
+ let group-ctx = ctx
+ group-ctx.groups.push(())
+
+ (ctx: group-ctx, drawables, bounds: _) = process.many(group-ctx, util.resolve-body(group-ctx, body), compute-bounds: false)
+
+ // Pass-through nodes and shared context data
+ ctx.nodes += group-ctx.nodes
+ ctx.shared-state = group-ctx.shared-state
+
+ return (
+ ctx: ctx,
+ drawables: drawables,
+ leak-nodes: true,
+ )
+},)
+
+
+/// Calculates the intersections between multiple paths and creates one anchor per intersection point.
+///
+/// All resulting anchors will be named numerically, starting at `0`. i.e., a call `intersections("a", ...)` will generate the anchors `"a.0"`, `"a.1"`, `"a.2"` to `"a.n"`, depending of the number of intersections.
+///
+/// ```example
+/// intersections("i", {
+/// circle((0, 0))
+/// bezier((0,0), (3,0), (1,-1), (2,1))
+/// line((0,-1), (0,1))
+/// rect((1.5,-1),(2.5,1))
+/// })
+/// for-each-anchor("i", (name) => {
+/// circle("i." + name, radius: .1, fill: blue)
+/// })
+/// ```
+///
+/// You can also use named elements:
+///
+/// ```example
+/// circle((0,0), name: "a")
+/// rect((0,0), (1,1), name: "b")
+/// intersections("i", "a", "b")
+/// for-each-anchor("i", (name) => {
+/// circle("i." + name, radius: .1, fill: blue)
+/// })
+/// ```
+///
+/// You can calculate intersections with hidden elements by using [`hide`](./hide).
+///
+/// - name (str): Name to prepend to the generated anchors. (Not to be confused with other `name` arguments that allow the use of anchor coordinates.)
+/// - ..elements (elements,str): Elements and/or element names to calculate intersections with. Elements referred to by name are (unlike elements passed) not drawn by the intersections function!
+/// - samples (int): Number of samples to use for non-linear path segments. A higher sample count can give more precise results but worse performance.
+/// - sort (none,function): A function of the form `(context, array<vector>) -> array<vector>`
+/// that gets called with the list of intersection points.
+/// - ignore-marks (bool): If true, ignore mark shapes.
+///
+/// CeTZ provides the following sorting functions:
+/// - sorting.points-by-distace(points, reference: (0, 0, 0))
+/// - sorting.points-by-angle(points, reference: (0, 0, 0))
+#let intersections(name, ..elements, samples: 10, sort: none, ignore-marks: true) = {
+ samples = calc.clamp(samples, 2, 2500)
+
+ assert(type(name) == str and name != "",
+ message: "Intersection must have a name, got:" + repr(name))
+ assert(elements.pos() != (),
+ message: "You must at least give one element to intersections.")
+
+ return scope((ctx => {
+ // List of drawables to calc intersections for;
+ // grouped by element.
+ let named-drawables = ()
+ // List of drawables passed as elements to calc intersections for;
+ // grouped by element.
+ let drawables = ()
+
+ for elem in elements.pos() {
+ if type(elem) == str {
+ assert(elem in ctx.nodes,
+ message: "No such element '" + elem + "' in elements " + repr(ctx.nodes.keys()))
+ named-drawables.push(ctx.nodes.at(elem).drawables)
+ } else {
+ for sub in elem {
+ let sub-drawables = ()
+ (ctx: ctx, drawables: sub-drawables, bounds: _) = process.element(ctx, sub, compute-bounds: false)
+ if sub-drawables != none and sub-drawables != () {
+ drawables.push(sub-drawables)
+ }
+ }
+ }
+ }
+
+ let elems = named-drawables + drawables
+ if ignore-marks { elems = drawable.filter-tagged(elems, drawable.TAG.mark) }
+
+ let pts = ()
+ if elems.len() > 1 {
+ for (i, elem-1) in elems.enumerate() {
+ for j in range(i + 1, elems.len()) {
+ let elem-2 = elems.at(j)
+ for path-1 in elem-1 {
+ for path-2 in elem-2 {
+ for pt in intersection.path-path(
+ path-1,
+ path-2,
+ samples: samples
+ ) {
+ if pt not in pts { pts.push(pt) }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ if sort != none {
+ pts = (sort)(ctx, pts)
+ }
+
+ let anchors = (:)
+ for (i, pt) in pts.enumerate() {
+ anchors.insert(str(i), pt)
+ }
+
+ return (
+ ctx: ctx,
+ name: name,
+ anchors: anchor_.setup(
+ anchor => {
+ anchors.at(anchor)
+ },
+ anchors.keys(),
+ transform: none,
+ name: name
+ ).last(),
+ drawables: drawables.flatten()
+ )
+ },))
+}
+
+/// Groups one or more elements together. This element acts as a scope, all state changes such as transformations and styling only affect the elements in the group. Elements after the group are not affected by the changes inside the group.
+///
+/// ```example
+/// // Create group
+/// group({
+/// stroke(5pt)
+/// scale(.5); rotate(45deg)
+/// rect((-1,-1),(1,1))
+/// })
+/// rect((-1,-1),(1,1))
+/// ```
+///
+/// - body (elements, function): Elements to group together. At least one is required. A function that accepts `ctx` and returns elements is also accepted.
+/// - anchor (none, str): Anchor to position the group and it's children relative to. For translation the difference between the groups `"default"` anchor and the passed anchor is used.
+/// - name (none, str):
+/// - ..style (style):
+///
+/// == Styling
+/// *Root:* `group`
+///
+/// - padding (none, number, array, dictionary) = none: How much padding to add around the group's bounding box. `none` applies no padding. A number applies padding to all sides equally. A dictionary applies padding following Typst's `pad` function: https://typst.app/docs/reference/layout/pad/. An array follows CSS like padding: `(y, x)`, `(top, x, bottom)` or `(top, right, bottom, left)`.
+///
+/// == Anchors
+/// Supports border and path anchors of the axis aligned bounding box of all the child elements of the group.
+///
+/// You can add custom named anchors to the group by using the [anchor](./anchor) element while in the scope of said group, see [anchor](./anchor) for more details.
+///
+/// The default anchor is `"center"` but this can be overridden by using [anchor](./anchor) to place a new anchor called `"default"`.
+///
+/// When using named elements within a group, you can access the element's anchors outside of the group by using the implicit anchor coordinate. e.g. `"a.b.north"`
+/// ```example
+/// group(name: "a", {
+/// circle((), name: "b")
+/// })
+/// circle("a.b.south", radius: 0.2)
+/// circle((name: "a", anchor: "b.north"), radius: 0.2)
+/// ```
+#let group(body, name: none, anchor: none, ..style) = {
+ // No extra positional arguments from the style sink
+ if style.pos().len() > 0 {
+ panic("Unexpected positional arguments: " + repr(style.pos()),)
+ }
+ util.assert-body(body)
+
+ (ctx => {
+ let style = styles.resolve(ctx.style, merge: style.named(), root: "group")
+
+ let bounds = none
+ let drawables = ()
+ let group-ctx = ctx
+ group-ctx.groups.push(())
+
+ let wants-bounds = name != none or anchor != none
+ (ctx: group-ctx, drawables, bounds) = process.many(group-ctx, util.resolve-body(group-ctx, body), compute-bounds: wants-bounds)
+
+ // Pass-through shared context data
+ ctx.shared-state = group-ctx.shared-state
+
+ // Fast path for anonymous groups
+ if name == none and anchor == none {
+ return (ctx: ctx, drawables: drawables)
+ }
+
+ // Apply bounds padding
+ bounds = if bounds != none {
+ let padding = util.map-dict(util.as-padding-dict(style.padding), (_, v) => {
+ util.resolve-number(ctx, v)
+ })
+ aabb.padded(bounds, padding)
+ }
+
+ // Calculate a bounding box path used for border anchor calculation.
+ let center = none
+ let width = none
+ let height = none
+ let path = none
+ if bounds != none {
+ (bounds.low.at(1), bounds.high.at(1)) = (bounds.high.at(1), bounds.low.at(1))
+ center = aabb.mid(bounds)
+ (width, height, ..) = aabb.size(bounds)
+
+ path = drawable.line-strip(aabb.corner-points(bounds), close: true)
+ }
+
+ // Children can be none if the groups array is empty
+ let anchors = (:)
+ for name in group-ctx.groups.last() {
+ let child = group-ctx.nodes.at(name)
+ if "anchors" in child {
+ anchors.insert(name, child.anchors)
+ }
+ }
+
+ let is-degenerate = (width != none and util.float-eq(width, 0)) or (height != none and util.float-eq(height, 0))
+
+ let all-anchors = if bounds != none {
+ (default: center, center: center)
+ } + anchors
+
+ let (transform, anchors) = anchor_.setup(
+ anchor => {
+ let (name, ..nested-anchors) = if type(anchor) == array {
+ anchor
+ } else {
+ (anchor,)
+ }
+ anchor = all-anchors.at(name)
+ if type(anchor) == function {
+ anchor(if nested-anchors == () { "default" } else { nested-anchors })
+ } else {
+ anchor
+ }
+ },
+ (anchors.keys() + if bounds != none { ("center",) }).dedup(),
+ name: name,
+ default: if bounds != none or "default" in anchors { "default" },
+ offset-anchor: anchor,
+ path-anchors: bounds != none,
+ border-anchors: bounds != none,
+ radii: (width, height),
+ path: path,
+ nested-anchors: true,
+ border-anchor-callback: if is-degenerate {
+ (center, angle) => {
+ let x = if util.float-eq(width, 0) { 0 } else { calc.cos(angle) }
+ let y = if util.float-eq(height, 0) { 0 } else { calc.sin(angle) }
+ return vector.add(center, (x * width / 2, y * height / 2))
+ }
+ } else {
+ none
+ }
+ )
+
+ return (
+ ctx: ctx,
+ name: name,
+ anchors: anchors,
+ drawables: drawable.apply-transform(transform, drawables),
+ )
+ },)
+}
+
+/// Creates a new anchor for the current group. The new anchor will be accessible from inside the group by using just the anchor's name as a coordinate.
+///
+/// ```example
+/// // Inside a group
+/// group(name: "g", {
+/// circle((0,0))
+/// anchor("x", (.4, .1))
+/// circle("x", radius: .2)
+/// })
+/// circle("g.x", radius: .1)
+/// ```
+///
+/// ```example
+/// // At the root scope
+/// anchor("x", (1, 1))
+/// // ...
+/// circle("x", radius: .1)
+/// ```
+///
+/// - name (str): The name of the anchor
+/// - position (coordinate): The position of the anchor
+#let anchor(name, position) = {
+ assert(name != none and name != "" and not name.starts-with("."),
+ message: "Anchors must not be none, \"\" or start with \".\"!")
+
+ return (ctx => {
+ let (ctx, position) = coordinate.resolve(ctx, position)
+ position = util.apply-transform(ctx.transform, position)
+ return (
+ ctx: ctx,
+ name: name,
+ anchors: anchor_.setup(
+ anchor => position,
+ ("default",),
+ default: "default",
+ name: name,
+ transform: none
+ ).last()
+ )
+ },)
+}
+
+/// Copies multiple anchors from one element into the current group. Panics when used outside of a group. Copied anchors will be accessible in the same way anchors created by the `anchor` element are.
+///
+/// - element (str): The name of the element to copy anchors from.
+/// - filter (auto,array): When set to `auto` all anchors will be copied to the group. An array of anchor names can instead be given so only the anchors that are in the element and the list will be copied over.
+#let copy-anchors(element, filter: auto) = {
+ (ctx => {
+ assert(
+ ctx.groups.len() > 0,
+ message: "copy-anchors cannot be used outside of a group.",
+ )
+ assert(
+ element in ctx.nodes,
+ message: "copy-anchors: Could not find element '" + element + "'",
+ )
+
+ let calc-anchors = ctx.nodes.at(element).anchors
+ let anchors = calc-anchors(())
+ if filter != auto {
+ anchors = anchors.filter(a => a in filter)
+ }
+
+ // Add each anchor as own element
+ for anchor in anchors {
+ ctx.nodes.insert(
+ anchor,
+ (anchors: name => {
+ if name == "default" {
+ calc-anchors(anchor)
+ } else if name == () {
+ ("default",)
+ } else {
+ calc-anchors((anchor,) + name)
+ }
+ })
+ )
+ ctx.groups.last().push(anchor)
+ }
+
+ return (ctx: ctx)
+ },)
+}
+
+/// An advanced element that allows you to modify the current canvas type:context.
+/// Note: The transformation matrix (`transform`) is rounded after calling the `callback` function and therefore might be not exactly the matrix specified. This is due to rounding errors and should not cause any problems.
+///
+/// ```example
+/// // Setting custom shared state
+/// set-ctx(ctx => {
+/// ctx.shared-state.my-state = (
+/// key: 123
+/// )
+/// return ctx
+/// })
+///
+/// // ...
+///
+/// // Access the context object
+/// get-ctx(ctx => content((), [#repr(ctx.shared-state)]))
+/// ```
+///
+/// You can store shared context data under a key in the `ctx.shared-state`
+/// dictionary. Note: the `ctx.shared-state` dictionary is not scoped by
+/// `group` or `scope` elements and can be used for canvas global state.
+///
+/// - callback (function): A function that accepts the type:context dictionary and only returns a new one.
+#let set-ctx(callback) = {
+ assert(type(callback) == function)
+ return (ctx => {
+ let new-ctx = callback(ctx)
+ assert(new-ctx != none, message: "set-ctx must return a context!")
+
+ if new-ctx.transform != ctx.transform {
+ // User supplied matrices can cause rounding issues
+ new-ctx.transform = matrix.round(new-ctx.transform)
+ }
+ (ctx: new-ctx)
+ },)
+}
+
+/// An advanced element that allows you to read the current `context` through a callback and return `element`s based on it.
+///
+/// ```example
+/// // Print the transformation matrix
+/// get-ctx(ctx => {
+/// content((), [#repr(ctx.transform)])
+/// })
+/// ```
+///
+/// - callback (function): A function that accepts the type:context and can return elements.
+#let get-ctx(callback) = {
+ assert(type(callback) == function)
+ (ctx => {
+ let body = callback(ctx)
+ if body != none {
+ let (ctx, drawables) = process.many(ctx, body, compute-bounds: false)
+ return (ctx: ctx, drawables: drawables)
+ }
+ return (ctx: ctx)
+ },)
+}
+
+/// Iterates through all named anchors of an element and calls a callback for each one.
+///
+/// ```example
+/// // Label nodes anchors
+/// rect((0, 0), (2,2), name: "my-rect")
+/// for-each-anchor("my-rect", exclude: ("start", "mid", "end"), (name) => {
+/// content((), box(inset: 1pt, fill: white, text(8pt, [#name])), angle: -30deg)
+/// })
+/// ```
+///
+/// - name (str): The name of the element with the anchors to loop through.
+/// - callback (function): A function that takes the anchor name and can return elements.
+/// - exclude (array): An array of anchor names to not include in the loop.
+#let for-each-anchor(name, callback, exclude: ()) = {
+ get-ctx(ctx => {
+ if not name in ctx.nodes {
+ panic(strfmt("Unknown element {} in elements {}", name, repr(ctx.nodes.keys())))
+ }
+
+ for anchor in (ctx.nodes.at(name).anchors)(()) {
+ if anchor == none or (anchor in exclude) { continue }
+ move-to(name + "." + anchor)
+ callback(anchor)
+ }
+ })
+}
+
+/// Places elements on a specific layer.
+///
+/// A layer determines the position of an element in the draw queue. A lower layer is drawn before a higher layer.
+///
+/// Layers can be used to draw behind or in front of other elements, even if the other elements were created before or after. An example would be drawing a background behind a text, but using the text's calculated bounding box for positioning the background.
+///
+/// ```example
+/// // Draw something behind text
+/// set-style(stroke: none)
+/// content((0, 0), [This is an example.], name: "text")
+/// on-layer(-1, {
+/// circle("text.north-east", radius: .3, fill: red)
+/// circle("text.south", radius: .4, fill: green)
+/// circle("text.north-west", radius: .2, fill: blue)
+/// })
+/// ```
+///
+/// - layer (float, int): The layer to place the elements on. Elements placed without `on-layer` are always placed on layer 0.
+/// - body (elements, function): Elements to draw on the layer specified. A function that accepts `ctx` and returns elements is also accepted.
+#let on-layer(layer, body) = {
+ util.assert-body(body)
+ assert(type(layer) in (int, float),
+ message: "Layer must be a float or integer, 0 being the default layer. Got: " + repr(layer))
+
+ return (ctx => {
+ let (ctx, drawables, bounds: _) = process.many(ctx, util.resolve-body(ctx, body), compute-bounds: false)
+ drawables = drawables.map(d => {
+ if d.at("z-index", default: none) == none {
+ d.z-index = layer
+ }
+ return d
+ })
+
+ return (
+ ctx: ctx,
+ drawables: drawables
+ )
+ },)
+}
diff --git a/render/packages/preview/cetz/0.5.2/src/draw/projection.typ b/render/packages/preview/cetz/0.5.2/src/draw/projection.typ
new file mode 100644
index 0000000..4b46944
--- /dev/null
+++ b/render/packages/preview/cetz/0.5.2/src/draw/projection.typ
@@ -0,0 +1,375 @@
+#import "grouping.typ": group, get-ctx, set-ctx, scope
+#import "transformations.typ": set-transform
+#import "/src/process.typ"
+#import "/src/matrix.typ"
+#import "/src/drawable.typ"
+#import "/src/util.typ"
+#import "/src/polygon.typ"
+#import "/src/path-util.typ"
+#import "/src/aabb.typ"
+
+// Get an orthographic view matrix for 3 angles
+#let ortho-matrix(x, y, z) = matrix.mul-mat(
+ matrix.ident(4),
+ matrix.transform-rotate-x(x),
+ matrix.transform-rotate-y(y),
+ matrix.transform-rotate-z(z),
+)
+
+#let ortho-projection-matrix = (
+ (1, 0, 0, 0),
+ (0, 1, 0, 0),
+ (0, 0, 0, 0),
+ (0, 0, 0, 1),
+)
+
+// Build perspective view matrix from rotation and camera distance.
+#let _perspective-view-matrix(view-rotation-matrix, distance) = {
+ matrix.mul-mat(
+ matrix.transform-translate(0, 0, -distance),
+ view-rotation-matrix,
+ )
+}
+
+// Perspective divide for a single point.
+#let _perspective-project-point(pt, near, ref-depth) = {
+ let x = pt.at(0)
+ let y = pt.at(1)
+ let z = pt.at(2, default: 0.0)
+ let w = calc.max(-z, near)
+ // Normalize by a reference depth so scale is anchored at that plane.
+ (ref-depth * x / w, ref-depth * y / w, z)
+}
+
+#let _sort-by-distance(drawables) = {
+ return drawables.sorted(key: d => {
+ let z = none
+ for ((origin, closed, segments)) in d.segments {
+ z = if z == none {
+ calc.max(origin.at(2))
+ } else {
+ calc.max(z, origin.at(2))
+ }
+ for ((kind, ..pts)) in segments {
+ pts = pts.map(p => p.at(2))
+ z = if z == none {
+ calc.max(..pts)
+ } else {
+ calc.max(z, ..pts)
+ }
+ }
+ }
+ return z
+ })
+}
+
+// Filter out all clock-wise polygons, or if `invert` is true,
+// all counter clock-wise ones.
+#let _filter-cw-faces(drawables, mode: "cw") = {
+ return drawables.filter(d => {
+ return if d.type != "content" and d.segments != () {
+ let poly = polygon.from-subpath(d.segments.first())
+ poly.first() != poly.last() or polygon.winding-order(poly) == mode
+ } else {
+ true
+ }
+ })
+}
+
+// Compute aggregate bounds from a list of drawables.
+#let _drawables-bounds(drawables) = {
+ let bounds = none
+ for d in drawable.filter-tagged(drawables, drawable.TAG.no-bounds) {
+ let pts = if d.type == "path" {
+ path-util.bounds(d.segments)
+ } else if d.type == "content" {
+ let (x, y, _, w, h,) = d.pos + (d.width, d.height)
+ ((x + w / 2, y - h / 2, 0.0), (x - w / 2, y + h / 2, 0.0))
+ } else {
+ ()
+ }
+ if pts != () {
+ bounds = aabb.aabb(pts, init: bounds)
+ }
+ }
+ return bounds
+}
+
+// Resolve reference depth as nearest drawable depth in camera space.
+#let _resolve-reference-depth(ctx, body, view-rotation-matrix, distance, near) = {
+ let probe-ctx = ctx
+ probe-ctx.transform = view-rotation-matrix
+ let (ctx: _, bounds: _, drawables: probe-drawables) = process.many(
+ probe-ctx,
+ util.resolve-body(probe-ctx, body))
+ let probe-bounds = _drawables-bounds(probe-drawables)
+ if probe-bounds == none {
+ return near
+ }
+
+ // In camera space, depth is w = distance - z_rot. The nearest depth is at z_max.
+ let z-max = probe-bounds.high.at(2)
+ calc.max(distance - z-max, near)
+}
+
+// Resolve distance/near values, including support for `auto`.
+#let _resolve-camera-distance-near(ctx, body, view-rotation-matrix, distance) = {
+ let distance = if distance == auto { auto } else { util.resolve-number(ctx, distance) }
+
+ let probe-ctx = ctx
+ probe-ctx.transform = view-rotation-matrix
+ let (ctx: _, bounds: _, drawables: probe-drawables) = process.many(
+ probe-ctx,
+ util.resolve-body(probe-ctx, body))
+ let probe-bounds = _drawables-bounds(probe-drawables)
+
+ let z-max = if probe-bounds == none { 0 } else { probe-bounds.high.at(2) }
+ let z-min = if probe-bounds == none { 0 } else { probe-bounds.low.at(2) }
+ let depth-span = calc.abs(z-max - z-min)
+ let probe-near = calc.max(0.001, 0.01 * calc.max(depth-span, 1))
+
+ if distance == auto {
+ // Use a larger margin to reduce perspective intensity for auto distance.
+ let margin = calc.max(probe-near * 3, depth-span * 2)
+ distance = calc.max(z-max + margin, probe-near * 2)
+ }
+
+ // Keep the camera in front of the nearest geometry after rotation.
+ let min-margin = calc.max(probe-near * 2, depth-span * 0.1)
+ let min-distance = z-max + min-margin
+ distance = calc.max(distance, min-distance)
+
+ let scene-scale = calc.max(depth-span, 1)
+ let min-w = distance - z-max
+ let near = if min-w > 0 {
+ calc.max(0.001, calc.min(min-w * 0.5, scene-scale * 0.05))
+ } else {
+ calc.max(0.001, scene-scale * 0.01)
+ }
+
+ assert(distance > 0, message: "distance must be > 0.")
+ assert(near > 0, message: "near must be > 0.")
+ (distance, near)
+}
+
+// Sets up a view matrix to transform all `body` elements. The current context
+// transform is not modified.
+//
+// - body (element): Elements
+// - view-matrix (matrix): View matrix
+// - projection-matrix (matrix): Projection matrix
+// - reset-transform (bool): Ignore the current transformation matrix
+// - sorted (bool): Sort drawables by maximum distance (front to back)
+// - cull-face (none,str): Enable back-face culling if set to `"cw"` for clockwise
+// or `"ccw"` for counter-clockwise. Polygons of the specified order will not get drawn.
+// - flatten (bool): Set $z=0$ for all geometry
+#let _projection(body, view-matrix, projection-matrix, reset-transform: true, sorted: true, cull-face: "cw", flatten: false) = {
+ (ctx => {
+ let transform = ctx.transform
+ let perspective-mode = type(projection-matrix) == function
+ let previous-perspective-mode = ctx.at("_perspective-projection", default: false)
+ if perspective-mode {
+ ctx._perspective-projection = true
+ }
+
+ let local-ctx = ctx
+ let local-transform = if flatten {
+ local-ctx.transform = matrix.mul-mat(
+ ((1,0,0,0), (0,1,0,0), (0,0,0,0), (0,0,0,1.0)),
+ view-matrix)
+ } else {
+ local-ctx.transform = view-matrix
+ }
+
+ let (ctx, drawables, bounds) = process.many(local-ctx, util.resolve-body(ctx, body))
+
+ if cull-face != none {
+ assert(cull-face in ("cw", "ccw"),
+ message: "cull-face must be none, cw or ccw.")
+ drawables = _filter-cw-faces(drawables, mode: cull-face)
+ }
+
+ if sorted {
+ drawables = _sort-by-distance(drawables)
+ }
+
+ ctx.transform = transform
+ if perspective-mode {
+ drawable.apply-transform(projection-matrix, drawables)
+ ctx._perspective-projection = previous-perspective-mode
+ }
+ if not reset-transform {
+ drawables = drawable.apply-transform(ctx.transform, drawables)
+ }
+
+ return (
+ ctx: ctx,
+ bounds: bounds,
+ drawables: drawables,
+ )
+ },)
+}
+
+// Apply function `fn` to all vertices of all
+// elements in `body`.
+//
+// - body (element): Elements
+// - ..mat (matrix): Transformation matrices
+#let scoped-transform(body, ..mat) = {
+ scope({
+ set-ctx(ctx => {
+ ctx.transform = matrix.mul-mat(ctx.transform, ..mat.pos().filter(m => m != none))
+ return ctx
+ })
+ body
+ })
+}
+
+/// Set-up an orthographic projection environment.
+///
+/// This is a transformation matrix that rotates elements around the x, the y and the z axis by the parameters given.
+///
+/// By default an isometric projection (x ≈ 35.264°, y = 45°) is set.
+///
+/// ```example
+/// ortho({
+/// on-xz({
+/// rect((-1,-1), (1,1))
+/// })
+/// })
+/// ```
+///
+/// - x (angle): X-axis rotation angle
+/// - y (angle): Y-axis rotation angle
+/// - z (angle): Z-axis rotation angle
+/// - sorted (bool): Sort drawables by maximum distance (front to back)
+/// - cull-face (none,str): Enable back-face culling if set to `"cw"` for clockwise
+/// or `"ccw"` for counter-clockwise. Polygons of the specified order will not get drawn.
+/// - reset-transform (bool): Ignore the current transformation matrix
+/// - flatten (bool): Set all z-components to 0.
+/// - body (element): Elements to draw
+#let ortho(x: 35.264deg, y: 45deg, z: 0deg, sorted: true, cull-face: none, reset-transform: false, flatten: false, body) = scope(ctx => {
+ _projection(body, ortho-matrix(x, y, z), ortho-projection-matrix,
+ sorted: sorted,
+ cull-face: cull-face,
+ reset-transform: reset-transform,
+ flatten: flatten)
+})
+
+/// Draw elements on the xy-plane with optional z offset.
+///
+/// All vertices of all elements will be changed in the following way: $mat(x, y, z_"argument")$, where $z_"argument"$ is the z-value given as argument.
+///
+/// ```example
+/// ortho({
+/// on-xy({
+/// rect((-1, -1), (1, 1))
+/// })
+/// })
+/// ```
+///
+/// - z (number): Z offset for all coordinates
+/// - body (element): Elements to draw
+#let on-xy(z: 0, body) = get-ctx(ctx => {
+ let z = util.resolve-number(ctx, z)
+ scoped-transform(body, if z != 0 {
+ matrix.transform-translate(0, 0, z)
+ }, matrix.ident(4))
+})
+
+/// Draw elements on the xz-plane with optional y offset.
+///
+/// All vertices of all elements will be changed in the following way: $mat(x, y_"argument", y)$, where $y_"argument"$ is the y-value given as argument.
+///
+/// ```example
+/// ortho({
+/// on-xz({
+/// rect((-1, -1), (1, 1))
+/// })
+/// })
+/// ```
+///
+/// - y (number): Y offset for all coordinates
+/// - body (element): Elements to draw
+#let on-xz(y: 0, body) = get-ctx(ctx => {
+ let y = util.resolve-number(ctx, y)
+ scoped-transform(body, if y != 0 {
+ matrix.transform-translate(0, y, 0)
+ }, matrix.transform-rotate-x(90deg))
+})
+
+/// Draw elements on the zy-plane with optional x offset.
+///
+/// All vertices of all elements will be changed in the following way:
+/// $mat(x_"argument", y, x)$, where $x_"argument"$ is the x-value given
+/// as argument.
+///
+/// ```example
+/// ortho({
+/// on-zy({
+/// rect((-1, -1), (1, 1))
+/// })
+/// })
+/// ```
+///
+/// - x (number): X offset for all coordinates
+/// - body (element): Elements to draw
+#let on-zy(x: 0, body) = get-ctx(ctx => {
+ let x = util.resolve-number(ctx, x)
+ scoped-transform(body, if x != 0 {
+ matrix.transform-translate(x, 0, 0)
+ }, matrix.transform-rotate-y(90deg))
+})
+
+/// Set-up a perspective projection environment.
+///
+/// Coordinates are transformed by a view matrix and then projected with
+/// perspective division:
+/// $x' = (d_"ref" * x) / w$ and $y' = (d_"ref" * y) / w$,
+/// where $w = max(-z, "near")$ in view space.
+///
+/// By default this uses the same isometric camera angles as `ortho`, but with
+/// perspective foreshortening.
+///
+/// ```example
+/// perspective({
+/// on-xz({
+/// rect((-1,-1), (1,1))
+/// })
+/// })
+/// ```
+///
+/// - x (angle): X-axis rotation angle
+/// - y (angle): Y-axis rotation angle
+/// - z (angle): Z-axis rotation angle
+/// - distance (number,auto): Distance from camera to scene origin. `auto`
+/// derives a stable value from scene depth.
+/// - sorted (bool): Sort drawables by depth (back to front)
+/// - cull-face (none,str): Enable back-face culling if set to `"cw"` for clockwise
+/// or `"ccw"` for counter-clockwise. Polygons of the specified order will not get drawn.
+/// - reset-transform (bool): Ignore the current transformation matrix
+/// - body (element): Elements to draw
+#let perspective(
+ x: 35.264deg,
+ y: 45deg,
+ z: 0deg,
+ distance: auto,
+ sorted: true,
+ cull-face: none,
+ reset-transform: false,
+ body,
+) = scope(ctx => {
+ let view-rotation-matrix = ortho-matrix(x, y, z)
+
+ let (distance, near) = _resolve-camera-distance-near(ctx, body,
+ view-rotation-matrix, distance)
+ let view-matrix = _perspective-view-matrix(view-rotation-matrix, distance)
+
+ let ref-depth = _resolve-reference-depth(ctx, body, view-rotation-matrix, distance, near)
+ let projection = pt => _perspective-project-point(pt, near, ref-depth)
+
+ _projection(body, view-matrix, projection,
+ sorted: sorted,
+ cull-face: cull-face,
+ reset-transform: reset-transform)
+})
diff --git a/render/packages/preview/cetz/0.5.2/src/draw/shapes.typ b/render/packages/preview/cetz/0.5.2/src/draw/shapes.typ
new file mode 100644
index 0000000..ad75690
--- /dev/null
+++ b/render/packages/preview/cetz/0.5.2/src/draw/shapes.typ
@@ -0,0 +1,2238 @@
+#import "/src/coordinate.typ"
+#import "/src/drawable.typ"
+#import "/src/styles.typ"
+#import "/src/path-util.typ"
+#import "/src/util.typ"
+#import "/src/vector.typ"
+#import "/src/matrix.typ"
+#import "/src/process.typ"
+#import "/src/bezier.typ" as bezier_
+#import "/src/hobby.typ" as hobby_
+#import "/src/anchor.typ" as anchor_
+#import "/src/mark.typ" as mark_
+#import "/src/mark-shapes.typ" as mark-shapes_
+#import "/src/polygon.typ" as polygon_
+#import "/src/aabb.typ"
+
+#import "transformations.typ": *
+#import "styling.typ": *
+#import "grouping.typ": *
+
+/// Draws a circle or ellipse.
+///
+/// ```example
+/// // Draw a circle with center (0, 0)
+/// circle((0, 0))
+/// ```
+///
+/// ```example
+/// // Draw an ellipse
+/// circle((2, 0), radius: (1, 0.5))
+/// ```
+///
+/// ```example
+/// let (a, b) = ((2, 1), (1, 1))
+///
+/// // Draw a circle with its center at (2, 1), going
+/// // through point (1, 1)
+/// circle(a, b)
+///
+/// // Show both points
+/// set-style(content: (frame: "circle", padding: 1pt, fill: white))
+/// content(a, [A]); content(b, [B])
+/// ```
+///
+///
+/// - ..points-style (coordinate, style): The position to place the circle on.
+/// If given two coordinates, the distance between them is used as radius.
+/// If given a single coordinate, the radius can be set via the `radius` (style)
+/// argument.
+/// - name (none,str):
+/// - anchor (none, str):
+///
+/// === Styling
+/// *Root*: `circle`
+///
+/// - radius (number, array) = 1: A number that defines the size of the circle's radius. Can also be set to a tuple of two numbers to define the radii of an ellipse, the first number is the `x` radius and the second is the `y` radius.
+///
+/// === Anchors
+/// Supports border and path anchors. The `"center"` anchor is the default.
+///
+#let circle(..points-style, name: none, anchor: none) = {
+ let style = points-style.named()
+ let points = points-style.pos()
+ assert(points.len() in (1, 2),
+ message: "circle expects one or two points, got " + repr(points))
+ assert(points.len() != 2 or "radius" not in style,
+ message: "unexpected radius for circle constructed by two points")
+
+ (ctx => {
+ let (center, outer) = if points.len() == 1 {
+ (points.at(0), none)
+ } else {
+ points
+ }
+
+ let (ctx, center) = coordinate.resolve(ctx, center)
+ let style = styles.resolve(ctx.style, merge: style, root: "circle")
+
+ // If we got two points, use the second one to calculate
+ // the radius.
+ let (rx, ry) = if outer != none {
+ (ctx, outer) = coordinate.resolve(ctx, outer, update: false)
+ (vector.dist(center, outer),) * 2
+ } else {
+ util.resolve-radius(style.radius).map(util.resolve-number.with(ctx))
+ }
+ let (cx, cy, cz) = center
+
+ let drawables = drawable.ellipse(
+ cx, cy, cz,
+ rx, ry,
+ fill: style.fill,
+ stroke: style.stroke
+ )
+
+ let (transform, anchors) = anchor_.setup(
+ (_) => center,
+ ("center",),
+ default: "center",
+ name: name,
+ offset-anchor: anchor,
+ transform: ctx.transform,
+ border-anchors: true,
+ path-anchors: true,
+ radii: (rx*2, ry*2),
+ path: drawables,
+ )
+
+ return (
+ ctx: ctx,
+ name: name,
+ anchors: anchors,
+ drawables: drawable.apply-transform(transform, drawables),
+ )
+ },)
+}
+
+/// Draws a circle through three coordinates.
+///
+/// ```example
+/// let (a, b, c) = ((0, 0), (2, -0.5), (1, 1))
+///
+/// // Draw a circle through 3 points
+/// circle-through(a, b, c, name: "c")
+///
+/// // Show the points
+/// set-style(content: (frame: "circle", padding: 1pt, fill: white))
+/// content(a, [A]); content(b, [B]); content(c, [C])
+/// ```
+///
+/// - a (coordinate): Coordinate a.
+/// - b (coordinate): Coordinate b.
+/// - c (coordinate): Coordinate c.
+/// - name (none,str):
+/// - anchor (none,str):
+/// - ..style (style):
+///
+/// === Styling
+/// *Root*: `circle`
+///
+/// `circle-through` has the same styling as `circle` except for
+/// `radius` as the circle's radius is calculated by the
+/// given coordinates.
+///
+/// === Anchors
+/// Supports the same anchors as `circle` as well as:
+/// / a: Coordinate a
+/// / b: Coordinate b
+/// / c: Coordinate c
+#let circle-through(a, b, c, name: none, anchor: none, ..style) = {
+ assert.eq(style.pos(), (), message: "Unexpected positional arguments: " + repr(style.pos()))
+ style = style.named()
+
+ return (ctx => {
+ let (ctx, a, b, c) = coordinate.resolve(ctx, a, b, c)
+
+ let center = util.calculate-circle-center-3pt(a, b, c)
+
+ let style = styles.resolve(ctx.style, merge: style, root: "circle")
+ let (cx, cy, cz) = center
+ let r = vector.dist(a, (cx, cy))
+
+ let drawables = drawable.ellipse(
+ cx, cy, 0,
+ r, r,
+ fill: style.fill,
+ stroke: style.stroke
+ )
+
+ let (transform, anchors) = anchor_.setup(
+ (anchor) => (
+ center: center,
+ a: a,
+ b: b,
+ c: c
+ ).at(anchor),
+ ("center", "a", "b", "c"),
+ default: "center",
+ name: name,
+ offset-anchor: anchor,
+ transform: ctx.transform,
+ border-anchors: true,
+ path-anchors: true,
+ radii: (r*2, r*2),
+ path: drawables,
+ )
+
+ return (
+ ctx: ctx,
+ name: name,
+ anchors: anchors,
+ drawables: drawable.apply-transform(
+ transform,
+ drawables
+ )
+ )
+ },)
+}
+
+/// Draws a circular segment.
+///
+/// ```example
+/// arc((0,0), start: 45deg, stop: 135deg)
+/// arc((0,-0.5), start: 45deg, delta: 90deg, mode: "CLOSE")
+/// arc((0,-1), stop: 135deg, delta: 90deg, mode: "PIE")
+/// ```
+///
+/// Note that two of the three angle arguments (`start`, `stop` and `delta`) must be set.
+/// The current position `()` gets updated to the arc's end coordinate (anchor `arc-end`).
+///
+/// - position (coordinate): Position to place the arc at.
+/// - start (auto,angle): The angle at which the arc should start. Remember that `0deg` points directly towards the right and `90deg` points up.
+/// - stop (auto,angle): The angle at which the arc should stop.
+/// - delta (auto,angle): The change in angle away start or stop.
+/// - name (none,str):
+/// - anchor (none, str):
+/// - ..style (style):
+///
+/// == Styling
+/// *Root*: `arc`\
+/// - radius (number, array) = 1: The radius of the arc. An elliptical arc can be created by passing a tuple of numbers where the first element is the x radius and the second element is the y radius.
+/// - mode (str) = "OPEN": The options are: `"OPEN"` no additional lines are drawn so just the arc is shown; `"CLOSE"` a line is drawn from the start to the end of the arc creating a circular segment; `"PIE"` lines are drawn from the start and end of the arc to the origin creating a circular sector.
+/// - update-position (bool) = true: Update the current canvas position to the arc's end point (anchor `"arc-end"`). This overrides the default of `true`, that allows chaining of (arc) elements.
+///
+/// == Anchors
+/// Supports border and path anchors.
+/// / arc-start: The position at which the arc's curve starts, this is the default.
+/// / arc-end: The position of the arc's curve end.
+/// / arc-center: The midpoint of the arc's curve.
+/// / center: The center of the arc, this position changes depending on if the arc is closed or not.
+/// / chord-center: Center of chord of the arc drawn between the start and end point.
+/// / origin: The origin of the arc's circle.
+#let arc(
+ position,
+ start: auto,
+ stop: auto,
+ delta: auto,
+ name: none,
+ anchor: none,
+ ..style,
+) = {
+ // Start, stop, delta check
+ assert(
+ (start, stop, delta).filter(it => { it == auto }).len() == 1,
+ message: "Exactly two of three options start, stop and delta should be defined.",
+ )
+
+ // No extra positional arguments from the style sink
+ assert.eq(
+ style.pos(),
+ (),
+ message: "Unexpected positional arguments: " + repr(style.pos()),
+ )
+ let style = style.named()
+
+ let start-angle = if start == auto { stop - delta } else { start }
+ let stop-angle = if stop == auto { start + delta } else { stop }
+ // Border angles can break if the angle is 0.
+ assert.ne(start-angle, stop-angle, message: "Angle must be greater than 0deg")
+
+ return (ctx => {
+ let style = styles.resolve(ctx.style, merge: style, root: "arc")
+ assert(style.mode in ("OPEN", "PIE", "CLOSE"))
+
+ let (ctx, arc-start) = coordinate.resolve(ctx, position)
+ let (rx, ry) = util.resolve-radius(style.radius).map(util.resolve-number.with(ctx))
+
+ let (x, y, z) = arc-start
+ let drawables = drawable.arc(
+ ..arc-start,
+ start-angle,
+ stop-angle,
+ rx,
+ ry,
+ stroke: style.stroke,
+ fill: style.fill,
+ mode: style.mode
+ )
+
+ let sector-center = (
+ x - rx * calc.cos(start-angle),
+ y - ry * calc.sin(start-angle),
+ z
+ )
+ let arc-end = (
+ sector-center.first() + rx * calc.cos(stop-angle),
+ sector-center.at(1) + ry * calc.sin(stop-angle),
+ z
+ )
+ let chord-center = vector.lerp(arc-start, arc-end, 0.5)
+ let arc-center = (
+ sector-center.first() + rx * calc.cos((stop-angle + start-angle)/2),
+ sector-center.at(1) + ry * calc.sin((stop-angle + start-angle)/2),
+ z
+ )
+
+ // Set the last position to arc-end
+ if style.update-position {
+ ctx.prev.pt = arc-end
+ }
+
+ // Center is calculated based on observations of tikz's circular sector and semi circle shapes.
+ let center = if style.mode != "CLOSE" {
+ // A circular sector's center anchor is placed half way between the sector-center and arc-center when the angle is 180deg. At 60deg it is placed 1/3 of the way between, this is mirrored at 300deg.
+ vector.lerp(
+ arc-center,
+ sector-center,
+ if (stop-angle + start-angle) > 180deg { (stop-angle + start-angle) } else { (stop-angle + start-angle) + 180deg } / 720deg
+ )
+ } else {
+ // A semi circle's center anchor is placed half way between the sector-center and arc-center, so that is always `center` when the arc is closed. Otherwise the point at which compass anchors are calculated from will be outside the lines.
+ vector.lerp(
+ arc-center,
+ chord-center,
+ 0.5
+ )
+ }
+
+ let (transform, anchors) = anchor_.setup(
+ anchor => (
+ arc-start: arc-start,
+ origin: sector-center,
+ arc-end: arc-end,
+ arc-center: arc-center,
+ chord-center: chord-center,
+ center: center,
+ ).at(anchor),
+ ("arc-center", "chord-center", "origin", "arc-start", "arc-end", "center"),
+ default: "arc-start",
+ name: name,
+ offset-anchor: anchor,
+ transform: ctx.transform,
+ border-anchors: true,
+ path-anchors: true,
+ radii: (rx, ry), // Don't multiply as its not from the arc's center
+ path: drawables
+ )
+
+ if mark_.check-mark(style.mark) {
+ drawables = mark_.place-marks-along-path(ctx, style.mark, transform, drawables)
+ } else {
+ drawables = drawable.apply-transform(transform, drawables)
+ }
+
+ return (
+ ctx: ctx,
+ name: name,
+ anchors: anchors,
+ drawables: drawables,
+ )
+ },)
+}
+
+/// Draws an arc that passes through three points a, b and c.
+///
+/// Note that all three points must not lie on a straight line, otherwise
+/// the function fails.
+///
+/// ```example
+/// let (a, b, c) = ((0, 1), (2, 2), (2, 0))
+///
+/// // Draw an arc through 3 points
+/// arc-through(a, b, c)
+///
+/// // Show the points
+/// set-style(content: (frame: "circle", padding: 1pt, fill: white))
+/// content(a, [A]); content(b, [B]); content(c, [C])
+/// ```
+///
+/// - a (coordinate): Start position of the arc
+/// - b (coordinate): Position the arc passes through
+/// - c (coordinate): End position of the arc
+/// - name (none, str):
+/// - ..style (style):
+///
+/// === Styling
+/// *Root*: `arc` \
+/// Uses the same styling as `arc`.
+///
+/// === Anchors
+/// For anchors see `arc`.
+///
+#let arc-through(
+ a,
+ b,
+ c,
+ name: none,
+ ..style,
+) = get-ctx(ctx => {
+ let (ctx, a, b, c) = coordinate.resolve(ctx, a, b, c)
+ (a, b, c) = (a, b, c).map(pt => pt.map(calc.round.with(digits: matrix.precision)))
+
+ assert(a.at(2) == b.at(2) and b.at(2) == c.at(2),
+ message: "The z coordinate of all points must be equal, but is: " + repr((a, b, c).map(v => v.at(2))))
+
+ // Calculate the circle center from three points or fails if all
+ // three points are on one straight line.
+ let center = util.calculate-circle-center-3pt(a, b, c)
+ let radius = vector.dist(center, a)
+
+ // Find the start and inner angle between a-center-c
+ let start = vector.angle2(center, a)
+ let delta = vector.angle(a, center, c)
+
+ // Returns a negative number if pt is left of the line a-b,
+ // if pt is right to a-b, a positive number is returned,
+ // otherwise zero.
+ let side-on-line(a, b, pt) = {
+ let (x1, y1, ..) = a
+ let (x2, y2, ..) = b
+ let (x, y, ..) = pt
+ return (x - x1) * (y2 - y1) - (y - y1) * (x2 - x1)
+ }
+
+ // Center & b b is left,
+ // are left center not
+ //
+ // +-b-+ +-b-+
+ // / \ / \
+ // | C | --a-------c--
+ // \ / \ C /
+ // ---a---c--- +---+
+ //
+ // If b and C are on the same side of a-c, the arcs radius is >= 180deg,
+ // otherwise the radius is < 180deg.
+ let center-is-left = side-on-line(a, c, center) < 0
+ let b-is-left = side-on-line(a, c, b) < 0
+
+ // If the center and point b are on the same side of a-c,
+ // the arcs delta must be > 180deg. Note, that delta is
+ // the inner angle between a-center-c, so we need to calculate
+ // the outer angle by subtracting from 360deg.
+ if center-is-left == b-is-left {
+ delta = 360deg - delta
+ }
+
+ // If b is left of a-c, swap a-c to c-a by using a negative delta
+ if b-is-left {
+ delta *= -1
+ }
+
+ return arc(
+ a,
+ start: start,
+ delta: delta,
+ radius: radius,
+ anchor: "arc-start",
+ name: name,
+ ..style
+ )
+})
+
+/// Draws a single mark pointing towards a target coordinate.
+///
+/// ```example
+/// // Show a grid
+/// grid((-1, -1), (1, 1), stroke: gray)
+///
+/// // Draw a mark with its tip at (0, 0) pointing to (1, 0)
+/// mark((0, 0), (1, 0), symbol: ")>", scale: 4)
+/// ```
+///
+/// ```example
+/// // Show a grid
+/// grid((-1, -1), (1, 1), stroke: gray)
+///
+/// // Draw a mark with its center at (0, 0) pointing to (1, 1)
+/// mark((0, 0), (1, 1), symbol: ">>", anchor: "center", scale: 5)
+/// ```
+///
+/// Note: To place a mark centered at the first coordinate (`from`) use
+/// the marks `anchor: "center"` style.
+///
+/// - from (coordinate): The position to place the mark.
+/// - to (coordinate,angle): The position or angle the mark should point towards.
+/// - ..style (str,style): If the third positional argument is of type string, it is treated as mark name (e.g. `">"`) and overrules style keys such as `mark.symbol` or `mark.end`
+///
+/// == Styling
+/// *Root*: `mark`
+///
+/// You can directly use the styling from mark styling.
+#let mark(from, to, ..style) = {
+ let symbol = if style.pos() != () {
+ assert.eq(type(style.pos().at(0)), str,
+ message: "Mark name must be of type string")
+ style.pos().at(0)
+ } else {
+ none
+ }
+
+ assert(
+ style.pos().len() <= 1,
+ message: "Unexpected positional arguments: " + repr(style.pos()))
+
+ let style = style.named()
+
+ if type(to) == angle {
+ // Construct a coordinate pointing (+1, 0) away from
+ // `from`, rotated by the angle given.
+ to = ((rel: (to, 1), to: from))
+ }
+
+ return (ctx => {
+ let (ctx, ..pts) = coordinate.resolve(ctx, from, to)
+ let style = styles.resolve(ctx.style, merge: style, root: "mark")
+
+ style.end = if symbol != none {
+ symbol
+ } else {
+ style.symbol
+ }
+
+ assert.ne(style.end, none,
+ message: "Missing mark symbol! You need to pass a mark name to the mark element.")
+
+ style.start = none
+ style.symbol = none
+
+ let (to, from) = (..pts)
+ from = vector.sub(to, vector.sub(from, to))
+
+ // Place marks and adjust segments
+ let drawables = drawable.line-strip((from, to))
+ if mark_.check-mark(style) {
+ drawables = mark_.place-marks-along-path(ctx, style, ctx.transform, drawables, add-path: false)
+ } else {
+ drawables = drawable.apply-transform(ctx.transform, drawables)
+ }
+
+ return (
+ ctx: ctx,
+ drawables: drawables,
+ )
+ },)
+}
+
+/// Draws a line, more than two points can be given to create a line-strip.
+///
+/// ```example
+/// // Draw a line between two points
+/// line((0, 0), (1.5, 1))
+/// ```
+///
+/// ```example
+/// // Draw a line between more than two points
+/// line((0, 0), (1, 0.5), (2, -0.5), (3, 0))
+/// ```
+///
+/// ```example
+/// // Draw a polygon using `close: true`
+/// line((0, 0), (0, 1), (1, 2), (2, 1), (2,0), close: true)
+/// ```
+///
+/// If the first or last coordinates are given as the name of an element,
+/// that has a `"default"` anchor, the intersection of that element's border
+/// and a line from the first or last two coordinates given is used as coordinate.
+/// This is useful to span a line between the borders of two elements. Note, that passing
+/// strings bypasses custom resolvers when trying to find elements!
+///
+/// ```example
+/// circle((1,2), radius: .5, name: "a")
+/// rect((2,1), (rel: (1,1)), name: "b")
+/// line("a", "b")
+/// ```
+/// - ..pts-style (coordinate,style): Positional two or more coordinates to draw lines between. Accepts style key-value pairs.
+/// - close (bool): If true, the line-strip gets closed to form a polygon
+/// - name (none,str):
+///
+/// == Styling
+/// *Root:* `line`
+///
+/// Supports mark styling.
+///
+/// == Anchors
+/// Supports path anchors.
+/// / centroid: The centroid anchor is calculated for _closed non self-intersecting_ polygons if all vertices share the same z value.
+#let line(..pts-style, close: false, name: none) = {
+ // Extra positional arguments from the pts-style sink are interpreted as coordinates.
+ let pts = pts-style.pos()
+ let style = pts-style.named()
+
+ assert(pts.len() >= 2, message: "Line must have a minimum of two points")
+
+ // Find the intersection between line a-b next to b
+ // if no intersection could be found, return a.
+ let element-line-intersection(ctx, elem, a, b) = {
+ // Vectors a and b are not transformed yet, but the vectors of the
+ // drawable are.
+ let (ta, tb) = util.apply-transform(ctx.transform, a, b)
+
+ let pts = ()
+ for d in elem.at("drawables", default: ()).filter(d => d.type == "path") {
+ pts += intersection.line-path(ta, tb, d)
+ }
+ return if pts == () {
+ a
+ } else {
+ // Find the nearest point
+ let pt = util.sort-points-by-distance(tb, pts).first()
+
+ // Reverse the transformation
+ return util.revert-transform(ctx.transform, pt)
+ }
+ }
+
+ return (ctx => {
+ let first-elem = pts.first()
+ let first-is-elem = type(first-elem) == str and not first-elem.contains(".")
+
+ let last-elem = pts.last()
+ let last-is-elem = type(last-elem) == str and not last-elem.contains(".")
+
+ let (ctx, ..pts) = coordinate.resolve(ctx, ..pts)
+
+ // If the first/last element, test for intersection
+ // of that element and a line from the two first/last coordinates of this
+ // line strip.
+ if first-is-elem {
+ let elem = ctx.nodes.at(first-elem)
+ pts.first() = element-line-intersection(ctx, elem, ..pts.slice(0, 2))
+ }
+ if last-is-elem {
+ let elem = ctx.nodes.at(last-elem)
+ pts.last() = element-line-intersection(ctx, elem, ..pts.slice(-2).rev())
+ }
+
+ let style = styles.resolve(ctx.style, merge: style, root: "line")
+
+ let drawables = drawable.path(
+ (path-util.make-subpath(pts.first(), pts.slice(1).map(pt => ("l", pt)), closed: close),),
+ fill: style.fill,
+ fill-rule: style.fill-rule,
+ stroke: style.stroke,
+ )
+
+ // Get bounds
+ let (transform, anchors) = anchor_.setup(
+ name => {
+ if name == "centroid" {
+ return polygon_.simple-centroid(pts)
+ }
+ },
+ if close != none { ("centroid",) } else { () },
+ default: if close != none { "centroid" },
+ name: name,
+ transform: ctx.transform,
+ path-anchors: true,
+ path: drawables
+ )
+
+ // Place marks and adjust segments
+ if mark_.check-mark(style.mark) {
+ drawables = mark_.place-marks-along-path(ctx, style.mark, transform, drawables)
+ } else {
+ drawables = drawable.apply-transform(transform, drawables)
+ }
+
+ return (
+ ctx: ctx,
+ name: name,
+ anchors: anchors,
+ drawables: drawables,
+ )
+ },)
+}
+
+/// Draws a regular polygon.
+///
+/// ```example
+/// set-style(polygon: (radius: 0.65))
+///
+/// polygon((0, 0), 3, angle: 90deg)
+/// polygon((1.5,0), 5)
+/// polygon((3, 0), 7)
+/// ```
+///
+/// - origin (coordinate): Coordinate to draw the polygon at
+/// - sides (int): Number of sides of the polygon (>= 3)
+/// - angle (angle) = 0deg: Angle angle to rotate the polygon arround its origin
+/// - name (none, str):
+///
+/// == Styling
+/// *Root*: `polygon`
+/// - radius (number) = 1: Radius of the polygon
+#let polygon(origin, sides, angle: 0deg, name: none, anchor: none, ..style) = {
+ assert(type(sides) == int and sides >= 3,
+ message: "Invalid number of sides: " + repr(sides))
+
+ let style = style.named()
+ return (ctx => {
+ let anchors = ()
+
+ let style = styles.resolve(ctx.style, merge: style, root: "polygon")
+
+ let (ctx, origin) = coordinate.resolve(ctx, origin)
+ let (rx, ry) = util.resolve-radius(style.radius).map(util.resolve-number.with(ctx))
+
+ let points = range(0, sides).map(i => {
+ let alpha = angle + 360deg / sides * i
+ vector.add(origin, (calc.cos(alpha) * rx, calc.sin(alpha) * ry, 0))
+ })
+
+ let drawables = drawable.line-strip(
+ points,
+ close: true,
+ fill: style.fill,
+ stroke: style.stroke)
+
+ let edge-anchors = range(0, sides).map(i => "edge-" + str(i))
+ let corner-anchors = range(0, sides).map(i => "corner-" + str(i))
+
+ let (transform, anchors) = anchor_.setup(
+ name => {
+ return if name == "center" or name == "default" {
+ origin
+ } else if name in edge-anchors {
+ let idx = edge-anchors.position(item => item == name)
+ vector.lerp(
+ points.at(idx),
+ points.at(idx + 1, default: points.first()),
+ .5)
+ } else if name in corner-anchors {
+ let idx = corner-anchors.position(item => item == name)
+ points.at(idx)
+ }
+ },
+ ("center",) + edge-anchors + corner-anchors,
+ name: name,
+ transform: ctx.transform,
+ path-anchors: false,
+ border-anchors: true,
+ radii: (rx*2, ry*2),
+ path: drawables,
+ offset-anchor: anchor,
+ default: "center",
+ )
+
+ return (
+ ctx: ctx,
+ name: name,
+ anchors: anchors,
+ drawables: drawable.apply-transform(transform, drawables),
+ )
+ },)
+}
+
+
+/// Draws a n-pointed star.
+///
+/// ```example
+/// set-style(n-star: (radius: 0.65))
+///
+/// n-star((0, 0), 5)
+///
+/// // An 8-pointed star, rotated
+/// n-star((1.5, 0), 8, angle: 11.25deg)
+///
+/// // A 6-pointed star showing its inner hexagon
+/// n-star((3, 0), 6, show-inner: true)
+/// ```
+///
+/// - origin (coordinate): Coordinate to draw the star's center at.
+/// - sides (int): Number of points of the star (>= 3).
+/// - angle (angle) = 0deg: Angle to rotate the star around its origin.
+/// - name (none, str): An optional name to identify the shape.
+///
+/// == Styling
+/// Root: nstar
+///
+/// - radius (number): The radius of the star's outer points.
+/// - inner-radius (number,ratio): The radius (if of type ratio, relative to the outer radius) of the star's inner points of the star's inner points.
+/// - show-inner (bool) = false: If true, also draws the inner polygon connecting the star's inner points.
+/// - fill (color, gradient): The fill color for the star.
+/// - stroke (color, thickness, ...): The stroke for the star and the inner polygon.
+#let n-star(origin, sides, angle: 0deg, name: none, anchor: none, ..style) = {
+ assert(type(sides) == int and sides >= 3,
+ message: "Invalid number of sides: " + repr(sides))
+
+ let style = style.named()
+ return (ctx => {
+ let anchors = ()
+
+ let style = styles.resolve(ctx.style, merge: style, root: "n-star")
+ if type(style.radius) == array {
+ panic("n-star: Expected a single radius, got an array. Note: You can pass the inner radius as `inner-radius:` to n-star.")
+ }
+
+ let (ctx, origin) = coordinate.resolve(ctx, origin)
+ let outer-radius = util.resolve-number(ctx, style.radius)
+ let inner-radius = if type(style.inner-radius) == ratio {
+ outer-radius * style.inner-radius / 100%
+ } else {
+ util.resolve-number(ctx, style.inner-radius)
+ }
+
+ let angle-step = 360deg / sides
+
+ let point-pairs = range(0, sides).map(i => {
+ let inner-angle = angle + i * angle-step
+ let inner-point = vector.add(origin, (
+ calc.cos(inner-angle) * inner-radius,
+ calc.sin(inner-angle) * inner-radius,
+ 0
+ ))
+ let outer-angle = inner-angle + angle-step / 2
+ let outer-point = vector.add(origin, (
+ calc.cos(outer-angle) * outer-radius,
+ calc.sin(outer-angle) * outer-radius,
+ 0
+ ))
+
+ (inner-point, outer-point)
+ })
+
+ let drawables = {
+ let main_shape = drawable.line-strip(
+ point-pairs.flatten().chunks(3),
+ close: true,
+ fill: style.fill,
+ stroke: style.stroke,
+ )
+ if style.show-inner {
+ let inner_shape = drawable.line-strip(
+ point-pairs.map(pair => pair.at(0)),
+ close: true,
+ fill: style.fill,
+ stroke: style.stroke,
+ )
+ (main_shape, inner_shape)
+ } else {
+ main_shape
+ }
+ }
+
+ let edge-anchors = range(0, sides * 2).map(i => "edge-" + str(i))
+ let corner-anchors = range(0, sides * 2).map(i => "corner-" + str(i))
+
+ let (transform, anchors) = anchor_.setup(
+ name => {
+ return if name == "center" or name == "default" {
+ origin
+ } else if name in edge-anchors {
+ let idx = edge-anchors.position(item => item == name)
+ vector.lerp(
+ points.at(idx),
+ points.at(idx + 1, default: points.first()),
+ .5)
+ } else if name in corner-anchors {
+ let idx = corner-anchors.position(item => item == name)
+ points.at(idx)
+ }
+ },
+ ("center",) + edge-anchors + corner-anchors,
+ name: name,
+ transform: ctx.transform,
+ path-anchors: false,
+ border-anchors: true,
+ radii: (outer-radius * 2, outer-radius * 2),
+ path: (drawables),
+ offset-anchor: anchor,
+ default: "center",
+ )
+
+ return (
+ ctx: ctx,
+ name: name,
+ anchors: anchors,
+ drawables: drawable.apply-transform(transform, drawables),
+ )
+ },)
+}
+
+/// Draws a grid between two coordinates
+///
+/// ```example
+/// // Draw a grid
+/// grid((0,0), (2,2))
+///
+/// // Draw a smaller blue grid
+/// grid((1,1), (2,2), stroke: blue, step: .25)
+/// ```
+///
+/// - from (coordinate): The top left of the grid
+/// - to (coordinate): The bottom right of the grid
+/// - name (none,str):
+/// - ..style (style):
+///
+/// == Styling
+/// *Root*: `grid`
+/// - step (number, array, dictionary) = 1: Distance between grid lines. A distance of $1$ means to draw a grid line every $1$ length units in x- and y-direction. If given a dictionary with `x` and `y` keys or a tuple, the step is set per axis.
+/// - shift (number, array, dictionary) = 0: Offset of the grid lines. Supports an array of the form `(x, y)` or a dictionary of the form `(x: <number>, y: <number>)`.
+/// - help-lines (bool) = false: If true, force the stroke style to `gray + 0.2pt`
+///
+/// == Anchors
+/// Supports border anchors.
+#let grid(from, to, name: none, ..style) = {
+ assert.eq(style.pos(), (), message: "Unexpected positional arguments: " + repr(style.pos()))
+ style = style.named()
+
+ return (ctx => {
+ let (ctx, from, to) = coordinate.resolve(ctx, from, to)
+
+ (from, to) = {
+ let pairs = ((from.at(0), to.at(0)), (from.at(1), to.at(1)), (from.at(2), from.at(2)))
+ (
+ pairs.map(e => calc.min(..e)),
+ pairs.map(e => calc.max(..e))
+ )
+ }
+
+ let style = styles.resolve(ctx.style, merge: style, root: "grid", base: (
+ step: 1,
+ stroke: auto,
+ help-lines: false,
+ ))
+ if style.help-lines {
+ style.stroke = 0.2pt + gray
+ }
+
+ let (x-step, y-step) = if type(style.step) == dictionary {
+ (style.step.at("x", default: 1), style.step.at("y", default: 1))
+ } else if type(style.step) == array {
+ style.step
+ } else {
+ (style.step, style.step)
+ }.map(util.resolve-number.with(ctx))
+
+ let (from-x, from-y, ..) = from
+ let (to-x, to-y, ..) = to
+
+ // Resolve shift parameter
+ let shift = style.at("shift", default: 0)
+ if type(shift) == dictionary {
+ shift = (shift.at("x", default: 0), shift.at("y", default: 0))
+ }
+ let (shift-x, shift-y) = if type(shift) == array {
+ style.shift.map(util.resolve-number.with(ctx))
+ } else {
+ (shift, shift).map(util.resolve-number.with(ctx))
+ }
+
+ let x-steps = if x-step != 0 {
+ // Calculate offset start position based on shift
+ let start-x = from-x + calc.rem(shift-x, x-step)
+ // Adjust range to account for shift
+ let count = int((to.at(0) - start-x) / x-step) + 1
+ range(count).map(x => {
+ return (x * x-step) + start-x
+ }).filter(x => x >= from-x and x <= to-x)
+ } else { () }
+
+ let y-steps = if y-step != 0 {
+ // Calculate offset start position based on shift
+ let start-y = from-y + calc.rem(shift-y, y-step)
+ // Adjust range to account for shift
+ let count = int((to.at(1) - start-y) / y-step) + 1
+ range(count).map(y => {
+ return (y * y-step) + start-y
+ }).filter(y => y >= from-y and y <= to-y)
+ } else { () }
+
+
+ let drawables = ()
+
+ let low-x = x-steps.first()
+ let high-x = x-steps.last()
+ let low-y = y-steps.first()
+ let high-y = y-steps.last()
+
+ // Draw inner grid lines (vertical and horizontal)
+ drawables += x-steps.slice(1, -1).map(x => drawable.line-strip(
+ ((x, from-y), (x, to-y)), stroke: style.stroke))
+ drawables += y-steps.slice(1, -1).map(y => drawable.line-strip(
+ ((from-x, y), (to-x, y)), stroke: style.stroke))
+
+ // Draw outer border lines as connected path when corners touch
+ let outer-lines = (
+ ((from-x, low-y), (to-x, low-y)),
+ ((high-x, from-y), (high-x, to-y)),
+ ((to-x, high-y), (from-x, high-y)),
+ ((low-x, to-y), (low-x, from-y)),
+ ).map(s => s.map(pt => pt.map(calc.round.with(digits: 6))))
+
+ let at-border = (
+ low-x == from-x,
+ low-y == from-y,
+ high-x == to-x,
+ high-y == to-y,
+ )
+
+ let outer-strips = ()
+ for i in range(0, 4) {
+ let i = calc.rem(i, 4)
+
+ let added = false
+ for j in range(0, outer-strips.len()) {
+ if outer-strips.at(j).last() == outer-lines.at(i).first() {
+ outer-strips.at(j).push(outer-lines.at(i).last())
+ added = true
+ break
+ } else if outer-strips.at(j).first() == outer-lines.at(i).last() {
+ outer-strips.at(j).insert(0, outer-lines.at(i).first())
+ added = true
+ break
+ }
+ }
+
+ if not added {
+ outer-strips.push(outer-lines.at(i))
+ }
+ }
+
+ // Connect first and last strip, if the touch
+ if outer-strips.len() > 1 and outer-strips.last().last() == outer-strips.first().first() {
+ outer-strips.last() += outer-strips.first()
+ outer-strips.remove(0)
+ }
+
+ drawables += outer-strips.map(s => drawable.line-strip(
+ s, stroke: style.stroke, close: at-border.all(v => v)))
+
+ let center = vector.lerp(from, to, .5)
+ let (transform, anchors) = anchor_.setup(
+ _ => center,
+ ("center",),
+ name: name,
+ transform: ctx.transform,
+ border-anchors: true,
+ radii: (vector.dist(center, from) * 2,) * 2,
+ path: drawable.line-strip(
+ (from, (from.first(), to.at(1), 0), to, (to.first(), from.at(1), 0)),
+ close: true)
+ )
+
+ return (
+ ctx: ctx,
+ name: name,
+ anchors: anchors,
+ drawables: drawable.apply-transform(
+ transform,
+ drawables
+ )
+ )
+ },)
+}
+
+/// Positions Typst content in the canvas. Note that the content itself is not transformed only its position is.
+///
+/// ```example
+/// content((0,0), [Hello World!])
+/// ```
+/// To put text on a line you can let the function calculate the angle between its position and a second coordinate by passing it to `angle`:
+///
+/// ```example
+/// line((0, 0), (3, 1), name: "line")
+/// content(
+/// ("line.start", 50%, "line.end"),
+/// angle: "line.end",
+/// padding: .1,
+/// anchor: "south",
+/// [Text on a line]
+/// )
+/// ```
+///
+/// ```example
+/// // Place content in a rect between two coordinates
+/// content(
+/// (0, 0),
+/// (2, 2),
+/// box(
+/// par(justify: false)[This is a long text.],
+/// stroke: 1pt,
+/// width: 100%,
+/// height: 100%,
+/// inset: 1em
+/// )
+/// )
+/// ```
+///
+/// - ..args-style (coordinate, content, style): When one coordinate is given as a positional argument, the content will be placed at that position. When two coordinates are given as positional arguments, the content will be placed inside a rectangle between the two positions. All named arguments are styling and any additional positional arguments will panic.
+/// - angle (angle,coordinate): Rotates the content by the given angle. A coordinate can be given to rotate the content by the angle between it and the first coordinate given in `args`. This effectively points the right hand side of the content towards the coordinate. This currently exists because Typst's rotate function does not change the width and height of content.
+/// - anchor (none, str):
+/// - name (none, str):
+///
+/// == Styling
+/// *Root*: `content`
+/// - padding (number, dictionary) = 0: Sets the spacing around content. Can be a single number to set padding on all sides or a dictionary to specify each side specifically. The dictionary follows Typst's `pad` function: https://typst.app/docs/reference/layout/pad/
+/// - frame (str, none) = none: Sets the frame style. Can be {{none}}, `"rect"` or `"circle"` and inherits the `stroke` and `fill` style.
+/// - auto-scale (bool): If `true`, apply current canvas scaling to the content. Defaults to `false`.
+/// - wrap (function, none) = none: A function to apply the content body to. Must return content. Example: `text.with(red)` to wrap every content element in a `text(red, <body>)` element.
+///
+/// == Anchors
+/// Supports border anchors, the default anchor is set to *center*.
+/// / mid: Content center, from baseline to top bounds
+/// / mid-east: Content center extended to the east
+/// / mid-west: Content center extended to the west
+/// / base: Horizontally centered baseline of the content
+/// / base-east: Baseline height extended to the east
+/// / base-west: Baseline height extended to the west
+/// / text: Position at the content start on the baseline of the content
+#let content(
+ ..args-style,
+ angle: 0deg,
+ anchor: none,
+ name: none,
+ ) = {
+ let (args, style) = (args-style.pos(), args-style.named())
+
+ let (a, b, body) = if args.len() == 2 {
+ args.insert(1, auto)
+ args
+ } else if args.len() == 3 {
+ args
+ } else {
+ panic("Expected 2 or 3 positional arguments, got " + str(args.len()))
+ }
+
+ return (ctx => {
+ let style = styles.resolve(ctx.style, merge: style, root: "content")
+ let padding = util.map-dict(util.as-padding-dict(style.padding), (_, v) => {
+ util.resolve-number(ctx, v)
+ })
+
+ let body = if "wrap" in style and type(style.wrap) == function {
+ (style.wrap)(body)
+ } else {
+ body
+ }
+
+ let (ctx, a) = coordinate.resolve(ctx, a)
+ let b = b
+ let auto-size = b == auto
+ if not auto-size {
+ (ctx, b) = coordinate.resolve(ctx, b)
+ }
+
+ let angle = if type(angle) != std.angle {
+ let (_, c) = coordinate.resolve(ctx, angle)
+ vector.angle2(a, util.apply-transform(ctx.transform, c))
+ } else {
+ angle
+ }
+
+ // Optionally scale content with current canvas scaling
+ if style.auto-scale == true {
+ let sx = vector.len(matrix.column(ctx.transform, 0))
+ let sy = vector.len(matrix.column(ctx.transform, 1))
+
+ body = std.scale(x: sx * 100%, y: sy * 100%, body, reflow: true)
+ }
+
+ // Compute the baseline offset
+ let (_, line-baseline-height) = util.measure(ctx, text(top-edge: "cap-height", bottom-edge: "baseline",
+ [ #show linebreak: [ ]; #body]))
+ let (_, line-bounds-height) = util.measure(ctx, text(top-edge: "cap-height", bottom-edge: "bounds",
+ [ #show linebreak: [ ]; #body]))
+ let baseline-offset = line-bounds-height - line-baseline-height
+
+ // Size of the bounding box
+ let (content-width, content-height, ..) = if auto-size {
+ util.measure(ctx, text(top-edge: "cap-height", bottom-edge: "baseline", body))
+ } else {
+ vector.sub(b, a)
+ }
+
+ let baseline-height = calc.abs(content-height)
+ let bounds-width = calc.abs(content-width)
+ let bounds-height = calc.abs(content-height + baseline-offset)
+ let content-width = calc.abs(content-width)
+
+ let width = calc.max(0, bounds-width + padding.left + padding.right)
+ let height = calc.max(0, bounds-height + padding.top + padding.bottom)
+
+ let anchors = {
+ let w = width / 2
+ let h = height / 2
+
+ let bounds-center = if auto-size {
+ a
+ } else {
+ vector.lerp(a, b, .5)
+ }
+
+ // Only the center anchor gets transformed. All other anchors
+ // must be calculated relative to the transformed center!
+ bounds-center = matrix.mul4x4-vec3(ctx.transform,
+ vector.as-vec(bounds-center, init: (0, 0, 0)))
+
+ let rotate-z(v, angle) = {
+ let (x, y, _) = v
+ v.at(0) = x * calc.cos(angle) - y * calc.sin(angle)
+ v.at(1) = x * calc.sin(angle) + y * calc.cos(angle)
+ return v
+ }
+
+ let east-dir = rotate-z((1, 0, 0), angle)
+ let north-dir = rotate-z((0, 1, 0), angle)
+ let east-scaled = vector.scale(east-dir, +w)
+ let west-scaled = vector.scale(east-dir, -w)
+ let north-scaled = vector.scale(north-dir, +h)
+ let south-scaled = vector.scale(north-dir, -h)
+
+ let north = vector.add(bounds-center, north-scaled)
+ let south = vector.add(bounds-center, south-scaled)
+ let east = vector.add(bounds-center, east-scaled)
+ let west = vector.add(bounds-center, west-scaled)
+ let north-east = vector.add(bounds-center, vector.add(north-scaled, east-scaled))
+ let north-west = vector.sub(bounds-center, vector.add(south-scaled, east-scaled))
+ let south-east = vector.add(bounds-center, vector.add(south-scaled, east-scaled))
+ let south-west = vector.sub(bounds-center, vector.add(north-scaled, east-scaled))
+
+ let base = vector.add(south,
+ vector.scale(north-dir, padding.bottom + baseline-offset))
+ let mid = vector.lerp(
+ vector.sub(north, vector.scale(north-dir, padding.top)),
+ base,
+ 0.5)
+ let base-east = vector.add(base, east-scaled)
+ let base-west = vector.add(base, west-scaled)
+ let text = vector.add(base, vector.scale(east-dir, -content-width / 2))
+ let mid-east = vector.add(mid, east-scaled)
+ let mid-west = vector.add(mid, west-scaled)
+
+ (
+ center: bounds-center,
+ mid: mid,
+ mid-east: mid-east,
+ mid-west: mid-west,
+ base: base,
+ base-east: base-east,
+ base-west: base-west,
+ text: text,
+ north: north,
+ north-east: north-east,
+ north-west: north-west,
+ south: south,
+ south-east: south-east,
+ south-west: south-west,
+ east: east,
+ west: west,
+ )
+ }
+
+ let frame-stroke = if style.frame != none {
+ style.stroke
+ }
+ let frame-fill = if style.frame != none {
+ style.fill
+ }
+
+ let rect-shape = drawable.apply-tags(
+ drawable.line-strip(
+ (anchors.north-west, anchors.north-east,
+ anchors.south-east, anchors.south-west),
+ close: true,
+ stroke: frame-stroke,
+ fill: frame-fill,
+ ),
+ drawable.TAG.content-frame,
+ )
+
+ let frame-shape = if style.frame in (none, "rect") {
+ rect-shape
+ } else if style.frame == "circle" {
+ let (x, y, z) = util.calculate-circle-center-3pt(anchors.north-west, anchors.south-west, anchors.south-east)
+ let r = vector.dist((x, y, z), anchors.north-west)
+ drawable.apply-tags(drawable.ellipse(
+ x, y, z,
+ r, r,
+ stroke: frame-stroke,
+ fill: frame-fill,
+ ), drawable.TAG.content-frame)
+ }
+
+ // Shape used for path & border-anchors. Defaults
+ // to "rect" if the content frame is unset.
+ let anchor-shape = if frame-shape != none {
+ frame-shape
+ } else {
+ rect-shape
+ }
+
+ let (aabb-width, aabb-height, ..) = aabb.size(aabb.aabb(
+ (anchors.north-west, anchors.north-east,
+ anchors.south-west, anchors.south-east)))
+
+ let drawables = ()
+ if frame-shape != none {
+ drawables.push(frame-shape)
+ }
+
+ // Because of precision problems with some fonts (e.g. "Source Sans 3")
+ // we need to round the block sizes up. Otherwise, unwanted hyphenation
+ // gets introduced.
+ let round-up(v, digits: 8) = {
+ calc.ceil(v * calc.pow(10, digits)) / calc.pow(10, digits)
+ }
+
+ drawables.push(
+ drawable.content(
+ anchors.center,
+ aabb-width,
+ aabb-height,
+ frame-shape.segments,
+ std.rotate(-angle,
+ reflow: true,
+ origin: center + horizon,
+ block(
+ width: round-up(width) * ctx.length,
+ height: round-up(height) * ctx.length,
+ inset: (
+ top: padding.at("top", default: 0) * ctx.length,
+ left: padding.at("left", default: 0) * ctx.length,
+ bottom: padding.at("bottom", default: 0) * ctx.length,
+ right: padding.at("right", default: 0) * ctx.length,
+ ),
+ text(top-edge: "cap-height", bottom-edge: "baseline", body)
+ )
+ )
+ )
+ )
+
+ let (transform, anchors) = anchor_.setup(
+ anchor => {
+ if type(anchor) == str {
+ anchors.at(anchor)
+ }
+ },
+ anchors.keys(),
+ default: if auto-size { "center" } else { "north-west" },
+ offset-anchor: anchor,
+ transform: none, // Content does not get transformed, see the calculation of anchors.
+ name: name,
+ path-anchors: anchor-shape != none,
+ border-anchors: anchor-shape != none,
+ path: anchor-shape,
+ radii: (calc.max(width, height) * 2, calc.max(width, height) * 2),
+ )
+
+ return (
+ ctx: ctx,
+ name: name,
+ anchors: anchors,
+ drawables: drawable.apply-transform(
+ transform,
+ drawables
+ )
+ )
+ },)
+}
+
+/// Draws a rectangle between two coordinates.
+/// ```example
+/// // Draw a rect from A(0, 0) to B(1, 1)
+/// rect((0, 0), (1, 1))
+///
+/// // Show the points
+/// set-style(content: (frame: "circle", padding: 1pt, fill: white))
+/// content((0, 0), [A]); content((1, 1), [B])
+/// ```
+///
+/// ```example-vertical
+/// rect((0,0), (rel: (1,1)), radius: 0)
+/// rect((2,0), (rel: (1,1)), radius: 25%)
+/// rect((4,0), (rel: (1,1)), radius: (north: 50%))
+/// rect((6,0), (rel: (1,1)), radius: (north-east: 50%))
+/// rect((8,0), (rel: (1,1)), radius: (south-west: 0, rest: 50%))
+/// rect((10,0), (rel: (1,1)), radius: (rest: (20%, 50%)))
+/// ```
+///
+/// == Styling
+/// *Root*: `rect`
+///
+/// - a (coordinate): Coordinate of the bottom left corner of the rectangle.
+/// - b (coordinate): Coordinate of the top right corner of the rectangle. You can draw a rectangle with a specified width and height by using relative coordinates for this parameter `(rel: (width, height))`.
+/// - name (none,str):
+/// - anchor (none, str):
+/// - ..style (style):
+/// - radius (number,ratio,dictionary) = 0: The rectangle's corner radius. If set to a single number, that radius is applied to all four corners of the rectangle. If passed a dictionary you can set the radii per corner. The following keys support either a type:number, type:ratio or an array of type:number or type:ratio for specifying a different x- and y-radius: `north`, `east`, `south`, `west`, `north-west`, `north-east`, `south-west` and `south-east`. To set a default value for remaining corners, the `rest` key can be used.
+/// Ratio values are relative to the rectangle's width and height.
+///
+/// == Anchors
+/// Supports border and path anchors. It's default is the `"center"` anchor.
+///
+#let rect(a, b, name: none, anchor: none, ..style) = {
+ // No extra positional arguments from the style sink
+ assert.eq(
+ style.pos(),
+ (),
+ message: "Unexpected positional arguments: " + repr(style.pos()),
+ )
+ let style = style.named()
+
+ return (
+ ctx => {
+ let ctx = ctx
+ let (ctx, a, b) = coordinate.resolve(ctx, a, b)
+ assert(a.at(2) == b.at(2),
+ message: "Both rectangle points must have the same z value.")
+ (a, b) = {
+ let lo = (
+ calc.min(a.at(0), b.at(0)),
+ calc.min(a.at(1), b.at(1)),
+ calc.min(a.at(2), b.at(2)),
+ )
+ let hi = (
+ calc.max(a.at(0), b.at(0)),
+ calc.max(a.at(1), b.at(1)),
+ calc.max(a.at(2), b.at(2)),
+ )
+ (lo, hi)
+ }
+
+ let style = styles.resolve(ctx.style, merge: style, root: "rect")
+ let (x1, y1, z1) = a
+ let (x2, y2, z2) = b
+
+ let size = (calc.abs(x2 - x1), calc.abs(y2 - y1))
+ let (north-west: nw, north-east: ne,
+ south-west: sw, south-east: se) = util.as-corner-radius-dict(ctx, style.radius, size)
+
+ let no-radius = style.radius == none or style.radius == 0
+ let drawables = if no-radius {
+ let segments = ()
+ // Four corner points for a non-rounded rectangle:
+ //
+ // p0-----p3
+ // | |
+ // | |
+ // p1-----p2
+ //
+ let p0 = (x1, y2, z1)
+ let p1 = (x1, y1, z1)
+ let p2 = (x2, y1, z1)
+ let p3 = (x2, y2, z1)
+ drawable.line-strip((p0, p1, p2, p3), fill: style.fill, stroke: style.stroke, close: true)
+ } else {
+ let z = z1
+
+ // Compute two corner points offset by radius from origin pt.
+ //
+ // x radius * a
+ // |----|
+ // --p1←--pt ---
+ // | | y radius * b
+ // ↓ |
+ // p2 ---
+ // |
+ //
+ // parameters a and b function as direction vectors in which
+ // direction the resulting points p1 and p2 should get offset to.
+ //
+ // The point pt is the corner point of the non-rounded rectangle.
+ // If the radius is zero, we can just return that point for both
+ // new corners.
+ let get-corner-pts(radius, pt, a, b) = {
+ let (rx, ry) = radius
+ if rx > 0 or ry > 0 {
+ let (xa, ya) = a
+ let (xb, yb) = b
+ (vector.add(pt, (xa * rx, ya * ry)),
+ vector.add(pt, (xb * rx, yb * ry)))
+ } else {
+ (pt, pt)
+ }
+ }
+
+ // Get segments for arc between start- and stop angle, starting
+ // at point. If radius is zero for both axes, x and y, nothing
+ // gets returned.
+ //
+ // s----p0/
+ // p1
+ // |
+ // e
+ //
+ // Returns a cubic bezier curve between s and e
+ // with the control points pointing from s in direction
+ // p0 * radius and from e in direction p1 * radius.
+ // The bezier approximates a 90 degree arc.
+ let corner-arc(radius, s, e, p0, p1) = {
+ let (rx, ry) = radius
+ if rx > 0 or ry > 0 {
+ let m = 0.551784
+ let p0 = (p0.at(0) * m * rx,
+ p0.at(1) * m * ry)
+ let p1 = (p1.at(0) * m * rx,
+ p1.at(1) * m * ry)
+ ("c", vector.add(s, p0), vector.add(e, p1), e)
+ }
+ }
+
+ // Compute all eight corner points:
+ //
+ // p1-------p2
+ // / | | \
+ // p0--+ +--p3
+ // | |
+ // p7--+ +--p4
+ // \ | | /
+ // p6-------p5
+ //
+ // If a corner has radius (0,0), both of its
+ // corner points are the same. See the comment on get-corner-pts
+ // on how the corners get computed.
+ let (p0, p1) = get-corner-pts(nw, (x1, y2, z), ( 0,-1), ( 1, 0))
+ let (p2, p3) = get-corner-pts(ne, (x2, y2, z), (-1, 0), ( 0,-1))
+ let (p4, p5) = get-corner-pts(se, (x2, y1, z), ( 0, 1), (-1, 0))
+ let (p6, p7) = get-corner-pts(sw, (x1, y1, z), ( 1, 0), ( 0, 1))
+
+ let segments = ()
+ segments.push(corner-arc(nw, p1, p0, (-1,0), (0, 1)))
+ if p0 != p7 { segments.push(("l", p7)) }
+ segments.push(corner-arc(sw, p7, p6, (0,-1), (-1,0)))
+ if p6 != p5 { segments.push(("l", p5)) }
+ segments.push(corner-arc(se, p5, p4, (1, 0), (0,-1)))
+ if p4 != p3 { segments.push(("l", p3)) }
+ segments.push(corner-arc(ne, p3, p2, (0, 1), (1, 0)))
+ if p2 != p1 { segments.push(("l", p1)) }
+
+ drawable.path(((p1, true, segments.filter(s => s != none)),),
+ fill: style.fill, stroke: style.stroke)
+ }
+
+ // Calculate border anchors
+ let center = vector.lerp(a, b, .5)
+ let (width, height, ..) = size
+ let (transform, anchors) = anchor_.setup(
+ _ => center,
+ ("center",),
+ default: "center",
+ name: name,
+ offset-anchor: anchor,
+ transform: ctx.transform,
+ border-anchors: true,
+ path-anchors: true,
+ radii: (width * 2, height * 2),
+ path: drawables,
+ )
+
+ return (
+ ctx: ctx,
+ name: name,
+ anchors: anchors,
+ drawables: drawable.apply-transform(transform, drawables),
+ )
+ },
+ )
+}
+
+/// Draws a quadratic or cubic bezier curve
+///
+/// ```example
+/// let (a, b, c) = ((0, 0), (2, 0), (1, 1))
+/// bezier(a, b, c)
+///
+/// set-style(content: (frame: "circle", padding: 1pt, fill: white))
+/// content(a, [A]); content(b, [B]); content(c, [C])
+/// ```
+///
+/// ```example
+/// let (a, b, c, d) = ((0, 0), (2, 0), (.5, -1), (1.5, 1))
+/// bezier(a, b, c, d)
+///
+/// set-style(content: (frame: "circle", padding: 1pt, fill: white))
+/// content(a, [A]); content(b, [B]); content(c, [C]); content(d, [D])
+/// ```
+///
+/// - start (coordinate): Start position
+/// - end (coordinate): End position (last coordinate)
+/// - name (none,str):
+/// - ..ctrl-style (coordinate,style): The first two positional arguments are taken as cubic bezier control points, where the first is the start control point and the second is the end control point. One control point can be given for a quadratic bezier curve instead. Named arguments are for styling.
+///
+/// == Styling
+/// *Root* `bezier`
+///
+/// Supports marks.
+///
+/// == Anchors
+/// Supports path anchors.
+/// / ctrl-n: nth control point where n is an integer starting at 0
+///
+#let bezier(start, end, ..ctrl-style, name: none) = {
+ // Extra positional arguments are treated like control points.
+ let (ctrl, style) = (ctrl-style.pos(), ctrl-style.named())
+
+ // Control point check
+ let len = ctrl.len()
+ assert(
+ len in (1, 2),
+ message: "Bezier curve expects 1 or 2 control points. Got " + str(len),
+ )
+ let coordinates = (start, ..ctrl, end)
+
+ return (
+ ctx => {
+ let (ctx, start, ..ctrl, end) = coordinate.resolve(ctx, ..coordinates)
+
+ if ctrl.len() == 1 {
+ (start, end, ..ctrl) = bezier_.quadratic-to-cubic(start, end, ..ctrl)
+ }
+
+ let style = styles.resolve(ctx.style, merge: style, root: "bezier")
+ let drawables = drawable.path(
+ (path-util.make-subpath(start, (("c", ..ctrl, end),)),),
+ fill: style.fill,
+ fill-rule: style.fill-rule,
+ stroke: style.stroke,
+ )
+
+ let (transform, anchors) = anchor_.setup(
+ anchor => (
+ ctrl-0: ctrl.at(0),
+ ctrl-1: ctrl.at(1),
+ ).at(anchor),
+ ("ctrl-0", "ctrl-1"),
+ default: "start",
+ name: name,
+ transform: ctx.transform,
+ path-anchors: true,
+ path: drawables,
+ )
+
+ if mark_.check-mark(style.mark) {
+ drawables = mark_.place-marks-along-path(ctx, style.mark, transform, drawables)
+ } else {
+ drawables = drawable.apply-transform(transform, drawables)
+ }
+
+ return (
+ ctx: ctx,
+ name: name,
+ anchors: anchors,
+ drawables: drawables,
+ )
+ },
+ )
+}
+
+/// Draws a cubic bezier curve through a set of three points.
+/// See `bezier` for style and anchor details.
+///
+/// ```example
+/// let (a, b, c) = ((0, 0), (1, 1), (2, -1))
+/// bezier-through(a, b, c, name: "curve")
+///
+/// // Show the computed control points: 1 and 2
+/// set-style(content: (frame: "circle", padding: 1pt, fill: white))
+/// content(a, [A]); content(b, [B]); content(c, [C])
+/// content("curve.ctrl-1", [2]); content("curve.ctrl-0", [1])
+/// ```
+///
+/// - start (coordinate): The position to start the curve.
+/// - pass-through (coordinate): The position to pass the curve through.
+/// - end (coordinate): The position to end the curve.
+/// - name (none,str):
+/// - ..style (style):
+#let bezier-through(start, pass-through, end, name: none, ..style) = {
+ assert.eq(style.pos(), (), message: "Unexpected positional arguments: " + repr(style.pos()))
+ style = style.named()
+
+ return (ctx => {
+ let (ctx, start, pass-through, end) = coordinate.resolve(ctx, start, pass-through, end)
+
+ let (start, end, ..control) = bezier_.cubic-through-3points(start, pass-through, end)
+
+ return bezier(start, end, ..control, ..style, name: name).first()(ctx)
+ },)
+}
+
+/// Draws a Catmull-Rom curve through a set of points.
+///
+/// ```example
+/// catmull((0,0), (1,1), (2,-1), (3,0), tension: .4, stroke: blue)
+/// catmull((0,0), (1,1), (2,-1), (3,0), tension: .5, stroke: red)
+/// ```
+///
+/// - ..pts-style (coordinate,style): Positional arguments should be coordinates that the curve should pass through. Named arguments are for styling.
+/// - close (bool): Closes the curve with a straight line between the start and end of the curve.
+/// - name (none,str):
+///
+/// == Styling
+/// *Root*: `catmull`
+///
+/// Supports marks.
+///
+/// - tension (float) = 0.5: How tight the curve should fit to the points. The higher the tension the less curvy the curve.
+///
+/// == Anchors
+/// Supports path anchors.
+/// / pt-n: The nth given position (0 indexed so "pt-0" is equal to "start")
+#let catmull(..pts-style, close: false, name: none) = {
+ let (pts, style) = (pts-style.pos(), pts-style.named())
+
+ assert(pts.len() >= 2, message: "Catmull-rom curve requires at least two points. Got " + repr(pts.len()) + "instead.")
+
+ return (ctx => {
+ let (ctx, ..pts) = coordinate.resolve(ctx, ..pts)
+ let style = styles.resolve(ctx.style, merge: style, root: "catmull")
+
+ let curves = bezier_.catmull-to-cubic(
+ pts,
+ style.tension,
+ close: close)
+
+ let drawables = drawable.path(
+ ((curves.first().first(), close, curves.map(((s, e, c1, c2)) => ("c", c1, c2, e))),),
+ fill: style.fill,
+ fill-rule: style.fill-rule,
+ stroke: style.stroke)
+
+ let (transform, anchors) = {
+ let a = for (i, pt) in pts.enumerate() {
+ (("pt-" + str(i)): pt)
+ }
+ anchor_.setup(
+ anchor => a.at(anchor), // Would like to return just `a.at` but Typst is mean :<
+ a.keys(),
+ name: name,
+ default: "start",
+ transform: ctx.transform,
+ path-anchors: true,
+ path: drawables,
+ )
+ }
+
+ if mark_.check-mark(style.mark) {
+ drawables = mark_.place-marks-along-path(ctx, style.mark, transform, drawables)
+ } else {
+ drawables = drawable.apply-transform(transform, drawables)
+ }
+
+ return (
+ ctx: ctx,
+ name: name,
+ anchors: anchors,
+ drawables: drawables,
+ )
+ },)
+}
+
+/// Draws a Hobby curve through a set of points.
+///
+/// ```example
+/// hobby((0, 0), (1, 1), (2, -1), (3, 0), omega: 0, stroke: blue)
+/// hobby((0, 0), (1, 1), (2, -1), (3, 0), omega: 1, stroke: red)
+/// ```
+///
+/// - ..pts-style (coordinate,style): Positional arguments are the coordinates to use to draw the curve with, a minimum of two is required. Named arguments are for styling.
+/// - tb (auto,array): Incoming tension at `pts.at(n+1)` from `pts.at(n)` to `pts.at(n+1)`. The number given must be one less than the number of points.
+/// - ta (auto, array): Outgoing tension at `pts.at(n)` from `pts.at(n)` to `pts.at(n+1)`. The number given must be one less than the number of points.
+/// - close (bool): Closes the curve with a proper smooth curve between the start and end of the curve.
+/// - name (none,str):
+///
+/// == Styling
+/// *Root* `hobby`
+///
+/// Supports marks.
+/// - omega (array) = (1, 1): A tuple of floats that describe how curly the curve should be at each endpoint. When the curl is close to zero, the spline approaches a straight line near the endpoints. When the curl is close to one, it approaches a circular arc.
+///
+/// == Anchors
+/// Supports path anchors.
+/// / pt-n: The nth given position (0 indexed, so "pt-0" is equal to "start")
+#let hobby(..pts-style, ta: auto, tb: auto, close: false, name: none) = {
+ let (pts, style) = (pts-style.pos(), pts-style.named())
+
+ assert(pts.len() >= 2, message: "Hobby curve requires at least two points. Got " + repr(pts.len()) + "instead.")
+
+ return (ctx => {
+ let (ctx, ..pts) = coordinate.resolve(ctx, ..pts)
+ let style = styles.resolve(ctx.style, merge: style, root: "hobby")
+
+ let curves = hobby_.hobby-to-cubic(
+ pts,
+ ta: ta,
+ tb: tb,
+ omega: style.omega,
+ close: close)
+
+ let drawables = drawable.path(
+ ((curves.first().first(), close, curves.map(((s, e, c1, c2)) => ("c", c1, c2, e))),),
+ fill: style.fill,
+ fill-rule: style.fill-rule,
+ stroke: style.stroke)
+
+ let (transform, anchors) = {
+ let a = for (i, pt) in pts.enumerate() {
+ (("pt-" + str(i)): pt)
+ }
+ anchor_.setup(
+ anchor => {
+ if type(anchor) == str and anchor in a {
+ return a.at(anchor)
+ }
+ },
+ a.keys(),
+ name: name,
+ default: "start",
+ transform: ctx.transform,
+ path-anchors: true,
+ path: drawables,
+ )
+ }
+
+ if mark_.check-mark(style.mark) {
+ drawables = mark_.place-marks-along-path(ctx, style.mark, transform, drawables)
+ } else {
+ drawables = drawable.apply-transform(transform, drawables)
+ }
+
+ return (
+ ctx: ctx,
+ name: name,
+ anchors: anchors,
+ drawables: drawables,
+ )
+ },)
+}
+
+/// Create a new path with each element used as sub-paths.
+/// This can be used to create paths with holes.
+///
+/// Unlike `merge-path`, this function groups the shapes as sub-paths
+/// instead of concatenating them into a single continuous path.
+///
+/// ```example
+/// compound-path({
+/// rect((-1, -1), (1, 1))
+/// circle((0, 0), radius: .5)
+/// }, fill: blue, fill-rule: "even-odd")
+/// ```
+///
+/// == Anchors
+/// / *centroid*: Centroid of the _closed and non self-intersecting_ shape. Only exists if `close` is true.
+/// Supports path anchors and shapes where all vertices share the same z-value.
+///
+/// - body (elements): Elements with paths to be merged together.
+/// - name (none,str):
+/// - ..style (style):
+#let compound-path(body, name: none, ..style) = {
+ assert.eq(style.pos().len(), 0,
+ message: "compound-path: Unexpected positional arguments")
+
+ let style = style.named()
+ return (
+ ctx => {
+ let subpaths = ()
+ for element in util.resolve-body(ctx, body) {
+ let r = process.element(ctx, element)
+ if r != none and "drawables" in r {
+ ctx = r.ctx
+
+ subpaths += drawable.filter-tagged(r.drawables, drawable.TAG.debug)
+ .map(d => d.segments).join()
+ }
+ }
+
+ assert.ne(subpaths, (),
+ message: "compound-path must at least contain one element!")
+
+ let (_, first-path-closed, _) = subpaths.first()
+
+ let style = styles.resolve(ctx.style, merge: style)
+ let drawables = drawable.path(
+ fill: style.fill, fill-rule: style.fill-rule, stroke: style.stroke,
+ subpaths)
+
+ let (transform, anchors) = anchor_.setup(
+ name => {
+ if name == "centroid" {
+ return polygon_.simple-centroid(polygon_.from-subpath(
+ subpaths.first()))
+ }
+ },
+ if first-path-closed != none { ("centroid",) } else { () },
+ name: name,
+ transform: none,
+ path-anchors: true,
+ path: drawables,
+ )
+
+ return (
+ ctx: ctx,
+ name: name,
+ anchors: anchors,
+ drawables: drawables,
+ )
+ },
+ )
+}
+
+/// Merges two or more paths by concatenating their elements. Anchors and visual styling, such as `stroke` and `fill`, are not preserved. When an element's path does not start at the same position the previous element's path ended, a straight line is drawn between them so that the final path is continuous. You must then pay attention to the direction in which element paths are drawn.
+///
+/// ```example
+/// merge-path(fill: white, {
+/// line((0, 0), (1, 0))
+/// bezier((), (0, 0), (1,1), (0,1))
+/// })
+/// ```
+///
+/// Elements hidden via [hide](../grouping/hide) are ignored.
+///
+/// == Anchors
+/// / centroid: Centroid of the _closed and non self-intersecting_ shape. Only exists if `close` is true.
+/// Supports path anchors and shapes where all vertices share the same z-value.
+///
+/// - body (elements): Elements with paths to be merged together.
+/// - join (bool): Connect all sub-paths with a straight line
+/// - close (bool): Close the path with a straight line from the start of the path to its end.
+/// - ignore-marks (bool): If true, remove marks from input elements
+/// - ignore-hidden (bool): If true, ignore all hidden elements
+/// - name (none,str):
+/// - ..style (style):
+#let merge-path(body, join: true, ignore-marks: true, ignore-hidden: true, close: false, name: none, ..style) = {
+ // No extra positional arguments from the style sink
+ assert.eq(
+ style.pos(),
+ (),
+ message: "Unexpected positional arguments: " + repr(style.pos()),
+ )
+ let style = style.named()
+
+ return (
+ ctx => {
+ let ctx = ctx
+ let subpaths = ()
+
+ for element in body {
+ let r = process.element(ctx, element)
+ if r != none {
+ ctx = r.ctx
+
+ let tags = (drawable.TAG.debug,)
+ if ignore-hidden { tags.push(drawable.TAG.hidden) }
+ if ignore-marks { tags.push(drawable.TAG.mark) }
+
+ let drawables = drawable.filter-tagged(r.drawables, ..tags)
+ if join and drawables.len() > 0 and subpaths.len() > 0 {
+ let (origin, closed, segments) = subpaths.last()
+ let (next-origin, _, next-segments) = drawables.first().segments.first()
+
+ // Close the gap using a line
+ if next-origin != path-util.subpath-end(subpaths.last()) {
+ segments.push(("l", next-origin))
+ }
+
+ segments += next-segments
+ subpaths.last() = (origin, closed or close, segments)
+ subpaths += drawables.slice(1).filter(d => {
+ d.type == "path"
+ }).map(d => d.segments).join()
+ } else {
+ subpaths += drawables.filter(d => {
+ d.type == "path"
+ }).map(d => d.segments).join()
+ }
+ }
+ }
+
+ // Close paths
+ if close {
+ subpaths = subpaths.map(((origin, closed, elems)) => {
+ (origin, close or closed, elems)
+ })
+ }
+
+ let style = styles.resolve(ctx.style, merge: style)
+ let drawables = drawable.path(fill: style.fill, fill-rule: style.fill-rule, stroke: style.stroke, subpaths)
+
+ let (transform, anchors) = anchor_.setup(
+ name => {
+ if name == "centroid" {
+ // Try finding a closed shapes center by
+ // Sampling it to a polygon.
+ return polygon_.simple-centroid(polygon_.from-subpath(drawables.segments.first()))
+ }
+ },
+ if close != none { ("centroid",) } else { () },
+ name: name,
+ transform: none,
+ path-anchors: true,
+ path: drawables,
+ )
+
+ // Place marks and adjust segments
+ if mark_.check-mark(style.mark) {
+ drawables = mark_.place-marks-along-path(ctx, style.mark, transform, drawables)
+ } else {
+ drawables = drawable.apply-transform(transform, drawables)
+ }
+
+ return (
+ ctx: ctx,
+ name: name,
+ anchors: anchors,
+ drawables: drawables,
+ )
+ },
+ )
+}
+
+/// Draws an axis aligned bounding box around all given coordinates and/or elements.
+/// Everything else (styling, anchors) is similar to `rect`.
+///
+/// Bounds of elements are calculated by computing the bounding box of their paths,
+/// or as a fallback, using all anchors of the element.
+///
+/// ```example
+/// circle((1, 1), radius: 0.1, fill: blue, name: "c1")
+/// circle((0, 1), radius: 0.1, fill: red, name: "c2")
+/// rect((0, 2), (1, 2.5), name: "r1")
+/// rect-around("c1", "c2", "r1", stroke: yellow, padding: 0.1)
+/// ```
+/// - ..pts-style (coordinates,style): Positional two or more coordinates/elements to calculate bounding box of. Accepts style key-value pairs.
+/// - ignore-marks (bool): If true, ignore mark shapes when calculating a shape's bounding box
+/// - ignore-hidden (bool):
+/// - ignore-floating (bool):
+/// - ignore-shapes (bool): Use only anchors for bounds calculation
+///
+/// == Styling
+/// The padding attribute can be used to control spacing.
+/// Other attributes are forwarded to the rect shape.
+///
+/// == Anchors
+/// The same as for the rect shape.
+#let rect-around(..pts-style, ignore-marks: false, ignore-hidden: false, ignore-floating: false, ignore-shapes: false) = {
+ let pts = pts-style.pos()
+ let style = pts-style.named()
+
+ get-ctx(ctx => {
+
+ let inverse = matrix.inverse(ctx.transform)
+
+ let bounds = ()
+ for pt in pts {
+ // If elements are given (by name)
+ if type(pt) == str and pt in ctx.nodes {
+ let original = if not ignore-shapes { ctx.nodes.at(pt).at("drawables", default: ()) } else { () }
+ let filtered = drawable.filter-tagged(
+ original,
+ drawable.TAG.debug,
+ if ignore-marks { drawable.TAG.mark },
+ if ignore-hidden { drawable.TAG.hidden },
+ if ignore-floating { drawable.TAG.no-bounds },
+ )
+
+ if filtered != () {
+ for d in filtered {
+ bounds += path-util.bounds(d.segments, transform: inverse)
+ }
+ } else if original == () {
+ // If we have no drawables (e.g. an anchor element)
+ // we fall back to all anchors the element has.
+ let anchors = (ctx.nodes.at(pt).anchors)(()).map(v => pt + "." + v)
+ let (_, ..pts) = coordinate.resolve(ctx, ..anchors)
+ bounds += pts
+ }
+ } else {
+ (ctx, pt) = coordinate.resolve(ctx, pt)
+ bounds.push(pt)
+ }
+ }
+
+ if bounds == () {
+ return
+ }
+
+ let style = styles.resolve(ctx.style, merge: style, root: "rect", base: (padding: none))
+
+ // Resolve padding and convert to canvas units
+ let padding = util.as-padding-dict(style.padding)
+ // Swap top and bottom padding for reasons
+ (padding.top, padding.bottom) = (padding.bottom, padding.top)
+ for (k, v) in padding {
+ padding.insert(k, util.resolve-number(ctx, v))
+ }
+
+ let new-bounds = aabb.padded(aabb.aabb(bounds), padding)
+ rect(new-bounds.low, new-bounds.high, ..style)
+ })
+}
+
+/// Create a new path from a SVG-like list of commands.
+///
+/// The following commands are supported (uppercase command names use absolute coordinates, lowercase use relative coordinates)
+/// - `("l", coordinate)` line to `coordinate`
+/// - `("h", number)` Horizontal line
+/// - `("v", number)` Vertical line
+/// - `("m", coordinate)` Move to `coordinate`
+/// - `("c", ctrl-coordinate-a, ctrl-coordinate-b, coordinate)` Cubic bezier curve to `coordinate` with two control points a and b
+/// - `("q", ctrl-coordinate, coordinate)` Quadratic bezier curve
+/// - `("z",)` Close the current path
+/// - `("anchor", "<anchor-name>", [coordinate=(0, 0)])` named anchor.
+/// If the anchor coordinate is unset, the default `(0, 0, 0)` is used.
+/// The anchor named "default" serves as origin for the `anchor:` argument.
+///
+/// ```example
+/// svg-path(("h", 2),
+/// ("anchor", "here"),
+/// ("c", (0, 1), (0, 0), (-1, 0)),
+/// ("v", -0.5),
+/// ("h", -1),
+/// ("z",), name: "svg")
+/// circle("svg.here", fill: white, radius: 0.1cm)
+/// ```
+///
+/// - name (none, string):
+/// - anchor (none, coordinate):
+/// - ..commands-style (any): Path commands and style keys
+#let svg-path(name: none, anchor: none, ..commands-style) = {
+ let style = commands-style.named()
+ let commands = commands-style.pos().map(cmd => {
+ if type(cmd) == str {
+ (cmd,)
+ } else {
+ cmd
+ }
+ })
+
+ assert.ne(commands, (),
+ message: "Empty svg-path commands")
+
+ return (ctx => {
+ let paths = ()
+
+ let origin = (0.0, 0.0, 0.0)
+ let current = ()
+
+ // Dictionary of user anchors
+ let anchors = (:)
+
+ for ((cmd, ..args)) in commands {
+ assert(cmd in ("m", "M", "l", "L", "c", "C", "h", "H", "v", "V", "z", "Z", "q", "Q", "anchor", "Anchor"),
+ message: "Unknown svg-path command: " + repr(cmd))
+
+ // Transform lower-case commands to relative coordinates
+ let is-relative = cmd in ("m", "l", "c", "h", "v", "q", "anchor")
+ let wrap-coordinate = if is-relative {
+ x => (rel: x)
+ } else {
+ x => x
+ }
+
+ // The name of the current anchor command
+ let current-name = none
+
+ if cmd in ("h", "H") {
+ assert.eq(args.len(), 1)
+ let (x, ..rest) = args
+ args = ((x, 0.0, 0.0),)
+ cmd = if cmd == "h" { "l" } else { "L" }
+ } else if cmd in ("v", "V") {
+ assert.eq(args.len(), 1)
+ let (y, ..rest) = args
+ args = ((0.0, y, 0.0),)
+ cmd = if cmd == "v" { "l" } else { "L" }
+ } else if cmd in ("anchor", "Anchor") {
+ current-name = args.at(0)
+ args = if args.len() != 1 {
+ args.slice(1)
+ } else {
+ ((0, 0, 0),)
+ }
+ }
+
+ // Save the current coordinate before
+ // resolving the list of arguments.
+ let prev-pt = ctx.prev.pt
+
+ (ctx, ..args) = coordinate.resolve(ctx, ..args.map(wrap-coordinate))
+
+ if cmd in ("z", "Z") {
+ assert.eq(args.len(), 0)
+ if current != () {
+ paths.push(path-util.make-subpath(origin, current, closed: cmd == "z"))
+ }
+
+ current = ()
+ }
+
+ if cmd in ("m", "M", "l", "L") {
+ if cmd in ("m", "M") {
+ assert.eq(args.len(), 1)
+ origin = args.at(0, default: (0, 0, 0))
+ args.pop()
+ }
+
+ current += args.map(pt => ("l", pt))
+ } else if cmd in ("c", "C") {
+ assert.eq(args.len(), 3)
+ let (c1, c2, pt) = args
+ current.push(("c", c1, c2, pt))
+ } else if cmd in ("q", "Q") {
+ assert.eq(args.len(), 2)
+ let (c1, pt) = args
+ let (_, pt, c1, c2) = bezier_.quadratic-to-cubic(prev-pt, pt, c1)
+ current.push(("c", c1, c2, pt))
+ } else if cmd in ("anchor", "Anchor") {
+ assert.eq(args.len(), 1)
+ assert(current-name not in (none, ""))
+ anchors.insert(current-name, args.at(0))
+ }
+ }
+
+ if current != () {
+ paths.push(path-util.make-subpath(origin, current, closed: false))
+ }
+
+ let style = styles.resolve(ctx.style, merge: style)
+ let drawables = drawable.path(paths, stroke: style.stroke, fill: style.fill, fill-rule: style.fill-rule)
+
+ let (transform, anchors) = anchor_.setup(
+ key => anchors.at(key),
+ anchors.keys(),
+ default: if "default" in anchors { "default" } else { none },
+ name: name,
+ offset-anchor: anchor,
+ transform: ctx.transform,
+ // For border anchors we would need a radius + a "center" anchor.
+ // border-anchors: "center" in anchors,
+ path-anchors: true,
+ path: drawables,
+ )
+
+ if mark_.check-mark(style.mark) {
+ drawables = mark_.place-marks-along-path(ctx, style.mark, transform, drawables)
+ } else {
+ drawables = drawable.apply-transform(transform, drawables)
+ }
+
+ return (
+ ctx: ctx,
+ name: name,
+ anchors: anchors,
+ drawables: drawables,
+ )
+ },)
+}
diff --git a/render/packages/preview/cetz/0.5.2/src/draw/styling.typ b/render/packages/preview/cetz/0.5.2/src/draw/styling.typ
new file mode 100644
index 0000000..603f249
--- /dev/null
+++ b/render/packages/preview/cetz/0.5.2/src/draw/styling.typ
@@ -0,0 +1,96 @@
+#import "/src/util.typ"
+#import "/src/styles.typ"
+
+/// Set current style
+///
+/// - ..style (style): Style key-value pairs
+#let set-style(..style) = {
+ assert.eq(
+ style.pos().len(),
+ 0,
+ message: "set-style takes no positional arguments",
+ )
+
+ (ctx => {
+ ctx.style = styles.merge(ctx.style, style.named())
+
+ return (ctx: ctx)
+ },)
+}
+
+/// Set current fill style
+///
+/// Shorthand for `set-style(fill: <fill>)`
+///
+/// - fill (paint): Fill style
+#let fill(fill) = set-style(fill: fill)
+
+/// Set current stroke style
+///
+/// Shorthand for `set-style(stroke: <fill>)`
+///
+/// - stroke (stroke): Stroke style
+#let stroke(stroke) = set-style(stroke: stroke)
+
+/// Register a custom mark to the canvas
+///
+/// The mark should contain both anchors called *tip* and *base* that are used to determine the marks orientation. If unset both default to `(0, 0)`.
+/// An anchor named *center* is used as center of the mark, if present. Otherwise the mid between *tip* and *base* is used.
+///
+/// ```example
+/// register-mark(":)", style => {
+/// circle((0,0), radius: .5, fill: yellow)
+/// arc((0,0), start: 180deg + 30deg, delta: 180deg - 60deg, anchor: "origin", radius: .3)
+/// circle((-0.15, 0.15), radius: .1, fill: white)
+/// circle((-0.10, 0.10), radius: .025, fill: black)
+/// circle(( 0.15, 0.15), radius: .1, fill: white)
+/// circle(( 0.20, 0.10), radius: .025, fill: black)
+///
+/// anchor("tip", ( 0.5, 0))
+/// anchor("base", (-0.5, 0))
+/// })
+///
+/// line((0,0), (3,0), mark: (end: ":)"))
+/// ```
+///
+/// - symbol (str): Mark name
+/// - mnemonic (none, str): Mark short name
+/// - body (function): Mark drawing callback, receiving the mark style as argument and returning elements. Format `(styles) => elements`.
+/// - tip (none, number, coordinate): Tip coordinate (if passed a number, the y component is 0)
+/// - base (none, number, coordinate): Base coordinate (see tip)
+/// - center (none, number, coordinate): Center coordinate (see tip)
+/// - reverse-tip (none, number, coordinate): Reversed tip coordinate (see tip)
+/// - reverse-base (none, number, coordinate): Reversed base coordinate (see tip)
+/// - reverse-center (none, number, coordinate): Reversed center coordinate (see tip)
+#let register-mark(symbol, body, mnemonic: none, tip: none, base: none, center: none, reverse-tip: none, reverse-base: none, reverse-center: none) = {
+ import "/src/draw/grouping.typ": anchor
+
+ assert(type(symbol) == str)
+ assert(type(body) == function)
+ assert(type(mnemonic) in (type(none), str))
+
+ // Generate anchors, if passed via arguments
+ let anchors = (("tip", tip), ("base", base), ("reverse-tip", reverse-tip), ("reverse-base", reverse-base)).map(((key, value)) => {
+ if value != none {
+ // Translate atomic values to vectors with the y-component set to 0.
+ if type(value) in (int, float) {
+ value = (value, 0.0)
+ }
+
+ anchor(key, value)
+ }
+ }).filter(v => v != none)
+
+ // Prepend generated anchors to the body function
+ let new-body = (ctx) => {
+ anchors + body(ctx)
+ }
+
+ (ctx => {
+ ctx.marks.marks.insert(symbol, body)
+ if type(mnemonic) == str and mnemonic.len() > 0 {
+ ctx.marks.mnemonics.insert(mnemonic, symbol)
+ }
+ return (ctx: ctx)
+ },)
+}
diff --git a/render/packages/preview/cetz/0.5.2/src/draw/transformations.typ b/render/packages/preview/cetz/0.5.2/src/draw/transformations.typ
new file mode 100644
index 0000000..0e9005c
--- /dev/null
+++ b/render/packages/preview/cetz/0.5.2/src/draw/transformations.typ
@@ -0,0 +1,295 @@
+#import "/src/coordinate.typ"
+#import "/src/matrix.typ"
+#import "/src/vector.typ"
+#import "/src/util.typ"
+
+// Utility for applying translation to and from
+// the origin to apply a transformation matrix to.
+//
+// - ctx (context): Context
+// - transform (matrix): Transformation matrix
+// - origin (coordinate): Origin coordinate or none
+#let _transform-around-origin(ctx, transform, origin) = {
+ if origin != none {
+ let (_, origin) = coordinate.resolve(ctx, origin, update: false)
+ let a = matrix.transform-translate(..origin)
+ let b = matrix.transform-translate(..vector.scale(origin, -1))
+
+ matrix.mul-mat(a, matrix.mul-mat(transform, b))
+ } else {
+ transform
+ }
+}
+
+/// Overwrites the transformation matrix.
+///
+/// - mat (none, matrix): The 4x4 transformation matrix to set. If `none` is passed, the transformation matrix is set to the identity matrix (`matrix.ident(4)`).
+#let set-transform(mat) = {
+ let mat = if mat == none {
+ matrix.ident(4)
+ } else {
+ matrix.round(mat)
+ }
+
+ assert(
+ type(mat) == array,
+ message: "Transformtion matrix must be of type array, got: " + repr(mat))
+ assert.eq(
+ mat.len(),
+ 4,
+ message: "Transformation matrix must be of size 4x4, got: " + repr(mat))
+
+ (ctx => {
+ ctx.transform = mat
+ return (ctx: ctx)
+ },)
+}
+
+/// Applies a $4 times 4$ transformation matrix to the current transformation.
+///
+/// Given the current transformation $C$ and the new transformation $T$,
+/// the function sets the new canvas' transformation $C'$ to $C' = C T$.
+///
+/// - mat (none, matrix): The 4x4 transformation matrix to set. If `none` is passed, the transformation matrix is set to the identity matrix (`matrix.ident(4)`).
+#let transform(mat) = {
+ let mat = if mat == none {
+ matrix.ident(4)
+ } else {
+ matrix.round(mat)
+ }
+
+ assert(
+ type(mat) == array,
+ message: "Transformtion matrix must be of type array, got: " + repr(mat))
+ assert.eq(
+ mat.len(),
+ 4,
+ message: "Transformation matrix must be of size 4x4, got: " + repr(mat))
+
+ (ctx => {
+ ctx.transform = matrix.mul-mat(ctx.transform, mat)
+ return (ctx: ctx)
+ },)
+}
+
+/// Rotates the transformation matrix on the z-axis by a given angle or other axes when specified.
+///
+/// ```example
+/// // Rotate on z-axis
+/// rotate(z: 45deg)
+/// rect((-1,-1), (1,1))
+/// // Rotate on y-axis
+/// rotate(y: 80deg)
+/// circle((0,0))
+/// ```
+///
+/// - ..angles (angle): A single angle as a positional argument to rotate on the z-axis by.
+/// Named arguments of `x`, `y` or `z` can be given to rotate on their respective axis.
+/// You can give named arguments of `yaw`, `pitch` or `roll`, too.
+/// - origin (none,coordinate): Origin to rotate around, or (0, 0, 0) if set to `none`.
+#let rotate(..angles, origin: none) = {
+ assert(angles.pos().len() == 1 or angles.named().len() > 0,
+ message: "Rotate takes a single z-angle or angles " +
+ "(x, y, z or yaw, pitch, roll) as named arguments, got: " + repr(angles))
+
+ let named = angles.named()
+ let names = named.keys()
+
+ let mat = if angles.pos().len() == 1 {
+ matrix.transform-rotate-z(angles.pos().at(0))
+ } else if names.all(n => n in ("x", "y", "z")) {
+ matrix.transform-rotate-xyz(named.at("x", default: 0deg),
+ named.at("y", default: 0deg),
+ named.at("z", default: 0deg))
+ } else if names.all(n => n in ("yaw", "pitch", "roll")) {
+ matrix.transform-rotate-ypr(named.at("yaw", default: 0deg),
+ named.at("pitch", default: 0deg),
+ named.at("roll", default: 0deg))
+ } else {
+ panic("Invalid rotate arguments." +
+ "Rotate expects: A single (z-axis) angle or any combination of x, y,z or any combination of yaw, pitch, roll. " +
+ "Got: " + repr(named))
+ }
+
+ (ctx => {
+ ctx.transform = matrix.mul-mat(ctx.transform,
+ _transform-around-origin(ctx, mat, origin))
+ return (ctx: ctx)
+ },)
+}
+
+/// Translates the transformation matrix by the given vector or dictionary.
+///
+/// ```example
+/// // Outer rect
+/// rect((0, 0), (2, 2))
+/// // Inner rect
+/// translate(x: .5, y: .5)
+/// rect((0, 0), (1, 1))
+/// ```
+///
+/// - ..args (vector, float, length): A single vector or any combination of the named arguments `x`, `y` and `z` to translate by.
+/// A translation matrix with the given offsets gets multiplied with the current transformation depending on the value of `pre`.
+/// - pre (bool): Specify matrix multiplication order
+/// - false: `World = World * Translate`
+/// - true: `World = Translate * World`
+#let translate(..args, pre: false) = {
+ assert((args.pos().len() == 1 and args.named() == (:)) or
+ (args.pos() == () and args.named() != (:)),
+ message: "Expected a single positional argument or one or more named arguments, got: " + repr(args))
+
+ let pos = args.pos()
+ let named = args.named()
+
+ let vec = if named != (:) {
+ (named.at("x", default: 0), named.at("y", default: 0), named.at("z", default: 0))
+ } else {
+ vector.as-vec(pos.at(0), init: (0, 0, 0))
+ }
+
+ (ctx => {
+ // Allow translating by length values
+ let vec = vec.map(v => if type(v) == length {
+ util.resolve-number(ctx, v)
+ } else {
+ v
+ })
+
+ let t = matrix.transform-translate(..vec)
+ if pre {
+ ctx.transform = matrix.mul-mat(t, ctx.transform)
+ } else {
+ ctx.transform = matrix.mul-mat(ctx.transform, t)
+ }
+ return (ctx: ctx)
+ },)
+}
+
+/// Scales the transformation matrix by the given factor(s).
+///
+/// ```example
+/// // Scale the y-axis
+/// scale(y: 50%)
+/// circle((0,0))
+/// ```
+///
+/// Note that content like text does not scale automatically. See `auto-scale` styling of content for that.
+///
+/// - ..args (float, ratio): A single value to scale the transformation matrix by or per axis
+/// scaling factors. Accepts a single float or ratio value or any combination of the named arguments
+/// `x`, `y` and `z` to set per axis scaling factors. A ratio of 100% is the same as the value $1$.
+/// - origin (none,coordinate): Origin to rotate around, or (0, 0, 0) if set to `none`.
+#let scale(..args, origin: none) = {
+ assert((args.pos().len() == 1 and args.named() == (:)) or
+ (args.pos() == () and args.named() != (:)),
+ message: "Expected a single positional argument or one or more named arguments, got: " + repr(args))
+
+ let pos = args.pos()
+ let named = args.named()
+
+ let vec = if args.named() != (:) {
+ (named.at("x", default: 1), named.at("y", default: 1), named.at("z", default: 1))
+ } else if type(pos.at(0)) == array {
+ vector.as-vec(pos, init: (1, 1, 1))
+ } else {
+ let factor = pos.at(0)
+ (factor, factor, factor)
+ }
+
+ // Allow scaling using ratio values
+ vec = vec.map(v => if type(v) == ratio {
+ v / 100%
+ } else {
+ v
+ })
+
+ (ctx => {
+ let mat = matrix.transform-scale(vec)
+ ctx.transform = matrix.mul-mat(ctx.transform,
+ _transform-around-origin(ctx, mat, origin))
+ return (ctx: ctx)
+ },)
+}
+
+/// Sets the given position as the new origin `(0, 0, 0)`
+///
+/// ```example
+/// // Draw some rect
+/// rect((0,0), (2,2), name: "r")
+///
+/// // Move (0, 0) to the top edge of “r”
+/// set-origin("r.north")
+/// circle((0, 0), radius: .1, fill: white)
+/// ```
+///
+/// - origin (coordinate): Coordinate to set as new origin `(0,0,0)`
+#let set-origin(origin) = {
+ (
+ ctx => {
+ let (ctx, c) = coordinate.resolve(ctx, origin)
+ let (x, y, z) = vector.sub(
+ util.apply-transform(ctx.transform, c),
+ util.apply-transform(ctx.transform, (0, 0, 0)),
+ )
+ ctx.transform = matrix.mul-mat(matrix.transform-translate(x, y, z), ctx.transform)
+ return (ctx: ctx)
+ },
+ )
+}
+
+/// Sets the previous coordinate.
+///
+/// The previous coordinate can be used via `()` (empty coordinate).
+/// It is also used as base for relative coordinates if not specified
+/// otherwise.
+///
+/// ```example
+/// circle((), radius: .25)
+/// move-to((1,0))
+/// circle((), radius: .15)
+/// ```
+///
+/// - pt (coordinate): The coordinate to move to.
+#let move-to(pt) = {
+ return (ctx => {
+ let (ctx, pt) = coordinate.resolve(ctx, pt)
+ return (ctx: ctx)
+ },)
+}
+
+/// Span viewport between two coordinates and set-up scaling and translation
+///
+/// ```example
+/// rect((0,0), (2,2))
+/// set-viewport((0,0), (2,2), bounds: (10, 10))
+/// circle((5,5))
+/// ```
+///
+/// - from (coordinate): Bottom left corner coordinate
+/// - to (coordinate): Top right corner coordinate
+/// - bounds (vector): Viewport bounds vector that describes the inner width,
+/// height and depth of the viewport
+#let set-viewport(from, to, bounds: (1, 1, 1)) = {
+ return (ctx => {
+ let bounds = vector.as-vec(bounds, init: (1, 1, 1))
+
+ let (ctx, from, to) = coordinate.resolve(ctx, from, to)
+ let (fx, fy, fz) = from
+ let (tx, ty, tz) = to
+
+ // Compute scaling
+ let (sx, sy, sz) = vector.sub((tx, ty, tz),
+ (fx, fy, fz)).enumerate().map(((i, v)) => if bounds.at(i) == 0 {
+ 0
+ } else {
+ v / bounds.at(i)
+ })
+
+ ctx.transform = matrix.mul-mat(ctx.transform,
+ matrix.transform-translate(fx, fy, fz))
+ ctx.transform = matrix.mul-mat(ctx.transform,
+ matrix.transform-scale((sx, sy, sz)))
+ return (ctx: ctx)
+ },)
+}
+
diff --git a/render/packages/preview/cetz/0.5.2/src/draw/util.typ b/render/packages/preview/cetz/0.5.2/src/draw/util.typ
new file mode 100644
index 0000000..dd638cd
--- /dev/null
+++ b/render/packages/preview/cetz/0.5.2/src/draw/util.typ
@@ -0,0 +1,58 @@
+/// Assert that the cetz version of the canvas matches the given version (range).
+///
+/// - min (version): Minimum version (current >= min)
+/// - max (none, version): First unsupported version (current < max)
+/// - hint (string): Name of the function/module this assert is called from
+#let assert-version(min, max: none, hint: "") = {
+ if hint != "" { hint = " by " + hint }
+ (ctx => {
+ /* Default to 2.0.0, as this is the first version that had elements as single functions. */
+ let v = ctx.at("version", default: version(0,2,0))
+ assert(min <= v,
+ message: "CeTZ canvas version is " + str(v) + ", but the minimum required version" + hint + " is " + str(min))
+ if max != none {
+ assert(max > v,
+ message: "CeTZ canvas version is " + str(v) + ", but the maximum supported version" + hint + " is " + str(min))
+ }
+
+ return (ctx: ctx)
+ },)
+}
+
+/// Push a custom coordinate resolve function to the list of coordinate
+/// resolvers. This resolver is scoped to the current context scope!
+///
+/// A coordinate resolver must be a function of the format `(context, coordinate) => coordinate`. And must _always_ return a valid coordinate or panic, in case of an error.
+///
+/// If multiple resolvers are registered, coordinates get passed through all
+/// resolvers in reverse registering order. All coordinates get passed to cetz'
+/// default coordinate resolvers.
+///
+/// ```example
+/// register-coordinate-resolver((ctx, c) => {
+/// if type(c) == dictionary and "log" in c {
+/// c = c.log.map(n => calc.log(n, base: 10))
+/// }
+/// return c
+/// })
+///
+/// circle((log: (10, 1e-6)), radius: .25)
+/// circle((log: (100, 1e-6)), radius: .25)
+/// circle((log: (1000, 1e-6)), radius: .25)
+/// ```
+///
+/// - resolver (function): The resolver function, taking a context and a single coordinate and returning a single coordinate
+#let register-coordinate-resolver(resolver) = {
+ assert.eq(type(resolver), function,
+ message: "Coordinate resolver must be of type function (ctx, coordinate) => coordinate.")
+
+ return (ctx => {
+ if type(ctx.resolve-coordinate) == array {
+ ctx.resolve-coordinate.push(resolver)
+ } else {
+ ctx.resolve-coordinate = (resolver,)
+ }
+
+ return (ctx: ctx)
+ },)
+}
diff --git a/render/packages/preview/cetz/0.5.2/src/drawable.typ b/render/packages/preview/cetz/0.5.2/src/drawable.typ
new file mode 100644
index 0000000..44328ef
--- /dev/null
+++ b/render/packages/preview/cetz/0.5.2/src/drawable.typ
@@ -0,0 +1,273 @@
+#import "vector.typ"
+#import "util.typ"
+#import "path-util.typ"
+#import "matrix.typ"
+
+// Tag constants
+#let TAG = (
+ hidden: "hidden",
+ no-bounds: "no-bounds",
+ content-frame: "content-frame",
+ mark: "mark",
+ debug: "debug",
+)
+
+/// Applies a transform to drawables. If a single drawable is given it will be returned in a single element <Type>array</Type>.
+/// - transform (matrix): The transformation matrix.
+/// - drawables (drawable): The drawables to transform.
+/// -> drawable
+#let apply-transform(transform, drawables) = {
+ if type(drawables) == dictionary {
+ drawables = (drawables,)
+ }
+ if drawables.len() == 0 {
+ return ()
+ }
+ if transform == none or matrix.is-identity(transform) {
+ return drawables
+ }
+
+ for drawable in drawables {
+ if type(drawable) != dictionary {
+ panic("Expected drawable, got: ", drawable)
+ }
+
+ if "segments" in drawable {
+ drawable.segments = drawable.segments.map(((origin, closed, segments)) => {
+ origin = util.apply-transform(transform, origin)
+ if segments != () {
+ if type(segments.first()) != array {
+ panic("Segments must be an array, got: ", segments)
+ }
+ segments = segments.map(((kind, ..args)) => {
+ if args.len() == 1 {
+ (kind, util.apply-transform(transform, ..args))
+ } else if args.len() > 1 {
+ (kind, ..util.apply-transform(transform, ..args))
+ } else {
+ (kind,)
+ }
+ })
+ }
+
+ return (origin, closed, segments)
+ })
+ }
+ if drawable.type == "content" {
+ drawable.pos = util.apply-transform(transform, drawable.pos)
+ }
+ (drawable,)
+ }
+}
+
+/// Adds `tags` to one or more drawables.
+///
+/// - drawables (drawable, array): A single drawable or an array of type:drawable.
+/// - ..tags (str): The list of tags to add to the drawable
+/// -> drawable A single drawable
+/// -> array An array of type:drawable
+#let apply-tags(drawables, ..tags) = {
+ let tags = tags.pos().filter(v => v != none)
+ assert(tags.all(v => type(v) == str))
+
+ if type(drawables) == array {
+ return drawables.map(d => apply-tags(d, ..tags))
+ }
+
+ drawables.insert("tags", (drawables.at("tags", default: ()) + tags).dedup())
+ return drawables
+}
+
+/// Filter out all drawables that have one of the given tags assigned.
+///
+/// - drawables (drawable, array): A single drawable or an array of type:drawables.
+/// - ..tags (str): The list of tags to use as a filter.
+/// -> drawable A single drawable
+/// -> array An array of type:drawable
+#let filter-tagged(drawables, ..tags) = {
+ if type(drawables) == array {
+ return drawables.map(d => filter-tagged(d, ..tags)).filter(d => d != none)
+ }
+
+ let tags = tags.pos()
+ if drawables.at("tags", default: ()).any(t => t in tags) {
+ return none
+ }
+ return drawables
+}
+
+/// Creates a path drawable from path segements.
+/// - segments (array): The segments to create the path from.
+/// - close (bool): If `true` the path will be closed.
+/// - fill (color,none): The color to fill the path with.
+/// - fill-rule (str): One of "even-odd" or "non-zero".
+/// - stroke (stroke): The stroke of the path.
+/// -> drawable
+#let path(fill: none, stroke: none, fill-rule: "non-zero", tags: (), path) = {
+ assert.eq(type(path), array)
+
+ for subpath in path {
+ assert.eq(subpath.len(), 3)
+ let (origin, closed, segments) = subpath
+ assert.eq(type(origin), array)
+ assert.eq(type(closed), bool)
+ assert.eq(type(segments), array)
+ for ((kind, ..args)) in segments {
+ if kind == "l" {
+ assert.eq(args.len(), 1)
+ } else if kind == "c" {
+ assert.eq(args.len(), 3)
+ }
+ }
+ }
+
+ path = path-util.normalize(path)
+ return (
+ type: "path",
+ segments: path,
+ fill: fill,
+ fill-rule: fill-rule,
+ stroke: stroke,
+ tags: tags)
+}
+
+/// Construct a line-strip from a list of points
+/// - points (array): Array of points
+/// - close (bool):
+/// - fill (none,fill):
+/// - stroke (none,stroke):
+/// - fill-rule (str):
+/// -> drawable
+#let line-strip(points, close: false, fill: none, stroke: none, fill-rule: "non-zero", tags: ()) = {
+ assert.eq(type(points), array)
+
+ return path(
+ ((points.first(), close, points.slice(1).map((pt) => ("l", pt))),),
+ stroke: stroke,
+ fill: fill,
+ fill-rule: fill-rule,
+ tags: tags)
+}
+
+
+/// Creates a content drawable.
+/// - pos (vector): The position of the drawable.
+/// - width (float): The width of the drawable.
+/// - height (float): The height of the drawable.
+/// - border (segment): A segment to define the border of the drawable with.
+/// - body (content): The content of the drawable.
+/// -> drawable
+#let content(pos, width, height, border, body) = {
+ return (
+ type: "content",
+ pos: pos,
+ width: width,
+ height: height,
+ segments: border,
+ body: body,
+ tags: (),
+ )
+}
+
+/// Creates a path drawable in the shape of an ellipse.
+/// - x (float): The $x$ position of the ellipse.
+/// - y (float): The $y$ position of the ellipse.
+/// - z (float): The $z$ position of the ellipse.
+/// - rx (float): The radius of the ellipse in the $x$ axis.
+/// - ry (float): The radius of the ellipse in the $y$ axis.
+/// - fill (color,none): The color to fill the ellipse with.
+/// - stroke (stroke): The stroke of the ellipse's path.
+/// -> drawable
+#let ellipse(x, y, z, rx, ry, fill: none, stroke: none) = {
+ let m = 0.551784
+ let mx = m * rx
+ let my = m * ry
+ let left = x - rx
+ let right = x + rx
+ let top = y + ry
+ let bottom = y - ry
+
+ path(
+ (((x, top, z), true, (
+ ("c", (x - m * rx, top, z),
+ (left, y + m * ry, z),
+ (left, y, z)),
+ ("c", (left, y - m * ry, z),
+ (x - m * rx, bottom, z),
+ (x, bottom, z)),
+ ("c", (x + m * rx, bottom, z),
+ (right, y - m * ry, z),
+ (right, y, z)),
+ ("c", (right, y + m * ry, z),
+ (x + m * rx, top, z),
+ (x, top, z))
+ )),),
+ stroke: stroke,
+ fill: fill,
+ )
+}
+
+/// Creates a path drawable in the shape of an arc.
+/// - x (float): The $x$ position of the start of the arc.
+/// - y (float): The $y$ position of the start of the arc.
+/// - z (float): The $z$ position of the start of the arc.
+/// - start (angle): The angle along an ellipse to start drawing the arc from.
+/// - stop (angle): The angle along an ellipse to stop drawing the arc at.
+/// - rx (float): The radius of the arc in the $x$ axis.
+/// - ry (float): The radius of the arc in the $y$ axis.
+/// - mode (str): How to draw the arc: `"OPEN"` leaves the path open, `"CLOSED"` closes the arc by drawing a straight line between the end of the arc and its start, `"PIE"` also closes the arc by drawing a line from its end to its origin then to its start.
+/// - fill (color,none): The color to fill the arc with.
+/// - stroke (stroke): The stroke of the arc's path.
+/// -> drawable
+#let arc(x, y, z, start, stop, rx, ry, mode: "OPEN", fill: none, stroke: none) = {
+ let delta = calc.max(-360deg, calc.min(stop - start, 360deg))
+ let num-curves = calc.max(1, calc.min(calc.ceil(calc.abs(delta) / 90deg), 4))
+
+ // Move x/y to the center
+ x -= rx * calc.cos(start)
+ y -= ry * calc.sin(start)
+
+ // Calculation of control points is based on the method described here:
+ // https://pomax.github.io/bezierinfo/#circles_cubic
+ let segments = ()
+ let origin = (x, y, z)
+ for n in range(0, num-curves) {
+ let start = start + delta / num-curves * n
+ let stop = start + delta / num-curves
+
+ let d = delta / num-curves
+ let k = 4 / 3 * calc.tan(d / 4)
+
+ let sx = x + rx * calc.cos(start)
+ let sy = y + ry * calc.sin(start)
+ let ex = x + rx * calc.cos(stop)
+ let ey = y + ry * calc.sin(stop)
+
+ let s = (sx, sy, z)
+ let c1 = (
+ x + rx * (calc.cos(start) - k * calc.sin(start)),
+ y + ry * (calc.sin(start) + k * calc.cos(start)),
+ z,
+ )
+ let c2 = (
+ x + rx * (calc.cos(stop) + k * calc.sin(stop)),
+ y + ry * (calc.sin(stop) - k * calc.cos(stop)),
+ z,
+ )
+ let e = (ex, ey, z)
+
+ if n == 0 {
+ origin = s
+ }
+ segments.push(("c", c1, c2, e))
+ }
+
+ if mode == "PIE" and calc.abs(delta) < 360deg {
+ segments.push(("l", (x, y, z)))
+ }
+
+ return path(
+ ((origin, mode != "OPEN", segments),),
+ fill: fill,
+ stroke: stroke)
+}
diff --git a/render/packages/preview/cetz/0.5.2/src/hobby.typ b/render/packages/preview/cetz/0.5.2/src/hobby.typ
new file mode 100644
index 0000000..fccab46
--- /dev/null
+++ b/render/packages/preview/cetz/0.5.2/src/hobby.typ
@@ -0,0 +1,284 @@
+#import "/src/vector.typ"
+#import "/src/complex.typ"
+
+// Implementation by @Enivex
+//
+// Notation comes from https://tug.org/TUGboat/tb34-2/tb107jackowski.pdf
+//
+// points = (P_0, P_1, ... , P_n)
+//
+// ta = (tau_(a,0),tau_(a,1), ... , tau_(a,n-1))
+// ta(i) = tau_(a,i) is the outgoing tension at P_i on the curve from P_i to P_(i+1)
+//
+// tb = (tau_(b,0),tau(b,1), ..., tau_(b,n-1))
+// tb(i) = tau_(b,i) is the incoming tension at P_(i+1) on the curve from P_i to P_(i+1)
+//
+// omega = (omega_0,omega_n)
+// curl at the start and end of curve (size of mock curvature relative to nearest point)
+//
+// v(i) = P_(i+1) - P_i
+// vector pointing from point i to point i + 1 (direction of ith chord)
+//
+// d(i) = |v(i)|
+// length of the ith chord
+//
+// gamma(i) = signed angle from v(i - 1) to v(i) (change in angle at P_i)
+// Note: gamma(0) = gamma(n) = 0
+//
+// ca(i) = first control point on chord i
+// cb(i) = second control point on chord i
+//
+// alpha(i) = signed angle from v(i) to ca(i) - P(i)
+// beta(i) = signed angle from P(i + 1) - cb(i) to v(i)
+
+// Solve tridiagonal system
+//
+// - a,b,c,d have the same length, n + 1
+// - a(0) and c(n) are not used
+//
+// Solves Ax=d
+// where A=
+// [ b_0 c_0
+// a_1 b_1 c_1
+// ......
+// a_(n-1) b_(n-1) c_(n-1)
+// a_n b_n ]
+#let thomas(a, b, c, d) = {
+ let n = a.len() - 1
+
+ for i in range(1,n + 1) {
+ let w = a.at(i) / b.at(i - 1)
+ b.at(i) = b.at(i) - w*c.at(i - 1)
+ d.at(i) = d.at(i) - w*d.at(i - 1)
+ }
+
+ let x = (0,)*(n + 1)
+ x.last() = d.last() / b.last()
+ for i in range(n - 1, -1 , step: -1) {
+ x.at(i) = (d.at(i) - c.at(i)*x.at(i + 1)) / b.at(i)
+ }
+ return x
+}
+
+// Solve cyclic tridiagonal system
+//
+// - a,b,c,d have the same length, n+1
+//
+// Solves Ax=d
+// where A=
+// [ b_0 c_0 a_0
+// a_1 b_1 c_1
+// ......
+// a_(n-1) b_(n-1) c_(n-1)
+// c_n a_n b_n ]
+#let thomas-cyclic(a, b, c, d) = {
+ let n = a.len() - 1
+
+ let u = (a.first(),) + (0,)*(n - 1) + (c.last(),)
+ let v = (1,) + (0,)*(n - 1) + (1,)
+
+ let bp = array.zip(b,u).map(((s,t)) => s - t)
+ let y = thomas(a, bp, c, d)
+ let z = thomas(a, bp, c, u)
+
+ // Sherman-Morrison formula
+ return vector.sub(y, vector.scale(z, vector.dot(v,y) / (1 + vector.dot(v, z))))
+}
+
+/// Calculates a bezier spline for an open Hobby curve through a list of points. Returns an {{array}} of {{bezier}}s
+///
+/// - points (array): List of points
+/// - ta (auto,array): Outgoing tension per point
+/// - tb (auto,array): Incoming tension per point
+/// - rho (auto,function): The rho function of the form `(float, float) => float`
+/// - omega (auto,array): Tuple of the curl at the start and end of the curve `(start, end)` as floats
+///
+/// -> array
+#let hobby-to-cubic-open(points, ta: auto, tb: auto, rho: auto, omega: auto) = {
+ let n = points.len() - 1
+
+ if ta == auto {
+ ta = (1,)*n
+ } else {
+ assert.eq(type(ta), array, message: "ta must be an array")
+ assert.eq(ta.len(), n, message: "ta must have length n for n + 1 points")
+ assert(ta.all(x => x > 0), message: "ta must contain only positive numbers")
+ }
+ if tb == auto {
+ tb = (1,)*n
+ } else {
+ assert.eq(type(tb), array, message: "tb must be an array")
+ assert.eq(tb.len(), n, message: "tb must have length n for n + 1 points")
+ assert(tb.all(x => x > 0), message: "tb must contain only positive numbers")
+ }
+ if rho == auto {
+ rho = (a,b) => {
+ (2 + calc.sqrt(2)*(calc.sin(a) - calc.sin(b)/16)*(calc.sin(b)-calc.sin(a)/16)*(calc.cos(a)-calc.cos(b)))/(1 + calc.cos(a)*(calc.sqrt(5)-1)/2 + calc.cos(b)*(3-calc.sqrt(5))/2)
+ }
+ } else {
+ assert.eq(type(rho), function,
+ message: "rho must be a function")
+ }
+
+ let v = range(n).map(i => complex.sub(points.at(i + 1),points.at(i)))
+ let d = v.map(complex.norm)
+
+ let gamma = (0,) + range(n - 1).map(i => complex.ang(v.at(i),v.at(i + 1))) + (0,)
+
+ let ita = ta.map(x => 1/x)
+ let itasq = ita.map(x => x*x)
+
+ let itb = tb.map(x => 1/x)
+ let itbsq = itb.map(x => x*x)
+
+ let (omega0, omegan) = omega
+
+ let A = (0,) * (n + 1); let B = A; let C = A; let D = A; let E = A
+
+ C.at(0) = omega0 * ita.at(0) * itasq.at(0) / itbsq.at(0) + 3 - itb.at(0)
+ D.at(0) = omega0 * itasq.at(0) / itbsq.at(0) * (3 - ita.at(0)) + itb.at(0)
+ E.at(0) = - D.at(0) * gamma.at(1)
+
+ for i in range(1, n) {
+ A.at(i) = ita.at(i - 1) / (d.at(i - 1) * itbsq.at(i - 1))
+ B.at(i) = (3 - ita.at(i - 1))/(d.at(i - 1) * itbsq.at(i - 1))
+ C.at(i) = (3 - itb.at(i))/(d.at(i) * itasq.at(i))
+ D.at(i) = itb.at(i) / (d.at(i) * itasq.at(i))
+ E.at(i) = - B.at(i) * gamma.at(i) - D.at(i) * gamma.at(i + 1)
+ }
+
+ A.at(n) = omegan * itbsq.at(n - 1) / itasq.at(n - 1) * ( 3 - itb.at(n - 1)) + ita.at(n - 1)
+ B.at(n) = omegan * itb.at(n - 1) * itbsq.at(n - 1) / itasq.at(n - 1) + 3 - ita.at(n - 1)
+
+ let alpha = thomas(A,vector.add(B,C), D, E)
+ let beta = vector.scale(vector.add(alpha,gamma).slice(1), -1)
+
+ let ca = (0,)*n; let cb = ca
+ for i in range(n) {
+ let a = rho(alpha.at(i),beta.at(i)) * d.at(i) / 3
+ let b = rho(beta.at(i),alpha.at(i)) * d.at(i) / 3
+ ca.at(i) = complex.add(points.at(i), complex.scale(complex.unit(complex.rot(v.at(i),alpha.at(i))), a))
+ cb.at(i) = complex.sub(points.at(i + 1), complex.scale(complex.unit(complex.rot(v.at(i),-beta.at(i))), b))
+ }
+ return range(n).map(i => (points.at(i), points.at(i+1), ca.at(i), cb.at(i)))
+}
+
+/// Calculates a bezier spline for a closed Hobby curve through a list of points. Returns an {{array}} of {{bezier}}s.
+///
+/// - points (array): List of points
+/// - ta (auto,array): Outgoing tension per point
+/// - tb (auto,array): Incoming tension per point
+/// - rho (auto,array): The rho function of the form `(float, b) => float`
+///
+/// -> array
+#let hobby-to-cubic-closed(points, ta: auto, tb: auto, rho: auto) = {
+ if points.first() != points.last() {
+ points.push(points.first())
+ }
+
+ let n = points.len() - 1
+ points.push(points.at(1))
+
+ if ta == auto {
+ ta = (1,)*n
+ } else {
+ assert.eq(type(ta), array, message: "ta must be an array")
+ assert.eq(ta.len(), n, message: "ta must have length n for n + 1 points")
+ assert(ta.all(x => x > 0), message: "ta must contain only positive numbers")
+ }
+ if tb == auto {
+ tb = (1,)*n
+ } else {
+ assert.eq(type(tb), array, message: "tb must be an array")
+ assert.eq(tb.len(), n, message: "tb must have length n for n + 1 points")
+ assert(tb.all(x => x > 0), message: "tb must contain only positive numbers")
+ }
+ if rho == auto {
+ rho = (a,b) => {
+ (2 + calc.sqrt(2)*(calc.sin(a) - calc.sin(b)/16)*(calc.sin(b)-calc.sin(a)/16)*(calc.cos(a)-calc.cos(b)))/(1 + calc.cos(a)*(calc.sqrt(5)-1)/2 + calc.cos(b)*(3-calc.sqrt(5))/2)
+ }
+ } else {
+ assert.eq(type(rho), function,
+ message: "rho must be a function")
+ }
+
+ let v = range(n + 1).map(i => complex.sub(points.at(i + 1),points.at(i)))
+ let d = v.map(complex.norm)
+
+ let gamma = range(n).map(i => complex.ang(v.at(i),v.at(i + 1)))
+ gamma = (gamma.last(),..gamma)
+
+ let ita = ta.map(x => 1/x)
+ let itasq = ita.map(x => x*x)
+
+ let itb = tb.map(x => 1/x)
+ let itbsq = itb.map(x => x*x)
+
+ let A = (0,) * n; let B = A; let C = A; let D = A; let E = A
+
+ A.at(0) = ita.at(n - 1) / (d.at(n - 1) * itbsq.at(n - 1))
+ B.at(0) = (3 - ita.at(n - 1))/(d.at(n - 1) * itbsq.at(n - 1))
+ C.at(0) = (3 - itb.at(0))/(d.at(0) * itasq.at(0))
+ D.at(0) = itb.at(0) / (d.at(0) * itasq.at(0))
+ E.at(0) = - B.at(0) * gamma.at(0) - D.at(0) * gamma.at(1)
+
+ for i in range(1, n) {
+ A.at(i) = ita.at(i - 1) / (d.at(i - 1) * itbsq.at(i - 1))
+ B.at(i) = (3 - ita.at(i - 1))/(d.at(i - 1) * itbsq.at(i - 1))
+ C.at(i) = (3 - itb.at(i))/(d.at(i) * itasq.at(i))
+ D.at(i) = itb.at(i) / (d.at(i) * itasq.at(i))
+ E.at(i) = - B.at(i) * gamma.at(i) - D.at(i) * gamma.at(i + 1)
+ }
+
+ let alpha = thomas-cyclic(A,vector.add(B,C), D, E)
+ alpha.push(alpha.at(0))
+ let beta = vector.scale(vector.add(alpha,gamma), -1)
+ beta = (..beta.slice(1),beta.at(0))
+
+ let ca = (0,) * n; let cb = ca
+ for i in range(n) {
+ let a = rho(alpha.at(i),beta.at(i)) * d.at(i) / 3
+ let b = rho(beta.at(i),alpha.at(i)) * d.at(i) / 3
+ ca.at(i) = complex.add(points.at(i), complex.scale(complex.unit(complex.rot(v.at(i),alpha.at(i))), a))
+ cb.at(i) = complex.sub(points.at(i + 1), complex.scale(complex.unit(complex.rot(v.at(i),-beta.at(i))), b))
+ }
+
+ return range(n).map(i => (points.at(i), points.at(i+1), ca.at(i), cb.at(i)))
+}
+
+/// Calculates a bezier spline for a Hobby curve through a list of points. Returns an {{array}} of {{bezier}}s.
+///
+/// - points (array): List of points
+/// - ta (auto,array): Outgoing tension per point
+/// - tb (auto,array): Incoming tension per point
+/// - rho (auto,array): The rho function of the form `(float, float) => float`
+/// - omega (auto,array): Tuple of the curl at the start and end of the curve `(start, end)` as floats
+/// - close (bool): Close the curve
+///
+/// -> array
+#let hobby-to-cubic(points, ta: auto, tb: auto, rho: auto, omega: auto, close: false) = {
+ let omega = if omega == auto {
+ (1, 1)
+ } else if type(omega) == array {
+ omega
+ } else {
+ (omega, omega)
+ }
+ assert.eq(type(omega), array,
+ message: "Omega must be of type array")
+ assert.eq(omega.len(), 2,
+ message: "Omega must be of length 2")
+ assert(omega.all(x => x >= 0),
+ message: "Omega must contain positive values only")
+
+ if not close and points.len() == 2 {
+ let (a, b) = points
+ return ((a, b, a, b),)
+ }
+
+ return if close {
+ hobby-to-cubic-closed(points, ta: ta, tb: tb, rho: rho)
+ } else {
+ hobby-to-cubic-open(points, ta: ta, tb: tb, rho: rho, omega: omega)
+ }
+}
diff --git a/render/packages/preview/cetz/0.5.2/src/intersection.typ b/render/packages/preview/cetz/0.5.2/src/intersection.typ
new file mode 100644
index 0000000..1cb225d
--- /dev/null
+++ b/render/packages/preview/cetz/0.5.2/src/intersection.typ
@@ -0,0 +1,148 @@
+#import "vector.typ"
+#import "util.typ"
+
+/// Checks for a line-line intersection between the given points and returns
+/// its position, otherwise `none`.
+///
+/// - p1 (vector): Point 1
+/// - p2 (vector): Point 2
+/// - p3 (vector): Point 3
+/// - p4 (vector): Point 4
+/// - ray (bool): If true, handle both lines as infinite rays
+/// - eps (float): Epsilon
+/// -> vector The intersection point between both lines
+/// -> none None, if both lines are parallel
+#let line-line(p1, p2, p3, p4, ray: false, eps: 1e-6) = {
+ let (x1, y1, z1, ..) = if p1.len() >= 3 { p1 } else { (..p1, 0) }
+ let (x2, y2, z2, ..) = if p2.len() >= 3 { p2 } else { (..p2, 0) }
+ let (x3, y3, z3, ..) = if p3.len() >= 3 { p3 } else { (..p3, 0) }
+ let (x4, y4, z4, ..) = if p4.len() >= 3 { p4 } else { (..p4, 0) }
+
+ let p13 = (x1 - x3, y1 - y3, z1 - z3)
+ let p21 = (x2 - x1, y2 - y1, z2 - z1)
+ let p43 = (x4 - x3, y4 - y3, z4 - z3)
+
+ let d-21-21 = vector.dot(p21, p21)
+ let d-43-43 = vector.dot(p43, p43)
+ if d-21-21 <= calc.pow(eps, 2) or d-43-43 <= calc.pow(eps, 2) {
+ return none
+ }
+
+ let d-43-21 = vector.dot(p43, p21)
+ let d-13-43 = vector.dot(p13, p43)
+ let d-13-21 = vector.dot(p13, p21)
+ let d = d-21-21 * d-43-43 - d-43-21 * d-43-21
+ let parallel-eps = calc.pow(eps, 2) * d-21-21 * d-43-43
+ if calc.abs(d) <= parallel-eps {
+ return none
+ }
+
+ let m-a = (d-13-43 * d-43-21 - d-13-21 * d-43-43) / d
+ let m-b = (d-13-43 + m-a * d-43-21) / d-43-43
+
+ if not ray and (m-a < -eps or m-a > 1 + eps or m-b < -eps or m-b > 1 + eps) {
+ return none
+ }
+
+ let m-a = if ray { m-a } else { calc.clamp(m-a, 0, 1) }
+ let m-b = if ray { m-b } else { calc.clamp(m-b, 0, 1) }
+
+ let a = (x1 + m-a * (x2 - x1), y1 + m-a * (y2 - y1), z1 + m-a * (z2 - z1))
+ let b = (x3 + m-b * (x4 - x3), y3 + m-b * (y4 - y3), z3 + m-b * (z4 - z3))
+ let d-ab = vector.dist(a, b)
+ let distance-eps = eps * calc.max(1, calc.sqrt(d-21-21), calc.sqrt(d-43-43))
+
+ return if d-ab <= distance-eps {
+ a
+ } else {
+ none
+ }
+}
+
+/// Finds the intersections of a line and cubic bezier.
+///
+/// - s (vector): Bezier start point
+/// - e (vector): Bezier end point
+/// - c1 (vector): Bezier control point 1
+/// - c2 (vector): Bezier control point 2
+/// - la (vector): Line start point
+/// - lb (vector): Line end point
+/// - ray (bool): When `true`, intersections will be found for the whole line instead of inbetween the given points.
+/// -> array
+#let line-cubic(la, lb, s, e, c1, c2) = {
+ import "/src/bezier.typ": line-cubic-intersections as line-cubic
+ return line-cubic(la, lb, s, e, c1, c2)
+}
+
+/// Finds the intersections of a line and path in 2D. The path should be given as a {{drawable}} of type `path`.
+///
+/// - la (vector): Line start
+/// - lb (vector): Line end
+/// - path (drawable): The path.
+/// -> array
+#let line-path(la, lb, path) = {
+ let pts = ()
+
+ for ((start, closed, segments)) in path.at("segments", default: ()) {
+ let origin = start
+ for ((kind, ..args)) in segments {
+ if kind == "l" {
+ let pt = line-line(la, lb, origin, args.last())
+ if pt != none {
+ pts.push(pt)
+ }
+ } else if kind == "c" {
+ let (c1, c2, e) = args
+ pts += line-cubic(la, lb, origin, e, c1, c2)
+ }
+
+ origin = args.last()
+ }
+
+ if closed {
+ let pt = line-line(la, lb, origin, start)
+ if pt != none {
+ pts.push(pt)
+ }
+ }
+ }
+
+ return pts
+}
+
+/// Finds the intersections between two path {{drawable}}s in 2D.
+///
+/// - a (path): Path a
+/// - b (path): Path b
+/// - samples (int): Number of samples to use for bezier curves
+/// -> array
+#let path-path(a, b, samples: 8) = {
+ import "bezier.typ": cubic-point
+
+ let pts = ()
+
+ for ((start, closed, segments)) in a.at("segments", default: ()) {
+ let origin = start
+ for ((kind, ..args)) in segments {
+ if kind == "l" {
+ pts += line-path(origin, args.last(), b)
+ } else if kind == "c" {
+ let (c1, c2, e) = args
+ let line-strip = range(samples + 1).map(t => {
+ cubic-point(origin, e, c1, c2, t / samples)
+ })
+
+ for i in range(1, line-strip.len()) {
+ pts += line-path(line-strip.at(i - 1), line-strip.at(i), b)
+ }
+ }
+
+ origin = args.last()
+ }
+
+ if closed {
+ pts += line-path(origin, start, b)
+ }
+ }
+ return pts
+}
diff --git a/render/packages/preview/cetz/0.5.2/src/lib.typ b/render/packages/preview/cetz/0.5.2/src/lib.typ
new file mode 100644
index 0000000..aa00d81
--- /dev/null
+++ b/render/packages/preview/cetz/0.5.2/src/lib.typ
@@ -0,0 +1,27 @@
+#import "version.typ": version
+
+#import "canvas.typ": canvas
+#import "draw.typ"
+
+// Expose utilities
+#import "vector.typ"
+#import "matrix.typ"
+#import "styles.typ"
+#import "coordinate.typ"
+#import "intersection.typ"
+#import "drawable.typ"
+#import "process.typ"
+#import "util.typ"
+#import "path-util.typ"
+#import "mark.typ"
+#import "mark-shapes.typ"
+#import "sorting.typ"
+
+// Libraries
+#import "lib/palette.typ"
+#import "lib/angle.typ"
+#import "lib/tree.typ"
+#import "lib/decorations.typ"
+
+// expose name
+#let name = "cetz"
\ No newline at end of file
diff --git a/render/packages/preview/cetz/0.5.2/src/lib/angle.typ b/render/packages/preview/cetz/0.5.2/src/lib/angle.typ
new file mode 100644
index 0000000..161a380
--- /dev/null
+++ b/render/packages/preview/cetz/0.5.2/src/lib/angle.typ
@@ -0,0 +1,208 @@
+#import "/src/styles.typ"
+#import "/src/vector.typ"
+#import "/src/util.typ": resolve-number, resolve-radius, float-eq
+#import "/src/coordinate.typ"
+#import "/src/anchor.typ" as anchor_
+#import "/src/draw.typ"
+
+// Angle default-style
+#let default-style = (
+ fill: none,
+ stroke: auto,
+ radius: .5,
+ label-radius: 50%,
+ mark: auto,
+)
+
+/// Draw an angle counter-clock-wise between `a` and `b` through origin `origin`
+///
+/// ```example
+/// line((0, 0), (60deg, 2), name: "a")
+/// line((0, 0), (330deg, 2), name: "b")
+///
+/// // Draw an angle between the two lines
+/// cetz.angle.angle("a.start", "a.end", "b.end", label: $alpha$,
+/// mark: (end: ">"), radius: 1.5)
+/// cetz.angle.angle("a.start", "b.end", "a.end", label: $beta$,
+/// radius: 50%, direction: "ccw")
+/// ```
+///
+/// - origin (coordinate): Angle origin
+/// - a (coordinate): Coordinate of side `a`, containing an angle between `origin` and `b`.
+/// - b (coordinate): Coordinate of side `b`, containing an angle between `origin` and `a`.
+/// - direction (string): Direction of the angle. Accepts "ccw" (counter-clockwise), "cw" (clockwise), "near" (inner angle), "far" (outer angle), the first one being the default.
+/// - label (none,content,function): Draw a label at the angles "label" anchor. If label is a function, it gets the angle value passed as argument. The function must be of the format `angle => content`.
+/// - name (none,str): Element name, used for querying anchors.
+/// - ..style (style): Style key-value pairs.
+///
+/// == Styling
+/// *Root:* `angle` \
+///
+/// - radius (number) = 0.5: The radius of the angles arc. If of type `ratio`, it is relative to the smaller distance of either origin to a or origin to b.
+/// - label-radius (number, ratio) = 50%: The radius of the angles label origin. If of type `ratio`, it is relative to `radius`.
+///
+/// == Anchors
+/// / a: Point a
+/// / b: Point b
+/// / origin: Origin
+/// / label: Label center
+/// / start: Arc start
+/// / end: Arc end
+#let angle(
+ origin,
+ a,
+ b,
+ direction: "ccw",
+ label: none,
+ name: none,
+ ..style
+) = draw.group(name: name, ctx => {
+ let style = styles.resolve(ctx.style, merge: style.named(), base: default-style, root: "angle")
+ let radius = resolve-number(ctx, style.radius)
+ let label-radius = resolve-number(ctx, style.label-radius)
+
+ let (ctx, origin) = coordinate.resolve(ctx, origin)
+ let (ctx, a, b) = coordinate.resolve(ctx, a, b, update: false)
+
+ assert(float-eq(origin.at(2), a.at(2)) and float-eq(a.at(2), b.at(2)),
+ message: "Angle z coordinates of all three points must be equal")
+
+ assert(direction in ("cw", "ccw", "near", "far"),
+ message: "Invalid angle direction " + repr(direction))
+
+ let (start, delta) = {
+ let s = vector.angle2(origin, a)
+ if s < 0deg { s += 360deg }
+
+ let e = vector.angle2(origin, b)
+ if e < 0deg { e += 360deg }
+
+ if e < s {
+ e += 360deg
+ }
+
+ let d = e - s
+ if direction == "ccw" or (direction == "near" and d < 180deg) or (direction == "far" and d >= 180deg) {
+ (s, (e - s))
+ }
+ else {
+ (s, -(360deg - (e - s)))
+ }
+ }
+
+ let mid = start + delta / 2
+
+ // Radius can be relative to the min-distance between origin-a and origin-b
+ if type(radius) == ratio {
+ radius = radius * calc.min(vector.dist(origin, a), vector.dist(origin, b)) / 100%
+ }
+
+ // Label radius can be relative to radius
+ if type(label-radius) == ratio {
+ label-radius = label-radius * radius / 100%
+ }
+
+ let label-pt = vector.add(origin, (calc.cos(mid) * label-radius, calc.sin(mid) * label-radius, 0))
+ let start-pt = vector.add(origin, (calc.cos(start) * radius, calc.sin(start) * radius, 0))
+ let end-pt = vector.add(origin, (calc.cos(start + delta) * radius, calc.sin(start + delta) * radius, 0))
+ draw.anchor("origin", origin)
+ draw.anchor("label", label-pt)
+ draw.anchor("start", start-pt)
+ draw.anchor("end", end-pt)
+ draw.anchor("a", a)
+ draw.anchor("b", b)
+ draw.anchor("center", ("a", 50%, "b"))
+
+ if delta != 0deg {
+ if style.fill != none {
+ draw.arc(origin, start: start, delta: delta, anchor: "origin",
+ name: "arc", ..style, radius: radius, mode: "PIE", mark: none, stroke: none)
+ }
+ if style.stroke != none {
+ draw.arc(origin, start: start, delta: delta, anchor: "origin",
+ name: "arc", ..style, radius: radius, fill: none)
+ }
+ }
+
+ let label = if type(label) == function { label(calc.abs(delta)) } else { label }
+ if label != none {
+ draw.content(label-pt, label)
+ }
+})
+
+/// Draw a right angle between `a` and `b` through origin `origin`
+///
+/// ```example
+/// line((0,0), (1,2), name: "a")
+/// line((0,0), (2,-1), name: "b")
+///
+/// // Draw an angle between the two lines
+/// cetz.angle.right-angle(
+/// "a.start",
+/// "a.end",
+/// "b.end",
+/// radius: 1.5
+/// )
+/// ```
+///
+/// - origin (coordinate): Angle origin
+/// - a (coordinate): Coordinate of side `a`, containing an angle between `origin` and `b`.
+/// - b (coordinate): Coordinate of side `b`, containing an angle between `origin` and `a`.
+/// - label (none,content): Draw a label at the angles "label" anchor.
+/// - name (none,str): Element name, used for querying anchors.
+/// - ..style (style): Style key-value pairs.
+///
+/// == Styling
+/// Styling is the same as the `angle` function.
+///
+/// == Anchors
+/// Anchors are the same as the `angle` function
+///
+#let right-angle(
+ origin,
+ a,
+ b,
+ label: "•",
+ name: none,
+ ..style
+) = draw.group(name: name, ctx => {
+ let style = styles.resolve(ctx.style, merge: style.named(), base: default-style, root: "angle")
+ let (ctx, origin) = coordinate.resolve(ctx, origin)
+ let (ctx, a, b) = coordinate.resolve(ctx, a, b, update: false)
+ let vo = origin; let va = a; let vb = b
+
+ // Radius can be relative to the min-distance between origin-a and origin-b
+ if type(style.radius) == ratio {
+ style.radius = style.radius * calc.min(vector.dist(vo, va), vector.dist(vo, vb)) / 100%
+ }
+ let (r, _) = resolve-radius(style.radius).map(resolve-number.with(ctx))
+
+ let va = vector.add(vo, vector.scale(vector.norm(vector.sub(va, vo)), r))
+ let vb = vector.add(vo, vector.scale(vector.norm(vector.sub(vb, vo)), r))
+ let angle-b = vector.angle2(vo, vb)
+ let vm = vector.add(va, (calc.cos(angle-b) * r, calc.sin(angle-b) * r, 0))
+
+ // Label radius can be relative to the distance between origin and the
+ // angle corner
+ if type(style.label-radius) == ratio {
+ style.label-radius = style.label-radius * vector.dist(vm, vo) / 100%
+ }
+ let (ra, _) = resolve-radius(style.label-radius).map(resolve-number.with(ctx))
+
+ if style.fill != none {
+ draw.line(vo, va, vm, vb, close: true, stroke: none, fill: style.fill)
+ }
+ draw.line(va, vm, vb, ..style, fill: none)
+
+ let label-pt = vector.add(vo, vector.scale(vector.norm(vector.sub(vm, vo)), ra))
+ if label != none {
+ draw.content(label-pt, label)
+ }
+
+ draw.anchor("a", a)
+ draw.anchor("b", b)
+ draw.anchor("origin", origin)
+ draw.anchor("corner", vm)
+ draw.anchor("label", label-pt)
+ draw.anchor("center", ("a", 50%, "b"))
+})
diff --git a/render/packages/preview/cetz/0.5.2/src/lib/decorations.typ b/render/packages/preview/cetz/0.5.2/src/lib/decorations.typ
new file mode 100644
index 0000000..f91786c
--- /dev/null
+++ b/render/packages/preview/cetz/0.5.2/src/lib/decorations.typ
@@ -0,0 +1,2 @@
+#import "decorations/brace.typ": brace, brace-default-style, flat-brace, flat-brace-default-style
+#import "decorations/path.typ": zigzag, wave, coil, square
diff --git a/render/packages/preview/cetz/0.5.2/src/lib/decorations/brace.typ b/render/packages/preview/cetz/0.5.2/src/lib/decorations/brace.typ
new file mode 100644
index 0000000..fbe2bcd
--- /dev/null
+++ b/render/packages/preview/cetz/0.5.2/src/lib/decorations/brace.typ
@@ -0,0 +1,387 @@
+#import "/src/vector.typ"
+#import "/src/matrix.typ"
+#import "/src/util.typ"
+#import "/src/draw.typ"
+#import "/src/coordinate.typ"
+#import "/src/styles.typ"
+
+
+#let brace-default-style = (
+ amplitude: 0.25,
+
+ // Thickness relative to half the amplitude
+ thickness: 0.015cm,
+
+ // Outset of the inner side of the mid spike
+ pointiness: 80%,
+
+ // Draw a tapered brace
+ taper: true,
+
+ // Inset of the outer spike curves
+ outer-inset: 0.5cm,
+ outer-curvyness: 60%,
+
+ // Outset of the inner spike curves
+ inner-outset: 0.2cm,
+ inner-curvyness: 80%,
+
+ // Extra inset applied to both tips of the brace
+ outer-thickness: 0,
+
+ // Vertically flip
+ flip: false,
+
+ // Offset to apply to the "content" anchor
+ content-offset: .3cm,
+
+ stroke: none,
+ fill: black,
+)
+
+/// Draw a curly brace between two points.
+///
+/// ```example
+/// cetz.decorations.brace((0,1),(2,1))
+/// cetz.decorations.brace((0,0),(2,0), outer-inset: 0)
+/// ```
+///
+/// - start (coordinate): Start point
+/// - end (coordinate): End point
+/// - name (string, none): Element name used for querying anchors
+/// - ..style (style): Style key-value pairs
+///
+/// == Styling
+/// *Root:* `brace`
+/// - amplitude (number) = 0.25cm: Sets the height of the brace, from its baseline to its middle tip.
+/// - thickness (number,ratio) = 0.015cm: Thickness of tapered braces (if ratio, relative to half the amplitude).
+/// - pointiness (ratio) = 50%: Thickness of the mid-spice
+/// - taper (bool) = true: Draw a tapered brace
+/// - outer-inset (number,ratio): Inset of the outer curve points
+/// - outer-curvyness (ratio): Curvyness of the outer curves
+/// - inner-outset (number,ratio): Inset of the inner tip curve points
+/// - inner-curvyness (ratio): Curvyness of the inner tip curves
+/// - outer-thickness (number) = 0: Thickness of the outer tips
+/// - content-offset (number) = 0.3: Offset of the `"content"` anchor from the spike of the brace.
+/// - flip (bool) = false: Mirror the brace along the line between start and end.
+///
+/// Use the `fill` style for tapered braces and set `stroke` to none.
+///
+/// == Anchors
+/// / start: Where the brace starts, same as the `start` parameter.
+/// / end: Where the brace end, same as the `end` parameter.
+/// / spike: Point of the spike, halfway between `start` and `end` and shifted by `amplitude` towards the pointing direction.
+/// / content: Point to place content/text at, in front of the spike.
+/// / center: Center of the enclosing rectangle.
+#let brace(start, end, ..style, name: none) = {
+ import draw: line, bezier, merge-path, scope, scale, translate, anchor, group
+
+ let lerp(a, b, t) = {
+ t = if type(t) == ratio { t / 100% } else { t }
+ return (1 - t) * a + t * b
+ }
+
+ let draw-shape(x0, x1, x2, style, is-inner: false) = {
+ let x-dist = x1 - x0
+
+ let height = style.amplitude
+ let pointiness = style.pointiness
+ let thickness = style.thickness * (if is-inner { -1 } else { 1 })
+ if style.flip {
+ height *= -1
+ thickness *= -1
+ }
+
+ let mid = height / 2
+
+ let outer-inset = calc.min(style.outer-inset, x-dist / 2)
+ let outer-curve-slant = 100% - style.outer-curvyness
+
+ let inner-outset = calc.min(style.inner-outset, x-dist / 2)
+ let inner-curve-slant = 100% - style.inner-curvyness
+
+ let outer-thickness = if is-inner {
+ style.outer-thickness
+ } else {
+ 0
+ }
+
+ let a = (x0 + outer-thickness, 0)
+ let a-b = (lerp(x0, x0 + outer-inset, outer-curve-slant), mid + thickness)
+ let b = (x0 + outer-inset, mid + thickness)
+
+ let c = (x1 - inner-outset, mid + thickness)
+ let c-d = (lerp(x1, x1 - inner-outset, inner-curve-slant), mid + thickness)
+ let d = if is-inner {
+ (x1, lerp(mid + thickness, height, pointiness))
+ } else {
+ (x1, height)
+ }
+
+ let d-e = (lerp(x1, x1 + inner-outset, inner-curve-slant), mid + thickness)
+ let e = (x1 + inner-outset, mid + thickness)
+
+ let f = (x2 - outer-inset, mid + thickness)
+ let f-g = (lerp(x2, x2 - outer-inset, outer-curve-slant), mid + thickness)
+ let g = (x2 - outer-thickness, 0)
+
+ if not is-inner {
+ bezier(a, b, a-b, a-b)
+ line(b, c)
+ bezier(c, d, c-d, c-d)
+
+ bezier(d, e, d-e, d-e)
+ line(e, f)
+ bezier(f, g, f-g, f-g)
+ } else {
+ bezier(g, f, f-g, f-g)
+ line(f, e)
+ bezier(e, d, d-e, d-e)
+
+ bezier(d, c, c-d, c-d)
+ line(c, b)
+ bezier(b, a, a-b, a-b)
+ }
+ }
+
+ draw.group(name: name, ctx => {
+ let (_, x0, x1) = coordinate.resolve(ctx, start, end)
+
+ let style = styles.resolve(ctx.style, root: "brace", base: brace-default-style, merge: style.named())
+
+ // Resolve thickness
+ if type(style.thickness) == ratio {
+ style.thickness = style.thickness / 100% * style.amplitude / 2
+ }
+
+ // Resolve relative style keys
+ for key in ("inner-outset", "outer-inset") {
+ if type(style.at(key)) == ratio {
+ style.at(key) = style.at(key) / 50% * vector.dist(x0, x1)
+ }
+ }
+
+ // Resolve length style keys
+ for key in ("inner-outset", "outer-inset", "thickness", "amplitude", "content-offset") {
+ style.at(key) = util.resolve-number(ctx, style.at(key))
+ }
+
+ let width = vector.dist(x0, x1)
+ let angle = vector.angle2(x0, x1)
+
+ draw.set-origin(x0)
+ draw.rotate(angle)
+
+ merge-path({
+ draw-shape(0, width / 2, width, style)
+ if style.taper {
+ draw-shape(0, width / 2, width, style, is-inner: true)
+ }
+ }, close: style.taper, stroke: style.stroke, fill: style.fill)
+
+ // Account for flip when positioning anchors
+ let anchor-amplitude = style.amplitude * (if style.flip { -1 } else { 1 })
+ let anchor-offset = style.content-offset * (if style.flip { -1 } else { 1 })
+
+ anchor("start", (0, 0))
+ anchor("default", (width / 2, 0))
+ anchor("end", (width, 0))
+ anchor("spike", (width / 2, anchor-amplitude))
+ anchor("content", (width / 2, anchor-amplitude + anchor-offset))
+
+ draw.move-to(end)
+ })
+}
+
+
+#let flat-brace-default-style = (
+ stroke: auto,
+ fill: none,
+ amplitude: .3,
+ aspect: 50%,
+ curves: (1, .5, .6, .15),
+ outer-curves: auto,
+ content-offset: .3,
+ debug-text-size: 6pt,
+)
+
+/// Draw a flat curly brace between two points.
+///
+/// ```example
+/// cetz.decorations.flat-brace((0,1),(2,1))
+///
+/// cetz.decorations.flat-brace((0,0),(2,0),
+/// curves: .2,
+/// aspect: 25%)
+/// cetz.decorations.flat-brace((0,-1),(2,-1),
+/// outer-curves: 0,
+/// aspect: 75%)
+/// ```
+///
+/// This mimics the braces from TikZ's [`decorations.pathreplacing` library](https://github.com/pgf-tikz/pgf/blob/6e5fd71581ab04351a89553a259b57988bc28140/tex/generic/pgf/libraries/decorations/pgflibrarydecorations.pathreplacing.code.tex#L136-L185).
+/// In contrast to the `brace` function, these braces use straight line segments, resulting in better looks for long braces with a small amplitude.
+///
+/// - start (coordinate): Start point
+/// - end (coordinate): End point
+/// - flip (bool): Flip the brace around
+/// - name (str, none): Element name for querying anchors
+/// - debug (bool):
+/// - ..style (style): Style key-value pairs
+///
+/// == Styling
+///
+/// *Root:* `flat-brace`
+/// - amplitude (number) = 0.3: Determines how much the brace rises above the base line.
+/// - aspect (ratio) = 50% Determines the fraction of the total length where the spike will be placed.
+/// - curves (number, auto, array) = auto: Curviness factor of the brace, a factor of 0 means no curves.
+/// - outer-curves (number, auto, array) = auto: Curviness factor of the outer curves of the brace. A factor of 0 means no curves.
+///
+/// == Anchors
+/// / start: Where the brace starts, same as the `start` parameter.
+/// / end: Where the brace end, same as the `end` parameter.
+/// / spike: Point of the spike's top.
+/// / content: Point to place content/text at, in front of the spike.
+/// / center: Center of the enclosing rectangle.
+#let flat-brace(
+ start,
+ end,
+ flip: false,
+ debug: false,
+ name: none,
+ ..style,
+) = {
+ draw.group(name: name, ctx => {
+ // Get styles and validate their types and values
+ let style = styles.resolve(ctx.style, merge: style.named(),
+ root: "flat-brace", base: flat-brace-default-style)
+
+ let amplitude = style.amplitude
+ assert(
+ type(amplitude) in (int, float),
+ message: "amplitude must be a number, got " + repr(amplitude),
+ )
+
+ let aspect = style.aspect
+ assert(
+ (type(aspect) == ratio
+ and aspect >= 0% and aspect <= 100%)
+ or (type(aspect) in (int, float)
+ and aspect >= 0 and aspect <= 1),
+ message: "aspect must be a ratio between 0% and 100%, got " + repr(aspect),
+ )
+ if type(aspect) == ratio { aspect /= 100% }
+
+ let inner-curves = style.curves
+ assert(
+ type(inner-curves) in (int, float)
+ or type(inner-curves) == array
+ and inner-curves.all(v => type(v) in (int, float, type(auto))),
+ message: "curves must be a number, or an array of numbers or auto, got " + repr(inner-curves),
+ )
+ if type(inner-curves) in (int, float) { inner-curves = (inner-curves,) }
+ while inner-curves.len() < flat-brace-default-style.curves.len() {
+ inner-curves.push(auto)
+ }
+ inner-curves = inner-curves.enumerate().map(((idx, v)) => if v == auto {
+ flat-brace-default-style.curves.at(idx)
+ } else { v })
+
+ let outer-curves = style.outer-curves
+ assert(
+ type(outer-curves) in (int, float, type(auto))
+ or type(outer-curves) == array
+ and outer-curves.all(v => type(v) in (int, float, type(auto))),
+ message: "outer-curves must be auto, a number, or an array of numbers or auto, got " + repr(outer-curves),
+ )
+ if outer-curves == auto {
+ outer-curves = inner-curves
+ } else {
+ if type(outer-curves) in (int, float) { outer-curves = (outer-curves,) }
+ while outer-curves.len() < inner-curves.len() { outer-curves.push(auto) }
+ outer-curves = outer-curves.enumerate()
+ .map(((idx, v)) => if v == auto { inner-curves.at(idx) } else { v })
+ }
+
+ let content-offset = style.content-offset
+ assert(
+ type(content-offset) in (int, float),
+ message: "content-offset must be a number, got " + repr(content-offset),
+ )
+
+ // all the following code assumes the brace to start at (0, 0), growing to the right,
+ // pointing upwards, so we set the origin and rotate the entire group accordingly
+ let (_, start, end) = coordinate.resolve(ctx, start, end)
+ draw.set-origin(start)
+ draw.rotate(vector.angle2(start, end))
+
+ // we achieve flipping by inverting the amplitude
+ if flip {
+ amplitude *= -1
+ content-offset *= -1
+ }
+
+ let length = vector.dist(start, end)
+ let middle = aspect * length
+ let horizon = amplitude / 2
+
+ let normal-outer = calc.abs(amplitude * outer-curves.at(0))
+ let normal-inner = calc.abs(amplitude * inner-curves.at(0))
+ let length-left = middle
+ let length-right = length - middle
+
+ // width of left-outer, left-inner, right-inner, right-outer curve segments
+ let lo = if 2 * normal-outer > length-left { length-left / 2 } else { normal-outer }
+ let li = if 2 * normal-inner > length-left { length-left / 2 } else { normal-inner }
+ let ri = if 2 * normal-inner > length-right { length-right / 2 } else { normal-inner }
+ let ro = if 2 * normal-outer > length-right { length-right / 2 } else { normal-outer }
+
+ // 'a' and 'b' are start and end
+ let a = ( 0, 0)
+ let b = (length, 0)
+ // 'c' is the spike's top
+ let c = (middle, amplitude)
+ // 'de' is the left line, 'fg' is the right line
+ let d = ( lo, horizon)
+ let e = (middle - li, horizon)
+ let f = (middle + ri, horizon)
+ let g = (length - ro, horizon)
+ // 'h' is where to place content, above the spike
+ let h = (middle, amplitude + content-offset)
+
+ // list of all named points to show in debug mode
+ let points = (a: a, b: b, c: c, d: d, e: e, f: f, g: g, h: h)
+
+ // bezier control points: in 'dlc' 'd' stands for the point 'd' where the control point is used,
+ // 'l' stands for left of spike, 'c' stands for control point
+ let dlc = ( (1 - outer-curves.at(1)) * lo, horizon)
+ let elc = (middle - (1 - inner-curves.at(1)) * li, horizon)
+ let frc = (middle + (1 - inner-curves.at(1)) * ri, horizon)
+ let grc = (length - (1 - outer-curves.at(1)) * ro, horizon)
+ let alc = ( outer-curves.at(3) * lo, outer-curves.at(2) / 2 * amplitude)
+ let clc = (middle - inner-curves.at(3) * li, (1 - inner-curves.at(2) / 2) * amplitude)
+ let crc = (middle + inner-curves.at(3) * ri, (1 - inner-curves.at(2) / 2) * amplitude)
+ let brc = (length - outer-curves.at(3) * ro, outer-curves.at(2) / 2 * amplitude)
+
+ draw.merge-path({
+ draw.bezier(a, d, alc, dlc)
+ draw.bezier(e, c, elc, clc)
+ draw.bezier(c, f, crc, frc)
+ draw.bezier(g, b, grc, brc)
+ }, stroke: style.stroke, fill: style.fill)
+
+ // Define some named anchors
+ draw.anchor("spike", c)
+ draw.anchor("content", h)
+ draw.anchor("start", a)
+ draw.anchor("end", b)
+ draw.anchor("default", (d, 50%, g))
+
+ // Define anchors for all points
+ for (name, point) in points {
+ draw.anchor(name, point)
+ }
+ })
+
+ // Move to end point so the current position after this is the end position
+ draw.move-to(end)
+}
diff --git a/render/packages/preview/cetz/0.5.2/src/lib/decorations/path.typ b/render/packages/preview/cetz/0.5.2/src/lib/decorations/path.typ
new file mode 100644
index 0000000..55e6321
--- /dev/null
+++ b/render/packages/preview/cetz/0.5.2/src/lib/decorations/path.typ
@@ -0,0 +1,502 @@
+// Library for drawing springs
+#import "/src/draw.typ"
+#import "/src/styles.typ"
+#import "/src/coordinate.typ"
+#import "/src/vector.typ"
+#import "/src/process.typ"
+#import "/src/path-util.typ"
+#import "/src/util.typ"
+#import "/src/bezier.typ"
+
+#let default-style = (
+ /// Number of segments
+ segments: 10,
+ /// Length of a single segments
+ segment-length: none,
+
+ /// Amplitude of a segment in the direction of the segments normal.
+ /// The following types are supported:
+ /// - float
+ /// - function ratio -> float (the segment ratio is given as argument)
+ /// - array of floats (the rounded down segment number is used as index modulo the array length)
+ amplitude: 1,
+ /// Decoration start
+ start: 0%,
+ /// Decoration stop
+ stop: 100%,
+ /// Decoration alignment on the target path
+ align: "START",
+ /// Draw remaining space as line ("LINE") or none
+ rest: "LINE",
+
+ /// Up-vector for 3D lines
+ z-up: (0, 1, 0),
+ /// Up-vector for 2D lines
+ xy-up: (0, 0, -1),
+
+ stroke: auto,
+ fill: none,
+ mark: auto,
+)
+
+// Zig-Zag default style
+#let zigzag-default-style = (
+ ..default-style,
+ /// Midpoint factor
+ /// 0%: Sawtooth (up-down)
+ /// 50%: Triangle
+ /// 100%: Sawtooth (down-up)
+ factor: 50%,
+)
+
+// Wave default style
+#let wave-default-style = (
+ ..default-style,
+ /// Wave (catmull-rom) tension
+ tension: .5,
+)
+
+// Coil default style
+#let coil-default-style = (
+ ..default-style,
+ /// Coil "overshoot" factor
+ factor: 150%,
+)
+
+// Square default style
+#let square-default-style = (
+ ..default-style,
+ /// Midpoint factor
+ factor: 50%,
+)
+
+#let resolve-amplitude(ctx, amplitude, segment, num-segments) = {
+ segment = calc.max(0, calc.min(segment, num-segments))
+ let amp = if type(amplitude) == function {
+ (amplitude)(segment / num-segments * 100%)
+ } else if type(amplitude) == array {
+ amplitude.at(calc.rem(int(2*segment), amplitude.len()), default: 0)
+ } else {
+ amplitude
+ }
+ return util.resolve-number(ctx, amp)
+}
+
+#let resolve-style(ctx, segments, style) = {
+ assert(not (style.segments == none and style.segment-length == none),
+ message: "Only one of segments or segment-length must be set, while the other must be auto")
+ assert(style.segments != none or style.segment-length != none,
+ message: "Either segments or segment-length must be not equal to none")
+
+ // Calculate absolute start/stop distances
+ let len = path-util.length(segments)
+ if type(style.start) == ratio {
+ style.start = len * style.start / 100%
+ }
+ style.start = calc.max(0, calc.min(style.start, len))
+ if type(style.stop) == ratio {
+ style.stop = len * style.stop / 100%
+ }
+ style.stop = calc.max(0, calc.min(style.stop, len))
+
+ if style.segment-length != none {
+ // Calculate number of divisions
+ let n = (style.stop - style.start) / style.segment-length
+ style.segments = calc.floor(n)
+
+ // Divides the rest between start, stop or both
+ let r = (n - calc.floor(n)) * style.segment-length
+ if style.align == "MID" {
+ let m = (style.start + style.stop) / 2
+ style.start = m - n * style.segment-length / 2
+ style.stop = m + n * style.segment-length / 2
+ } else if style.align == "STOP" {
+ style.start = style.stop - n * style.segment-length
+ } else if style.align == "START" {
+ style.stop = style.start + n * style.segment-length
+ }
+ }
+
+ return style
+}
+
+#let get-segments(ctx, target) = {
+ if type(target) == array {
+ assert.eq(target.len(), 1,
+ message: "Expected a single element, got " + str(target.len()))
+ target = target.first()
+ }
+
+ let (ctx, drawables, ..) = process.element(ctx, target)
+ if drawables == none or drawables == () {
+ return ()
+ }
+
+ let first = drawables.first()
+ let closed = path-util.first-subpath-closed(first.segments)
+ return (segments: first.segments, close: closed)
+}
+
+// Add optional line elements from segments start to mid-path start
+// and mid-path end to sgements end
+#let finalize-path(ctx, segments, style, mid-path, close: false) = {
+ let add = style.rest == "LINE" and not close
+
+ let (ctx, drawables, ..) = process.many(ctx, mid-path)
+ let mid-first = drawables.first().segments.first()
+ let mid-last = drawables.last().segments.last()
+
+ if add {
+ let start = path-util.first-subpath-start(segments)
+ start = util.revert-transform(ctx.transform, start)
+
+ let mid-start = path-util.subpath-start(mid-first)
+ mid-start = util.revert-transform(ctx.transform, mid-start)
+ draw.line(start, mid-start, mark: none)
+ }
+ mid-path;
+ if add {
+ let end = path-util.last-subpath-end(segments)
+ end = util.revert-transform(ctx.transform, end)
+
+ let mid-end = path-util.subpath-end(mid-last)
+ mid-end = util.revert-transform(ctx.transform, mid-end)
+ draw.line(mid-end, end, mark: none)
+ }
+ // TODO: Add marks on path.
+}
+
+// Call callback `fn` for each decoration segment
+// on path `segments`.
+//
+// The callback gets called with the following arguments:
+// - i Segment index
+// - start Segment start point
+// - end Segment end point
+// - norm Normal vector (length 1)
+// Result values get returned as an array
+#let _path-effect(ctx, segments, fn, close: false, style) = {
+ let n = style.segments
+ assert(n > 0,
+ message: "Number of segments must be greater than 0")
+
+ let (start, stop) = (style.start, style.stop)
+ let inc = (stop - start) / n
+ let pts = ()
+ let len = path-util.length(segments)
+ for i in range(0, n) {
+ let p0 = path-util.point-at(segments, calc.max(start,
+ start + inc * i)).point
+ let p1 = path-util.point-at(segments, calc.min(stop,
+ start + inc * (i + 1))).point
+ if p0 == p1 { continue }
+
+ (p0, p1) = util.revert-transform(ctx.transform, p0, p1)
+
+ let dir = vector.norm(vector.sub(p1, p0))
+ let norm = vector.cross(dir, if p0.at(2) != p1.at(2) {
+ style.z-up
+ } else {
+ style.xy-up
+ })
+
+ pts += fn(i, p0, p1, norm)
+ }
+ return pts
+}
+
+/// Draw a zig-zag or saw-tooth wave along a path.
+///
+/// The number of tooths can be controlled via the `segments` or `segment-length` style key, and the width via `amplitude`.
+///
+/// ```example
+/// line((0,0), (2,1), stroke: gray)
+/// cetz.decorations.zigzag(line((0,0), (2,1)), amplitude: .25, start: 10%, stop: 90%)
+/// ```
+///
+/// - target (drawable): Target path
+/// - close (auto,bool): Close the path
+/// - name (none,string): Element name
+/// - ..style (style): Style
+///
+/// == Styling
+/// *Root*: `zigzag`
+/// - factor (ratio) = 100%: Triangle mid between its start and end. Setting this to 0% leads to a falling sawtooth shape, while 100% results in a raising sawtooth.
+#let zigzag(target, name: none, close: auto, ..style) = draw.get-ctx(ctx => {
+ let style = styles.resolve(ctx.style, merge: style.named(),
+ base: zigzag-default-style, root: "zigzag")
+
+ let (segments, close) = get-segments(ctx, target)
+ let style = resolve-style(ctx, segments, style)
+ let num-segments = style.segments
+
+ // Return points for a zigzag line
+ //
+ // m1 ▲
+ // / \ │ Up
+ // ..a....\....b.. '
+ // \ /
+ // m2
+ // |--|
+ // q-dir (quarter length between a and b)
+ //
+ // For the first/last segment, a/b get added. For all
+ // other segments we only have to add m1 and m2 to the
+ // list of points for the line-strip.
+ let fn(i, a, b, norm) = {
+ let ab = vector.sub(b, a)
+ let f = .25 - (50% - style.factor) / 50% * .25
+ let q-dir = vector.scale(ab, f)
+ let up = vector.scale(norm, resolve-amplitude(ctx, style.amplitude, i + .25, num-segments) / 2)
+ let down = vector.scale(norm, -resolve-amplitude(ctx, style.amplitude, i + .75, num-segments) / 2)
+
+ let m1 = vector.add(vector.add(a, q-dir), up)
+ let m2 = vector.add(vector.sub(b, q-dir), down)
+
+ return if not close and i == 0 {
+ (a, m1, m2) // First segment: add a
+ } else if not close and i == num-segments - 1 {
+ (m1, m2, b) // Last segment: add b
+ } else {
+ (m1, m2)
+ }
+ }
+
+ let pts = _path-effect(ctx, segments, fn, close: close, style)
+ return draw.merge-path(
+ finalize-path(ctx, segments, style,
+ draw.line(..pts, name: name, ..style, mark: none),
+ close: close),
+ close: close,
+ ..style)
+})
+
+/// Draw a stretched coil/loop spring along a path
+///
+/// The number of windings can be controlled via the `segments` or `segment-length` style key, and the width via `amplitude`.
+///
+/// ```example
+/// line((0,0), (2,1), stroke: gray)
+/// cetz.decorations.coil(line((0,0), (2,1)), amplitude: .25, start: 10%, stop: 90%)
+/// ```
+/// - target (drawable): Target path
+/// - close (auto,bool): Close the path
+/// - name (none,string): Element name
+/// - ..style (style): Style
+///
+/// == Styling
+/// *Root*: `coil`
+/// - factor (ratio) = 150%: Factor of how much the coil overextends its length to form a curl.
+#let coil(target, close: auto, name: none, ..style) = draw.get-ctx(ctx => {
+ let style = styles.resolve(ctx.style, merge: style.named(),
+ base: coil-default-style, root: "coil")
+
+ let (segments, close) = get-segments(ctx, target)
+ let style = resolve-style(ctx, segments, style)
+
+ let num-segments = calc.max(style.segments, 1)
+ let length = path-util.length(segments)
+ let phase-length = length / num-segments
+ let overshoot = calc.max(0, (style.factor - 100%) / 100% * phase-length)
+
+ // Offset both control points so the curve approximates
+ // an elliptic arc
+ let ellipsize-cubic(s, e, c1, c2) = {
+ let m = vector.scale(vector.add(c1, c2), .5)
+ let d = vector.sub(e, s)
+
+ c1 = vector.sub(m, vector.scale(d, .5))
+ c2 = vector.add(m, vector.scale(d, .5))
+
+ return (s, e, c1, c2)
+ }
+
+ // Return a list of drawables to form a coil-like loop
+ //
+ // ____ ┐
+ // / \ │ Upper curve
+ // | | ┘
+ // ..a...b..|.. ┐ Lower curve
+ // \_/ ┘
+ //
+ // └──┘
+ // Overshoot
+ //
+ let fn(i, a, b, norm) = {
+ let ab = vector.sub(b, a)
+ let amplitude = resolve-amplitude(ctx, style.amplitude, i, num-segments)
+ let up = vector.scale(norm, amplitude / 2)
+ let dist = vector.dist(a, b)
+
+ let d = vector.norm(ab)
+ let overshoot-at(i) = if num-segments <= 1 {
+ 0
+ } else if close {
+ overshoot / 2
+ } else {
+ i / (num-segments - 1) * overshoot
+ }
+
+ let next-a = vector.sub(b, vector.scale(d, overshoot-at(i + 1)))
+ let a = vector.sub(a, vector.scale(d, overshoot-at(i)))
+ let b = vector.add(b, vector.scale(d, overshoot-at(num-segments - i)))
+ let m = vector.scale(vector.add(a, b), .5)
+ let m-up = vector.add(m, up)
+ let m-down = vector.sub(vector.scale(vector.add(next-a, b), .5), up)
+
+ let upper = bezier.cubic-through-3points(a, m-up, b)
+ upper = ellipsize-cubic(..upper)
+
+ let lower = bezier.cubic-through-3points(b, m-down, next-a)
+ lower = ellipsize-cubic(..lower)
+
+ if i < num-segments - 1 or close {
+ return (
+ draw.bezier(..upper, mark: none),
+ draw.bezier(..lower, mark: none),
+ )
+ } else {
+ return (draw.bezier(..upper, mark: none),)
+ }
+ }
+
+ return draw.merge-path(
+ finalize-path(ctx, segments, style,
+ _path-effect(ctx, segments, fn, close: close, style).flatten(),
+ close: close),
+ ..style,
+ name: name,
+ close: close)
+})
+
+/// Draw a wave along a path using a catmull-rom curve
+///
+/// The number of phases can be controlled via the `segments` or `segment-length` style key, and the width via `amplitude`.
+///
+/// ```example
+/// line((0,0), (2,1), stroke: gray)
+/// cetz.decorations.wave(line((0,0), (2,1)), amplitude: .25, start: 10%, stop: 90%)
+/// ```
+///
+/// - target (drawable): Target path
+/// - close (auto,bool): Close the path
+/// - name (none,string): Element name
+/// - ..style (style): Style
+///
+/// == Styling
+/// *Root*: `wave`
+///
+/// - tension (float) = 0.5 Catmull-Rom curve tension, see [Catmull](/api/draw-functions/shapes/catmull)
+#let wave(target, close: auto, name: none, ..style) = draw.get-ctx(ctx => {
+ let style = styles.resolve(ctx.style, merge: style.named(),
+ base: wave-default-style, root: "wave")
+
+ let (segments, close) = get-segments(ctx, target)
+ let style = resolve-style(ctx, segments, style)
+ let num-segments = style.segments
+
+ // Return a list of points for the catmull-rom curve
+ //
+ // ╭ ma ╮ ▲
+ // │ │ │ Up
+ // ..a....m....b.. '
+ // │ │
+ // ╰ mb ╯
+ //
+ let fn(i, a, b, norm) = {
+ let ab = vector.sub(b, a)
+ let up = vector.scale(norm, +resolve-amplitude(ctx, style.amplitude, i + .25, num-segments) / 2)
+ let down = vector.scale(norm, -resolve-amplitude(ctx, style.amplitude, i + .75, num-segments) / 2)
+
+ let ma = vector.add(vector.add(a, vector.scale(ab, .25)), up)
+ let m = vector.add(a, vector.scale(ab, .50))
+ let mb = vector.add(vector.sub(b, vector.scale(ab, .25)), down)
+
+ if not close {
+ if num-segments == 1 {
+ return (a, ma, mb, b)
+ } else if i == 0 {
+ return (a, ma, mb)
+ } else if i == num-segments - 1 {
+ return (ma, mb, b,)
+ }
+ }
+
+ return (ma, mb)
+ }
+
+ return draw.merge-path(
+ finalize-path(ctx, segments, style, draw.catmull(
+ .._path-effect(ctx, segments, fn, close: close, style),
+ close: close), close: close) ,
+ name: name,
+ close: close,
+ ..style)
+})
+
+/// Draw a square-wave along a path using a line-strip
+///
+/// The number of phases can be controlled via the `segments` or `segment-length` style key, and the width via `amplitude`.
+///
+/// ```example
+/// line((0,0), (2,1), stroke: gray)
+/// cetz.decorations.square(line((0,0), (2,1)), amplitude: .25, start: 10%, stop: 90%)
+/// ```
+///
+/// - target (drawable): Target path
+/// - close (auto,bool): Close the path
+/// - name (none,string): Element name
+/// - ..style (style): Style
+///
+/// == Styling
+/// *Root*: `squre`
+///
+/// - factor (ratio) = 50% Square-Wave midpoint
+#let square(target, close: auto, name: none, ..style) = draw.get-ctx(ctx => {
+ let style = styles.resolve(ctx.style, merge: style.named(),
+ base: square-default-style, root: "square")
+
+ let (segments, close) = get-segments(ctx, target)
+ let style = resolve-style(ctx, segments, style)
+ let num-segments = style.segments
+ let factor = calc.max(0, calc.min(style.factor / 100%, 1))
+
+ // Return a list of points for the line-strip
+ //
+ // +----+ ▲
+ // | | │ Up
+ // ..a....m....b.. '
+ // | |
+ // +----+
+ //
+ let fn(i, a, b, norm) = {
+ let ab = vector.sub(b, a)
+ let up = vector.scale(norm, +resolve-amplitude(ctx, style.amplitude, i + .25, num-segments) / 2)
+ let down = vector.scale(norm, -resolve-amplitude(ctx, style.amplitude, i + .75, num-segments) / 2)
+ let m = vector.add(a, vector.scale(ab, factor))
+
+ if not close {
+ if i == 0 {
+ return (a, vector.add(a, up),
+ vector.add(m, up), vector.add(m, down),
+ vector.add(b, down))
+ } else if i == num-segments - 1 {
+ return (vector.add(a, up),
+ vector.add(m, up), vector.add(m, down),
+ vector.add(b, down), b)
+ }
+ }
+
+ return (vector.add(a, up),
+ vector.add(m, up), vector.add(m, down),
+ vector.add(b, down))
+ }
+
+ return draw.merge-path(
+ finalize-path(ctx, segments, style, draw.line(
+ .._path-effect(ctx, segments, fn, close: close, style),
+ close: close), close: close) ,
+ name: name,
+ close: close,
+ ..style)
+})
diff --git a/render/packages/preview/cetz/0.5.2/src/lib/palette.typ b/render/packages/preview/cetz/0.5.2/src/lib/palette.typ
new file mode 100644
index 0000000..2eb5cd9
--- /dev/null
+++ b/render/packages/preview/cetz/0.5.2/src/lib/palette.typ
@@ -0,0 +1,125 @@
+#let base-style = (stroke: (paint: black), fill: none)
+
+/// Create a new palette based on a base style
+///
+/// ```example
+/// let p = cetz.palette.new(colors: (red, blue, green))
+/// for i in range(0, p("len")) {
+/// set-style(..p(i))
+/// circle((0,0), radius: .5)
+/// set-origin((1.1, 0))
+/// }
+/// ```
+///
+/// The functions returned by this function have the following named arguments:
+/// - fill (bool) = true: If true, the returned fill color is one of the colors from the `colors` list, otherwise the base styles fill is used.
+/// - stroke (bool) = false: If true, the returned stroke color is one of the colors from the `colors` list, otherwise the base styles stroke color is used.
+///
+/// You can use a palette for stroking via: `red.with(stroke: true)`.
+///
+/// - base (style): Style dictionary to use as base style for the styles generated per color
+/// - colors (none, array): List of colors the returned palette should return styles with.
+/// - dash (none, array): List of stroke dash patterns the returned palette should return styles with.
+/// -> function
+#let new(base: base-style, colors: (), dash: ()) = {
+ if not "stroke" in base { base.stroke = (paint: black, thickness: 1pt, dash: "solid") }
+ if not "fill" in base { base.fill = none }
+
+ let color-n = colors.len()
+ let pattern-n = dash.len()
+ return (index, fill: true, stroke: false) => {
+ if index == "len" { return calc.max(color-n, pattern-n, 1) }
+
+ let style = base
+ if pattern-n > 0 {
+ style.stroke.dash = dash.at(calc.rem(index, pattern-n))
+ }
+ if color-n > 0 {
+ if stroke {
+ style.stroke.paint = colors.at(calc.rem(index, color-n))
+ }
+ if fill {
+ style.fill = colors.at(calc.rem(index, color-n))
+ }
+ }
+ return style
+ }
+}
+
+// Predefined color themes
+#let tango-colors = (
+ "edd400", "f57900", "c17d11",
+ "73d216", "3465a4", "75507b",
+ "cc0000", "d3d7cf", "555753").map(rgb)
+#let tango-light-colors = (
+ "fce94f", "fcaf3e", "e9b96e",
+ "8ae234", "729fcf", "ad7fa8",
+ "ef2929", "eeeeec", "888a85").map(rgb)
+#let tango-dark-colors = (
+ "c4a000", "ce5c00", "8f5902",
+ "4e9a06", "204a87", "5c3566",
+ "a40000", "babdb6", "2e3436").map(rgb)
+#let rainbow-colors = (
+ "#9400D4", "#4B0082", "#0000FF",
+ "#00FF00", "#FFFF00", "#FF7F00",
+ "#FF0000").map(rgb)
+
+#let red-colors = (
+ "#FFCCCC", "#FF9999", "#FF6666",
+ "#FF3333", "#CC0000").map(rgb)
+#let orange-colors = (
+ "#FFE5CC", "#FFCC99", "#FFB266",
+ "#FF9933", "#FF8000").map(rgb)
+#let light-green-colors = (
+ "#E5FFCC", "#CCFF99", "#B2FF66",
+ "#99FF33", "#72E300", "#66CC00",
+ "#55A800", "#478F00", "#3A7300",
+ "#326300").map(rgb)
+#let dark-green-colors = (
+ "#80E874", "#5DD45D", "#3CC23C",
+ "#009900", "#006E00").map(rgb)
+#let turquoise-colors = (
+ "#C0FFD3", "#99FFCC", "#66FFB2",
+ "#33FF99", "#4BD691").map(rgb)
+#let cyan-colors = (
+ "#CCFFFF", "#99FFFF", "#66FFFF",
+ "#00F3F3", "#00DADA").map(rgb)
+#let blue-colors = (
+ "#BABAFF", "#9999FF", "#6666FF",
+ "#3333FF", "#0000CC").map(rgb)
+#let indigo-colors = (
+ "#BABAFF", "#9999FF", "#6666FF",
+ "#3333FF", "#0000CC").map(rgb)
+#let purple-colors = (
+ "#E0C2FF", "#CC99FF", "#B266FF",
+ "#9933FF", "#7F00FF").map(rgb)
+#let magenta-colors = (
+ "#FFD4FF", "#FF99FF", "#FF66FF",
+ "#F331F3", "#DA00DA").map(rgb)
+#let pink-colors = (
+ "#FFCCE5", "#FF99CC", "#FF66B2",
+ "#FF3399", "#F20C7F", "#DB006B",
+ "#C30061", "#99004C", "#800040",
+ "#660033").map(rgb)
+
+
+// Predefined palettes
+#let gray = new(colors: range(90, 40, step: -12).map(v => luma(v * 1%)))
+
+#let red = new(colors: red-colors)
+#let orange = new(colors: orange-colors)
+#let light-green = new(colors: light-green-colors)
+#let dark-green = new(colors: dark-green-colors)
+#let turquoise = new(colors: turquoise-colors)
+#let cyan = new(colors: cyan-colors)
+#let blue = new(colors: blue-colors)
+#let indigo = new(colors: indigo-colors)
+#let purple = new(colors: purple-colors)
+#let magenta = new(colors: magenta-colors)
+#let pink = new(colors: pink-colors)
+
+#let rainbow = new(colors: rainbow-colors)
+
+#let tango = new(colors: tango-colors)
+#let tango-light = new(colors: tango-light-colors)
+#let tango-dark = new(colors: tango-dark-colors)
diff --git a/render/packages/preview/cetz/0.5.2/src/lib/tree.typ b/render/packages/preview/cetz/0.5.2/src/lib/tree.typ
new file mode 100644
index 0000000..0aa9905
--- /dev/null
+++ b/render/packages/preview/cetz/0.5.2/src/lib/tree.typ
@@ -0,0 +1,246 @@
+// CeTZ Library for Layouting Tree-Nodes
+#import "/src/util.typ"
+#import "/src/draw.typ"
+#import "/src/coordinate.typ"
+#import "/src/vector.typ"
+#import "/src/matrix.typ"
+#import "/src/process.typ"
+#import "/src/anchor.typ" as anchor_
+#import "/src/aabb.typ"
+#import "/src/drawable.typ"
+#import "/src/matrix.typ"
+
+#let cetz-core = plugin("../../cetz-core/cetz_core.wasm")
+
+
+/// Default edge draw callback
+///
+/// - parent (node): Parent tree node. The field `group-name` (str) provides the elements name.
+/// - child (node): Child tree node. The field `group-name` (str) provides the elements name.
+#let default-draw-edge(parent, child) = {
+ draw.line(parent.group-name, child.group-name)
+}
+
+/// Default node draw callback
+///
+/// - node (node): The node to draw
+#let default-draw-node(node) = {
+ let text = if type(node) in (content, str, int, float) {
+ [#node]
+ } else if type(node) == dictionary {
+ node.content
+ }
+
+ draw.content((0,0), text)
+}
+
+
+#let layout-node(node, grow, spread) = {
+ let just-heights-and-weights(node) = {
+ (
+ height: float(node.height),
+ width: float(node.width),
+ children: node.children.map(x => just-heights-and-weights(x)),
+ )
+ }
+ let encoded = cbor.encode((just-heights-and-weights(node), float(grow), float(spread)))
+ let positions = cbor(cetz-core.layout_tree_func(encoded))
+
+ let weave-together(node, positions) = {
+ node.x = positions.x
+ node.y = positions.y
+
+ node.children = node.children.zip(positions.children).map(x => weave-together(x.first(), x.last()))
+ return node
+ }
+
+ return weave-together(node, positions)
+}
+
+/// Lays out and renders tree nodes.
+///
+/// For each node, the `tree` function creates an anchor of the format `"[<child-index>-]<child-index>"` (the root is `"0"`, its first child `"0-0"`, second `"0-1"` and so on) that can be used to query a nodes position on the canvas.
+///
+/// ```example
+/// import cetz.tree
+/// set-style(content: (padding: .1))
+/// tree.tree(([Root], ([A], [A.A], [A.B]), ([B], [B.A])))
+/// ```
+///
+/// The `node` object passed to callbacks contains the following keys:
+/// - `name` (str): Name of the node's anchor
+/// - `group-name` (str): Name of the node's group element
+/// - `depth` (int): Depth of the node
+/// - `n` (int): Sibling index of the node
+/// - `content` (any): Content of the node
+///
+/// - root (array): A nested array of content that describes the structure the tree should take. Example: `([root], [child 1], ([child 2], [grandchild 1]))`
+/// - draw-node (auto,function): The function to call to draw a node. The function will be passed the node to draw (a dictionary with a `content` key) and is expected to return elements (`(node) => elements`). The node must be drawn at the `(0,0)` coordinate. If `auto` is given, just the node's value will be drawn as content.
+/// - draw-edge (none,auto,function): The function to call draw an edge between two nodes. The function will be passed the name of the starting node, the name of the ending node, the start node, the end node, and is expected to return elements (`(parent-node, child-node) => elements`). If `auto` is given, a straight line will be drawn between nodes.
+/// - direction (str): A string describing the direction the tree should grow in ("up", "down", "left", "right")
+/// - grow (float): Depth grow factor
+/// - spread (float): Sibling spread factor
+/// - name (none,str): The tree element's name
+/// - node-layer (int): Layer to draw nodes on
+/// - edge-layer (int): Layer to draw edges on
+/// - anchor (none, string): Name of the anchor to align the tree to. Use the root node anchor (`"0"`) to align the tree to the root nodes position.
+/// - group-name-prefix (string): Prefix of node group names
+#let tree(
+ root,
+ draw-node: auto,
+ draw-edge: auto,
+ direction: "down",
+ grow: 1,
+ spread: 1,
+ name: none,
+ node-layer: 1,
+ edge-layer: 0,
+ measure-content: true,
+ anchor: none,
+ group-name-prefix: "g",
+) = {
+ assert(grow >= 0)
+ assert(spread >= 0)
+
+ direction = (
+ up: "north",
+ down: "south",
+ right: "east",
+ left: "west",
+ ).at(direction, default: "south")
+
+ if draw-edge == auto {
+ draw-edge = default-draw-edge
+ } else if draw-edge == none {
+ draw-edge = (..) => ()
+ }
+
+ if draw-node == auto {
+ draw-node = default-draw-node
+ }
+ assert(draw-node != none, message: "Node draw callback must be set!")
+
+ draw.get-ctx(ctx => {
+ let build-node(tree, depth: 0, sibling: 0) = {
+ let children = ()
+ let content = none
+ if type(tree) == array {
+ children = tree.slice(1).enumerate().map(((n, c)) => build-node(c, depth: depth + 1, sibling: n))
+ content = tree.at(0)
+ } else {
+ content = tree
+ }
+
+ let node = (
+ height: 0.0,
+ width: 0.0,
+ n: sibling,
+ depth: depth,
+ children: children,
+ content: content,
+ )
+
+ // Measure the node
+ if measure-content {
+ let (ctx: _, drawables: _, bounds) = process.many(ctx, {
+ draw.set-origin((0, 0))
+ (draw-node)(node)
+ })
+
+ if bounds != none {
+ (node.width, node.height, ..) = aabb.size(bounds)
+ }
+ }
+
+ return node
+ }
+
+
+ let node-position(node) = {
+ if direction == "south" {
+ return (node.x, -node.y)
+ } else if direction == "north" {
+ return (node.x, node.y)
+ } else if direction == "west" {
+ return (-node.y, node.x)
+ } else if direction == "east" {
+ return (node.y, node.x)
+ } else {
+ panic(message: "Invalid tree direction.")
+ }
+ }
+
+ let anchors(node, parent-path) = {
+ if parent-path != none {
+ parent-path += "-"
+ } else {
+ parent-path = ""
+ }
+
+ let d = (:)
+ d.insert(parent-path + str(node.n), node-position(node))
+ for child in node.children {
+ d += anchors(child, parent-path + str(node.n))
+ }
+ return d
+ }
+
+ let build-element(node, parent-name) = {
+ let name = if parent-name != none {
+ parent-name + "-" + str(node.n)
+ } else {
+ "0"
+ }
+
+ // Render element
+ node.name = name
+ node.group-name = group-name-prefix + name
+ node.element = {
+ draw.anchor(node.name, node-position(node))
+ draw.group(name: node.group-name, ctx => {
+ let (x, y) = node-position(node)
+ draw.translate((x, y, 0))
+ draw.anchor("default", (0, 0))
+ draw-node(node)
+ },
+ )
+ }
+
+ // Render children
+ node.children = node.children.map(c => build-element(c, name))
+
+ // Render edges
+ node.edges = if node.children != () {
+ draw.group({
+ for child in node.children {
+ draw-edge(node, child)
+ }
+ })
+ } else { () }
+
+ return node
+ }
+
+ let root = build-node(root)
+ let nodes = layout-node(root, grow, spread)
+ let node = build-element(nodes, none)
+
+ // Render node recursive
+ let render(node) = {
+ if node.element != none {
+ draw.on-layer(node-layer, node.element)
+ if "children" in node {
+ for child in node.children {
+ render(child)
+ }
+ }
+ draw.on-layer(edge-layer, node.edges)
+ }
+ }
+
+ draw.group(name: name, anchor: anchor, {
+ draw.anchor("default", (0,0))
+ render(node)
+ })
+ })
+}
diff --git a/render/packages/preview/cetz/0.5.2/src/mark-shapes.typ b/render/packages/preview/cetz/0.5.2/src/mark-shapes.typ
new file mode 100644
index 0000000..b9c29ad
--- /dev/null
+++ b/render/packages/preview/cetz/0.5.2/src/mark-shapes.typ
@@ -0,0 +1,412 @@
+#import "drawable.typ"
+#import "path-util.typ"
+#import "vector.typ"
+
+// Custom line function without all the special logic
+// we do not need.
+#let fast-line(..pts, stroke: none, fill: none, fill-rule: "non-zero", close: false) = {
+ let pts = pts.pos()
+ (ctx => {
+ let transform = ctx.transform
+ let drawables = drawable.line-strip(pts,
+ stroke: stroke, fill: fill, close: close,
+ fill-rule: fill-rule)
+
+ return (
+ ctx: ctx,
+ drawables: drawable.apply-transform(transform, drawables),
+ )
+ },)
+}
+
+// Tiny bezier element.
+#let fast-bezier(..pts, stroke: none, fill: none, fill-rule: "non-zero") = {
+ import "bezier.typ" as bezier_
+
+ let pts = pts.pos()
+ if pts.len() == 3 {
+ pts = bezier_.quadratic-to-cubic(..pts)
+ }
+
+ let (p1, p2, p3, p4) = pts
+ (ctx => {
+ let transform = ctx.transform
+ let drawables = drawable.path(((p1, false, (("c", p3, p4, p2),)),),
+ stroke: stroke, fill: fill, fill-rule: fill-rule)
+
+ return (
+ ctx: ctx,
+ drawables: drawable.apply-transform(transform, drawables),
+ )
+ },)
+}
+
+// Calculate triangular tip offset, depending on the strokes
+// join type.
+//
+// The angle is calculated for an isosceles triangle of base style.width
+// and height style.length
+#let _calculate-tip-offset(style) = {
+ if style.stroke.join == "round" {
+ return style.canvas-thickness / 2
+ }
+
+ if style.length == 0 {
+ return 0
+ }
+
+ let angle = calc.atan(style.width / (2 * style.length) / if style.harpoon { 2 } else { 1 } ) * 2
+ // If the miter length divided by the stroke width exceeds
+ // the stroke miter limit then the miter join is converted to a bevel.
+ // See: https://svgwg.org/svg2-draft/painting.html#LineJoin
+ if style.stroke.join == "miter" {
+ let angle = calc.abs(angle)
+ if angle > 0deg {
+ let miter-limit = 1 / calc.sin(angle / 2)
+ if miter-limit <= style.stroke.miter-limit {
+ return miter-limit * (style.canvas-thickness / 2)
+ }
+ }
+ }
+
+ // style.stroke.join must be "bevel"
+ return calc.sin(angle/2) * (style.canvas-thickness / 2)
+}
+
+#let create-tip-and-base-anchor(style, tip, base, center: none, respect-stroke-thickness: false) = {
+ if base == auto or base == tip {
+ base = vector.add(tip, (1e-6, 0, 0))
+ }
+ let dir = vector.norm(vector.sub(tip, base))
+
+ let thickness = if respect-stroke-thickness {
+ let dist = vector.dist(tip, base)
+
+ calc.min(style.canvas-thickness, dist / 2) / 2
+ } else {
+ 0
+ }
+
+ import "/src/draw.typ": anchor
+ anchor("tip", vector.add(tip, vector.scale(dir, thickness)))
+ anchor("base", vector.sub(base, vector.scale(dir, thickness)))
+}
+
+#let create-triangle-tip-and-base-anchor(style, tip, base, center: none) = {
+ if base == auto or base == tip {
+ base = vector.add(tip, (1e-6, 0, 0))
+ }
+ let dir = vector.norm(vector.sub(tip, base))
+ let dist = vector.dist(tip, base)
+ let thickness = calc.min(style.at("canvas-thickness", default: 0), dist) / 2
+
+ import "/src/draw.typ": anchor
+ if style.reverse {
+ // Since tip and base are now "swapped", we add the stroke thickness to the triangle
+ // base. To get smooth looking connections between the triangle tip and a connecting line,
+ // we do not add the tip-offset.
+ anchor("tip", tip)
+ anchor("base", vector.sub(base, vector.scale(dir, thickness)))
+ } else {
+ anchor("tip", vector.add(tip, vector.scale(dir, _calculate-tip-offset(style))))
+ anchor("base", base)
+ }
+}
+
+#let create-diamond-tip-and-base-anchor(style, tip, base, center: none, ratio: 50%) = {
+ if base == tip { base = vector.add(tip, (1e-8, 0, 0)) }
+ let dir = vector.norm(vector.sub(tip, base))
+
+ import "/src/draw.typ": anchor
+
+ let tip-style = style
+ tip-style.length = style.length * (ratio / 100%)
+ if style.reverse {
+ anchor("tip", tip)
+ } else {
+ anchor("tip", vector.add(tip, vector.scale(dir, _calculate-tip-offset(tip-style))))
+ }
+ if style.reverse {
+ anchor("base", vector.sub(base, vector.scale(dir, _calculate-tip-offset(tip-style))))
+ } else {
+ anchor("base", base)
+ }
+}
+
+// Dictionary of built-in mark styles
+//
+// (style) => (<elements..>)
+#let marks = (
+ triangle: (style) => {
+ let pts = if style.harpoon {
+ ((0,0), (style.length, 0), (style.length, style.width / 2))
+ } else {
+ ((0,0), (style.length, -style.width / 2), (style.length, style.width / 2))
+ }
+
+ fast-line(..pts, stroke: style.stroke, fill: style.fill, close: true)
+ create-triangle-tip-and-base-anchor(style, (0, 0), (style.length, 0))
+ },
+ // A mark in the shape of an arrow tip.
+ stealth: (style) => {
+ let (l, w, i) = (style.length, style.width, style.inset)
+
+ let pts = if style.harpoon {
+ ((0,0), (l, w / 2), (l - i, 0))
+ } else {
+ ((0,0), (l, w / 2), (l - i, 0), (l, -w / 2))
+ }
+
+ fast-line(..pts, stroke: style.stroke, fill: style.fill, close: true)
+ create-triangle-tip-and-base-anchor(style, (0, 0), (l - i, 0))
+ },
+ curved-stealth: (style) => {
+ import "/src/draw.typ": merge-path, intersections, line, anchor, hide
+
+ let (l, w, i) = (style.length, style.width, style.inset)
+
+ // Force round join
+ style.stroke.join = "round"
+
+ intersections("i", merge-path(
+ stroke: style.stroke,
+ fill: style.fill,
+ close: true, {
+ fast-bezier(
+ (0, 0),
+ (l, w / 2),
+ (l / 3, w / 8))
+ fast-bezier(
+ (l, w / 2),
+ (l, -w / 2),
+ (l - i, 0))
+ fast-bezier(
+ (l, -w / 2),
+ (0, 0),
+ (l / 3, -w / 8))
+ }),
+ hide(fast-line((0,0), (l, 0)))
+ )
+
+ let thickness = style.canvas-thickness
+ create-triangle-tip-and-base-anchor(style, (0, 0), (l - i + thickness / 2, 0)) // BUG: Base is the control point, but not the curve extrema
+ anchor("base", "i.1")
+ },
+ bar: (style) => {
+ import "/src/draw.typ": anchor
+
+ let w = style.width
+
+ let pts = if style.harpoon {
+ ((0, w / 2), (0, 0))
+ } else {
+ ((0, w / 2), (0, -w / 2))
+ }
+
+ fast-line(..pts, stroke: style.stroke, fill: style.fill)
+ let offset = style.canvas-thickness / 2
+ create-tip-and-base-anchor(style, (-offset, 0), (offset, 0))
+ anchor("center", (0, 0))
+ },
+ ellipse: (style) => {
+ import "/src/draw.typ": arc, circle
+
+ let r = (style.length / 2, style.width / 2)
+
+ if style.harpoon {
+ arc((0, 0), stroke: style.stroke, fill: style.fill, delta: -180deg, start: 0deg, radius: r, anchor: "origin", mode: "PIE")
+ } else {
+ circle((0, 0), radius: r, fill: style.fill, stroke: style.stroke)
+ }
+
+ create-tip-and-base-anchor(style, (r.at(0), 0), (-r.at(0), 0), respect-stroke-thickness: true)
+ },
+ circle: (style) => {
+ import "/src/draw.typ": arc, circle
+
+ let r = calc.min(style.length, style.width) / 2
+
+ if style.harpoon {
+ arc((0, 0), delta: -180deg, start: 0deg, radius: r, anchor: "origin", mode: "PIE", stroke: style.stroke, fill: style.fill)
+ } else {
+ circle((0, 0), radius: r, fill: style.fill, stroke: style.stroke)
+ }
+
+ create-tip-and-base-anchor(style, (r, 0), (-r, 0), respect-stroke-thickness: true)
+ },
+ bracket: (style) => {
+ let (l, w, i) = (style.length, style.width, style.inset)
+
+ let pts = if style.harpoon {
+ ((l + i, w / 2), (0, w / 2), (0, 0))
+ } else {
+ ((l + i, w / 2), (0, w / 2), (0, -w / 2), (l + i, -w / 2))
+ }
+
+ fast-line(..pts, stroke: style.stroke, fill: none)
+ create-tip-and-base-anchor(style, (0, 0), (0, 0), respect-stroke-thickness: true)
+ },
+ diamond: (style) => {
+ let (l, w) = (style.length, style.width)
+
+ let pts = if style.harpoon {
+ ((0,0), (l / 2, w / 2), (l, 0))
+ } else {
+ ((0,0), (l / 2, w / 2), (l, 0), (l / 2, -w / 2))
+ }
+
+ fast-line(..pts, stroke: style.stroke, fill: style.fill, close: true)
+ create-diamond-tip-and-base-anchor(style, (0, 0), (l, 0))
+ },
+ rect: (style) => {
+ import "/src/draw.typ": *
+
+ let (l, w) = (style.length, style.width)
+
+ if style.harpoon {
+ rect((0, -w / 2), (-l, +w / 2), stroke: style.stroke)
+ } else {
+ rect((0, -w / 2), (-l, +w / 2), stroke: style.stroke)
+ }
+
+ create-tip-and-base-anchor(style, (0, 0), (-l, 0), respect-stroke-thickness: true)
+ },
+ hook: (style) => {
+ import "/src/draw.typ": merge-path, arc
+
+ let r = calc.min(style.length, style.width / 2) / 2
+ let (l, i) = (style.length, style.inset)
+
+ merge-path({
+ fast-line((i, -2 * r), (0, -2 * r))
+ arc((0, 0), delta: -180deg, start: -90deg, radius: r, anchor: "end")
+ if not style.harpoon {
+ arc((0, 0), delta: -180deg, start: -90deg, radius: r, anchor: "start")
+ fast-line((i, +2 * r), (0, +2 * r))
+ }
+ }, stroke: style.stroke, fill: none)
+
+ create-tip-and-base-anchor(style, (-r, 0), (0, 0), center: ((-r + i) / 2, 0))
+ },
+ // An unfilled mark in the shape of an angle bracket (>).
+ straight: (style) => {
+ let (l, w) = (style.length, style.width)
+
+ let pts = if style.harpoon {
+ ((l, w / 2), (0, 0))
+ } else {
+ ((l, w / 2), (0, 0), (l, -w / 2))
+ }
+
+ fast-line(..pts, stroke: style.stroke, fill: none)
+ if style.harpoon {
+ create-tip-and-base-anchor(style, (0, 0), (0, 0))
+ } else {
+ create-triangle-tip-and-base-anchor(style, (0, 0), (0, 0))
+ }
+ },
+ barbed: (style) => {
+ import "/src/draw.typ": merge-path, anchor
+
+ let style = style
+ style.stroke.join = "round"
+
+ let (l, w) = (style.length, style.width)
+
+ let thickness = style.canvas-thickness / 2
+ let offset = if not style.reverse {
+ thickness
+ } else { 0 }
+ let ctrl-a = (l + offset, 0)
+ let ctrl-b = (0 + offset, 0)
+
+ merge-path({
+ fast-bezier((l + offset, w / 2), (offset, 0), ctrl-a, ctrl-b)
+ if not style.harpoon {
+ fast-bezier((offset, 0), (l + offset, -w / 2), ctrl-b, ctrl-a)
+ }
+ }, ..style)
+
+ anchor("tip", (0, 0))
+ anchor("base", (thickness, 0))
+ anchor("reverse-tip", (0, 0))
+ anchor("reverse-base", (-thickness, 0))
+ },
+ plus: (style) => {
+ let (l, w) = (style.length, style.width)
+
+ fast-line((-l / 2, 0), (+l / 2, 0), stroke: style.stroke)
+ fast-line((0, -w / 2), (0, +w / 2), stroke: style.stroke)
+
+ create-tip-and-base-anchor(style, (0, 0), (0, 0))
+ },
+ x: (style) => {
+ let (l, w) = (style.length, style.width)
+
+ fast-line((-l / 2, w / 2), (+l / 2, -w / 2), stroke: style.stroke)
+ fast-line((-l / 2, -w / 2), (+l / 2, +w / 2), stroke: style.stroke)
+
+ create-tip-and-base-anchor(style, (0, 0), (0, 0))
+ },
+ star: (style) => {
+ let (l, w) = (style.length, style.width)
+
+ let n = 5
+ for i in range(0, n) {
+ let a = 360deg / n * i
+ fast-line((0, 0), (calc.cos(a) * l / 2, calc.sin(a) * w / 2), stroke: style.stroke)
+ }
+
+ create-tip-and-base-anchor(style, (0, 0), (0, 0))
+ },
+ parenthesis: (style) => {
+ import "/src/draw.typ": *
+
+ let thickness = style.canvas-thickness
+ let width = style.width / 2
+ let angle = style.at("angle", default: 80deg) / 2
+ let radius = width / calc.sin(angle)
+ let offset = radius / 4 + style.canvas-thickness / 2
+
+ arc((-offset, 0), stroke: style.stroke, radius: radius, start: -angle, stop: angle, anchor: "center")
+
+ anchor("tip", (0, 0))
+ anchor("base", (-thickness, 0))
+ },
+)
+#let names = marks.keys()
+
+// Mark mnemonics
+// Each mnemonic maps to a dictionary of:
+// - reverse (bool)
+// - flip (bool)
+// - harpoon (bool)
+// TODO: Resolve mark styles at a later point, to support all style keys here
+#let mnemonics = (
+ ">": ("triangle", (:)),
+ "<": ("triangle", (reverse: true)),
+ "<>": ("diamond", (:)),
+ "[]": ("rect", (:)),
+ "]": ("bracket", (:)),
+ "[": ("bracket", (reverse: true)),
+ "|": ("bar", (:)),
+ "o": ("circle", (:)),
+ "+": ("plus", (:)),
+ "x": ("x", (:)),
+ "*": ("star", (:)),
+ ")>": ("curved-stealth", (:)),
+ ">>": ("stealth", (:)),
+ ")": ("parenthesis", (:)),
+)
+
+// Get a mark shape + reverse tuple for a mark name
+#let get-mark(ctx, symbol) = {
+ symbol = ctx.marks.mnemonics.at(symbol, default: symbol)
+ if symbol in ctx.marks.marks {
+ return (ctx.marks.marks.at(symbol), (:))
+ }
+
+ let (symbol, defaults) = mnemonics.at(symbol, default: (symbol, (:)))
+ assert(symbol in marks, message: "Unknown mark '" + symbol + "'")
+ return (marks.at(symbol), defaults)
+}
diff --git a/render/packages/preview/cetz/0.5.2/src/mark.typ b/render/packages/preview/cetz/0.5.2/src/mark.typ
new file mode 100644
index 0000000..be7e5dd
--- /dev/null
+++ b/render/packages/preview/cetz/0.5.2/src/mark.typ
@@ -0,0 +1,428 @@
+#import "drawable.typ"
+#import "vector.typ"
+#import "matrix.typ"
+#import "util.typ"
+#import "path-util.typ"
+#import "styles.typ"
+#import "mark-shapes.typ": get-mark
+#import "process.typ"
+
+/// Checks if a mark should be drawn according to the current style.
+/// - style (style): The current style.
+/// -> bool
+#let check-mark(style) = {
+ style != none and ("start", "end", "symbol").any(key =>
+ style.at(key, default: none) != none)
+}
+
+/// Processes the mark styling.
+/// TODO: remember what is actually going on here.
+///
+/// - ctx (context): The context object.
+/// - style (style): The current style.
+/// - root (str): Where the mark is being placed, normally either `"start"` or `"end"`. Allows different styling for marks in different directions.
+/// - path-length (float): The length of the path. This is used for relative offsets.
+#let process-style(ctx, style, root, path-length) = {
+ let base-style = (
+ symbol: auto,
+ fill: auto,
+ stroke: auto,
+ slant: auto,
+ harpoon: auto,
+ flip: auto,
+ reverse: auto,
+ inset: auto,
+ width: auto,
+ scale: auto,
+ length: auto,
+ sep: auto,
+ pos: auto,
+ offset: auto,
+ xy-up: auto,
+ z-up: auto,
+ shorten-to: auto,
+ position-samples: auto,
+ anchor: auto,
+ transform-shape: auto,
+ )
+
+ if type(style.at(root)) != array {
+ style.at(root) = (style.at(root),)
+ }
+ if type(style.symbol) != array {
+ style.symbol = (style.symbol,)
+ }
+
+ let out = ()
+ for i in range(calc.max(style.at(root).len(), style.symbol.len())) {
+ let style = style
+ style.symbol = style.symbol.at(i, default: auto)
+ style.at(root) = style.at(root).at(i, default: auto)
+
+ if type(style.symbol) == dictionary {
+ style = styles.resolve(style, merge: style.symbol)
+ }
+
+ if type(style.at(root)) == str {
+ style.symbol = style.at(root)
+ } else if type(style.at(root)) == dictionary {
+ style = styles.resolve(style, root: root, base: base-style)
+ }
+
+ style.stroke = util.resolve-stroke(style.stroke)
+ style.canvas-thickness = util.resolve-number(ctx, style.stroke.thickness)
+
+ if "angle" in style and type(style.angle) == angle {
+ style.width = calc.tan(style.angle / 2) * style.length * 2
+ }
+
+ // Stroke canvas-thickness relative attributes
+ for (k, v) in style {
+ if k in ("length", "width", "inset", "sep") {
+ style.insert(k, if type(v) == ratio {
+ style.canvas-thickness * v / 100%
+ } else {
+ util.resolve-number(ctx, v)
+ } * style.scale)
+ }
+ }
+
+ // Path length relative attributes
+ for k in ("offset", "pos",) {
+ let v = style.at(k)
+ if v != none and v != auto {
+ style.insert(k, if type(v) == ratio {
+ v * path-length / 100%
+ } else {
+ util.resolve-number(ctx, v)
+ })
+ }
+ }
+
+ // Flip transformed marks
+ if style.transform-shape {
+ style.flip = not style.flip
+ }
+
+ out.push(style)
+ }
+ return out
+}
+
+#let transform-mark(style, mark, pos, dir, flip: false, reverse: false, slant: none, harpoon: false) = {
+ let up = style.xy-up
+ if dir.at(2) != 0 {
+ up = style.z-up
+ }
+
+ assert(style.anchor in ("tip", "base", "center"))
+ let (tip, base, center) = if reverse {
+ (mark.reverse-tip, mark.reverse-base, mark.reverse-center)
+ } else {
+ (mark.tip, mark.base, mark.center)
+ }
+
+ let origin = (tip: tip, base: base, center: center).at(style.anchor)
+ mark.offset = vector.dist(origin, tip)
+
+ let t = (
+ // Translate & rotate to the target coordinate & direction
+ matrix.transform-translate(..pos.slice(0, 3)),
+ matrix.transform-rotate-dir(dir, up),
+ matrix.transform-rotate-z(-90deg),
+
+ // Rotate mark to have base->tip on the x-axis
+ matrix.transform-rotate-z(if reverse {
+ vector.angle2(tip, base)
+ } else {
+ vector.angle2(base, tip)
+ }),
+
+ // Translate mark to have its anchor (tip, base) at (0,0)
+ matrix.transform-translate(..vector.scale(origin.slice(0, 3), if reverse {1} else {-1})),
+
+ // Mirror on x and/or y axis
+ if not flip or reverse {
+ matrix.transform-scale({
+ if not flip {
+ (y: -1)
+ }
+ if reverse {
+ (x: -1)
+ }
+ })
+ },
+
+ // Slant on x axis
+ if slant not in (none, 0%) {
+ if type(slant) == ratio {
+ slant /= 100%
+ }
+ matrix.transform-shear-x(slant)
+ },
+ )
+
+ mark.drawables = drawable.apply-transform(
+ matrix.mul-mat(..t.filter(m => m != none)),
+ mark.drawables
+ )
+
+ return mark
+}
+
+#let _eval-mark-shape-and-anchors(ctx, mark, style) = {
+ if "eval-mark-guard" in ctx {
+ panic("Recursive mark drawing is not allowed")
+ }
+ ctx.eval-mark-guard = true
+
+ ctx.groups = ()
+ ctx.nodes = (:)
+ ctx.transform = matrix.ident(4)
+
+ import "/src/draw.typ"
+ let body = {
+ draw.set-style(
+ stroke: util.resolve-stroke(style.at("stroke", default: none)),
+ fill: style.at("fill", default: none),
+ mark: none,
+ line: (mark: none),
+ bezier: (mark: none),
+ arc: (mark: none),
+ )
+ mark
+ }
+ let (ctx: ctx, bounds: _, drawables: drawables) = process.many(ctx, body, compute-bounds: false)
+
+ // Fetch special mark anchors
+ let get-anchor(name, default: none) = {
+ if default != none {
+ if not name in ctx.nodes {
+ return default
+ }
+ }
+ return (ctx.nodes.at(name).anchors)("default")
+ }
+
+ let tip = get-anchor("tip")
+ assert.ne(tip, none, message: "Mark has no 'tip' anchor!")
+ let base = get-anchor("base")
+ assert.ne(base, none, message: "Mark has no 'base' anchor!")
+ let center = get-anchor("center", default:
+ vector.lerp(tip, base, 0.5))
+
+ let reverse-tip = get-anchor("reverse-tip", default: base)
+ let reverse-base = get-anchor("reverse-base", default: tip)
+ let reverse-center = get-anchor("reverse-center", default:
+ vector.lerp(reverse-tip, reverse-base, 0.5))
+
+ return (
+ tip: tip,
+ base: base,
+ center: center,
+ reverse-tip: reverse-tip,
+ reverse-base: reverse-base,
+ reverse-center: reverse-center,
+ length: vector.dist(tip, base),
+ drawables: drawables,
+ )
+}
+
+/// Places a mark on the given path. Returns a {{dictionary}} with the following keys:
+/// - drawables (drawable): The mark drawables.
+/// - distance (float): The length to shorten the path by.
+/// - pos (float): The position of the mark, can be used to snap the end of the path to after shortening.
+///
+/// ---
+///
+/// - ctx (context): The canvas context object.
+/// - styles (style): A processed mark styling.
+/// - segments (drawable): The path to place the mark on.
+/// - is-end (bool): Start from the end of the path
+/// -> dictionary Dictionary with the following keys: pt, distance and drawable.
+#let place-mark-on-path(ctx, styles, segments, is-end: false) = {
+ if type(styles) != array {
+ styles = (styles,)
+ }
+ let distance = 0
+ let shorten-distance = 0
+ let shorten-pos = none
+ let drawables = ()
+
+ for (i, style) in styles.enumerate() {
+ let is-last = i + 1 == styles.len()
+ if style.symbol == none {
+ continue
+ }
+
+ // Override position, if set
+ if style.pos != none {
+ distance = style.pos
+ }
+
+ // Apply mark offset
+ distance += style.offset
+
+ let (mark-fn, defaults) = get-mark(ctx, style.symbol)
+
+ let merge-flag(style, key, default: false) = {
+ let old = style.at(key)
+ let def = defaults.at(key, default: default)
+ style.insert(key, (old or def) and not (old and def))
+ return style
+ }
+
+ style = merge-flag(style, "reverse")
+ style = merge-flag(style, "flip")
+ style = merge-flag(style, "harpoon")
+ style.mark = none
+
+ let mark = _eval-mark-shape-and-anchors(ctx, mark-fn(style), style)
+ let offset = style.at("offset", default: 0)
+ let inset = style.at("inset", default: 0)
+
+ let mark-tip-info = path-util.point-at(
+ segments, distance, reverse: is-end)
+ let mark-base-info = if mark.length != 0 {
+ path-util.point-at(
+ segments, distance + mark.length - inset, reverse: is-end)
+ } else {
+ mark-tip-info
+ }
+
+ // Do not try to place this mark, if we failed to
+ // get a tip/base info.
+ if mark-tip-info == none or mark-base-info == none {
+ continue
+ }
+
+ let dir = if mark-base-info.point != mark-tip-info.point {
+ vector.sub(mark-base-info.point, mark-tip-info.point)
+ } else {
+ mark-tip-info.direction
+ }
+ if vector.len(dir) == 0 {
+ dir = (1, 0, 0)
+ }
+
+ let pos = mark-tip-info.point
+
+ mark = transform-mark(
+ style,
+ mark,
+ pos,
+ dir,
+ reverse: style.reverse,
+ slant: style.slant,
+ flip: style.flip,
+ harpoon: style.harpoon,
+ )
+
+ let offset = mark.offset
+
+ // Shorten path to this mark
+ if style.shorten-to != none and (style.shorten-to == auto or i <= style.shorten-to) {
+ shorten-distance = distance + mark.length - offset
+ shorten-pos = mark-base-info.point
+ }
+
+ drawables += mark.drawables
+ distance += mark.length
+
+ // Add separator
+ distance += style.sep
+ }
+
+ return (
+ drawables: drawable.apply-tags(drawables, drawable.TAG.mark),
+ distance: shorten-distance,
+ pos: shorten-pos
+ )
+}
+
+/// Places marks along a path. Returns them as an {{array}} of {{drawable}}.
+///
+/// - ctx (context): The context object.
+/// - style (style): The current mark styling.
+/// - transform (matrix): The current transformation matrix.
+/// - path (drawable): The path to place the marks on.
+/// - add-path (bool): When `true` the shortened path will returned as the first {{drawable}} in the {{array}}
+/// -> array
+#let place-marks-along-path(ctx, style, transform, path, add-path: true) = {
+ let distance = (0, 0)
+ let snap-to = (none, none)
+ let drawables = ()
+ let perspective-mode = ctx.at("_perspective-projection", default: false)
+
+ // Temp. disable custom coordinate resolvers for placing marks on paths.
+ ctx.resolve-coordinate = ()
+
+ if style == none {
+ style = (start: none, end: none, symbol: none)
+ }
+ if perspective-mode {
+ style.transform-shape = true
+ }
+ let both-symbol = style.at("symbol", default: none)
+ let start-symbol = style.at("start",
+ default: both-symbol)
+ if start-symbol == none {
+ start-symbol = both-symbol
+ }
+ let end-symbol = style.at("end",
+ default: both-symbol)
+ if end-symbol == none {
+ end-symbol = both-symbol
+ }
+
+ let (path, is-transformed) = if not style.at("transform-shape", default: true) and transform != none {
+ (drawable.apply-transform(
+ matrix.mul-mat(matrix.transform-scale((1,1,0)), transform), path).first(), true)
+ } else {
+ (path, false)
+ }
+
+ let segments = path.segments
+ if start-symbol != none {
+ let (drawables: start-drawables, distance: start-distance, pos: pt) = place-mark-on-path(
+ ctx,
+ process-style(ctx, style, "start", path-util.length(segments)),
+ segments
+ )
+ drawables += start-drawables
+ distance.first() = start-distance
+ snap-to.first() = pt
+ }
+ if end-symbol != none {
+ let (drawables: end-drawables, distance: end-distance, pos: pt) = place-mark-on-path(
+ ctx,
+ process-style(ctx, style, "end", path-util.length(segments)),
+ segments,
+ is-end: true
+ )
+
+ drawables += end-drawables
+ distance.last() = end-distance
+ snap-to.last() = pt
+ }
+ if distance != (0, 0) {
+ segments = path-util.shorten-to(
+ segments,
+ distance,
+ samples: style.position-samples,
+ snap-to: snap-to)
+ }
+
+ if add-path {
+ path.segments = segments
+ drawables.insert(0, path)
+ }
+
+ // If not transformed pre mark placement,
+ // transform everything after mark placement.
+ if not is-transformed {
+ drawables = drawable.apply-transform(transform, drawables)
+ }
+
+ return drawables
+}
diff --git a/render/packages/preview/cetz/0.5.2/src/matrix.typ b/render/packages/preview/cetz/0.5.2/src/matrix.typ
new file mode 100644
index 0000000..c84e43b
--- /dev/null
+++ b/render/packages/preview/cetz/0.5.2/src/matrix.typ
@@ -0,0 +1,466 @@
+#import "vector.typ"
+#import "wasm.typ": call_wasm
+#let cetz-core = plugin("../cetz-core/cetz_core.wasm")
+
+// Global rounding precision
+#let precision = 10
+
+#let _round = calc.round.with(digits: precision)
+
+#let cos(x) = {
+ _round(calc.cos(x))
+}
+
+#let sin(x) = {
+ _round(calc.sin(x))
+}
+
+#let pi = calc.pi
+
+// List of identity matrices of dimension 1 x 1 to 4 x 4
+#let _ident = (
+ ((1.0),),
+ ((1.0, 0.0), (0.0, 1.0)),
+ ((1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, 1.0)),
+ ((1.0, 0.0, 0.0, 0.0), (0.0, 1.0, 0.0, 0.0), (0.0, 0.0, 1.0, 0.0), (0.0, 0.0, 0.0, 1.0)),
+)
+
+/// Create a (square) identity matrix with dimensions $"size" times "size"$
+///
+/// - size (int): Size of the matrix
+/// -> matrix
+#let ident(size) = {
+ assert(size >= 1, message: "Invalid dimension")
+ return _ident.at(size - 1, default:
+ range(0, size).map(j => range(0, size).map(k => {
+ if j == k { 1.0 } else { 0.0 }
+ })))
+}
+
+/// Create a square matrix with the diagonal set to the
+/// given values
+///
+/// - ..diag (float): Diagonal values
+/// -> matrix
+#let diag(..diag) = {
+ assert(diag.pos().len() >= 1, message: "Invalid dimension")
+ assert.eq(diag.named(), (), messaged: "Unexpected named argument")
+
+ let diag = diag.pos()
+ range(0, diag.len()).map(m => range(0, diag.len()).map(n => {
+ if n == m { diag.at(m) } else { 0.0 }
+ }))
+}
+
+/// Returns the dimension of the given matrix as `(m, n)`
+/// - m (matrix): The matrix
+/// -> array
+#let dim(m) = {
+ return (m.len(), if m.len() > 0 { m.at(0).len() } else { 0 })
+}
+
+/// Returns the n-th column of a matrix as a {{vector}}
+/// - mat (matrix): Input matrix
+/// - n (int): The column's index
+/// -> vector
+#let column(mat, n) = {
+ range(0, mat.len()).map(m => mat.at(m).at(n))
+}
+
+/// Rounds each value in the matrix to a precision.
+/// - mat (matrix): Input matrix
+/// - precision (int) = 8: Rounding precision (digits)
+/// -> matrix
+#let round(mat, precision: precision) = {
+ mat.map(r => r.map(v => _round(v, digits: precision)))
+}
+
+/// Returns a $4 times 4$ translation matrix
+/// - x (float): The translation in the $x$ direction.
+/// - y (float): The translation in the $y$ direction.
+/// - z (float): The translation in the $x$ direction.
+/// -> matrix
+#let transform-translate(x, y, z) = {
+ ((1, 0, 0, x), (0, 1, 0, y), (0, 0, 1, z), (0, 0, 0, 1))
+}
+
+/// Returns a $4 times 4$ x-shear matrix
+/// - factor (float): The shear in the $x$ direction.
+/// -> matrix
+#let transform-shear-x(factor) = {
+ ((1, factor, 0, 0), (0, 1, 0, 0), (0, 0, 1, 0), (0, 0, 0, 1))
+}
+
+
+/// Returns a $4 times 4$ z-shear matrix
+/// - factor (float): The shear in the $z$ direction.
+/// -> matrix
+#let transform-shear-z(factor) = {
+ ((1, 0, factor, 0), (0, 1, -factor, 0), (0, 0, 1, 0), (0, 0, 0, 1))
+}
+
+/// Returns a $4 times 4$ scale matrix
+/// - f (float,array,dictionary): The scale factor(s) of the matrix. An {{array}} of at least 3 {{float}}s sets the x, y and z scale factors. A {{dictionary}} sets the scale in the direction of the corresponding x, y and z keys. A single {{float}} sets the scale for all directions.
+/// -> matrix
+#let transform-scale(f) = {
+ let (x, y, z) = if type(f) == array {
+ vector.as-vec(f, init: (1, 1, 1))
+ } else if type(f) == dictionary {
+ (f.at("x", default: 1), f.at("y", default: 1), f.at("z", default: 1))
+ } else {
+ (f, f, f)
+ }
+ return (
+ (x, 0, 0, 0),
+ (0, y, 0, 0),
+ (0, 0, z, 0),
+ (0, 0, 0, 1),
+ )
+}
+
+/// Returns a $4 times 4$ rotation xyz matrix for a direction and up vector
+/// - dir (vector): idk
+/// - up (vector): idk
+/// -> matrix
+#let transform-rotate-dir(dir, up) = {
+ dir = vector.norm(dir.slice(0, 3))
+ up = vector.norm(up.slice(0, 3))
+
+ let (dx, dy, dz) = dir
+ let (ux, uy, uz) = up
+ let (rx, ry, rz) = vector.norm(vector.cross(dir, up))
+
+ ((rx, dx, ux, 0), (ry, dy, uy, 0), (rz, dz, uz, 0), (0, 0, 0, 1))
+}
+
+// Return 4x4 rotate x matrix
+/// Returns a $4 times 4$ $x$ rotation matrix
+/// - angle (angle): The angle to rotate around the $x$ axis
+/// -> matrix
+#let transform-rotate-x(angle) = {
+ ((1, 0, 0, 0), (0, cos(angle), -sin(angle), 0), (0, sin(angle), cos(angle), 0), (0, 0, 0, 1))
+}
+
+// Return 4x4 rotate y matrix
+/// Returns a $4 times 4$ $y$ rotation matrix
+/// - angle (angle): The angle to rotate around the $y$ axis
+/// -> matrix
+#let transform-rotate-y(angle) = {
+ ((cos(angle), 0, -sin(angle), 0), (0, 1, 0, 0), (sin(angle), 0, cos(angle), 0), (0, 0, 0, 1))
+}
+
+// Return 4x4 rotate z matrix
+/// Returns a $4 times 4$ $z$ rotation matrix
+/// - angle (angle): The angle to rotate around the $z$ axis
+/// -> matrix
+#let transform-rotate-z(angle) = {
+ ((cos(angle), -sin(angle), 0, 0), (sin(angle), cos(angle), 0, 0), (0, 0, 1, 0), (0, 0, 0, 1))
+}
+
+// 3D rotation matrix around an arbitrary axis (ax, ay, az).
+#let _rotate-axis-angle(ax, ay, az, angle) = {
+ let c = cos(angle)
+ let s = sin(angle)
+ (
+ (ax * ax * (1 - c) + c, ax * ay * (1 - c) - az * s, ax * az * (1 - c) + ay * s, 0),
+ (ay * ax * (1 - c) + az * s, ay * ay * (1 - c) + c, ay * az * (1 - c) - ax * s, 0),
+ (az * ax * (1 - c) - ay * s, az * ay * (1 - c) + ax * s, az * az * (1 - c) + c, 0),
+ (0, 0, 0, 1),
+ )
+}
+
+/// Returns a $4 times 4$ rotation matrix from azimuth/elevation/roll.
+/// Assumes the viewing convention where $z$ points up and $x$ points toward the viewer.
+/// - azimuth (angle): Rotation around z.
+/// - elevation (angle): Tilt above the xy plane.
+/// - roll (angle): Rotation around the current viewing axis.
+/// -> matrix
+#let transform-rotate-aer(azimuth, elevation, roll: 0deg) = {
+ let rotate-z-up = transform-rotate-x(-90deg)
+ let rotate-azimuth = transform-rotate-z(-90deg - azimuth)
+ let (ax, ay, az) = (-sin(azimuth), cos(azimuth), 0)
+ let rotate-elevation = _rotate-axis-angle(ax, ay, az, elevation)
+ let base = mul-mat(rotate-z-up, rotate-azimuth, rotate-elevation)
+
+ if roll == 0deg {
+ return base
+ }
+
+ // Roll around the current viewing axis after azimuth/elevation.
+ let (vx, vy, vz) = vector.norm(mul4x4-vec3(base, (1, 0, 0), w: 0))
+ let rotate-roll = _rotate-axis-angle(vx, vy, vz, roll)
+ mul-mat(rotate-roll, base)
+}
+
+// Return 4x4 rotate xz matrix
+/// Returns a $4 times 4$ $x z$ rotation matrix
+/// - x (angle): The angle to rotate around the $x$ axis
+/// - z (angle): The angle to rotate around the $z$ axis
+/// -> matrix
+#let transform-rotate-xz(x, z) = {
+ (
+ (cos(z), sin(z), 0, 0),
+ (-cos(x) * sin(z), cos(x) * cos(z), -sin(x), 0),
+ (sin(x) * sin(z), -sin(x) * cos(z), cos(x), 1),
+ (0, 0, 0, 1),
+ )
+}
+
+/// Returns a $4 times 4$ rotation matrix - yaw-pitch-roll
+///
+/// - a (angle): Yaw
+/// - b (angle): Pitch
+/// - c (angle): Roll
+/// -> matrix
+#let transform-rotate-ypr(a, b, c) = {
+ (
+ (cos(a) * cos(b), cos(a) * sin(b) * sin(c) - sin(a) * cos(c), cos(a) * sin(b) * cos(c) + sin(a) * sin(c), 0),
+ (sin(a) * cos(b), sin(a) * sin(b) * sin(c) + cos(a) * cos(c), sin(a) * sin(b) * cos(c) - cos(a) * sin(c), 0),
+ (-sin(b), cos(b) * sin(c), cos(b) * cos(c), 1),
+ (0, 0, 0, 1),
+ )
+}
+
+/// Returns a $4 times 4$ rotation matrix - euler angles
+///
+/// Calculates the product of the three rotation matrices
+/// $R = R_z(z) R_y(y) R_x(x)$
+///
+/// - x (angle): Rotation about x
+/// - y (angle): Rotation about y
+/// - z (angle): Rotation about z
+/// -> matrix
+#let transform-rotate-xyz(x, y, z) = {
+ (
+ (cos(y) * cos(z), sin(x) * sin(y) * cos(z) - cos(x) * sin(z), cos(x) * sin(y) * cos(z) + sin(x) * sin(z), 0),
+ (cos(y) * sin(z), sin(x) * sin(y) * sin(z) + cos(x) * cos(z), cos(x) * sin(y) * sin(z) - sin(x) * cos(z), 0),
+ (-sin(y), sin(x) * cos(y), cos(x) * cos(y), 0),
+ (0, 0, 0, 1),
+ )
+}
+
+/// Multiplies matrices on top of each other.
+/// - ..matrices (matrix): The matrices to multiply from left to right.
+/// -> matrix
+#let mul-mat(..matrices) = {
+ matrices = matrices.pos().filter(m => m != none)
+ let out = matrices.first()
+ for i in range(1, matrices.len()) {
+ let matrix = matrices.at(i)
+
+ // Short circuit multiplication with the neutral element
+ if out in _ident {
+ out = matrix
+ continue
+ } else if matrix in _ident {
+ continue
+ }
+
+ let m = out.len()
+ let n = out.at(0).len()
+ let p = matrix.at(0).len()
+ if m == 4 and n == 4 and matrix.len() == 4 and p == 4 {
+ let ((a1, a2, a3, a4), (a5, a6, a7, a8), (a9, a10, a11, a12), (a13, a14, a15, a16)) = out
+ let ((b1, b2, b3, b4), (b5, b6, b7, b8), (b9, b10, b11, b12), (b13, b14, b15, b16)) = matrix
+ out = (
+ (
+ _round(a1 * b1 + a2 * b5 + a3 * b9 + a4 * b13),
+ _round(a1 * b2 + a2 * b6 + a3 * b10 + a4 * b14),
+ _round(a1 * b3 + a2 * b7 + a3 * b11 + a4 * b15),
+ _round(a1 * b4 + a2 * b8 + a3 * b12 + a4 * b16),
+ ),
+ (
+ _round(a5 * b1 + a6 * b5 + a7 * b9 + a8 * b13),
+ _round(a5 * b2 + a6 * b6 + a7 * b10 + a8 * b14),
+ _round(a5 * b3 + a6 * b7 + a7 * b11 + a8 * b15),
+ _round(a5 * b4 + a6 * b8 + a7 * b12 + a8 * b16),
+ ),
+ (
+ _round(a9 * b1 + a10 * b5 + a11 * b9 + a12 * b13),
+ _round(a9 * b2 + a10 * b6 + a11 * b10 + a12 * b14),
+ _round(a9 * b3 + a10 * b7 + a11 * b11 + a12 * b15),
+ _round(a9 * b4 + a10 * b8 + a11 * b12 + a12 * b16),
+ ),
+ (
+ _round(a13 * b1 + a14 * b5 + a15 * b9 + a16 * b13),
+ _round(a13 * b2 + a14 * b6 + a15 * b10 + a16 * b14),
+ _round(a13 * b3 + a14 * b7 + a15 * b11 + a16 * b15),
+ _round(a13 * b4 + a14 * b8 + a15 * b12 + a16 * b16),
+ ),
+ )
+ } else {
+ out = (
+ for i in range(m) {
+ (
+ for j in range(p) {
+ let sum = 0
+ for k in range(n) {
+ sum += out.at(i).at(k) * matrix.at(k).at(j)
+ }
+ (_round(sum),)
+ },
+ )
+ }
+ )
+ }
+ }
+ return out
+}
+
+// Multiply 4x4 matrix with vector of size 3 or 4.
+// The value of vec_4 defaults to w (1).
+//
+// The resulting vector is of dimension 3
+/// Multiplies a $4 times 4$ matrix with a vector of size 3 or 4. The resulting is three dimensional
+/// - mat (matrix): The matrix to multiply
+/// - vec (vector): The vector to multiply
+/// - w (float): The default value for the fourth element of the vector if it is three dimensional.
+/// -> vector
+#let mul4x4-vec3(mat, vec, w: 1.0) = {
+ assert(vec.len() <= 4)
+
+ // Short circuit the neutral element
+ if mat == _ident.at(3) {
+ return (if vec.len() == 2 {
+ (..vec, 0.0)
+ } else {
+ vec
+ }).map(float)
+ }
+
+ let x = vec.at(0)
+ let y = vec.at(1)
+ let z = vec.at(2, default: 0)
+ let w = vec.at(3, default: w)
+
+ let ((a1, a2, a3, a4), (b1, b2, b3, b4), (c1, c2, c3, c4), _) = mat
+ return (
+ a1 * x + a2 * y + a3 * z + a4 * w,
+ b1 * x + b2 * y + b3 * z + b4 * w,
+ c1 * x + c2 * y + c3 * z + c4 * w,
+ )
+}
+
+// Multiply matrix with vector
+/// Multiplies an $m times n$ matrix with an $m$th dimensional vector where $m <= 4$. Prefer the use of `mul4x4-vec3` when possible as it does not use loops.
+/// - mat (matrix): The matrix to multiply
+/// - vec (vector): The vector to multiply
+/// -> vector
+#let mul-vec(mat, vec) = {
+ let m = mat.len()
+ let n = mat.at(0).len()
+ assert(n == vec.len(), message: "Matrix columns must be equal to vector rows")
+ if m == 2 and n == 2 {
+ let ((a1, a2), (b1, b2)) = mat
+ let x = vec.at(0)
+ let y = vec.at(1)
+ return (a1 * x + a2 * y, b1 * x + b2 * y)
+ } else if m == 3 and n == 3 {
+ let ((a1, a2, a3), (b1, b2, b3), (c1, c2, c3)) = mat
+ let x = vec.at(0)
+ let y = vec.at(1)
+ let z = vec.at(2)
+ return (
+ a1 * x + a2 * y + a3 * z,
+ b1 * x + b2 * y + b3 * z,
+ c1 * x + c2 * y + c3 * z,
+ )
+ } else if m == 4 and n == 4 {
+ let ((a1, a2, a3, a4), (b1, b2, b3, b4), (c1, c2, c3, c4), (d1, d2, d3, d4)) = mat
+ let x = vec.at(0)
+ let y = vec.at(1)
+ let z = vec.at(2)
+ let w = vec.at(3)
+ return (
+ a1 * x + a2 * y + a3 * z + a4 * w,
+ b1 * x + b2 * y + b3 * z + b4 * w,
+ c1 * x + c2 * y + c3 * z + c4 * w,
+ d1 * x + d2 * y + d3 * z + d4 * w,
+ )
+ }
+
+ // Short circuit the neutral element
+ if mat in _ident { return vec }
+
+ let new = (0,) * m
+ for i in range(0, m) {
+ let row = mat.at(i)
+ let acc = 0
+ for j in range(0, n) {
+ acc += row.at(j) * vec.at(j)
+ }
+ new.at(i) = acc
+ }
+ return new
+}
+
+/// Returns true if m is 1.
+///
+/// - m (matrix): Matrix to check
+/// -> bool
+#let is-identity(m) = {
+ if type(m) != array {
+ return false
+ }
+
+ if m in _ident {
+ return true
+ } else if m.len() > 4 {
+ for r in range(0, m.len()) {
+ for c in range(0, m.at(r).len()) {
+ if int(r == c) != m.at(r).at(c) {
+ return false
+ }
+ }
+ }
+ return true
+ }
+
+ return false
+}
+
+/// Calculates the inverse matrix of any size.
+/// - matrix (matrix): The matrix to inverse.
+/// -> matrix
+#let inverse(matrix) = {
+ // The identity is self inverse
+ if is-identity(matrix) {
+ return matrix
+ }
+
+ let n = {
+ let size = dim(matrix)
+ assert.eq(size.first(), size.last(), message: "Matrix must be square to perform inversion.")
+ size.first()
+ }
+
+ let N = range(n)
+ let inverted = ident(n)
+ let p
+ for j in N {
+ for i in range(j, n) {
+ if matrix.at(i).at(j) != 0 {
+ (matrix.at(j), matrix.at(i)) = (matrix.at(i), matrix.at(j))
+ (inverted.at(j), inverted.at(i)) = (inverted.at(i), inverted.at(j))
+
+ p = 1 / matrix.at(j).at(j)
+ for k in N {
+ matrix.at(j).at(k) *= p
+ inverted.at(j).at(k) *= p
+ }
+
+ for L in N {
+ if L != j {
+ p = -matrix.at(L).at(j)
+ for k in N {
+ matrix.at(L).at(k) += _round(p * matrix.at(j).at(k))
+ inverted.at(L).at(k) += _round(p * inverted.at(j).at(k))
+ }
+ }
+ }
+ }
+ }
+ }
+
+ return inverted
+}
diff --git a/render/packages/preview/cetz/0.5.2/src/path-util.typ b/render/packages/preview/cetz/0.5.2/src/path-util.typ
new file mode 100644
index 0000000..d601a37
--- /dev/null
+++ b/render/packages/preview/cetz/0.5.2/src/path-util.typ
@@ -0,0 +1,469 @@
+// This file contains utility functions for path calculation
+#import "util.typ"
+#import "vector.typ"
+#import "bezier.typ"
+#import "matrix.typ"
+#import "deps.typ"
+
+// A path is an array of subpaths.
+// A subpath is a triplet of the form:
+// (origin : vector, closed : bool, segments : array<segment>)
+// A segment is an array of the form:
+// (command : string, ..arguments : vector)
+
+/// Create a new subpath. A path is an array of subpaths.
+///
+/// - origin (vector): Origin
+/// - segments (array): Segments
+/// - closed (bool): Closed
+/// -> subpath
+#let make-subpath(origin, segments, closed: false) = {
+ (origin, closed, segments)
+}
+
+#let number-of-samples(n) = {
+ let default = 25
+ return if n == auto {
+ default
+ } else {
+ n
+ }
+}
+
+/// Get if the first subpath is closed
+/// -> boolean
+#let first-subpath-closed(path) = {
+ if path != () {
+ let (_, closed, _) = path.first()
+ return closed
+ }
+ return false
+}
+
+/// Get the start position of the first path
+/// -> vector
+#let first-subpath-start(path) = {
+ if path.len() > 0 {
+ let (origin, ..) = path.first()
+ return origin
+ }
+ return none
+}
+
+/// Get the start point of a subpath
+/// -> vector
+#let subpath-start(subpath) = {
+ let (origin, _, _) = subpath
+ return origin
+}
+
+/// Get the end point of a subpath
+/// -> vector
+#let subpath-end(subpath, ignore-close-flag: false) = {
+ let (origin, closed, segments) = subpath
+ return if closed and not ignore-close-flag {
+ origin
+ } else if segments != () {
+ let (_, ..args) = segments.last()
+ args.last()
+ } else {
+ origin
+ }
+}
+
+/// Get the end position of the last path
+/// -> vector
+#let last-subpath-end(path) = {
+ if path.len() > 0 {
+ let (origin, close, segments) = path.last()
+ if close {
+ return origin
+ }
+ return if segments != () {
+ return segments.last().last()
+ } else {
+ origin
+ }
+ }
+ return none
+}
+
+/// Tests whether every vertex in `path` lies on the same z-plane, returning
+/// `(z, same-z)` where `z` is the z-coordinate of the first vertex and `same-z` is
+/// `true` iff every other vertex is within `tol` of that z-coordinate.
+///
+/// - path (path): Input path; must be non-empty
+/// - tol (float): Absolute z tolerance
+/// -> array Tuple of the form (z, same-z)
+#let same-z-plane(path, tol: 1e-6) = {
+ assert(
+ path.len() > 0,
+ message: "Cannot determine z-plane of an empty path",
+ )
+ let z0 = path.first().at(0).at(2)
+ for (origin, _, segments) in path {
+ if calc.abs(origin.at(2) - z0) > tol { return (z0, false) }
+ for (kind, ..args) in segments {
+ for v in args {
+ if calc.abs(v.at(2) - z0) > tol { return (z0, false) }
+ }
+ }
+ }
+ return (z0, true)
+}
+
+/// Calculates the bounding points for a list of path segments
+///
+/// - path (array): Path
+/// - transform (none, matrix): Transformation to apply on each coordinate
+/// -> array
+#let bounds(path, transform: none) = {
+ let bounds = ()
+
+ for ((origin, closed, segments)) in path {
+ bounds.push(if transform != none { util.apply-transform(transform, origin) } else { origin })
+
+ for ((kind, ..args)) in segments {
+ if kind == "l" {
+ bounds += if transform != none {
+ args.map(matrix.mul4x4-vec3.with(transform))
+ } else {
+ args
+ }
+ } else if kind == "c" {
+ let (c1, c2, e) = if transform != none {
+ args.map(matrix.mul4x4-vec3.with(transform))
+ } else {
+ args
+ }
+ bounds += bezier.cubic-extrema(bounds.last(), e, c1, c2)
+ bounds.push(e)
+ }
+ }
+ }
+
+ return bounds
+}
+
+/// Returns an array of arrays with the lengths of all path segments.
+/// One sub-array for each subpath and its segments.
+///
+/// - path (path): Input path
+/// - samples (auto, int): Number of samples to use for curves
+/// -> array Array of arrays of floats containing the segment lengths
+#let segment-lengths(path, samples: auto) = {
+ let cur = none
+ let start = none
+ let lengths = ()
+ for ((origin, _, segments)) in path {
+ start = origin
+ cur = origin
+
+ let sub-lengths = ()
+ for ((kind, ..args)) in segments {
+ let length = 0
+ if kind == "l" {
+ for pt in args {
+ length += vector.dist(cur, pt)
+ cur = pt
+ }
+ } else if kind == "c" {
+ let (c1, c2, e) = args
+ length += bezier.cubic-arclen(
+ cur, e, c1, c2, samples: number-of-samples(samples))
+ cur = e
+ }
+
+ sub-lengths.push(length)
+ }
+
+ lengths.push(sub-lengths)
+ }
+ return lengths
+}
+
+/// Returns the sum of all segment lengths of a path.
+///
+/// - segments (path): Path segments
+/// - samples (auto, int): Number of samples to take for curves
+/// -> float Length
+#let length(segments, samples: auto) = {
+ return segment-lengths(segments, samples: samples).map(s => s.sum(default: 0)).sum(default: 0)
+}
+
+/// Get information about a point at a given distance on a path.
+///
+/// - path (path): The path
+/// - distance (ratio, number): Distance along the path
+/// - reverse (bool): Travel from end to start
+/// - ignore-subpaths (bool): If false consider the whole path, including sub-paths
+///
+/// -> none
+/// -> dictionary Dictionary with the following keys:
+/// - point (vector) The point on the path
+/// - previous-point (vector) Point previous to point
+/// - direction (vector) Normalized direction vector
+/// - subpath-index (int) Index of the subpath
+/// - segment-index (int) Index of the segment
+/// None is returned, if the path is empty/of length zero.
+#let point-at(path, distance, reverse: false, samples: auto, ignore-subpaths: true) = {
+ if samples == auto {
+ samples = number-of-samples(samples)
+ }
+
+ let travelled = 0
+
+ let lengths = segment-lengths(path)
+ let total = if ignore-subpaths {
+ lengths.first().sum(default: 0)
+ } else {
+ lengths.map(l => l.sum(default: 0)).sum(default: 0)
+ }
+
+ if total == 0 {
+ return none
+ }
+
+ if type(distance) == ratio {
+ distance = total * distance / 100%
+ }
+ if reverse {
+ distance = total - distance
+ }
+ distance = calc.max(0, calc.min(distance, total))
+
+ let point-on-segment(origin, segment, distance) = {
+ let (kind, ..args) = segment
+ if kind == "l" {
+ let pt = args.last()
+ let length = vector.dist(origin, pt)
+ if length != 0 {
+ return (
+ vector.lerp(origin, pt, calc.min(1, distance / length)),
+ vector.norm(vector.sub(pt, origin)))
+ } else {
+ return (
+ pt, (1, 0, 0))
+ }
+ } else if kind == "c" {
+ let (c1, c2, e) = args
+ let t = bezier.cubic-t-for-distance(origin, e, c1, c2, distance, samples: samples)
+ t = calc.min(1, calc.max(t, 0))
+
+ return (
+ bezier.cubic-point(origin, e, c1, c2, t),
+ bezier.cubic-derivative(origin, e, c1, c2, t))
+ }
+ }
+
+ for ((subpath-index, subpath-lengths)) in lengths.enumerate() {
+ for ((segment-index, length)) in subpath-lengths.enumerate() {
+ if distance >= travelled and distance <= travelled + length {
+ let (origin, _, segments) = path.at(subpath-index)
+ let segment = segments.at(segment-index)
+ if segment-index > 0 {
+ origin = segments.at(segment-index - 1).last()
+ }
+
+ let (point, direction) = point-on-segment(
+ origin, segment, distance - travelled)
+ if reverse {
+ direction = vector.scale(direction, -1)
+ }
+
+ // Calculate segment length
+ let segment-distance = distance - travelled
+ let relative-distance = segment-distance
+
+ // For reverse shortening, we need distance from the segment end
+ if reverse {
+ let (kind, ..args) = segment
+ if kind == "l" {
+ let segment-length = vector.dist(origin, args.last())
+ relative-distance = segment-length - segment-distance
+ } else if kind == "c" {
+ let (c1, c2, e) = args
+ let segment-length = bezier.cubic-arclen(origin, e, c1, c2, samples: samples)
+ relative-distance = segment-length - segment-distance
+ }
+ }
+
+ return (
+ previous-point: origin,
+ point: point,
+ direction: direction,
+ subpath-index: subpath-index,
+ segment-index: segment-index,
+ distance: relative-distance,
+ )
+ }
+
+ travelled += length
+ }
+
+ if ignore-subpaths {
+ break
+ }
+ }
+}
+
+/// Shorten a single line segment with a single point
+/// by a given distance.
+///
+/// - origin (vector): Path origin
+/// - previous (vector): Last point befor this segment
+/// - args (array): List of points
+/// - distance (float): Distance
+/// - reverse (bool): If true, start from the end
+/// -> array Array of the form (origin, points)
+#let _shorten-line(origin, previous, args, distance, reverse: false) = {
+ let pt = args.last()
+ let length = vector.dist(previous, pt)
+ if length > 0 {
+ let t = if reverse {
+ 1 - distance / length
+ } else {
+ distance / length
+ }
+
+ let new-pt = vector.lerp(previous, pt, t)
+ return if reverse {
+ (origin, (new-pt,))
+ } else {
+ (new-pt, (pt,))
+ }
+ }
+
+ return (origin, args)
+}
+
+/// Shorten a single cubic segment with a single point
+/// by a given distance.
+///
+/// - origin (vector): Path origin
+/// - previous (vector): Last point befor this segment
+/// - args (array): List of points
+/// - distance (float): Distance
+/// - reverse (bool): If true, start from the end
+/// -> array Array of the form (origin, points)
+#let _shorten-cubic(origin, previous, args, distance, reverse: false, mode: "CURVED") = {
+ let shorten-func = if mode == "CURVED" {
+ bezier.cubic-shorten
+ } else {
+ bezier.cubic-shorten-linear
+ }
+
+ let (c1, c2, e) = args
+ if reverse {
+ let (s, e, c1, c2) = shorten-func(
+ previous, e, c1, c2, calc.min(0, -distance))
+ return (previous, (c1, c2, e))
+ } else {
+ let (s, e, c1, c2) = shorten-func(
+ previous, e, c1, c2, calc.max(0, distance))
+ return (s, (c1, c2, e))
+ }
+}
+
+/// Shorten a path on one or both sides
+///
+/// - path (Path): Path
+/// - distance (number,ratio,array): Distance to shorten the path by
+/// - reverse (boolean): If true, start from the end
+/// - mode ('CURVED','LINEAR'): Shortening mode for cubic segments
+/// - samples (auto,int): Samples to take for measuring cubic segments
+/// - snap-to (none,array): Optional array of points to try to move the shortened segment to
+#let shorten-to(path, distance, reverse: false,
+ mode: "CURVED", samples: auto, snap-to: none) = {
+ let snap-to-threshold = 1e-4
+
+ // Shorten from both sides
+ if type(distance) == array {
+ let original-length = length(path)
+ let (start, end) = distance.map(v => {
+ if type(v) == ratio {
+ v * original-length
+ } else {
+ v
+ }
+ })
+
+ path = shorten-to(path, start, reverse: reverse, mode: mode, samples: samples, snap-to: if snap-to != none { snap-to.first() } else { none })
+ path = shorten-to(path, end, reverse: not reverse, mode: mode, samples: samples, snap-to: if snap-to != none { snap-to.last() } else { none })
+ return path
+ }
+
+ let point = point-at(path, distance, reverse: reverse)
+ if point != none {
+ // Find the subpath to modify
+ let (origin, close, segments) = path.at(point.subpath-index)
+ let (kind, ..args) = segments.at(point.segment-index)
+
+ let new-origin
+ if kind == "l" {
+ (new-origin, args) = _shorten-line(
+ origin, point.previous-point, args, point.distance,
+ reverse: reverse)
+ } else if kind == "c" {
+ (new-origin, args) = _shorten-cubic(
+ origin, point.previous-point, args, point.distance,
+ reverse: reverse, mode: mode)
+ }
+
+ // Test if we can "snap-to" the snap-to hint given
+ if snap-to != none and args.last() != none and vector.dist(args.last(), snap-to) < snap-to-threshold {
+ args.last() = snap-to
+ }
+
+ if (point.segment-index == 0) {
+ origin = new-origin
+ }
+
+ if reverse {
+ segments = segments.slice(0, point.segment-index) + ((kind, ..args,),)
+ } else {
+ segments = ((kind, ..args,),) + segments.slice(point.segment-index + 1)
+ }
+ return if reverse {
+ ((origin, close, segments),) + path.slice(point.subpath-index + 1)
+ } else {
+ path.slice(0, point.subpath-index) + ((origin, close, segments),)
+ }
+ }
+ return path
+}
+
+/// Normalize a path:
+/// - Add missing closing segments
+/// - Remove zero-length line segments
+///
+/// - path (path): Input path
+/// -> path
+#let normalize(path) = {
+ for subpath-index in range(path.len()) {
+ let subpath = path.at(subpath-index)
+ let (origin, closed, segments) = subpath
+
+ // Add a missing closing line
+ if closed and subpath-start(subpath) != subpath-end(subpath, ignore-close-flag: true) {
+ segments.push(("l", origin))
+ }
+
+ // Filter out zero-length lines
+ segments = segments.enumerate().filter(((i, segment)) => {
+ let (kind, ..args) = segment
+ if kind == "l" {
+ let end = args.last()
+ return if i == 0 {
+ end != origin
+ } else {
+ end != segments.at(i - 1).last()
+ }
+ }
+ return true
+ }).map(((i, segment)) => segment)
+
+ path.at(subpath-index) = (origin, closed, segments)
+ }
+ return path
+}
diff --git a/render/packages/preview/cetz/0.5.2/src/polygon.typ b/render/packages/preview/cetz/0.5.2/src/polygon.typ
new file mode 100644
index 0000000..fd74a1a
--- /dev/null
+++ b/render/packages/preview/cetz/0.5.2/src/polygon.typ
@@ -0,0 +1,112 @@
+#import "/src/vector.typ"
+
+/// Returns a list of polygon points from
+/// a list of segments.
+///
+/// Cubic segments get linearized by sampling.
+///
+/// - segment (array): List of segments
+/// - samples (int): Number of samples
+/// -> array
+#let from-subpath(subpath, samples: 10) = {
+ import "/src/bezier.typ": cubic-point
+ let (origin, _, segments) = subpath
+
+ let poly = (origin,)
+ for ((kind, ..args)) in segments {
+ if kind == "c" {
+ let (c1, c2, e) = args
+ poly += range(0, samples).map(t => {
+ cubic-point(poly.last(), e, c1, c2, t / (samples - 1))
+ })
+ } else {
+ poly += args
+ }
+ }
+ return poly
+}
+
+/// Computes the signed area of a 2D polygon.
+///
+/// The formula used is the following:
+/// $ 1/2 \sum_{i}=0^{n-1} x_i*y_i+1 - x_i+1*y_i $
+///
+/// - points (array): List of Vectors of dimension >= 2
+/// -> float
+#let signed-area(points) = {
+ let a = 0
+ let n = points.len()
+ let (cx, cy) = (0, 0)
+ for i in range(0, n) {
+ let (x0, y0, ..) = points.at(i)
+ let (x1, y1, ..) = points.at(calc.rem(i + 1, n))
+ cx += (x0 + x1) * (x0 * y1 - x1 * y0)
+ cy += (y0 + y1) * (x0 * y1 - x1 * y0)
+ a += x0 * y1 - x1 * y0
+ }
+ return .5 * a
+}
+
+/// Returns the winding order of a 2D polygon
+/// by using it's signed area.
+///
+/// Returns either "ccw" (counter clock-wise) or "cw" (clock-wise) or none.
+///
+/// - point (array): List of polygon points
+/// -> none
+/// -> str
+#let winding-order(points) = {
+ let area = signed-area(points)
+ if area > 0 {
+ "cw"
+ } else if area < 0 {
+ "ccw"
+ } else {
+ none
+ }
+}
+
+// Calculate triangle centroid
+#let triangle-centroid(points) = {
+ assert.eq(points.len(), 3)
+
+ let (mx, my, mz) = (0, 0, 0)
+ for p in points {
+ let (x, y, z) = p
+ mx += x
+ my += y
+ mz += z
+ }
+ return (mx / 3, my / 3, mz / 3)
+}
+
+// Calculate the centroid of a line, triangle or simple polygon
+// Formulas:
+// https://en.wikipedia.org/wiki/Centroid
+#let simple-centroid(points) = {
+ return if points.len() <= 1 {
+ none
+ } else if points.len() == 2 {
+ vector.lerp(..points, .5)
+ } else if points.len() == 3 {
+ triangle-centroid(points)
+ } else if points.len() >= 3 {
+ // Skip polygons with multiple z values
+ let z = points.first().at(2, default: 0)
+ if points.any(p => p.at(2) != z) {
+ return none
+ }
+
+ let a = 0
+ let n = points.len()
+ let (cx, cy) = (0, 0)
+ for i in range(0, n) {
+ let (x0, y0, ..) = points.at(i)
+ let (x1, y1, ..) = points.at(calc.rem(i + 1, n))
+ cx += (x0 + x1) * (x0 * y1 - x1 * y0)
+ cy += (y0 + y1) * (x0 * y1 - x1 * y0)
+ a += x0 * y1 - x1 * y0
+ }
+ return (cx/(3*a), cy/(3*a), z)
+ }
+}
diff --git a/render/packages/preview/cetz/0.5.2/src/process.typ b/render/packages/preview/cetz/0.5.2/src/process.typ
new file mode 100644
index 0000000..ff84512
--- /dev/null
+++ b/render/packages/preview/cetz/0.5.2/src/process.typ
@@ -0,0 +1,109 @@
+#import "util.typ"
+#import "path-util.typ"
+#import "aabb.typ"
+#import "drawable.typ"
+#import "vector.typ"
+
+
+/// Processes an element's function to get its drawables and bounds. Returns a {{dictionary}} with the key-values: `ctx` The modified context object, `bounds` The {{aabb}} of the element's drawables, `drawables` An {{array}} of the element's {{drawable}}s.
+///
+/// - ctx (ctx): The current context object.
+/// - element-func (function): A function that when passed {{ctx}}, it should return an element dictionary.
+/// - compute-bounds (bool): Enable bounds computation.
+/// -> dictionary (ctx:, bounds:, drawables:)
+#let element(ctx, element-func, compute-bounds: true) = {
+ let bounds = none
+ let element
+ let anchors = (:)
+
+ (ctx, ..element,) = element-func(ctx)
+
+ if "drawables" in element {
+ if type(element.drawables) == dictionary {
+ element.drawables = (element.drawables,)
+ }
+
+ if compute-bounds {
+ let points = ()
+ for d in element.drawables {
+ // We inline the filter here to not pay function-call cost in the hot path
+ if drawable.TAG.no-bounds in d.tags {
+ continue
+ }
+
+ points += if d.type == "path" {
+ path-util.bounds(d.segments)
+ } else if d.type == "content" {
+ let (x, y, _, w, h,) = d.pos + (d.width, d.height)
+ ((x - w / 2, y - h / 2, 0.0), (x + w / 2, y + h / 2, 0.0))
+ }
+ }
+
+ if points.len() > 0 {
+ bounds = aabb.aabb(points)
+ }
+ }
+ }
+
+ let name = element.at("name", default: none)
+ element.name = name
+ if name != none {
+ assert.eq(type(name), str,
+ message: "Element name must be a string")
+ assert(not name.contains("."),
+ message: "Invalid name for element '" + element.name + "'; name must not contain '.'")
+
+ if "anchors" in element {
+ ctx.nodes.insert(name, element)
+ if ctx.groups.len() > 0 {
+ ctx.groups.last().push(name)
+ }
+ }
+ } else if element.at("leak-nodes", default: false) {
+ // #930 We need to pass down nodes from scope if the parent
+ // element is a group.
+ if ctx.groups.len() > 0 {
+ ctx.groups.last() += ctx.nodes.keys()
+ }
+ }
+
+ // Draw a debug bounding box.
+ if ctx.debug and bounds != none {
+ element.drawables.push(drawable.line-strip(
+ (bounds.low,
+ (bounds.high.at(0), bounds.low.at(1), 0.0),
+ bounds.high,
+ (bounds.low.at(0), bounds.high.at(1), 0.0)
+ ),
+ close: true,
+ stroke: red,
+ tags: (drawable.TAG.debug,)))
+ }
+
+ return (
+ ctx: ctx,
+ bounds: bounds,
+ drawables: element.at("drawables", default: ()),
+ )
+}
+
+/// Runs the `element` function for a list of element functions and aggregates the results.
+/// - ctx (ctx): The current context object.
+/// - body (array): The array of element functions to process.
+/// - compute-bounds (bool): Enable bounds computation.
+/// -> dictionary (ctx:, bounds:, drawables:)
+#let many(ctx, body, compute-bounds: true) = {
+ let drawables = ()
+ let bounds = none
+
+ for el in body {
+ let r = element(ctx, el, compute-bounds: compute-bounds)
+ if r != none {
+ bounds = aabb.merge(bounds, r.bounds)
+
+ ctx = r.ctx
+ drawables += r.drawables
+ }
+ }
+ return (ctx: ctx, bounds: bounds, drawables: drawables)
+}
diff --git a/render/packages/preview/cetz/0.5.2/src/sorting.typ b/render/packages/preview/cetz/0.5.2/src/sorting.typ
new file mode 100644
index 0000000..3778b8c
--- /dev/null
+++ b/render/packages/preview/cetz/0.5.2/src/sorting.typ
@@ -0,0 +1,29 @@
+#import "/src/vector.typ"
+#import "/src/util.typ"
+
+/// Sort list of points by distance to a
+/// reference point.
+///
+/// - points (array): List of points to sort
+/// - reference (vec): Reference point
+/// -> List of points
+#let points-by-distance(ctx, points, reference: (0, 0, 0)) = {
+ let reference = util.apply-transform(ctx.transform, reference)
+ return points.sorted(key: pt => {
+ vector.dist(pt, reference)
+ })
+}
+
+/// Sort list of 2D points by angle to a
+/// reference 2D point in CCW order.
+/// Z component is ignored.
+///
+/// - points (array): List of points to sort
+/// - reference (vec): Reference point
+/// -> List of points
+#let points-by-angle(ctx, points, reference: (0, 0, 0)) = {
+ let (rx, ry, ..) = util.apply-transform(ctx.transform, reference)
+ return points.sorted(key: ((px, py, ..)) => {
+ 360deg - calc.atan2(rx - px, ry - py)
+ })
+}
diff --git a/render/packages/preview/cetz/0.5.2/src/styles.typ b/render/packages/preview/cetz/0.5.2/src/styles.typ
new file mode 100644
index 0000000..89cd0bd
--- /dev/null
+++ b/render/packages/preview/cetz/0.5.2/src/styles.typ
@@ -0,0 +1,368 @@
+#import "util.typ"
+
+#let default = (
+ fill: none,
+ fill-rule: "non-zero",
+ stroke: (paint: black, thickness: 1pt),
+ radius: 1,
+ /// Bezier shortening mode:
+ /// - "LINEAR" Moving the affected point and it's next control point (like TikZ "quick" key)
+ /// - "CURVED" Preserving the bezier curve by calculating new control points
+ shorten: "LINEAR",
+
+ // Allowed values:
+ // - none
+ // - Number
+ // - Array: (y, x), (top, y, bottom), (top, right, bottom, left)
+ // - Dictionary: (top:, right:, bottom:, left:)
+ padding: none,
+ mark: (
+ scale: 1, // A factor that is applied to length, width, and inset.
+ length: .2cm, // The size of the mark along its direction
+ width: 0.15cm, // The size of the mark along the normal of its direction
+ inset: .05cm, // The inner length of some mark shapes, like triangles and brackets
+ sep: .1cm, // The distance between multiple marks along their path
+ pos: none, // Position override on the path (none, number or path-length ratio)
+ offset: 0, // Mark extra offset (number or path-length ratio)
+ start: none, // Mark start symbol(s)
+ end: none, // Mark end symbol(s)
+ symbol: none, // Mark symbol
+ xy-up: (0, 0, 1), // Up vector for 2D marks
+ z-up: (0, 1, 0), // Up vector for 3D marks
+ stroke: (dash: "solid"),
+ fill: auto,
+ slant: none, // Slant factor - 0%: no slant, 100%: 45 degree slant
+ harpoon: false,
+ flip: false,
+ reverse: false,
+ /// Max. number of samples to use for calculating curve positions
+ /// a higher number gives better results but may slow down compilation.
+ position-samples: 20,
+ /// Index of the mark the path should get shortened to, or auto
+ /// to shorten to the last mark. To apply different values per side,
+ /// set the default to `0` and to `auto` for the mark you want to
+ /// shorten the path to. Set to `none` to disable path shortening.
+ shorten-to: auto,
+ /// Apply shape transforms for marks. This is not honored per mark, but
+ /// for all marks on a path. If set to false, marks get placed after the
+ /// shape they are placed on got transformed, they appear "flat" or two-dimensional.
+ transform-shape: false,
+ /// Mark anchor used for placement
+ /// Possible values are:
+ /// - "tip"
+ /// - "center"
+ /// - "base"
+ anchor: "tip",
+ ),
+ circle: (
+ radius: auto,
+ stroke: auto,
+ fill: auto
+ ),
+ group: (
+ padding: auto,
+ fill: auto,
+ stroke: auto
+ ),
+ line: (
+ mark: auto,
+ fill: auto,
+ fill-rule: auto,
+ stroke: auto,
+ ),
+ bezier: (
+ stroke: auto,
+ fill: auto,
+ fill-rule: auto,
+ mark: auto,
+ shorten: auto,
+ ),
+ catmull: (
+ tension: .5,
+ mark: auto,
+ shorten: auto,
+ stroke: auto,
+ fill: auto,
+ fill-rule: auto,
+ ),
+ hobby: (
+ /// Curve start and end omega (curlyness)
+ omega: (0,0),
+ mark: auto,
+ shorten: auto,
+ stroke: auto,
+ fill: auto,
+ fill-rule: auto,
+ ),
+ boolean: (
+ stroke: auto,
+ fill: auto,
+ fill-rule: auto,
+ ),
+ rect: (
+ /// Rect corner radius that supports the following types:
+ /// - <radius>: Same x and y radius for all corners
+ /// - (west: <radius>, east: <radius>, north: <radius>, south: <radius>,
+ /// north-west: <radius>, north-east: <radius>, south-west: <radius>, south-east: <radius>,
+ /// rest: <radius: 0>)
+ ///
+ /// A radius can be either a number, a ratio or a tuple of numbers or ratios.
+ /// Ratios represent a value relative to the rects height or width.
+ /// E.g. the radius `50%` is equal to `(50%, 50%)` and represents a x and y radius
+ /// of 50% of the rects width/height.
+ radius: 0,
+ stroke: auto,
+ fill: auto,
+ ),
+ arc: (
+ // Supported values:
+ // - "OPEN"
+ // - "CLOSE"
+ // - "PIE"
+ mode: "OPEN",
+ update-position: true,
+ mark: auto,
+ stroke: auto,
+ fill: auto,
+ radius: auto
+ ),
+ polygon: (
+ radius: auto,
+ stroke: auto,
+ fill: auto,
+ fill-rule: auto,
+ ),
+ n-star: (
+ radius: auto,
+ inner-radius: 50%,
+ stroke: auto,
+ fill: auto,
+ // Connect inner points of the star
+ show-inner: false,
+ ),
+ content: (
+ padding: auto,
+ // Supported values
+ // - none
+ // - "rect"
+ // - "circle"
+ frame: none,
+ fill: auto,
+ stroke: auto,
+ // Apply canvas scaling to content
+ auto-scale: false,
+ // Function to apply to the content body. For example styling text
+ // via `wrap: text.with(red)`.
+ wrap: none,
+ ),
+)
+
+// Convert a stroke object to a dictionary
+#let _stroke-to-dict(s) = {
+ let t = type(s)
+ if t in (color, gradient, tiling) {
+ return (paint: s)
+ } else if t == length {
+ return (thickness: s)
+ } else if t == stroke {
+ return (
+ paint: s.paint,
+ thickness: s.thickness,
+ join: s.join,
+ cap: s.cap,
+ miter-limit: s.miter-limit,
+ dash: s.dash,
+ )
+ }
+ return (thickness: 0pt)
+}
+
+// This is a little hack to convert all
+// stroke compatible value with the key "stroke"
+// or all stroke values to dictionaries, so we
+// can properly merge them. Typst currently
+// does not support merging two stroke types and
+// also provides no easy method of constructing
+// complex stroke objects.
+#let _fix-types-recursive(dict) = {
+ let fix(dict) = {
+ for (key, value) in dict {
+ if value != auto {
+ if type(value) == std.stroke or (key == "stroke" and type(value) in (std.length, std.tiling, std.gradient, std.color)) {
+ dict.insert(key, _stroke-to-dict(value))
+ } else if type(value) == dictionary {
+ dict.insert(key, fix(value))
+ }
+ }
+ }
+ return dict
+ }
+ return fix(dict)
+}
+
+#let _fold-value(bottom, top, merge-dictionary-fn: util.merge-dictionary) = {
+ // Inherit base value
+ if top == auto {
+ return bottom
+ }
+
+ // Do not try to fold none values
+ if bottom == none or top == none {
+ return top
+ }
+
+ // Merge dictionaries
+ if type(bottom) == dictionary and type(top) == dictionary {
+ return merge-dictionary-fn(bottom, top)
+ }
+
+ return top
+}
+
+#let _at-root(style, root) = {
+ if root == () or root == none {
+ return none
+ }
+
+ for key in root {
+ style = style.at(key, default: none)
+ if style == none {
+ break
+ }
+ }
+
+ return style
+}
+
+/// You can use this to combine the style in `ctx`, the style given by a user for a single element and an element's default style.
+///
+/// `base` is first merged onto `dict` without overwriting existing values, and if `root` is given it is merged onto that key of `dict`. `merge` is then merged onto `dict` but does overwrite existing entries, if `root` is given it is merged onto that key of `dict`. Then entries in `dict` that are {{auto}} inherit values from their nearest ancestor and entries of type {{dictionary}} are merged with their closest ancestor.
+/// ```typ
+/// #let dict = (
+/// stroke: "black",
+/// fill: none,
+/// mark: (stroke: auto, fill: "blue"),
+/// line: (stroke: auto, mark: auto, fill: "red")
+/// )
+/// #cetz.styles.resolve(dict, merge: (mark: (stroke: "yellow")), root: "line")
+/// ```
+/// The following is a more detailed explanation of how the algorithm works to use as a reference if needed. It should be updated whenever changes are made.
+/// Remember that dictionaries are recursively merged, if an entry is any other type it is simply updated. (dict + dict = merged dict, value + dict = dict, dict + value = value)
+/// First if `base` is given, it will be merged without overwriting values onto `dict`. If `root` is given it will be merged onto that key of `dict`.
+/// Each level of `dict` is then processed with these steps. If `root` is given the level with that key will be the first, otherwise the whole of `dict` is processed.
+/// + Values on the corresponding level of `merge` are inserted into the level if the key does not exist on the level or if they are not both dictionaries. If they are both dictionaries their values will be inserted in the same stage at a lower level.
+/// + If an entry is `auto` or a dictionary, the tree is travelled back up until an entry with the same key is found. If the current entry is `auto` the value of the ancestor's entry is copied. Or if the current entry and ancestor entry is a dictionary, they are merged with the current entry overwriting any values in it's ancestors.
+/// + Each entry that is a dictionary is then resolved from step 1.
+///
+/// ```example
+/// get-ctx(ctx => {
+/// // Get the current "mark" style
+/// content((0,0), [#cetz.styles.resolve(ctx.style, root: "mark")])
+/// })
+/// ```
+///
+/// - dict (style): Current context style from `ctx.style`.
+/// - merge (style): Style values overwriting the current style. I.e. inline styles passed with an element: `line(.., stroke: red)`.
+/// - root (none, str, array): Style root element name or list of nested roots (`("my-package", "my-element")`).
+/// - base (none, style): Style values to merge into `dict` without overwriting it.
+/// -> style
+#let resolve(dict, root: (), merge: (:), base: (:)) = {
+ let root-dict = dict
+
+ if root == none {
+ root = ()
+ } else if type(root) != array {
+ root = (root,)
+ }
+
+ if root != () {
+ dict = _at-root(dict, root)
+ } else {
+ root-dict = none
+ }
+
+ let stack = (
+ root-dict, base, dict, merge,
+ ).filter(v => v != none and v != auto and v != (:))
+ .map(_fix-types-recursive)
+ .rev()
+
+ // Traverses upwards and folds values with parent values.
+ let traverse-up(key, stack) = {
+ let value = stack.first().at(key, default: auto)
+ for style in stack {
+ let root-style = _at-root(style, root)
+ if root-style != none and root-style != auto {
+ if type(root-style) == dictionary {
+ value = _fold-value(root-style.at(key, default: auto), value)
+ }
+ }
+ value = _fold-value(style.at(key, default: auto), value)
+ }
+ return value
+ }
+
+ // List of keys the final dictionary contains
+ let keys = (dict, base, merge)
+ .filter(v => v != none and v != auto)
+ .map(v => {
+ let keys = v.keys()
+ let root-style = _at-root(v, root)
+ if type(root-style) == dictionary {
+ keys += root-style.keys()
+ }
+ keys
+ })
+ .flatten()
+ .dedup()
+
+ // Recursively fold a dictionary
+ let fold-dict(dict) = {
+ let new-stack = (dict,) + stack
+ for (key, value) in dict {
+ value = traverse-up(key, new-stack)
+ if type(value) == dictionary and value != (:) {
+ value = fold-dict(value)
+ }
+ dict.insert(key, value)
+ }
+ return dict
+ }
+
+ let merged = (:)
+ for key in keys {
+ // Try resolve the value upwards
+ let value = traverse-up(key, stack)
+
+ // Recurse into dictionaries
+ if type(value) == dictionary {
+ value = fold-dict(value)
+ }
+ merged.insert(key, value)
+ }
+
+ return merged
+}
+
+/// Merge two style dictionaries by using cetz' style
+/// folding logic.
+///
+/// - bottom (dictionary) Base style dictionary.
+/// - top (dictionary) New style dictionary to merge on top of `bottom`.
+#let merge(bottom, top) = {
+ let merge-recursive(bottom, top) = {
+ for (k, v) in top {
+ // Fold if bottom is a dictionary _and_ v is not auto!
+ // Merging style dicts must preserve auto values.
+ if type(bottom) == dictionary and k in bottom and v != auto {
+ bottom.insert(k, _fold-value(bottom.at(k), v, merge-dictionary-fn: merge-recursive))
+ } else {
+ bottom.insert(k, v)
+ }
+ }
+ return bottom
+ }
+
+ return merge-recursive(_fix-types-recursive(bottom),
+ _fix-types-recursive(top))
+}
diff --git a/render/packages/preview/cetz/0.5.2/src/util.typ b/render/packages/preview/cetz/0.5.2/src/util.typ
new file mode 100644
index 0000000..63f7137
--- /dev/null
+++ b/render/packages/preview/cetz/0.5.2/src/util.typ
@@ -0,0 +1,411 @@
+#import "deps.typ"
+
+#import "matrix.typ"
+#import "vector.typ"
+#import "bezier.typ"
+
+/// Constant to be used as float rounding error
+#let float-epsilon = 0.000001
+
+/// Compare two floating point numbers
+/// - a (float): First number
+/// - b (float): Second number
+/// - epsilon (float): Maximum distance between both numbers
+/// -> bool
+#let float-eq(a, b, epsilon: float-epsilon) = {
+ return calc.abs(a - b) <= epsilon
+}
+
+/// Multiplies vectors by a transformation matrix. If multiple vectors are given they are returned as an array, if only one vector is given only one will be returned, if a dictionary is given they will be returned in the dictionary with the same keys.
+///
+/// - transform (matrix,function): The $4 times 4$ transformation matrix or a function that accepts and returns a vector.
+/// - ..vecs (vector): Vectors to get transformed. Only the positional part of the sink is used.
+/// -> vector
+/// -> array
+#let apply-transform(transform, ..vecs) = {
+ let t = if transform == none {
+ v => v
+ } else if type(transform) != function {
+ matrix.mul4x4-vec3.with(transform)
+ } else {
+ transform
+ }
+ if type(vecs.pos().first()) == dictionary {
+ vecs = vecs.pos().first()
+ for (k, vec) in vecs {
+ vecs.insert(k, t(vec))
+ }
+ } else {
+ vecs = vecs.pos().map(t)
+ if vecs.len() == 1 {
+ return vecs.first()
+ }
+ }
+ return vecs
+}
+
+/// Reverts the transform of the given vector
+///
+/// - transform (matrix): Transformation matrix
+/// - vec (vector): Vector to be transformed
+/// -> vector
+#let revert-transform(transform, ..vecs) = {
+ return apply-transform(matrix.inverse(transform), ..vecs)
+}
+
+/// Get orthogonal vector to line
+///
+/// - a (vector): Start point
+/// - b (vector): End point
+/// -> vector
+#let line-normal(a, b) = {
+ let v = vector.norm(vector.sub(b, a))
+ return (0 - v.at(1), v.at(0), v.at(2, default: 0))
+}
+
+/// Calculates the center of a circle from 3 points. The z coordinate is taken from point a.
+///
+/// - a (vector): Point 1
+/// - b (vector): Point 2
+/// - c (vector): Point 3
+/// -> vector
+#let calculate-circle-center-3pt(a, b, c) = {
+ let m-ab = vector.lerp(a, b, .5)
+ let m-bc = vector.lerp(b, c, .5)
+ let m-cd = vector.lerp(c, a, .5)
+
+ // If two of three points are the same,
+ // we already know the center.
+ if a == b {
+ return m-cd
+ } else if a == c {
+ return m-bc
+ } else if b == c {
+ return m-ab
+ }
+
+ let args = () // a, c, b, d
+ for i in range(0, 3) {
+ let (p1, p2) = ((a,b,c).at(calc.rem(i,3)),
+ (b,c,a).at(calc.rem(i,3)))
+ let m = vector.lerp(p1, p2, .5)
+ let n = line-normal(p1, p2)
+
+ // Find a line with a non upwards normal
+ if n.at(0) == 0 { continue }
+
+ let la = n.at(1) / n.at(0)
+ args.push(la)
+ args.push(m.at(1) - la * m.at(0))
+
+ // We need only 2 lines
+ if args.len() == 4 { break }
+ }
+
+ // Find intersection point of two 2d lines
+ // L1: a*x + c
+ // L2: b*x + d
+ let line-intersection-2d(a, c, b, d) = {
+ if a - b == 0 {
+ if c == d {
+ return (0, c, 0)
+ }
+ return none
+ }
+ let x = (d - c)/(a - b)
+ let y = a * x + c
+ return (x, y)
+ }
+
+ assert(args.len() == 4, message: "Could not find circle center")
+ return vector.as-vec(line-intersection-2d(..args), init: (0, 0, a.at(2)))
+}
+
+/// Converts a length to "canvas units"
+/// - ctx (context): The current context object.
+/// - num (number): The number to resolve.
+/// -> float or ratio
+#let resolve-number(ctx, num) = {
+ let t = type(num)
+ return if t == length {
+ float(num.to-absolute() / ctx.length)
+ } else if t == ratio {
+ num
+ } else {
+ float(num)
+ }
+}
+
+/// Call function `fn` for each key-value pair of `d`
+/// and return the transformed dictionary.
+///
+/// - d (dictionary) Input dictionary
+/// - fn (function) Transformation function
+/// -> dictionary
+#let map-dict(d, fn) = {
+ for ((key, value)) in d {
+ d.at(key) = fn(key, value)
+ }
+ return d
+}
+
+/// Ensures that a radius has an `x` and `y` component.
+/// - radius (number, array):
+/// -> array
+#let resolve-radius(radius) = {
+ return if type(radius) == array {radius} else {(radius, radius)}
+}
+
+/// Finds the minimum of a set of values while ignoring `none` values.
+/// - a (float,none):
+/// -> float
+#let min(..a) = {
+ let a = a.pos().filter(v => v != none)
+ return calc.min(..a)
+}
+
+/// Finds the maximum of a set of values while ignoring `none` values.
+/// - ..a (float,none):
+/// -> float
+#let max(..a) = {
+ let a = a.pos().filter(v => v != none)
+ return calc.max(..a)
+}
+
+/// Merges dictionary `b` onto dictionary `a`. If a key does not exist in `a` but does in `b`, it is inserted into `a` with `b`'s value. If a key does exist in `a` and `b`, the value in `b` is only inserted into `a` if the `overwrite` argument is `true`. If a key does exist both in `a` and `b` and both values are of type {{dictionary}} they will be recursively merged with this same function.
+///
+/// - a (dictionary): Dictionary a
+/// - b (dictionary): Dictionary b
+/// - overwrite (bool): Whether to override an entry in `a` that also exists in `b` with the value in `b`.
+/// -> dictionary
+#let merge-dictionary(a, b, overwrite: true) = {
+ for (k, v) in b {
+ if type(a) == dictionary and k in a and type(v) == dictionary and type(a.at(k)) == dictionary {
+ a.insert(k, merge-dictionary(a.at(k), v, overwrite: overwrite))
+ } else if overwrite or k not in a {
+ a.insert(k, v)
+ }
+ }
+ return a
+}
+
+/// Measures the size of some {{content}} in canvas coordinates.
+/// - ctx (context): The current context object.
+/// - cnt (content): The content to measure.
+/// -> vector
+#let measure(ctx, cnt) = {
+ let size = std.measure(cnt)
+ return (
+ calc.abs(size.width / ctx.length),
+ calc.abs(size.height / ctx.length)
+ )
+}
+
+/// Get a padding/margin dictionary with keys `(top, left, bottom, right)` from a padding value.
+///
+///
+/// Type of `padding`:
+/// / `none`: All sides padded by 0
+/// / `number`: All sides are padded by the same value
+/// / `array`: CSS like padding: `(y, x)`, `(top, x, bottom)` or `(top, right, bottom, left)`
+/// / `dictionary`: Converts a Typst padding dictionary (top, left, bottom, right, x, y, rest) to a dictionary containing top, left, bottom and right.
+///
+/// - padding (none, number, array, dictionary): Padding specification
+/// -> dictionary
+#let as-padding-dict(padding) = {
+ if padding == none {
+ padding = 0
+ }
+
+ if type(padding) == array {
+ // Allow CSS like padding array
+ assert(padding.len() in (2, 3, 4),
+ message: "Padding array formats are: (y, x), (top, x, bottom), (top, right, bottom, left)")
+ if padding.len() == 2 {
+ let (y, x) = padding
+ return (top: y, right: x, bottom: y, left: x)
+ } else if padding.len() == 3 {
+ let (top, x, bottom) = padding
+ return (top: top, right: x, bottom: bottom, left: x)
+ } else if padding.len() == 4 {
+ let (top, right, bottom, left) = padding
+ return (top: top, right: right, bottom: bottom, left: left)
+ }
+ } else if type(padding) == dictionary {
+ // Support typst padding dictionary
+ let rest = padding.at("rest", default: 0)
+ let x = padding.at("x", default: rest)
+ let y = padding.at("y", default: rest)
+ if not "left" in padding { padding.left = x }
+ if not "right" in padding { padding.right = x }
+ if not "top" in padding { padding.top = y }
+ if not "bottom" in padding { padding.bottom = y }
+
+ return padding
+ } else {
+ return (top: padding, left: padding, bottom: padding, right: padding)
+ }
+}
+
+/// Creates a corner-radius dictionary with keys `north-east`, `north-west`, `south-east` and `south-west` with values of a two element {{array}} of the radius in the `x` and `y` direction. Returns none if all radii are zero or none.
+///
+/// - ctx (context): The current canvas context object
+/// - radii (none, number, dictionary): The radius specification. A {{number}} will cause all corners to have the same radius. An {{array}} with two items will cause all corners to have the same rx and ry radius. A {{dictionary}} can be given where the key specifies the corner and the value specifies the radius. The value can be either {{number}} for a circle radius or {{array}} for an x and y radius. The keys `north`, `south`, `east` and `west` targets both corners in that cardinal direction e.g. `south` sets the south west and south east corners. The keys `north-east`, `north-west`, `south-east` and `south-west` targets the corresponding corner. The key `rest` targets all other corners that have not been target by other keys.
+/// - size (none, array): Tuple of type:number used to clamp the corner radii
+/// -> dictionary
+#let as-corner-radius-dict(ctx, radii, size) = {
+ if radii == none or radii == 0 {
+ return (north-west: (0,0), north-east: (0,0),
+ south-west: (0,0), south-east: (0,0))
+ }
+
+ let radii = (if type(radii) == dictionary {
+ let rest = radii.at("rest", default: (0,0))
+ let north = radii.at("north", default: auto)
+ let south = radii.at("south", default: auto)
+ let west = radii.at("west", default: auto)
+ let east = radii.at("east", default: auto)
+
+ if north != auto or south != auto {
+ assert(west == auto and east == auto,
+ message: "Corner radius north/south and west/east are mutually exclusive! Use per corner radii: north-west, .. instead.")
+ }
+ if west != auto or east != auto {
+ assert(north == auto and south == auto,
+ message: "Corner radius north/south and west/east are mutually exclusive! Use per corner radii: north-west, .. instead.")
+ }
+
+ let north-east = if north != auto { north } else if east != auto { east } else {rest}
+ let north-west = if north != auto { north } else if west != auto { west } else {rest}
+ let south-east = if south != auto { south } else if east != auto { east } else {rest}
+ let south-west = if south != auto { south } else if west != auto { west } else {rest}
+
+ (radii.at("north-west", default: north-west),
+ radii.at("north-east", default: north-east),
+ radii.at("south-west", default: south-west),
+ radii.at("south-east", default: south-east))
+ } else if type(radii) == array {
+ panic("Invalid corner radius type: " + type(radii))
+ } else {
+ (radii, radii, radii, radii)
+ }).map(v => if type(v) != array { (v, v) } else { v })
+
+ // Resolve lengths to floats
+ radii = radii.map(t => t.map(resolve-number.with(ctx)))
+
+ // Clamp radii to half the size
+ if size != none {
+ radii = radii.map(t => t.enumerate().map(((i, v)) => {
+ calc.max(0, calc.min(if type(v) == ratio {
+ v * size.at(i) / 100%
+ } else { v }, size.at(i) / 2))
+ }))
+ }
+
+ let (nw, ne, sw, se) = radii
+ return (
+ north-west: nw,
+ north-east: ne,
+ south-west: sw,
+ south-east: se,
+ )
+}
+
+/// Sorts an array of vectors by distance to a common position.
+/// - base (vector): The position to measure the distance of the other vectors from.
+/// - pts (array): The array of vectors to sort.
+/// -> array
+#let sort-points-by-distance(base, pts) = {
+ if pts.len() == 1 {
+ return pts
+ }
+
+ // Sort by transforming points into tuples of (point, distance),
+ // sorting them by key 1 and then transforming them back to points.
+ return pts.map(p => {
+ return (p, vector.dist(p, base))
+ })
+ .sorted(key: t => t.at(1))
+ .map(t => t.at(0))
+}
+
+/// Resolves a stroke into a usable dictionary with all fields that are missing or auto set to their Typst defaults.
+/// - stroke (none, stroke): The stroke to resolve.
+/// -> dictionary
+#let resolve-stroke(stroke) = {
+ if stroke == none {
+ return (paint: auto, thickness: 0pt, join: auto, cap: auto, miter-limit: 4)
+ }
+
+ if type(stroke) in (std.color, std.length) {
+ stroke = std.stroke(stroke)
+ }
+
+ if type(stroke) == std.stroke {
+ stroke = (
+ paint: stroke.paint,
+ thickness: stroke.thickness,
+ join: stroke.join,
+ cap: stroke.cap,
+ miter-limit: stroke.miter-limit,
+ dash: stroke.dash,
+ )
+ }
+
+ let or-default(key, default) = {
+ let v = stroke.at(key, default: default)
+ return if v == auto { default } else { v }
+ }
+
+ return (
+ paint: or-default("paint", black),
+ thickness: or-default("thickness", 1pt),
+ join: or-default("join", "miter"),
+ cap: or-default("cap", "butt"),
+ miter-limit: or-default("miter-limit", 4),
+ dash: or-default("dash", none),
+ )
+}
+
+/// Asserts whether a "body" has the correct type.
+#let assert-body(body) = {
+ assert(body == none or type(body) in (array, function),
+ message: "Body must be of type none, array or function")
+}
+
+// Returns body if of type array, an
+// empty array if body is none or
+// the result of body called with ctx if of type
+// function. A function result of none will return
+// an empty array.
+#let resolve-body(ctx, body) = {
+ if type(body) == function {
+ body = body(ctx)
+ }
+ if body == none {
+ body = ()
+ }
+ return body
+}
+
+
+#let str-to-number-regex = regex("^(-?\d*\.?\d+)(cm|mm|pt|em|in|%|deg|rad)?$")
+#let number-units = (
+ "%": 1%,
+ "cm": 1cm,
+ "mm": 1mm,
+ "pt": 1pt,
+ "em": 1em,
+ "in": 1in,
+ "deg": 1deg,
+ "rad": 1rad
+)
+#let str-is-number(string) = string.match(str-to-number-regex) != none
+#let str-to-number(string) = {
+ let (num, unit) = string.match(str-to-number-regex).captures
+ num = float(num)
+ if unit != none and unit in number-units {
+ num *= number-units.at(unit)
+ }
+ return num
+}
diff --git a/render/packages/preview/cetz/0.5.2/src/vector.typ b/render/packages/preview/cetz/0.5.2/src/vector.typ
new file mode 100644
index 0000000..c3fb32e
--- /dev/null
+++ b/render/packages/preview/cetz/0.5.2/src/vector.typ
@@ -0,0 +1,279 @@
+/// Converts a vector to a row or column matrix.
+///
+/// - v (vector): The vector to convert.
+/// - mode (str): The type of matrix to convert into. Must be one of `"row"` or `"column"`.
+/// -> matrix
+#let as-mat(v, mode: "row") = {
+ if mode == "column" {
+ return (v,)
+ } else if mode == "row" {
+ return (for c in v { (c,) },)
+ } else {
+ panic("Invalid mode " + mode)
+ }
+}
+
+/// Ensures a vector has an exact number of components. This is done by passing another vector `init` that has the required dimension. If the original vector does not have enough dimensions, the values from `init` will be inserted. It is recommended to use a zero vector for `init`.
+///
+/// - v (vector): The vector to ensure.
+/// - init (vector): The vector to check the dimension against.
+/// -> vector
+#let as-vec(v, init: (0, 0, 0)) = {
+ let l = init.len()
+ if l == 2 {
+ return (v.at(0, default: init.at(0)), v.at(1, default: init.at(1)))
+ } else if l == 3 {
+ return (
+ v.at(0, default: init.at(0)),
+ v.at(1, default: init.at(1)),
+ v.at(2, default: init.at(2)),
+ )
+ } else if l == 4 {
+ return (
+ v.at(0, default: init.at(0)),
+ v.at(1, default: init.at(1)),
+ v.at(2, default: init.at(2)),
+ v.at(3, default: init.at(3)),
+ )
+ }
+ let limit = calc.min(v.len(), l)
+ for i in range(0, limit) {
+ init.at(i) = v.at(i)
+ }
+ init
+}
+
+
+/// Return length/magnitude of a vector.
+///
+/// - v (vector): The vector to find the magnitude of.
+/// -> float
+#let len(v) = {
+ let l = v.len()
+ if l == 2 {
+ let x = v.at(0)
+ let y = v.at(1)
+ return calc.sqrt(x * x + y * y)
+ } else if l == 3 {
+ let x = v.at(0)
+ let y = v.at(1)
+ let z = v.at(2)
+ return calc.sqrt(x * x + y * y + z * z)
+ }
+ calc.sqrt(v.fold(0, (s, c) => s + c * c))
+}
+
+/// Adds two vectors of the same dimension
+///
+/// - v1 (vector): The vector on the left hand side.
+/// - v2 (vector): The vector on the right hand side.
+/// -> vector
+#let add(v1, v2) = {
+ let l1 = v1.len()
+ let l2 = v2.len()
+ let l = calc.max(l1, l2)
+ if l == 2 {
+ return (
+ v1.at(0, default: 0) + v2.at(0, default: 0),
+ v1.at(1, default: 0) + v2.at(1, default: 0),
+ )
+ } else if l == 3 {
+ return (
+ v1.at(0, default: 0) + v2.at(0, default: 0),
+ v1.at(1, default: 0) + v2.at(1, default: 0),
+ v1.at(2, default: 0) + v2.at(2, default: 0),
+ )
+ }
+ range(0, l).map(i => v1.at(i, default: 0) + v2.at(i, default: 0))
+}
+
+/// Subtracts two vectors of the same dimension
+///
+/// - v1 (vector): The vector on the left hand side.
+/// - v2 (vector): The vector on the right hand side.
+/// -> vector
+#let sub(v1, v2) = {
+ let l1 = v1.len()
+ let l2 = v2.len()
+ let l = calc.max(l1, l2)
+ if l == 2 {
+ return (
+ v1.at(0, default: 0) - v2.at(0, default: 0),
+ v1.at(1, default: 0) - v2.at(1, default: 0),
+ )
+ } else if l == 3 {
+ return (
+ v1.at(0, default: 0) - v2.at(0, default: 0),
+ v1.at(1, default: 0) - v2.at(1, default: 0),
+ v1.at(2, default: 0) - v2.at(2, default: 0),
+ )
+ }
+ range(0, l).map(i => v1.at(i, default: 0) - v2.at(i, default: 0))
+}
+
+/// Calculates the distance between two vectors by subtracting the length of vector `a` from vector `b`.
+///
+/// - a (vector): Vector a
+/// - b (vector): Vector b
+/// -> float
+#let dist(a, b) = {
+ let l = calc.max(a.len(), b.len())
+ if l == 2 {
+ let dx = b.at(0, default: 0) - a.at(0, default: 0)
+ let dy = b.at(1, default: 0) - a.at(1, default: 0)
+ return calc.sqrt(dx * dx + dy * dy)
+ } else if l == 3 {
+ let dx = b.at(0, default: 0) - a.at(0, default: 0)
+ let dy = b.at(1, default: 0) - a.at(1, default: 0)
+ let dz = b.at(2, default: 0) - a.at(2, default: 0)
+ return calc.sqrt(dx * dx + dy * dy + dz * dz)
+ }
+ len(sub(b, a))
+}
+
+/// Multiplys a vector with scalar `x`
+/// - v (vector): The vector to scale.
+/// - x (float): The scale factor.
+/// -> vector
+#let scale(v, x) = {
+ let l = v.len()
+ if l == 2 {
+ return (v.at(0) * x, v.at(1) * x)
+ } else if l == 3 {
+ return (v.at(0) * x, v.at(1) * x, v.at(2) * x)
+ }
+ v.map(s => s * x)
+}
+
+/// Divides a vector by scalar `x`
+/// - v (vector): The vector to be divded.
+/// - x (float): The inverse scale factor.
+#let div(v, x) = {
+ let inv = 1 / x
+ let l = v.len()
+ if l == 2 {
+ return (v.at(0) * inv, v.at(1) * inv)
+ } else if l == 3 {
+ return (v.at(0) * inv, v.at(1) * inv, v.at(2) * inv)
+ }
+ v.map(s => s * inv)
+}
+
+/// Negates each value in a vector
+/// - v (vector): The vector to negate.
+/// -> vector
+#let neg(v) = scale(v, -1)
+
+/// Normalizes a vector (divide by its length)
+/// - v (vector): The vector to normalize.
+/// -> vector
+#let norm(v) = {
+ let l = v.len()
+ if l == 2 {
+ let x = v.at(0)
+ let y = v.at(1)
+ let inv = 1 / calc.sqrt(x * x + y * y)
+ return (x * inv, y * inv)
+ } else if l == 3 {
+ let x = v.at(0)
+ let y = v.at(1)
+ let z = v.at(2)
+ let inv = 1 / calc.sqrt(x * x + y * y + z * z)
+ return (x * inv, y * inv, z * inv)
+ }
+ div(v, len(v))
+}
+
+/// Multiply two vectors component-wise
+/// - a (vector): First vector.
+/// - b (vector): Second vector.
+#let element-product(a, b) = {
+ let l = a.len()
+ range(l).map(i => a.at(i) * b.at(i))
+}
+
+/// Calculates the dot product between two vectors.
+/// - v1 (vector): The vector on the left hand side.
+/// - v2 (vector): The vector on the right hand side.
+/// -> float
+#let dot(v1, v2) = {
+ let l = v1.len()
+ assert(l == v2.len())
+ if l == 2 {
+ return v1.at(0) * v2.at(0) + v1.at(1) * v2.at(1)
+ } else if l == 3 {
+ return v1.at(0) * v2.at(0) + v1.at(1) * v2.at(1) + v1.at(2) * v2.at(2)
+ }
+ range(l).fold(0, (s, i) => s + v1.at(i) * v2.at(i))
+}
+
+/// Calculates the cross product of two vectors with a dimension of three.
+/// - v1 (vector): The vector on the left hand side.
+/// - v2 (vector): The vector on the right hand side.
+/// -> vector
+#let cross(v1, v2) = {
+ assert(v1.len() == 3 and v2.len() == 3)
+
+ let (x1, y1, z1) = v1
+ let (x2, y2, z2) = v2
+
+ return (y1 * z2 - z1 * y2, z1 * x2 - x1 * z2, x1 * y2 - y1 * x2)
+}
+
+/// Calculates the angle between two vectors and the x-axis in 2d space
+/// - a (vector): The vector to measure the angle from.
+/// - b (vector): The vector to measure the angle to.
+/// -> angle
+#let angle2(a, b) = {
+ // Typst's atan2 is (x, y) order, not (y, x)
+ return calc.atan2(b.at(0) - a.at(0), b.at(1) - a.at(1))
+}
+
+/// Calculates the angle between three vectors
+/// - v1 (vector): The vector to measure the angle from.
+/// - c (vector): The vector to measure the angle at.
+/// - v2 (vector): The vector to measure the angle to.
+#let angle(v1, c, v2) = {
+ if v1.len() != v2.len() {
+ panic("Vectors " + repr(v1) + " and " + repr(v2) + " do not have the same dimensions.")
+ }
+
+ if v1.len() == 2 or v1.len() == 3 {
+ v1 = sub(v1, c)
+ v2 = sub(v2, c)
+ let ip = dot(norm(v1), norm(v2))
+ return calc.acos(calc.clamp(ip, -1, 1))
+ } else {
+ panic("Invalid vector dimension")
+ }
+}
+
+/// Linear interpolation between two vectors.
+/// - v1 (vector): The vector to interpolate from.
+/// - v2 (vector): The vector to interpolate to.
+/// - t (float): The factor to interpolate by. A value of `0` is `v1` and a value of `1` is `v2`.
+#let lerp(v1, v2, t) = {
+ let l1 = v1.len()
+ let l2 = v2.len()
+ let l = if l1 > l2 { l1 } else { l2 }
+ if l == 2 {
+ let a0 = v1.at(0, default: 0)
+ let a1 = v1.at(1, default: 0)
+ let b0 = v2.at(0, default: 0)
+ let b1 = v2.at(1, default: 0)
+ return (a0 + (b0 - a0) * t, a1 + (b1 - a1) * t)
+ } else if l == 3 {
+ let a0 = v1.at(0, default: 0)
+ let a1 = v1.at(1, default: 0)
+ let a2 = v1.at(2, default: 0)
+ let b0 = v2.at(0, default: 0)
+ let b1 = v2.at(1, default: 0)
+ let b2 = v2.at(2, default: 0)
+ return (
+ a0 + (b0 - a0) * t,
+ a1 + (b1 - a1) * t,
+ a2 + (b2 - a2) * t,
+ )
+ }
+ add(v1, scale(sub(v2, v1), t))
+}
diff --git a/render/packages/preview/cetz/0.5.2/src/version.typ b/render/packages/preview/cetz/0.5.2/src/version.typ
new file mode 100644
index 0000000..da052ac
--- /dev/null
+++ b/render/packages/preview/cetz/0.5.2/src/version.typ
@@ -0,0 +1 @@
+#let version = version(0,5,2)
diff --git a/render/packages/preview/cetz/0.5.2/src/wasm.typ b/render/packages/preview/cetz/0.5.2/src/wasm.typ
new file mode 100644
index 0000000..539c407
--- /dev/null
+++ b/render/packages/preview/cetz/0.5.2/src/wasm.typ
@@ -0,0 +1,11 @@
+/// These functions are not in `util.typ` to avoid circular imports.
+
+/// Call a wasm function with the given arguments and return the result.
+///
+/// - func (function): The wasm function to call.
+/// - args (dictionary): The arguments to pass to the function.
+/// -> any
+#let call_wasm(func, args) = {
+ let encoded = cbor.encode(args)
+ cbor(func(encoded))
+}
diff --git a/render/packages/preview/cetz/0.5.2/typst.toml b/render/packages/preview/cetz/0.5.2/typst.toml
new file mode 100644
index 0000000..472ef21
--- /dev/null
+++ b/render/packages/preview/cetz/0.5.2/typst.toml
@@ -0,0 +1,16 @@
+[package]
+name = "cetz"
+version = "0.5.2"
+compiler = "0.14.0"
+repository = "https://github.com/cetz-package/cetz"
+homepage = "https://cetz-package.github.io/"
+entrypoint = "src/lib.typ"
+authors = [
+ "Johannes Wolf <https://github.com/johannes-wolf>",
+ "fenjalien <https://github.com/fenjalien>"
+]
+categories = [ "visualization" ]
+license = "LGPL-3.0-or-later"
+description = "Drawing with Typst made easy, providing an API inspired by TikZ and Processing."
+keywords = [ "draw", "canvas", "tree" ]
+exclude = [ "/gallery/*", "manual.pdf", "manual.typ" ]
diff --git a/render/packages/preview/cmarker/0.1.6/LICENSE b/render/packages/preview/cmarker/0.1.6/LICENSE
new file mode 100644
index 0000000..6be1b0d
--- /dev/null
+++ b/render/packages/preview/cmarker/0.1.6/LICENSE
@@ -0,0 +1,7 @@
+Copyright 2023 Sabrina Jewson
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/render/packages/preview/cmarker/0.1.6/README.md b/render/packages/preview/cmarker/0.1.6/README.md
new file mode 100644
index 0000000..cfe58a8
--- /dev/null
+++ b/render/packages/preview/cmarker/0.1.6/README.md
@@ -0,0 +1,513 @@
+<!--typst-begin-exclude-->
+
+# cmarker
+<!--typst-end-exclude-->
+
+This package enables you to write CommonMark Markdown,
+and import it directly into Typst.
+
+<table>
+<tr>
+<th><code>simple.typ</code></th>
+<th><code>simple.md</code></th>
+</tr>
+<tr>
+<td>
+
+```typst
+#import "@preview/cmarker:0.1.6"
+
+#cmarker.render(read("simple.md"))
+```
+</td>
+<td>
+
+```markdown
+# We can write Markdown!
+
+*Using* __lots__ ~of~ `fancy` [features](https://example.org/).
+```
+</td>
+</tr>
+</table>
+<table>
+<tr><th><code>simple.pdf</code></th></tr>
+<tr><td><img src="./examples/simple.png"></td></tr>
+</table>
+
+This document is available
+in [Markdown](https://github.com/SabrinaJewson/cmarker.typ/tree/main#cmarker)
+and [rendered PDF](https://github.com/SabrinaJewson/cmarker.typ/blob/main/README.pdf)
+formats.
+
+## API
+
+We offer a single function:
+
+```typc
+render(
+ markdown,
+ smart-punctuation: true,
+ math: none,
+ h1-level: 1,
+ raw-typst: true,
+ html: (:),
+ label-prefix: "",
+ prefix-label-uses: true,
+ scope: (:),
+ show-source: false,
+ blockquote: none,
+) -> content
+```
+
+The parameters are as follows:
+- `markdown`:
+ The [CommonMark](https://spec.commonmark.org/0.30/) Markdown string to be processed.
+ Parsed with the [pulldown-cmark](https://docs.rs/pulldown-cmark) Rust library.
+ You can set this to `read("somefile.md")` to import an external markdown file;
+ see the
+ [documentation for the read function](https://typst.app/docs/reference/data-loading/read/).
+ - Accepted values: Strings and raw text code blocks.
+ - Required.
+
+- `smart-punctuation`:
+ Automatically convert ASCII punctuation to Unicode equivalents:
+ - nondirectional quotations (" and ') become directional (“” and ‘’);
+ - three consecutive full stops (...) become ellipses (…);
+ - two and three consecutive hypen-minus signs (-- and ---)
+ become en and em dashes (– and —).
+
+ Note that although Typst also offers this functionality,
+ this conversion is done through the Markdown parser rather than Typst.
+ - Accepted values: Booleans.
+ - Default value: `true`.
+
+- `math`:
+ A callback to be used when equations are encountered in the Markdown,
+ or `none` if it should be treated as normal text.
+ Because Typst does not support LaTeX equations natively,
+ the user must configure this.
+ - Accepted values:
+ Functions that take a boolean argument named `block` and a positional string argument
+ (often, the `mitex` function from
+ [the mitex package](https://typst.app/universe/package/mitex)),
+ or `none`.
+ - Default value: `none`.
+
+ For example, to render math equation as a Typst math block,
+ one can use:
+ ```typst
+ #import "@preview/mitex:0.2.4": mitex
+ #cmarker.render(`$\int_1^2 x \mathrm{d} x$`, math: mitex)
+ ```
+ <!--raw-typst
+ which renders as: $integral_1^2 x dif x$
+ -->
+
+- `h1-level`:
+ The level that top-level headings in Markdown should get in Typst.
+ When set to zero,
+ top-level headings are treated as text,
+ `##` headings become `=` headings,
+ `###` headings become `==` headings,
+ et cetera;
+ when set to `2`,
+ `#` headings become `==` headings,
+ `##` headings become `===` headings,
+ et cetera.
+ - Accepted values: Integers in the range [0, 255].
+ - Default value: 1.
+
+- `raw-typst`:
+ Whether to allow raw Typst code to be injected into the document via HTML comments.
+ If disabled, the comments will act as regular HTML comments.
+ - Accepted values: Booleans.
+ - Default value: `true`.
+
+ For example, when this is enabled, `<!--raw-typst #circle(radius: 10pt) -->`
+ will result in a circle in the document
+ (but only when rendered through Typst).
+ See also `<!--typst-begin-exclude-->` and `<!--typst-end-exclude-->`,
+ which is the inverse of this.
+
+- `html`:
+ The dictionary of HTML elements that cmarker will support.
+ - Accepted values:
+ Dictionaries whose keys are the tag name (without the surrounding `<>`)
+ and whose values can be:
+ - `("normal", (attrs, body) => [/* … */])`:
+ Defines a normal element,
+ where `attrs` is a dictionary of strings, `body` is content,
+ and the function returns content.
+ - `("void", (attrs) => [/* … */])`:
+ Defines a void element (e.g. `<br>`, `<img>`, `<hr>`).
+ - `("raw-text", (attrs, body) => [/* … */])`:
+ Defines a raw text element (e.g. `<script>`, `<style>`),
+ where `body` is a string.
+ - `("escapable-raw-text", (attrs, body) => [/* … */])`:
+ Defines an escapable raw text element (e.g. `<textarea>`),
+ where `body` is a string.
+ - `(attrs, body) => [/* … */]`: Shorthand for
+ `("normal", (attrs, body) => [/* … */])`.
+ - Default value: `(:)`.
+ - Overridable keys:
+ The following HTML elements are provided by default,
+ but you are free to override them:
+ `<sub>`,
+ `<sup>`,
+ `<mark>`,
+ `<h1>`–`<h6>`,
+ `<ul>`,
+ `<ol>`,
+ `<li>`,
+ `<dl>`,
+ `<dt>`,
+ `<dd>`,
+ `<table>`,
+ `<thead>`,
+ `<tfoot>`,
+ `<tr>`,
+ `<th>`,
+ `<td>`,
+ `<hr>`,
+ `<a>`,
+ `<em>`,
+ `<strong>`,
+ `<s>`,
+ `<code>`,
+ `<br>`,
+ `<blockquote>`,
+ `<figure>`,
+ `<figcaption>`,
+ `<img>`.
+
+ For example, the following code
+ would allow you to write `<circle radius="25">` to render a 25pt circle:
+
+ ```typst
+ #cmarker.render(read("input.md"), html: (
+ circle: ("void", attrs => circle(radius: int(attrs.radius) * 1pt))
+ ))
+ ```
+
+- `label-prefix`:
+ If present, any labels autogenerated by footnotes and headings will be prefixed by this string.
+ This is useful to avoid collisions.
+ - Accepted values: A valid label or the empty string.
+ - Default value: The empty string.
+
+- `prefix-label-uses`:
+ Whether references to labels such as `[@label]` and `[link](#label)`
+ should be prefixed by `label-prefix`.
+ - Accepted values: Booleans.
+ - Default value: `true`.
+
+- `scope`:
+ A dictionary providing the context in which the evaluated Typst code runs.
+ It is useful to pass values in to code inside `<!--raw-typst-->` blocks,
+ but can also be used to override element functions generated by cmarker itself.
+ - Accepted values: Any dictionary.
+ - Default value: `(:)`.
+ - Overridable keys:
+ - All built-in Typst functions.
+ - `rule`:
+ Expected to be a function returning content.
+ Will be used when thematic breaks (`---` in Markdown) are encountered.
+ Defaults to `line.with(length: 100%)`.
+
+- `show-source`:
+ A debugging tool.
+ When set to `true`, the Typst code that would otherwise have been displayed
+ will be instead rendered in a code block.
+ - Accepted values: Booleans.
+ - Default value: `false`.
+
+- `blockquote`:
+ Deprecated!
+ This used to control how blockquotes were rendered,
+ but we now default to `quote(block: true)`.
+ If you want to override how blockquotes look,
+ either use `#show quote.where(block: true)`
+ or use `scope: (quote: …)`.
+ - Accepted values: Functions accepting content and returning content, or `none`.
+ - Default value: `none`.
+
+This function returns the rendered `content`.
+
+## Resolving Paths Correctly
+
+Because of how Typst handles paths,
+elements like images will by default resolve
+relative to the project root of `cmarker` itself
+and not your project.
+
+To fix this,
+one can override the `image` function in the scope the Typst code is evaluated.
+
+```typst
+#import "@preview/cmarker:0.1.6"
+
+#cmarker.render(
+ read("yourfile.md"),
+ scope: (image: (path, alt: none) => image(path, alt: alt))
+)
+```
+
+## References, Labels, Figures and Citations
+
+`cmarker.typ` integrates well with Typst’s native references and labels.
+Where in Typst you would write `@foo`, in Markdown you write `[@foo]`;
+where in Typst you would write `@foo[Chapter]`, in Markdown you’d write `[Chapter][@foo]`.
+You can also write `[some text](#foo)` to have “some text” be a link that points at `foo`.
+Headings are automatically given references according to their name,
+but lowercased and with spaces replaced by hyphens:
+
+```md
+# My nice heading
+
+We can make a link to [this section](#my-nice-heading).
+We can refer you to [@my-nice-heading]. <!-- generates “We can refer you to Section 1.” -->
+Or to [Chapter][@my-nice-heading]. <!-- generates “We can refer you to Chapter 1.” -->
+```
+
+If you have two headings with the same title,
+they’ll be numbered sequentially in the fashion of GitHub Markdown:
+`heading`, `heading-1`, `heading-2`, etc.
+
+If you want to cite something from a bibliography,
+you can do it much the same way: `[@citation]`.
+
+If you want to customize the label of a heading from the default,
+you can use `id=` in HTML:
+
+```md
+<h1 id="my-nice-section">My nice heading</h1>
+
+See [@my-nice-section]. <!-- generates “See Section 1.” -->
+```
+
+This can also be used with figures, which is very powerful:
+
+```md
+Please refer to [@my-graph]. <!-- generates “Please refer to Figure 1.” -->
+
+<figure id="my-graph">
+
+![a graph](graph.png)</figure>
+```
+
+If you encounter collision errors across multiple Markdown files,
+you can set the `label-prefix` option.
+For example, setting
+`label-prefix: "file-a-"` will convert the label of
+`# My Heading` into `file-a-my-heading`.
+By default, references within the file will expect the unprefixed name;
+this can be changed by setting `prefix-label-uses: false`.
+
+## Supported Markdown Syntax
+
+We support CommonMark with a couple extensions.
+
+- Paragraph breaks: Two newlines, i.e. one blank line.
+- Hard line breaks (used more in poetry than prose):
+ Put two spaces at the end of the line.
+- `*emphasis*` or `_emphasis_`: *emphasis*
+- `**strong**` or `__strong__`: **strong**
+- `~strikethrough~`: ~strikethrough~
+- `[links](https://example.org)`: [links](https://example.org/)
+- `### Headings`, where `#` is a top-level heading,
+ `##` a subheading, `###` a sub-subheading, etc
+- `` `inline code blocks` ``: `inline code blocks`
+-
+ ````
+ ```
+ out of line code blocks
+ ```
+ ````
+ Syntax highlighting can be achieved by specifying a language after the opening backticks:
+ ````
+ ```rust
+ let x = 5;
+ ```
+ ````
+ giving:
+ ```rust
+ let x = 5;
+ ```
+- `---`, making a horizontal rule.
+ This corresponds to the Typst code `#rule()`,
+ which, if not overridden by the `scope` parameter,
+ defaults to `#line(length: 100%)`:
+
+ ---
+-
+ ```md
+ - Unordered
+ - lists
+ ```
+ - Unordered
+ - Lists
+-
+ ```md
+ 1. Ordered
+ 1. Lists
+ ```
+ 1. Ordered
+ 1. Lists
+- `$x + y$` or `$$x + y$$`: math equations, if the `math` parameter is set.
+- `> blockquotes`, if the `blockquote` parameter is set.
+- Images: `![Some tiled hexagons](examples/hexagons.png)`, giving
+ ![Some tiled hexagons](examples/hexagons.png)
+- Tables:
+ ```md
+ | Column 1 | Column 2 |
+ | -------- | -------- |
+ | Row 1 Cell 1 | Row 1 Cell 2 |
+ | Row 2 Cell 1 | Row 2 Cell 2 |
+ ```
+
+| Column 1 | Column 2 |
+| -------- | -------- |
+| Row 1 Cell 1 | Row 1 Cell 2 |
+| Row 2 Cell 1 | Row 2 Cell 2 |
+- Footnotes:
+ ```md
+ Some text[^footnote]
+ [^footnote]: content
+ ```
+- HTML, e.g. `<sub>subscript</sub>` for <sub>subscript</sub>.
+
+## Interleaving Markdown and Typst
+
+Sometimes,
+you might want to render a certain section of the document
+only when viewed as Markdown,
+or only when viewed through Typst.
+To achieve the former,
+you can simply wrap the section in
+`<!--typst-begin-exclude-->` and `<!--typst-end-exclude-->`:
+
+```md
+<!--typst-begin-exclude-->
+Hello from not Typst!
+<!--typst-end-exclude-->
+```
+
+Most Markdown parsers support HTML comments,
+so from their perspective this is no different
+to just writing out the Markdown directly;
+but `cmarker.typ` knows to search for those comments
+and avoid rendering the content in between.
+
+Note that when the opening comment is followed by the end of an element,
+`cmarker.typ` will close the block for you.
+For example:
+
+```md
+> <!--typst-begin-exclude-->
+> One
+
+Two
+```
+
+In this code,
+“Two” will be given no matter where the document is rendered.
+This is done to prevent us from generating invalid Typst code.
+
+Conversely, one can put Typst code inside
+a HTML comment of the form
+`<!--raw-typst […]-->`
+to have it evaluated directly as Typst code
+(but only if the `raw-typst` option to `render` is set to `true`,
+otherwise it will just be seen as a regular comment and removed):
+
+```md
+<!--raw-typst Hello from #text(fill:blue)[Typst]!-->
+```
+
+## Limitations
+
+Although I tried my best to escape everything correctly,
+I won’t provide a hard guarantee that everything is fully sandboxed
+even if you set `raw-typst: false`.
+That said, Typst itself is well-sandboxed anyway.
+
+## FAQ
+
+### Typst is saying it can’t find my image – it’s looking inside `cmarker` for some reason!
+
+See [Resolving Paths Correctly](#resolving-paths-correctly).
+
+### How do I include multiple Markdown files in one project?
+
+See [the multi-file example](https://github.com/SabrinaJewson/cmarker.typ/blob/main/examples/multi-file.typ).
+
+Note that this example uses a _single_ call to `render` with concatenated Markdown,
+i.e. `cmarker.render(read("file-a.md") + read("file-b.md"))`.
+If you instead wish to use
+`cmarker.render(read("file-a.md"))` followed by `cmarker.render(read("file-b.md"))`,
+you may encounter collision issues if two headings have the same name.
+This can be resolved in two ways:
++ Giving the headings an explicit ID:
+ `<h1 id="my-id">My Heading</h1>` instead of `# My Heading`.
++ Setting a label prefix, e.g. `label-prefix: "my-file-"`.
+
+### My image file contains spaces, but it gets rendered as text!
+
+This is a Markdown quirk – `![alt](image path.png)` is seen as plain text
+instead of an image.
+To fix it, use `![alt](<image path.png>)`.
+
+### My Markdown after an open HTML tag is getting rendered as text!
+
+Another Markdown quirk –
+in code like `<p>hello _world_</p>`
+or `<!-- -->hello _world_`,
+italics will not be generated.
+
+There are two fixes:
+either insert some empty inline-level HTML at the start,
+e.g. `<span></span><p>hello _world_</p>`,
+or insert two newlines after the opening tag:
+
+```
+<p>
+
+hello _world_</p>
+```
+
+### How do I centre tables? How do I have them span the page width?
+
+This can be achieved via [show rules](https://typst.app/docs/reference/styling/#show-rules).
+For example, centring:
+
+```typst
+#show table: t => align(center, t)
+#cmarker.render("
+ | a | b |
+ | - | - |
+ | c | d |
+")
+```
+
+And having them span the page width:
+
+```typst
+#show table: t => {
+ if t.columns.all(c => c == auto) {
+ table(columns: (1fr,) * t.columns.len(), align: t.align, ..t.children)
+ } else {
+ t
+ }
+}
+```
+
+
+## Development
+
+- Build the plugin with `./build.sh`,
+ which produces the `plugin.wasm` necessary to use this.
+- Compile examples with `typst compile examples/{name}.typ`.
+- Compile this README to PDF with `typst compile README.typ`.
+- Run tests with `cargo test --workspace` and `cargo run -p test-runner`.
+- Fuzz the library with `cargo +nightly fuzz run fuzz`.
diff --git a/render/packages/preview/cmarker/0.1.6/lib.typ b/render/packages/preview/cmarker/0.1.6/lib.typ
new file mode 100644
index 0000000..bd2b380
--- /dev/null
+++ b/render/packages/preview/cmarker/0.1.6/lib.typ
@@ -0,0 +1,217 @@
+#let _p = plugin("./plugin.wasm")
+#let render(
+ markdown,
+ smart-punctuation: true,
+ math: none,
+ h1-level: 1,
+ raw-typst: true,
+ html: (:),
+ label-prefix: "",
+ prefix-label-uses: true,
+ scope: (:),
+ show-source: false,
+ blockquote: none,
+) = {
+ // A simple system for tagging content with invisible metadata.
+ // Used to implement various HTML tags that need some amount of structure.
+ let tag-content(content, tag, data: none) = [#metadata((tag, data))#content]
+ let is-tagged(content, tag) = (
+ content.func() == [].func()
+ and content.children.len() == 2
+ and content.children.at(0).func() == metadata
+ and content.children.at(0).value.len() == 2
+ and content.children.at(0).value.at(0) == tag
+ )
+ let untag-content(content) = (..content.children.at(0).value, content.children.at(1))
+ let take-tagged-children(content, tag) = {
+ if type(tag) != array {
+ tag = (tag,)
+ }
+ let tagged = ()
+ let rest = ()
+ if tag.any(t => is-tagged(content, t)) {
+ tagged.push(untag-content(content))
+ } else if content.func() == [].func() {
+ for child in content.children {
+ if tag.any(t => is-tagged(child, t)) {
+ tagged.push(untag-content(child))
+ } else {
+ rest.push(child)
+ }
+ }
+ } else {
+ rest.push(content)
+ }
+ (tagged: tagged, rest: for r in rest { r })
+ }
+ let untag-children(content, tag) = take-tagged-children(content, tag).tagged
+
+ if type(markdown) == content and markdown.has("text") {
+ markdown = markdown.text
+ }
+
+ scope = (rule: line.with(length: 100%), ..scope)
+
+ if blockquote != none {
+ scope += (
+ quote: (block: false, ..rest) => if block { blockquote(..rest) } else { quote(..rest) },
+ )
+ }
+
+ let labelify(content, attrs) = {
+ if "id" in attrs {
+ [#content #label(label-prefix + attrs.id)]
+ } else {
+ content
+ }
+ }
+
+ let label-use-prefix = if prefix-label-uses { label-prefix } else { "" }
+
+ let heading-fn(level) = (attrs, body) => {
+ labelify(scope.at("heading", default: heading)(level: h1-level + level, body), attrs)
+ }
+
+ html = (
+ sub: (attrs, body) => scope.at("sub", default: sub)(body),
+ sup: (attrs, body) => scope.at("sup", default: super)(body),
+ mark: (attrs, body) => scope.at("highlight", default: highlight)(body),
+ h1: heading-fn(0),
+ h2: heading-fn(1),
+ h3: heading-fn(2),
+ h4: heading-fn(3),
+ h5: heading-fn(4),
+ h6: heading-fn(5),
+
+ li: (attrs, body) => tag-content(body, "<li>"),
+ ul: (attrs, body) => {
+ scope.at("list", default: list)(..untag-children(body, "<li>").map(((_, _, c)) => c))
+ },
+ ol: (attrs, body) => {
+ scope.at("enum", default: enum)(..untag-children(body, "<li>").map(((_, _, c)) => c))
+ },
+
+ dt: (attrs, body) => tag-content(body, "<dt>"),
+ dd: (attrs, body) => tag-content(body, "<dd>"),
+ dl: (attrs, body) => scope.at("terms", default: terms)(..(
+ untag-children(body, ("<dt>", "<dd>"))
+ .map(((_, _, c)) => c)
+ .chunks(2, exact: true)
+ )),
+
+ tr: (attrs, body) => tag-content(body, "<tr>"),
+ thead: (attrs, body) => tag-content(body, "<thead>"),
+ tfoot: (attrs, body) => tag-content(body, "<tfoot>"),
+ th: (attrs, body) => tag-content(body, "<td>", data: attrs),
+ td: (attrs, body) => tag-content(body, "<td>", data: attrs),
+ table: (attrs, body) => {
+ let rows = (header: (), body: (), footer: ())
+ for (tag, _, child) in untag-children(body, ("<tr>", "<thead>", "<tfoot>")) {
+ if tag == "<thead>" {
+ for (_, _, row) in untag-children(child, "<tr>") {
+ rows.header.push(untag-children(row, "<td>"))
+ }
+ } else if tag == "<tfoot>" {
+ for (_, _, row) in untag-children(child, "<tr>") {
+ rows.footer.push(untag-children(row, "<td>"))
+ }
+ } else if tag == "<tr>" {
+ rows.body.push(untag-children(child, "<td>"))
+ }
+ }
+ // FIXME: This is likely buggy for exotic uses of rowspan and colspan.
+ let columns = calc.max(
+ ..rows.header.map(r => r.len()),
+ ..rows.body.map(r => r.len()),
+ ..rows.footer.map(r => r.len()),
+ )
+ let start_i = 0
+ for (k, section) in rows {
+ rows.insert(k, section.enumerate().map(((i, row)) => {
+ row = row.map(((_, attrs, td)) => {
+ let rowspan = int(attrs.at("rowspan", default: "1"))
+ let colspan = int(attrs.at("colspan", default: "1"))
+ table.cell(rowspan: rowspan, colspan: colspan, y: start_i + i, td)
+ })
+ row
+ }))
+ start_i += section.len()
+ }
+ let args = ()
+ if rows.header.len() != 0 {
+ args.push(table.header(..rows.header.flatten()))
+ }
+ args += rows.body.flatten()
+ if rows.footer.len() != 0 {
+ args.push(table.footer(..rows.footer.flatten()))
+ }
+ scope.at("table", default: table)(columns: columns, ..args)
+ },
+
+ figcaption: (attrs, body) => tag-content(body, "<figcaption>"),
+ figure: (attrs, body) => {
+ let (tagged: captions, rest) = take-tagged-children(body, "<figcaption>")
+ let caption = if captions.len() >= 1 { captions.at(0).at(2) } else { none }
+ labelify(figure(caption: caption, rest), attrs)
+ },
+
+ hr: ("void", (attrs) => (scope.rule)()),
+ a: (attrs, body) => scope.at("link", default: link)(
+ if attrs.href.starts-with("#") {
+ label(label-use-prefix + attrs.href.slice(1))
+ } else {
+ attrs.href
+ },
+ body,
+ ),
+ em: (attrs, body) => scope.at("emph", default: emph)(body),
+ strong: (attrs, body) => scope.at("strong", default: strong)(body),
+ s: (attrs, body) => scope.at("strike", default: strike)(body),
+ code: ("raw-text", (attrs, body) => scope.at("raw", default: raw)(body)),
+ br: ("void", (attrs) => scope.at("linebreak", default: linebreak)()),
+ img: ("void", (attrs) => scope.at("image", default: image)(attrs.src, alt: attrs.at("alt", default: none))),
+ blockquote: (attrs, body) => scope.at("quote", default: quote)(block: true, body),
+
+ ..html,
+ )
+
+ let flags = 0
+ if smart-punctuation {
+ flags += 0b00000001
+ }
+ if raw-typst {
+ flags += 0b00000010
+ }
+ if math != none {
+ flags += 0b00000100
+ scope += (inlinemath: math.with(block: false), displaymath: math.with(block: true))
+ }
+
+ let options-bytes = (flags, h1-level)
+
+ options-bytes += array(bytes(label-prefix)) + (0xFF,)
+ options-bytes += array(bytes(label-use-prefix)) + (0xFF,)
+
+ scope.html = (:)
+ for (tag-name, value) in html {
+ let (kind, callback) = if type(value) == function { ("normal", value) } else { value };
+ scope.html.insert(tag-name, callback)
+ options-bytes += array(bytes(tag-name))
+ options-bytes.push(if kind == "void" {
+ 0xFC
+ } else if kind == "raw-text" {
+ 0xFD
+ } else if kind == "escapable-raw-text" {
+ 0xFE
+ } else if kind == "normal" {
+ 0xFF
+ })
+ }
+
+ let rendered = str(_p.render(bytes(markdown), bytes(options-bytes)))
+ if show-source {
+ raw(rendered, block: true, lang: "typ")
+ } else {
+ eval(rendered, mode: "markup", scope: scope)
+ }
+}
diff --git a/render/packages/preview/cmarker/0.1.6/plugin.wasm b/render/packages/preview/cmarker/0.1.6/plugin.wasm
new file mode 100755
index 0000000..54bbeee
Binary files /dev/null and b/render/packages/preview/cmarker/0.1.6/plugin.wasm differ
diff --git a/render/packages/preview/cmarker/0.1.6/typst.toml b/render/packages/preview/cmarker/0.1.6/typst.toml
new file mode 100644
index 0000000..bdf3f87
--- /dev/null
+++ b/render/packages/preview/cmarker/0.1.6/typst.toml
@@ -0,0 +1,11 @@
+[package]
+name = "cmarker"
+version = "0.1.6"
+entrypoint = "lib.typ"
+authors = ["Sabrina Jewson"]
+license = "MIT"
+description = "Transpile CommonMark Markdown to Typst, from within Typst!"
+repository = "https://github.com/SabrinaJewson/cmarker.typ"
+keywords = ["Markdown", "CommonMark"]
+compiler = "0.13.1"
+exclude = ["examples", "README.pdf"]
diff --git a/render/packages/preview/fletcher/0.5.8/CONTRIBUTING.md b/render/packages/preview/fletcher/0.5.8/CONTRIBUTING.md
new file mode 100644
index 0000000..bd42bdf
--- /dev/null
+++ b/render/packages/preview/fletcher/0.5.8/CONTRIBUTING.md
@@ -0,0 +1,88 @@
+# Contributing to fletcher
+
+Thank you for your interest in contributing to fletcher! This guide explains how to install Pixi, run Tytanic tests, update the README, build the manual, and edit docstrings.
+
+## Installing Pixi
+
+Fletcher uses [Pixi](https://pixi.sh/) to run project commands and reproducibly install development tools such as [Tytanic](https://github.com/tytanic/tytanic) for testing, [Nushell](https://www.nushell.sh) for scripting, [Typos](https://crates.io/crates/typos) and also Typst itself.
+
+To install Pixi, run:
+
+```sh
+curl -fsSL https://pixi.sh/install.sh | bash
+```
+
+After installation, you should have access to all the development tools via `pixi run <commands>` or by activating the development environment with
+
+```sh
+pixi shell
+```
+
+which makes the tools available directly from the command line.
+
+
+## Running Tytanic Tests
+
+Fletcher uses [Tytanic](https://github.com/tytanic/tytanic) for testing. To run all the tests:
+
+```sh
+pixi run test
+```
+
+Alternatively, enter the development environment (`pixi shell`) and use `tt` (if Tytanic is not already on your system).
+
+Using Tytanic (see the [official docs](https://tingerrr.github.io/tytanic/)):
+
+- `tt run <test_set>` to run all tests
+- `tt update <test_set>` to update test reference images
+- Test sets can be specified like so:
+ - All tests, e.g., `tt run`.
+ - A single test, e.g., `tt run node/shapes`
+ - Tests matching glob pattern, e.g., `tt run -e g:node/*`
+
+## Updating the README
+
+The main `README.md` file is generated from a template `README.src.md`.
+To update the README, edit the template file and run
+```sh
+pixi run readme
+```
+to generate the main file. Don't edit `README.md` directly.
+
+The template is automatically populated with two kinds of example images:
+
+1. `docs/readme-examples/`: Short examples with light/dark modes displayed alongside the source code.
+ To compile these to light and dark SVGs, use `pixi run compile examples [pattern]`.
+ They are _not_ standalone Typst documents; more like snippets with a special syntax for switching between light/dark themes (see examples).
+2. `docs/gallery/`: Complex examples displayed in a table of images linking to source files.
+ These should be standalone documents.
+ Make sure they import the correct fletcher version!
+ Compile these with `pixi compile gallery [pattern]`.
+
+The optional `[pattern]` argument is a substring to filter filenames by.
+
+
+## Building the Manual
+
+To build the manual PDF (takes a while) and exit:
+
+```sh
+pixi run compile manual
+```
+
+You can also watch for changes and continuously edit with:
+
+```sh
+pixi run manual
+```
+
+## Editing Docstrings
+
+The manual uses [Tidy](https://typst.app/universe/package/tidy/) to parse docstrings and populate the manual.
+
+To create a clickable reference to a documented argument of a function, use `#param[fn][arg]` (which renders as `` `arg` ``) or `#the-param[fn][arg]` (which renders as ``the `arg` option of `fn` ``).
+
+## Additional Notes
+
+- Please ensure all tests pass before submitting a pull request.
+- Thank you! 🎈
diff --git a/render/packages/preview/fletcher/0.5.8/LICENSE b/render/packages/preview/fletcher/0.5.8/LICENSE
new file mode 100644
index 0000000..f8de216
--- /dev/null
+++ b/render/packages/preview/fletcher/0.5.8/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2023 Joseph Wilson
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
\ No newline at end of file
diff --git a/render/packages/preview/fletcher/0.5.8/README.md b/render/packages/preview/fletcher/0.5.8/README.md
new file mode 100644
index 0000000..9d7d34f
--- /dev/null
+++ b/render/packages/preview/fletcher/0.5.8/README.md
@@ -0,0 +1,328 @@
+![Version](https://img.shields.io/badge/version-0.5.8-green)
+[![Typst Universe](https://img.shields.io/badge/Typst-Universe-239dad)](https://typst.app/universe/package/fletcher/)
+[![Repo](https://img.shields.io/badge/GitHub-repo-444)](https://github.com/Jollywatt/typst-fletcher)
+[![Development version](https://img.shields.io/badge/dynamic/toml?url=https%3A%2F%2Fgithub.com%2FJollywatt%2Ftypst-fletcher%2Fraw%2Fmain%2Ftypst.toml&query=package.version&label=main&color=444)](https://github.com/Jollywatt/typst-fletcher/tree/main)
+
+# fletcher
+
+_**fletcher** (noun) a maker of arrows_
+
+A [Typst](https://typst.app/) package for drawing diagrams with arrows,
+built on top of [CeTZ](https://github.com/johannes-wolf/cetz).
+
+See the [manual](docs/manual.pdf?raw=true) for documentation or ask the community for help.
+
+[![Manual](https://img.shields.io/badge/docs-manual.pdf-orange)](docs/manual.pdf?raw=true)
+[![Ask on Discord](https://img.shields.io/badge/ask-on%20Typst%20forum-239dad
+)](https://forum.typst.app)
+[![Ask on Discord](https://img.shields.io/badge/ask-on%20Discord-2a4d7e
+)](https://discord.com/channels/1054443721975922748/1260973351900414102)
+
+
+```typ
+#import "@preview/fletcher:0.5.8" as fletcher: diagram, node, edge
+```
+
+
+<picture>
+ <source media="(prefers-color-scheme: dark)" srcset="docs/readme-examples/1-first-isomorphism-theorem-dark.svg">
+ <img src="docs/readme-examples/1-first-isomorphism-theorem-light.svg">
+</picture>
+
+```typ
+#diagram(cell-size: 15mm, $
+ G edge(f, ->) edge("d", pi, ->>) & im(f) \
+ G slash ker(f) edge("ur", tilde(f), "hook-->")
+$)
+```
+
+<picture>
+ <source media="(prefers-color-scheme: dark)" srcset="docs/readme-examples/2-flowchart-trap-dark.svg">
+ <img src="docs/readme-examples/2-flowchart-trap-light.svg">
+</picture>
+
+```typ
+// https://xkcd.com/1195/
+#import fletcher.shapes: diamond
+#set text(font: "Comic Neue", weight: 600) // testing: omit
+
+#diagram(
+ node-stroke: 1pt,
+ node((0,0), [Start], corner-radius: 2pt, extrude: (0, 3)),
+ edge("-|>"),
+ node((0,1), align(center)[
+ Hey, wait,\ this flowchart\ is a trap!
+ ], shape: diamond),
+ edge("d,r,u,l", "-|>", [Yes], label-pos: 0.1)
+)
+```
+
+<picture>
+ <source media="(prefers-color-scheme: dark)" srcset="docs/readme-examples/3-state-machine-dark.svg">
+ <img src="docs/readme-examples/3-state-machine-light.svg">
+</picture>
+
+```typ
+#set text(10pt)
+#diagram(
+ node-stroke: .1em,
+ node-fill: gradient.radial(blue.lighten(80%), blue, center: (30%, 20%), radius: 80%),
+ spacing: 4em,
+ edge((-1,0), "r", "-|>", `open(path)`, label-pos: 0, label-side: center),
+ node((0,0), `reading`, radius: 2em),
+ edge(`read()`, "-|>"),
+ node((1,0), `eof`, radius: 2em),
+ edge(`close()`, "-|>"),
+ node((2,0), `closed`, radius: 2em, extrude: (-2.5, 0)),
+ edge((0,0), (0,0), `read()`, "--|>", bend: 130deg),
+ edge((0,0), (2,0), `close()`, "-|>", bend: -40deg),
+)
+```
+
+<picture>
+ <source media="(prefers-color-scheme: dark)" srcset="docs/readme-examples/4-feynman-diagram-dark.svg">
+ <img src="docs/readme-examples/4-feynman-diagram-light.svg">
+</picture>
+
+```typ
+#diagram($
+ e^- edge("rd", "-<|-") & & & edge("ld", "-|>-") e^+ \
+ & edge(gamma, "wave") \
+ e^+ edge("ru", "-|>-") & & & edge("lu", "-<|-") e^- \
+$)
+```
+
+
+
+
+# More examples
+Pull requests are most welcome!
+
+<table>
+ <tr>
+ <td style="background: white;">
+ <a href="docs/gallery/01-commutative.typ">
+ <center>
+ <img src="docs/gallery/01-commutative.svg" width="100%"/>
+ </center>
+ </a>
+ </td>
+ <td style="background: white;">
+ <a href="docs/gallery/02-algebra-cube.typ">
+ <center>
+ <img src="docs/gallery/02-algebra-cube.svg" width="100%"/>
+ </center>
+ </a>
+ </td>
+ </tr>
+ <tr>
+ <td style="background: white;">
+ <a href="docs/gallery/03-ml-architecture.typ">
+ <center>
+ <img src="docs/gallery/03-ml-architecture.svg" width="100%"/>
+ </center>
+ </a>
+ </td>
+ <td style="background: white;">
+ <a href="docs/gallery/04-io-flowchart.typ">
+ <center>
+ <img src="docs/gallery/04-io-flowchart.svg" width="100%"/>
+ </center>
+ </a>
+ </td>
+ </tr>
+ <tr>
+ <td style="background: white;">
+ <a href="docs/gallery/05-digraph.typ">
+ <center>
+ <img src="docs/gallery/05-digraph.svg" width="100%"/>
+ </center>
+ </a>
+ </td>
+ <td style="background: white;">
+ <a href="docs/gallery/06-node-groups.typ">
+ <center>
+ <img src="docs/gallery/06-node-groups.svg" width="100%"/>
+ </center>
+ </a>
+ </td>
+ </tr>
+ <tr>
+ <td style="background: white;">
+ <a href="docs/gallery/07-uml-diagram.typ">
+ <center>
+ <img src="docs/gallery/07-uml-diagram.svg" width="100%"/>
+ </center>
+ </a>
+ </td>
+ <td style="background: white;">
+ <a href="docs/gallery/08-tree.typ">
+ <center>
+ <img src="docs/gallery/08-tree.svg" width="100%"/>
+ </center>
+ </a>
+ </td>
+ </tr>
+ <tr>
+ <td style="background: white;">
+ <a href="docs/gallery/09-feynman-diagram.typ">
+ <center>
+ <img src="docs/gallery/09-feynman-diagram.svg" width="100%"/>
+ </center>
+ </a>
+ </td>
+ <td style="background: white;">
+ <a href="docs/gallery/10-category-theory.typ">
+ <center>
+ <img src="docs/gallery/10-category-theory.svg" width="100%"/>
+ </center>
+ </a>
+ </td>
+ </tr>
+</table>
+
+
+
+## Change log
+
+### 0.5.8
+
+- Added bracket and parenthesis mark types, with shorthands `"["`, `"]"`, `"("`, `")"`, `"bracket"`, `"parenthesis"` (#102).
+- Added `cylinder`, `brace`, `bracket`, `paren` and `stretched-glyph` node shapes (#99, #109).
+- Allow specifying label positions as `(segment, position)` (#107, #112, [@deffi](https://github.com/deffi)).
+- Fix bugs with anchors of absolutely-positioned enclose nodes (#95, #113).
+- Fix some instabilities with edges related to division by zero (#100, #105).
+
+### 0.5.7
+
+- Update `cetz` dependency to `0.3.4` fixing bugs with `typst` version `0.13.1` (#89, #90, #91).
+
+### 0.5.6
+
+- **Require `typst` version `>=0.13.0`.**
+- Update `cetz` dependency to `0.3.3`.
+- Support CeTZ anchors on nodes which dynamically enclose other nodes (#81).
+- Allow nested enclosing of nodes (#45).
+- Add `floating` option to `edge()` to make certain objects not affect the diagram's bounds (#38).
+- Make `debug` annotations "floating" so they don't affect diagram size and layout.
+
+### 0.5.5
+
+- Update `cetz` dependency to `0.3.2`.
+- Fix deprecated type comparisons (#75).
+- Add space ` ` line style for empty stroke (#70).
+- Fix bug with `label-side` for corner edges (#74).
+
+### 0.5.4
+
+- Allow relative lengths for the `label-pos` option of `edge()` (#61).
+- Fix layout bugs for diagrams with non-default `axes` options (#62, #66).
+- Fix a line breaking issue with justified text in nodes (#64).
+
+### 0.5.3
+
+- Support CeTZ anchors in edge coordinates, e.g., `edge(<a.east>, ..)`.
+- Fix crash when `stroke: none` set on polyline edges (#60, [@SillyFreak](https://github.com/SillyFreak!)).
+- Fix bug with crossing edges in math mode (#54).
+- Fix layout bugs for diagrams with non-default `axes` options (#62, #66).
+
+### 0.5.2
+
+- **Require `typst` version `>=0.12.0`.**
+- Update `cetz` dependency to `0.3.1`. **Note:** This may slightly change edge label positions.
+- Add `loop-angle` option to `edge()` (#36).
+
+### 0.5.1
+
+- Fix nodes which `enclose` absolute coordinates.
+- Allow CeTZ-style coordinate expressions in node `enclose` option.
+- Fix crash with polar coordinates.
+- Fix edges which bend at 0deg or 180deg (e.g., `edge("r,r")` or `edge("r,l")`) and enhance the way the corner radius adapts to the bend angle. **Note:** This may change diagram layout from previous versions.
+- Improve error messages.
+- Add marks for crow's foot notation: `n` (many), `n?` (zero or more), `n!` (one or more), `1` (one), `1?` (zero or one), `1!` (exactly one).
+- Add `node-shape` option to `diagram()`.
+
+### 0.5.0
+
+- Greatly enhance coordinate system.
+ - Support CeTZ-style coordinate expressions (relative, polar, interpolating, named coordinates, etc).
+ - Absolute coordinates (physical lengths) can be used alongside "elastic" coordinates (row/column positions).
+- Add `label-angle` option to `edge()`.
+- Add `label-wrapper` option to allow changing the label inset, outline stroke, and so on (#26).
+- Add `label-size` option to control default edge label text size (#35)
+- Add `trapezium` node shape.
+- Disallow string labels to be passed as positional arguments to `edge()` (to eliminate ambiguity). Used named argument or pass content instead.
+
+### 0.4.5
+
+- Add isosceles triangle node shape (#31).
+- Add `fit` and `dir` options to various node shapes to adjust sizing and orientation.
+- Allow more than one consecutive edge to have an implicit end vertex.
+- Allow `snap-to` to be `none` to disable edge snapping (#32).
+
+### 0.4.4
+
+- Support fully customisable marks/arrowheads!
+ - Added new mark styles and tweaked some existing defaults. **Note.** This may change the micro-typography of diagrams from previous versions.
+- Add node groups via the `enclose` option of `node()`.
+- Node labels can be aligned inside the node with `align()`.
+- Node labels wrap naturally when label text is wider than the node. **Note:** This may change diagram layout from previous versions.
+- Add a `layer` option to nodes and edges to control drawing order.
+- Add node shapes: `ellipse`, `octagon`.
+
+### 0.4.3
+
+- Fixed edge crossing backgrounds being drawn above nodes (#14).
+- Add `fletcher.hide()` to hide elements with/without affecting layout, useful for incremental diagrams in slides (#15).
+- Support `shift`ing edges by coordinate deltas as well as absolute lengths (#13).
+- Support node names (#8).
+
+### 0.4.2
+
+- Improve edge-to-node snapping. Edges can terminate anywhere near a node (not just at its center) and will automatically snap to the node outline. Added `snap-to` option to `edge()`.
+- Fix node `inset` being half the amount specified. If upgrading from previous version, you will need to divide node `inset` values by two to preserve diagram layout.
+- Add `decorations` option to `edge()` for CeTZ path decorations (`"wave"`, `"zigzag"`, and `"coil"`, also accepted as positional string arguments).
+
+### 0.4.1
+
+- Support custom node shapes! Edges connect to node outlines automatically.
+ - New `shapes` submodule, containing `diamond`, `pill`, `parallelogram`, `hexagon`, and other node shapes.
+- Allow edges to have multiple segments.
+ - Add `vertices` an `corner-radius` options to `edge()`.
+ - Relative coordinate shorthands may be comma separated to signify multiple segments, e.g., `"r,u,ll"`.
+- Add `dodge` option to `edge()` to adjust end points.
+- Support `cetz:0.2.0`.
+
+### 0.4.0
+
+- Add ability to specify diagrams in math-mode, using `&` to separate nodes.
+- Allow implicit and relative edge coordinates, e.g., `edge("d")` becomes `edge(prev-node, (0, 1))`.
+- Add ability to place marks anywhere along an edge. Shorthands now accept an optional middle mark, for example `|->-|` and `hook-/->>`.
+- Add “hanging tail” correction to marks on curved edges. Marks now rotate a bit to fit more comfortably along tightly curving arcs.
+- Add more arrowheads for the sake of it: `}>`, `<{`, `/`, `\`, `x`, `X`, `*` (solid dot), `@` (solid circle).
+- Add `axes` option to `diagram()` to control the direction of each axis in the diagram's coordinate system.
+- Add `width`, `height` and `radius` options to `node()` for explicit control over size.
+- Add `corner-radius` option to `node()`.
+- Add `stroke` option to `edge()` replacing `thickness` and `paint` options.
+- Add `edge-stroke` option to `diagram()` replacing `edge-thickness`.
+
+### 0.3.0
+
+- Make round-style arrow heads better approximate the default math font.
+- Add solid arrow heads with shorthand `<|-`, `-|>` and double-bar `||-`, `-||`.
+- Add an `extrude` option to `node()` which duplicates and extrudes the node's stroke, enabling double stroke effects.
+
+### 0.2.0
+
+- Experimental support for customising arrowheads.
+- Add right-angled edges with `edge(..., corner: left/right)`.
+
+## Star History
+
+<a href="https://star-history.com/#jollywatt/typst-fletcher&Date">
+ <picture>
+ <source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=jollywatt/typst-fletcher&type=Date&theme=dark" />
+ <source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=jollywatt/typst-fletcher&type=Date" />
+ <img alt="Star History Chart" src="https://api.star-history.com/svg?repos=jollywatt/typst-fletcher&type=Date" />
+ </picture>
+</a>
\ No newline at end of file
diff --git a/render/packages/preview/fletcher/0.5.8/src/coords.typ b/render/packages/preview/fletcher/0.5.8/src/coords.typ
new file mode 100644
index 0000000..a4a39b1
--- /dev/null
+++ b/render/packages/preview/fletcher/0.5.8/src/coords.typ
@@ -0,0 +1,301 @@
+#import "utils.typ": *
+#import "deps.typ": cetz
+
+/// Convert from elastic to absolute coordinates, $(u, v) |-> (x, y)$.
+///
+/// _Elastic_ coordinates are specific to the diagram and adapt to row/column
+/// sizes; _absolute_ coordinates are the final, physical lengths which are
+/// passed to `cetz`.
+///
+/// - grid (dictionary): Representation of the grid layout, including:
+/// - `origin`
+/// - `centers`
+/// - `spacing`
+/// - `flip`
+/// The `grid` is passed to #the-param[diagram][render].
+/// - uv (array): Elastic coordinate, `(float, float)`.
+#let uv-to-xy(grid, uv) = {
+ let (i, j) = vector.sub(vector-2d(uv), grid.origin)
+
+ let (n-x, n-y) = grid.centers.map(array.len)
+ if grid.flip.xy { (n-x, n-y) = (n-y, n-x) }
+ if grid.flip.x { i = (n-x - 1) - i }
+ if grid.flip.y { j = (n-y - 1) - j }
+ if grid.flip.xy { (i, j) = (j, i) }
+
+ (i, j).zip(grid.centers, grid.spacing)
+ .map(((t, c, s)) => interp(c, t, spacing: s))
+}
+
+/// Convert from absolute to elastic coordinates, $(x, y) |-> (u, v)$.
+///
+/// Inverse of `uv-to-xy()`.
+#let xy-to-uv(grid, xy) = {
+ let (i, j) = xy.zip(grid.centers, grid.spacing)
+ .map(((x, c, s)) => interp-inv(c, x, spacing: s))
+
+ let (n-x, n-y) = grid.centers.map(array.len)
+ if grid.flip.xy { (n-x, n-y) = (n-y, n-x) }
+ if grid.flip.xy { (i, j) = (j, i) }
+ if grid.flip.x { i = (n-x - 1) - i }
+ if grid.flip.y { j = (n-y - 1) - j }
+
+ vector.add((i, j), grid.origin)
+}
+
+/// Jacobian of the coordinate map `uv-to-xy()`.
+///
+/// Used to convert a "nudge" in $u v$ coordinates to a "nudge" in $x y$
+/// coordinates. This is needed because $u v$ coordinates are non-linear
+/// (they're elastic). Uses a balanced finite differences approximation.
+///
+/// - grid (dictionary): Representation of the grid layout.
+/// The `grid` is passed to #the-param[diagram][render].
+/// - uv (array): The point `(float, float)` in the $u v$-manifold where the
+/// shift tangent vector is rooted.
+/// - duv (array): The shift tangent vector `(float, float)` in $u v$ coordinates.
+#let duv-to-dxy(grid, uv, duv) = {
+ let duv = vector.scale(duv, 0.5)
+ vector.sub(
+ uv-to-xy(grid, vector.add(uv, duv)),
+ uv-to-xy(grid, vector.sub(uv, duv)),
+ )
+}
+
+/// Jacobian of the coordinate map `xy-to-uv()`.
+#let dxy-to-duv(grid, xy, dxy) = {
+ let dxy = vector.scale(dxy, 0.5)
+ vector.sub(
+ xy-to-uv(grid, vector.add(xy, dxy)),
+ xy-to-uv(grid, vector.sub(xy, dxy)),
+ )
+}
+
+/// Return a vector rooted at a $x y$ coordinate with a given angle $θ$ in $x
+/// y$-space but with a length specified in either $x y$-space or $u v$-space.
+#let vector-polar-with-xy-or-uv-length(grid, xy, target-length, θ) = {
+ if type(target-length) == length {
+ vector-polar(target-length, θ)
+ } else {
+ let unit = vector-polar(1pt, θ)
+ let det = vector.len(dxy-to-duv(grid, xy, unit))
+ vector.scale(unit, target-length/det)
+ }
+}
+
+
+
+#let NAN_COORD = (float.nan, float.nan)
+
+#let default-ctx = (
+ prev: (pt: (0, 0)),
+
+ // cetz anchors assume y axis going up.
+ // see lines ending with the comment
+ // CETZ Y AXIS
+ transform:
+ ((1, 0, 0, 0),
+ (0,-1, 0, 0),
+ (0, 0, 1, 0),
+ (0, 0, 0, 1)),
+
+ nodes: (:),
+ length: 1cm,
+ em-size: (width: 11pt, height: 11pt),
+ style: cetz.styles.default,
+ groups: (),
+ debug: false,
+)
+
+
+#let resolve-system(coord) = {
+ if type(coord) == dictionary and ("u", "v").all(k => k in coord) {
+ return "uv"
+ } else if type(coord) == label {
+ return "element"
+ }
+
+ let cetz-system = cetz.coordinate.resolve-system(coord)
+ if cetz-system == "xyz" and coord.len() == 2 {
+ if coord.all(x => type(x) == length) {
+ "xyz"
+ } else if coord.all(x => type(x) in (int, float)) {
+ "uv"
+ } else {
+ error("Coordinates must be two numbers (for elastic coordinates) or two lengths (for physical coordinates); got #0.", coord)
+ }
+ } else {
+ cetz-system
+ }
+}
+
+#let resolve-anchor(ctx, c) = {
+ // (name: <string>, anchor: <number, angle, string> or <none>)
+ // "name.anchor"
+ // "name"
+ if type(c) == label { c = str(c) }
+
+ let (name, anchor) = if type(c) == str {
+ let (name, ..anchor) = c.split(".")
+ if anchor.len() == 0 {
+ anchor = "default"
+ }
+ (name, anchor)
+ } else {
+ (str(c.name), c.at("anchor", default: "default"))
+ }
+
+ if name not in ctx.nodes {
+ error("Node #0 not found. Named nodes are: #..1.", name, ctx.nodes.keys())
+ }
+
+ // Resolve length anchors
+ if type(anchor) == length {
+ anchor = util.resolve-number(ctx, anchor)
+ }
+
+ let calculate-anchors = ctx.nodes.at(name).anchors
+
+ (calculate-anchors)(anchor)
+}
+
+
+
+#let resolve-relative(resolve, ctx, c) = {
+ // (rel: <coordinate>, update: <bool> or <none>, to: <coordinate>)
+ let update = c.at("update", default: true)
+
+ let target-system = ctx.target-system
+ let sub-ctx = ctx + (target-system: auto)
+
+ let (ctx, rel) = resolve(sub-ctx, c.rel, update: false)
+
+ ctx.target-system = target-system
+ let (ctx, to) = if "to" in c {
+ resolve(ctx, c.to, update: false)
+ } else {
+ (ctx, ctx.prev.pt)
+ }
+
+ if is-nan-vector(to) {
+ return (coord: to, update: update)
+ }
+
+
+ let is-xy(coord) = coord.any(x => type(x) == length)
+ let is-uv(coord) = not is-xy(coord)
+
+ let error-value = (coord: NAN_COORD, update: update)
+
+ if is-xy(rel) and is-uv(to) {
+ if "grid" not in ctx { return error-value }
+ to = uv-to-xy(ctx.grid, to)
+ } else if is-uv(rel) and is-xy(to) {
+ if "grid" not in ctx { return error-value }
+ to = xy-to-uv(ctx.grid, to)
+ }
+
+ c = vector.add(rel, to)
+
+ if ctx.target-system == "xyz" and is-uv(c) {
+ if "grid" not in ctx { return error-value }
+ c = uv-to-xy(ctx.grid, c)
+ } else if ctx.target-system == "uv" and is-xy(c) {
+ if "grid" not in ctx { return error-value }
+ c = xy-to-uv(ctx.grid, c)
+ }
+
+ (coord: c, update: update)
+}
+
+
+/// Resolve CeTZ-style coordinate expressions to absolute vectors.
+///
+/// This is an drop-in replacement of `cetz.coordinate.resolve()` but extended
+/// to handle fletcher's elastic $u v$ coordinates alongside CeTZ' physical $x
+/// y$ coordinates. The target coordinate system must be specified in the
+/// context object `ctx`.
+///
+/// Resolving $u v$ coordinates to or from $x y$ coordinates requires the
+/// diagram's `grid`, which defines the non-linear maps `uv-to-xy()` and
+/// `xy-to-uv()`. The `grid` may be supplied in the context object `ctx`.
+///
+/// If `grid` is not supplied, *coordinate resolution may fail*, in which case
+/// the vector #fletcher.NAN_COORD is returned.
+///
+/// - ctx (dictionary): CeTZ canvas context object, additionally containing:
+/// - `target-system`: the target coordinate system to resolve to, one of
+/// `"uv"` or `"xyz"`.
+/// - `grid` (optional): the diagram's grid specification, defining the
+/// coordinate maps $u v <-> x y$. If not given, coordinates requiring this
+/// map resolve to #fletcher.NAN_COORD.
+///
+/// - ..coordinates (coordinate): CeTZ-style coordinate expression(s), e.g.,
+/// `(1, 2)`, `(45deg, 2cm)`, or `(rel: (+1, 0), to: "name")`.
+#let resolve(ctx, ..coordinates, update: true) = {
+ assert(ctx.target-system in (auto, "uv", "xyz"))
+
+ let result = ()
+ for c in coordinates.pos() {
+ let t = resolve-system(c)
+ let out = if t == "uv" {
+ if ctx.target-system in (auto, "uv") {
+ let (u, v) = c // also works for dictionaries
+ (u, v)
+ } else if ctx.target-system == "xyz" {
+ if "grid" in ctx { uv-to-xy(ctx.grid, c) }
+ else { NAN_COORD }
+ }
+ } else if t == "xyz" {
+ let c = cetz.coordinate.resolve-xyz(c)
+ c = vector-2d(c).map(x => x.abs + x.em*ctx.em-size.width)
+ if ctx.target-system in (auto, "xyz") {
+ c
+ } else if ctx.target-system == "uv" {
+ if "grid" in ctx { xy-to-uv(ctx.grid, c) }
+ else { NAN_COORD }
+ }
+ } else if t == "previous" {
+ (ctx, c) = resolve(ctx, ctx.prev.pt)
+ c
+ } else if t == "polar" {
+ c = vector-2d(cetz.coordinate.resolve-polar(c))
+ resolve(ctx, c).at(1) // ensure uv <-> xyz conversion
+ } else if t == "barycentric" {
+ cetz.coordinate.resolve-barycentric(ctx, c)
+ } else if t in ("element", "anchor") {
+ resolve-anchor(ctx, c)
+ } else if t == "tangent" {
+ cetz.coordinate.resolve-tangent(resolve, ctx, c)
+ } else if t == "perpendicular" {
+ cetz.coordinate.resolve-perpendicular(resolve, ctx, c)
+ } else if t == "relative" {
+ let result = resolve-relative(resolve, ctx, c)
+ update = result.update
+ result.coord
+ } else if t == "lerp" {
+ cetz.coordinate.resolve-lerp(resolve, ctx, c)
+ } else if t == "function" {
+ cetz.coordinate.resolve-function(resolve, ctx, c)
+ } else {
+ error("Failed to resolve coordinate #0.", c)
+ }
+
+ out = vector-2d(out)
+
+ if update { ctx.prev.pt = out }
+ result.push(out)
+ }
+
+ assert(result.all(c => c.len() == 2))
+
+ return (ctx, ..result)
+}
+
+
+#let is-grid-independent-uv-coordinate(coord) = {
+ let ctx = default-ctx + (target-system: "uv")
+ (ctx, coord) = resolve(ctx, coord)
+ not is-nan-vector(coord)
+}
+
diff --git a/render/packages/preview/fletcher/0.5.8/src/default-marks.typ b/render/packages/preview/fletcher/0.5.8/src/default-marks.typ
new file mode 100644
index 0000000..22e0506
--- /dev/null
+++ b/render/packages/preview/fletcher/0.5.8/src/default-marks.typ
@@ -0,0 +1,423 @@
+#import "deps.typ"
+#import deps.cetz.draw
+
+#let DEFAULT_MARKS = (
+ // all numbers are interpreted as multiples of stroke thickness
+
+ head: (
+ size: 7, // radius of curvature
+ sharpness: 24.7deg, // angle at vertex between central line and arrow's edge
+ delta: 53.5deg, // angle spanned by arc of curved arrow edge
+
+ tip-origin: 0.5,
+ tail-end: mark => calc.min(..mark.extrude),
+ tail-origin: mark => {
+ let dx = calc.cos(mark.sharpness) + calc.cos(mark.sharpness + mark.delta)
+ mark.tail-end - mark.size*mark.delta/1.8rad*dx
+ },
+
+ stroke: (cap: "round"),
+
+ draw: mark => {
+ for flip in (+1, -1) {
+ draw.arc(
+ (0, 0),
+ radius: mark.size,
+ start: flip*(90deg + mark.sharpness),
+ delta: flip*mark.delta,
+ fill: none,
+ )
+ }
+ },
+
+ cap-offset: (mark, y) => {
+ import calc: sin, sqrt, pow, cos, abs, max
+ let r = mark.size
+ let θ = mark.sharpness
+ r*(sin(θ) - sqrt(max(0, 1 - pow(cos(θ) - abs(y)/r, 2))))
+ },
+
+ ),
+
+ doublehead: (
+ inherit: "head",
+ size: 10.56,
+ sharpness: 19.4deg,
+ delta: 43.5deg,
+ ),
+
+ triplehead: (
+ inherit: "head",
+ size: 13.5,
+ sharpness: 25.5deg,
+ delta: 42.6deg,
+ ),
+
+ harpoon: (
+ inherit: "head",
+ draw: mark => {
+ draw.arc(
+ (0, 0),
+ radius: mark.size,
+ start: -(90deg + mark.sharpness),
+ delta: -mark.delta,
+ fill: none,
+ )
+ },
+ ),
+
+ straight: (
+ size: 10,
+ sharpness: 20deg,
+
+ tip-origin: mark => 0.5/calc.sin(mark.sharpness),
+ tail-origin: mark => -mark.size*calc.cos(mark.sharpness),
+
+ fill: none,
+
+ draw: mark => {
+ draw.line(
+ (180deg + mark.sharpness, mark.size),
+ (0, 0),
+ (180deg - mark.sharpness, mark.size),
+ )
+ },
+
+ cap-offset: (mark, y) => calc.tan(mark.sharpness + 90deg)*calc.abs(y),
+ ),
+
+ solid: (
+ inherit: "straight",
+
+ tip-origin: 0,
+ tip-end: mark => -0.5/calc.sin(mark.sharpness),
+ tail-end: mark => -0.5/calc.sin(mark.sharpness),
+
+ stroke: none,
+ fill: auto,
+ ),
+
+ stealth: (
+ size: 6,
+ stealth: 0.3,
+ angle: 25deg,
+ rear-angle: mark => calc.atan2(mark.stealth, calc.tan(mark.angle)),
+
+ tip-origin: mark => 0.5/calc.sin(mark.angle),
+ tip-end: mark => mark.size*(mark.stealth - 1)*calc.cos(mark.angle),
+ tail-origin: mark => {
+ if mark.stealth > 0 {
+ let wing-angle = (mark.rear-angle - mark.angle)/2
+
+ let miter-limit = if mark.stroke == none { 0 }
+ else { stroke(mark.stroke).miter-limit }
+
+ let miter-length = 1/calc.sin(wing-angle)
+ // stealth arrows with sharp wings look bigger due to long miter lengths
+ let extra-size = if miter-length < miter-limit {
+ // so account for extra apparent size
+ 0.4*miter-length
+ } else {
+ // unless over miter limit, since wings get clipped
+ 0
+ }
+
+ -(mark.size + extra-size)*calc.cos(mark.angle)
+ } else {
+ // negative stealth looks like a diamond
+ mark.tip-end - 0.5/calc.sin(mark.rear-angle)
+ }
+ },
+
+ stroke: (miter-limit: 20),
+
+ draw: mark => {
+ draw.line(
+ (0,0),
+ (180deg + mark.angle, mark.size),
+ (mark.tip-end, 0),
+ (180deg - mark.angle, mark.size),
+ close: true,
+ )
+ },
+
+ cap-offset: (mark, y) => if mark.tip {
+ -mark.stealth/calc.tan(mark.angle)*calc.abs(y)
+ } else {
+ calc.tan(mark.angle + 90deg)*calc.abs(y)
+ },
+ ),
+
+ latex: (
+ size: 23, // radius of curvature
+ sharpness: 10deg, // angle at vertex between central line and arrow's edge
+ delta: 20deg, // angle spanned by arc of curved arrow edge
+
+ tip-end: mark => mark.size*(calc.sin(mark.sharpness) - calc.sin(mark.sharpness + mark.delta)),
+ tail-end: mark => mark.tip-end/2,
+ tail-origin: mark => mark.tip-end,
+
+ fill: auto,
+ stroke: none,
+ draw: mark => {
+ for flip in (+1, -1) {
+ draw.merge-path({
+ draw.arc(
+ (0, 0),
+ radius: mark.size,
+ start: flip*(90deg + mark.sharpness),
+ delta: flip*mark.delta,
+ fill: none,
+ )
+ draw.line((), ((), "|-", (0, flip*1e-1)))
+ })
+ }
+ }
+ ),
+
+ cone: (
+ size: 8,
+ radius: 6,
+ angle: 30deg,
+
+ tip-end: mark => -mark.size,
+ tail-end: mark => mark.tip-end/2,
+ tail-origin: mark => mark.tip-end,
+
+ stroke: none,
+ draw: mark => {
+ for flip in (+1, -1) {
+ draw.merge-path({
+ draw.arc(
+ (-mark.size, -flip*1e-1),
+ radius: mark.radius,
+ start: 0deg,
+ stop: flip*mark.angle,
+ )
+ draw.line((), (0, 0))
+ })
+ }
+ }
+ ),
+
+ circle: (
+ size: 2,
+
+ tip-end: mark => -mark.size,
+ tail-end: mark => mark.size,
+ tip-origin: mark => mark.size + 0.5,
+ tail-origin: mark => -(mark.size + 0.5),
+
+ fill: none,
+
+ draw: mark => draw.circle((0,0), radius: mark.size, fill: mark.fill),
+
+ cap-offset: (mark, y) => {
+ let r = mark.size
+ let o = r - calc.sqrt(calc.max(0, r*r - y*y))
+ if not mark.tip { o *= -1 }
+ o
+ },
+ ),
+
+ square: (
+ size: 2,
+ angle: 0deg,
+ fill: none,
+ tip-origin: mark => +(mark.size + 0.5)/calc.cos(mark.angle),
+ tail-origin: mark => -(mark.size + 0.5)/calc.cos(mark.angle),
+ tip-end: mark => -mark.size/calc.cos(mark.angle),
+ tail-end: mark => +mark.size/calc.cos(mark.angle),
+ draw: mark => {
+ let x = mark.size
+ draw.rotate(mark.angle)
+ draw.rect(
+ (-x, -x), (+x, +x),
+ )
+ }
+ ),
+
+ diamond: (
+ inherit: "stealth",
+ size: 4,
+ angle: 45deg,
+ stealth: -1,
+ fill: none,
+ ),
+
+ bar: (
+ size: 4.9,
+ angle: 90deg,
+
+ tail-origin: mark => calc.min(..mark.extrude),
+
+ draw: mark => draw.line(
+ (mark.angle, -mark.size),
+ (mark.angle, +mark.size),
+ ),
+ cap-offset: (mark, y) => {
+ let o = y*calc.tan(mark.angle - 90deg)
+ // if mark.tip { o *= -1 }
+ -o
+ },
+ ),
+
+ cross: (
+ size: 4,
+ angle: 45deg,
+ draw: mark => {
+ draw.line((+mark.angle, -mark.size), (+mark.angle, +mark.size))
+ draw.line((-mark.angle, -mark.size), (-mark.angle, +mark.size))
+ },
+
+ cap-offset: (mark, y) => calc.tan(mark.angle + 90deg)*calc.abs(y),
+ ),
+
+ bracket: (
+ size: 6,
+ depth: 3,
+ draw: mark => draw.line(
+ (-mark.depth, mark.size),
+ (0, mark.size),
+ (0, -mark.size),
+ (-mark.depth, -mark.size),
+ fill: none,
+ ),
+ tail-origin: mark => -mark.depth,
+ ),
+
+ parenthesis: (
+ size: 8,
+ angle: 50deg,
+ draw: mark => draw.arc(
+ (0, 0),
+ start: -mark.angle,
+ stop: mark.angle,
+ radius: mark.size,
+ anchor: "origin",
+ fill: none,
+ ),
+ tail-end: mark => mark.size,
+ tip-end: mark => mark.size,
+ tip-origin: mark => mark.size,
+ tail-origin: mark => mark.size*calc.cos(mark.angle),
+ cap-offset: (mark, y) => mark.size*(calc.sqrt(1 - calc.pow(y/mark.size, 2)) - 1),
+ ),
+
+ hook: (
+ size: 2.88,
+ rim: 0.85,
+
+ tip-origin: mark => mark.size + 0.5,
+
+ stroke: (cap: "round"),
+
+ draw: mark => {
+ draw.arc(
+ (0,0),
+ start: -90deg,
+ stop: +90deg,
+ radius: mark.size,
+ fill: none,
+ )
+ draw.line((), (rel: (-mark.rim, 0)))
+ },
+ ),
+
+ hooks: (
+ inherit: "hook",
+ draw: mark => {
+ for flip in (-1, +1) {
+ draw.arc(
+ (0,0),
+ start: -flip*90deg,
+ stop: +flip*90deg,
+ radius: mark.size,
+ fill: none,
+ )
+ }
+ },
+ ),
+
+ ">": (inherit: "head", rev: false),
+ "<": (inherit: "head", rev: true),
+
+ ">>": (inherit: "head", extrude: (-2.88, 0), rev: false),
+ "<<": (inherit: "head", extrude: (-2.88, 0), rev: true),
+
+ ">>>": (inherit: "head", extrude: (-6, -3, 0), rev: false),
+ "<<<": (inherit: "head", extrude: (-6, -3, 0), rev: true),
+
+ "|>": (inherit: "solid", rev: false),
+ "<|": (inherit: "solid", rev: true),
+
+ "}>": (inherit: "stealth", rev: false),
+ "<{": (inherit: "stealth", rev: true),
+
+ "|": (inherit: "bar"),
+ "||": (inherit: "bar", extrude: (-3, 0)),
+ "|||": (inherit: "bar", extrude: (-6, -3, 0)),
+
+ "/": (inherit: "bar", angle: +60deg, rev: false),
+ "\\": (inherit: "bar", angle: -60deg, rev: false),
+
+ "x": (inherit: "cross"),
+ "X": (inherit: "cross", size: 7),
+
+ "o": (inherit: "circle"),
+ "O": (inherit: "circle", size: 4),
+ "*": (inherit: "circle", fill: auto),
+ "@": (inherit: "circle", size: 4, fill: auto),
+
+ "[]": (inherit: "square"),
+ "<>": (inherit: "diamond"),
+
+ "]": (inherit: "bracket", rev: false),
+ "[": (inherit: "bracket", rev: true),
+
+ ")": (inherit: "parenthesis", rev: false),
+ "(": (inherit: "parenthesis", rev: true),
+
+
+
+ // crow's foot notation
+ crowfoot: (
+ many-width: 5,
+ many-length: 8,
+ one-width: 5,
+ zero-width: 3.5,
+ gap: 3,
+ first-gap: 5,
+ many: true,
+ one: true,
+ zero: true,
+ tail-origin: mark => -mark.many-length,
+ zero-fill: white,
+ fill: none,
+ draw: mark => {
+ let x = 0
+ if mark.many {
+ draw.line((0, mark.many-width), (-mark.many-length - .5, 0), (0, -mark.many-width))
+ x -= mark.many-length
+ }
+ if mark.one {
+ x -= mark.gap
+ x = calc.min(x, -mark.first-gap)
+ draw.line((x, mark.one-width), (x, -mark.one-width))
+ }
+ if mark.zero {
+ x -= mark.gap
+ draw.circle((x - mark.zero-width, 0), radius: mark.zero-width, fill: mark.zero-fill)
+ }
+ }
+ ),
+ "n": (inherit: "crowfoot", zero: false, one: false, many: true),
+ "n!": (inherit: "crowfoot", zero: false, one: true, many: true),
+ "n?": (inherit: "crowfoot", zero: true, one: false, many: true),
+ "1": (inherit: "crowfoot", zero: false, one: true, many: false),
+ "1!": (inherit: "crowfoot", zero: false, one: true, many: false, extrude: mark => (0, -calc.max(4, mark.gap))),
+ "1?": (inherit: "crowfoot", zero: true, one: true, many: false),
+
+)
+
+#let MARKS = state("fletcher-marks", DEFAULT_MARKS)
diff --git a/render/packages/preview/fletcher/0.5.8/src/deps.typ b/render/packages/preview/fletcher/0.5.8/src/deps.typ
new file mode 100644
index 0000000..37fdc07
--- /dev/null
+++ b/render/packages/preview/fletcher/0.5.8/src/deps.typ
@@ -0,0 +1 @@
+#import "@preview/cetz:0.3.4"
diff --git a/render/packages/preview/fletcher/0.5.8/src/diagram.typ b/render/packages/preview/fletcher/0.5.8/src/diagram.typ
new file mode 100644
index 0000000..f8da773
--- /dev/null
+++ b/render/packages/preview/fletcher/0.5.8/src/diagram.typ
@@ -0,0 +1,561 @@
+#import "utils.typ": *
+#import "node.typ": *
+#import "edge.typ": *
+#import "draw.typ": draw-diagram
+#import "coords.typ": *
+
+
+
+/// Interpret #the-param[diagram][axes].
+///
+/// Returns a dictionary with:
+/// - `x`: Whether $u$ is reversed
+/// - `y`: Whether $v$ is reversed
+/// - `xy`: Whether the axes are swapped
+///
+/// - axes (array): Pair of directions specifying the interpretation of $(u, v)$
+/// coordinates. For example, `(ltr, ttb)` means $u$ goes $arrow.r$ and $v$
+/// goes $arrow.b$.
+/// -> dictionary
+#let interpret-axes(axes) = {
+ let dirs = axes.map(direction.axis)
+ let flip
+ if dirs == ("horizontal", "vertical") {
+ flip = false
+ } else if dirs == ("vertical", "horizontal") {
+ flip = true
+ } else {
+ error("Axes #0 cannot both be in the same direction. Try `axes: (ltr, ttb)`.", axes)
+ }
+
+ (
+ flip: (
+ x: axes.at(0) in (rtl, ttb),
+ y: axes.at(1) in (rtl, ttb),
+ xy: flip,
+ )
+ )
+}
+
+/// Convert an array of rects `(center: (x, y), size: (w, h))` with fractional
+/// positions into rects with integral positions.
+///
+/// If a rect is centered at a factional position `floor(x) < x < ceil(x)`, it
+/// will be replaced by two new rects centered at `floor(x)` and `ceil(x)`. The
+/// total width of the original rect is split across the two new rects according
+/// two which one is closer. (E.g., if the original rect is at `x = 0.25`, the
+/// new rect at `x = 0` has 75% the original width and the rect at `x = 1` has
+/// 25%.) The same splitting procedure is done for `y` positions and heights.
+///
+/// This is the algorithm used to determine grid layout in diagrams.
+///
+/// - rects (array): An array of rects of the form
+/// `(center: (x, y), size: (width, height))`. The coordinates `x` and `y` may
+/// be floats.
+/// -> array
+#let expand-fractional-rects(rects) = {
+ let new-rects
+ for axis in (0, 1) {
+ new-rects = ()
+ for rect in rects {
+ let coord = rect.center.at(axis)
+ let size = rect.size.at(axis)
+
+ if calc.fract(coord) == 0 {
+ rect.center.at(axis) = calc.trunc(coord)
+ new-rects.push(rect)
+ } else {
+ rect.center.at(axis) = calc.floor(coord)
+ rect.size.at(axis) = size*(calc.ceil(coord) - coord)
+ new-rects.push(rect)
+
+ rect.center.at(axis) = calc.ceil(coord)
+ rect.size.at(axis) = size*(coord - calc.floor(coord))
+ new-rects.push(rect)
+ }
+ }
+ rects = new-rects
+ }
+ new-rects
+}
+
+
+/// Determine the number and sizes of grid cells needed for a diagram with the
+/// given nodes and edges.
+///
+/// Returns a dictionary with:
+/// - `origin: (u-min, v-min)` Coordinate at the grid corner where elastic/`uv`
+/// coordinates are minimised.
+/// - `cell-sizes: (x-sizes, y-sizes)` Lengths and widths of each row and
+/// column.
+///
+/// - flip (dictionary): Describes axis order and orientation.
+/// - verts (array): Points that should be contained in the resulting grid.
+/// - rects (array): Rectangles (dictionaries of the form `(center, size)` which
+/// are used to determine cell sizes.
+#let compute-cell-sizes(flip, verts, rects) = {
+
+ if flip.xy {
+ // if x/y axes are flipped, transpose rectangles
+ rects = rects.map( ((center, size)) => {
+ (center: center, size: size.rev())
+ })
+ }
+ rects = expand-fractional-rects(rects)
+
+ // all points in diagram that should be spanned by coordinate grid
+ let points = rects.map(r => r.center)
+ points += verts
+
+ if points.len() == 0 { points.push((0,0)) }
+
+ let min-max-int(a) = (calc.floor(calc.min(..a)), calc.ceil(calc.max(..a)))
+ let (x-min, x-max) = min-max-int(points.map(p => p.at(0)))
+ let (y-min, y-max) = min-max-int(points.map(p => p.at(1)))
+ let origin = (x-min, y-min)
+ let bounding-dims = (x-max - x-min + 1, y-max - y-min + 1)
+
+ // Initialise row and column sizes
+ let cell-sizes = bounding-dims.map(n => (0pt,)*n)
+
+ // Expand cells to fit rects
+ for rect in rects {
+ let indices = vector.sub(rect.center, origin)
+ if flip.x { indices.at(0) = -1 - indices.at(0) }
+ if flip.y { indices.at(1) = -1 - indices.at(1) }
+ for axis in (0, 1) {
+ let i = indices.at(axis)
+ cell-sizes.at(axis).at(i) = calc.max(
+ cell-sizes.at(axis).at(i),
+ rect.size.at(axis),
+ )
+ }
+ }
+
+ if flip.xy {
+ cell-sizes = cell-sizes.rev()
+ }
+
+ (origin: origin, cell-sizes: cell-sizes)
+}
+
+/// Determine the centers of grid cells from their sizes and spacing between
+/// them.
+///
+/// Returns the a dictionary with:
+/// - `centers: (x-centers, y-centers)` Positions of each row and column,
+/// measured from the corner of the bounding box.
+/// - `bounding-size: (x-size, y-size)` Dimensions of the bounding box.
+///
+/// - grid (dictionary): Representation of the grid layout, including:
+/// - `cell-sizes: (x-sizes, y-sizes)` Lengths and widths of each row and
+/// column.
+/// - `spacing: (x-spacing, y-spacing)` Gap to leave between cells.
+/// -> dictionary
+#let compute-cell-centers(grid) = {
+ // (x: (c1x, c2x, ...), y: ...)
+ let centers = array.zip(grid.cell-sizes, grid.spacing)
+ .map(((sizes, spacing)) => {
+ array.zip(cumsum(sizes), sizes, range(sizes.len()))
+ .map(((end, size, i)) => end - size/2 + spacing*i)
+ })
+
+ let bounding-size = array.zip(centers, grid.cell-sizes)
+ .map(((centers, sizes)) => centers.at(-1) + sizes.at(-1)/2)
+
+ (
+ centers: centers,
+ bounding-size: bounding-size,
+ )
+}
+
+/// Determine the number, sizes and relative positions of rows and columns in
+/// the diagram's coordinate grid.
+///
+/// Rows and columns are sized to fit nodes. Coordinates are not required to
+/// start at the origin, `(0,0)`.
+#let compute-grid(rects, verts, options) = {
+ let grid = (
+ axes: options.axes,
+ spacing: options.spacing,
+ )
+
+ grid += interpret-axes(grid.axes)
+ grid += compute-cell-sizes(grid.flip, verts, rects)
+
+ // enforce minimum cell size
+ grid.cell-sizes = grid.cell-sizes.zip(options.cell-size)
+ .map(((sizes, min-size)) => sizes.map(calc.max.with(min-size)))
+
+ grid += compute-cell-centers(grid)
+
+ assert(grid.centers.at(0).len() == grid.cell-sizes.at(0).len())
+ assert(grid.centers.at(1).len() == grid.cell-sizes.at(1).len())
+
+ grid
+}
+
+#let extract-nodes-and-edges-from-equation(eq) = {
+ assert(eq.func() == math.equation)
+ let terms = flatten-sequence-to-array(eq.body)
+
+ let edges = ()
+ let nodes = ()
+
+ // convert math matrix into array-of-arrays matrix
+ let matrix = ((none,),)
+ let (x, y) = (0, 0)
+ for child in terms {
+ if child.func() == metadata {
+ if child.value.class == "node" {
+ let node = child.value
+ node.pos = (raw: (x, y))
+ nodes.push(node)
+ } else if child.value.class == "edge" {
+ let edge = child.value
+ edge.vertices.at(0) = map-auto(edge.vertices.at(0), (x, y))
+ if edge.label != none { edge.label = $edge.label$ } // why is this needed?
+ edge.vertices.at(-1) = map-auto(edge.vertices.at(-1), (rel: (1, 0)))
+ edge.node-index = none
+ edges.push(edge)
+ }
+ } else if repr(child.func()) == "linebreak" {
+ y += 1
+ x = 0
+ matrix.push((none,))
+ } else if repr(child.func()) == "align-point" {
+ x += 1
+ matrix.at(-1).push(none)
+ } else {
+ matrix.at(-1).at(-1) += child
+ }
+ }
+
+ // turn matrix into an array of nodes
+ for (y, row) in matrix.enumerate() {
+ for (x, item) in row.enumerate() {
+ if not is-space(item) {
+ nodes.push(node((x, y), $item$).value)
+ }
+ }
+ }
+
+
+ (
+ nodes: nodes,
+ edges: edges,
+ )
+}
+
+
+
+#let interpret-diagram-args(args) = {
+ if args.named().len() > 0 {
+ error("Unexpected named argument(s) #..0.", args.named().keys())
+ }
+
+ let positional-args = args.pos().flatten().join() + [] // join to ensure sequence
+ let objects = positional-args.children
+
+ let nodes = ()
+ let edges = ()
+
+ for obj in objects {
+ if obj.func() == metadata {
+ if obj.value.class == "node" {
+ let node = obj.value
+ nodes.push(node)
+
+ } else if obj.value.class == "edge" {
+ let edge = obj.value
+ edge.node-index = nodes.len()
+ edges.push(edge)
+ }
+
+ } else if obj.func() == math.equation {
+ let result = extract-nodes-and-edges-from-equation(obj)
+ nodes += result.nodes
+ edges += result.edges
+
+ } else {
+ panic("Unrecognised value passed to diagram:", obj)
+ }
+ }
+
+ (
+ nodes: nodes,
+ edges: edges,
+ )
+
+}
+
+
+
+/// Draw a diagram containing `node()`s and `edge()`s.
+///
+/// - ..args (array): Content to draw in the diagram, including nodes and edges.
+///
+/// The results of `node()` and `edge()` can be _joined_, meaning you can
+/// specify them as separate arguments, or in a block:
+///
+/// ```typ
+/// #diagram(
+/// // one object per argument
+/// node((0, 0), $A$),
+/// node((1, 0), $B$),
+/// {
+/// // multiple objects in a block
+/// // can use scripting, loops, etc
+/// node((2, 0), $C$)
+/// node((3, 0), $D$)
+/// },
+/// for x in range(4) { node((x, 1) [#x]) },
+/// )
+/// ```
+///
+/// Nodes and edges can also be specified in math-mode.
+///
+/// ```typ
+/// #diagram($
+/// A & B \ // two nodes at (0,0) and (1,0)
+/// C edge(->) & D \ // an edge from (0,1) to (1,1)
+/// node(sqrt(pi), stroke: #1pt) // a node with options
+/// $)
+/// ```
+///
+/// - debug (bool, 1, 2, 3): Level of detail for drawing debug information.
+/// Level `1` or `true` shows a coordinate grid; higher levels show bounding boxes and
+/// anchors, etc.
+///
+/// - spacing (length, pair of lengths): Gaps between rows and columns. Ensures
+/// that nodes at adjacent grid points are at least this far apart (measured as
+/// the space between their bounding boxes).
+///
+/// Separate horizontal/vertical gutters can be specified with `(x, y)`. A
+/// single length `d` is short for `(d, d)`.
+///
+/// - cell-size (length, pair of lengths): Minimum size of all rows and columns.
+/// A single length `d` is short for `(d, d)`.
+///
+/// - node-inset (length, pair of lengths): Default value of
+/// #the-param[node][inset].
+///
+/// - node-outset (length, pair of lengths): Default value of
+/// #the-param[node][outset].
+///
+/// - node-shape (rect, circle, function): Default value of
+/// #the-param[node][shape].
+///
+/// - node-stroke (stroke, none): Default value of #the-param[node][stroke].
+///
+/// The default stroke is folded with the stroke specified for the node. For
+/// example, if `node-stroke` is `1pt` and #the-param[node][stroke] is `red`,
+/// then the resulting stroke is `1pt + red`.
+///
+/// - node-fill (paint): Default value of #the-param[node][fill].
+///
+/// - edge-stroke (stroke): Default value of #the-param[edge][stroke]. By
+/// default, this is chosen to match the thickness of mathematical arrows such
+/// as $A -> B$ in the current font size.
+///
+/// The default stroke is folded with the stroke specified for the edge. For
+/// example, if `edge-stroke` is `1pt` and #the-param[edge][stroke] is `red`,
+/// then the resulting stroke is `1pt + red`.
+///
+/// - node-corner-radius (length, none): Default value of
+/// #the-param[node][corner-radius].
+///
+/// - edge-corner-radius (length, none): Default value of
+/// #the-param[edge][corner-radius].
+///
+/// - node-defocus (number): Default value of #the-param[node][defocus].
+///
+/// - label-sep (length): Default value of #the-param[edge][label-sep].
+///
+/// - label-size (length): Default value of #the-param[edge][label-size].
+///
+/// - label-wrapper (function): Default value of
+/// #the-param[edge][label-wrapper].
+///
+/// - mark-scale (percent): Default value of #the-param[edge][mark-scale].
+///
+/// - crossing-fill (paint): Color to use behind connectors or labels to give
+/// the illusion of crossing over other objects. See
+/// #the-param[edge][crossing-fill].
+///
+/// - crossing-thickness (number): Default thickness of the occlusion made by
+/// crossing connectors. See #param[edge][crossing-thickness].
+///
+/// - axes (pair of directions): The orientation of the diagram's axes.
+///
+/// This defines the elastic coordinate system used by nodes and edges. To make
+/// the $y$ coordinate increase up the page, use `(ltr, btt)`. For the matrix
+/// convention `(row, column)`, use `(ttb, ltr)`.
+///
+/// #stack(
+/// dir: ltr,
+/// spacing: 1fr,
+/// fletcher.diagram(
+/// axes: (ltr, ttb),
+/// debug: 1,
+/// node((0,0), $(0,0)$),
+/// edge((0,0), (1,0), "->"),
+/// node((1,0), $(1,0)$),
+/// node((1,1), $(1,1)$),
+/// node((0.5,0.5), `axes: (ltr, ttb)`),
+/// ),
+/// fletcher.diagram(
+/// axes: (ltr, btt),
+/// debug: 1,
+/// node((0,0), $(0,0)$),
+/// edge((0,0), (1,0), "->"),
+/// node((1,0), $(1,0)$),
+/// node((1,1), $(1,1)$),
+/// node((0.5,0.5), `axes: (ltr, btt)`),
+/// ),
+/// fletcher.diagram(
+/// axes: (ttb, ltr),
+/// debug: 1,
+/// node((0,0), $(0,0)$),
+/// edge((0,0), (1,0), "->", bend: -20deg),
+/// node((1,0), $(1,0)$),
+/// node((1,1), $(1,1)$),
+/// node((0.5,0.5), `axes: (ttb, ltr)`),
+/// ),
+/// )
+///
+/// - render (function): After the node sizes and grid layout have been
+/// determined, the `render` function is called with the following arguments:
+/// - `grid`: a dictionary of the row and column widths and positions;
+/// - `nodes`: an array of nodes (dictionaries) with computed attributes
+/// (including size and physical coordinates);
+/// - `edges`: an array of connectors (dictionaries) in the diagram; and
+/// - `options`: other diagram attributes.
+///
+/// This callback is exposed so you can access the above data and draw things
+/// directly with CeTZ.
+#let diagram(
+ ..args,
+ debug: false,
+ axes: (ltr, ttb),
+ spacing: 3em,
+ cell-size: 0pt,
+ edge-stroke: 0.048em,
+ node-stroke: none,
+ edge-corner-radius: 2.5pt,
+ node-corner-radius: none,
+ node-inset: 6pt,
+ node-outset: 0pt,
+ node-shape: auto,
+ node-fill: none,
+ node-defocus: 0.2,
+ label-sep: 0.4em,
+ label-size: 1em,
+ label-wrapper: edge => box(
+ [#edge.label],
+ inset: .2em,
+ radius: .2em,
+ fill: edge.label-fill,
+ ),
+ mark-scale: 100%,
+ crossing-fill: white,
+ crossing-thickness: 5,
+ render: (grid, nodes, edges, options) => {
+ cetz.canvas(draw-diagram(grid, nodes, edges, debug: options.debug))
+ },
+) = {
+
+ let spacing = as-pair(spacing).map(as-length)
+ let cell-size = as-pair(cell-size).map(as-length)
+
+ let options = (
+ debug: int(debug),
+ axes: axes,
+ spacing: spacing,
+ cell-size: cell-size,
+ node-inset: node-inset,
+ node-outset: node-outset,
+ node-shape: node-shape,
+ node-stroke: node-stroke,
+ node-fill: node-fill,
+ node-corner-radius: node-corner-radius,
+ edge-corner-radius: edge-corner-radius,
+ node-defocus: node-defocus,
+ label-sep: label-sep,
+ label-size: label-size,
+ label-wrapper: label-wrapper,
+ edge-stroke: as-stroke(edge-stroke),
+ mark-scale: mark-scale,
+ crossing-fill: crossing-fill,
+ crossing-thickness: crossing-thickness,
+ )
+
+ let (nodes, edges) = interpret-diagram-args(args)
+
+ box(context {
+ let options = options
+
+ options.em-size = 1em.to-absolute()
+ options.spacing = options.spacing.map(length.to-absolute)
+ options.cell-size = options.cell-size.map(length.to-absolute)
+
+ let nodes = nodes.map(node => {
+ node = resolve-node-options(node, options)
+ node = measure-node-size(node)
+ node
+ })
+ let edges = edges.map(edge => resolve-edge-options(edge, options))
+
+ // PHASE 1: Resolve uv coordinates where possible
+
+ // try resolving node uv coordinates. this resolves to NaN coords if the
+ // resolution fails (e.g., if the coords depend on physical lengths)
+ let (ctx-with-uv-anchors, nodes) = resolve-node-coordinates(
+ nodes, ctx: (target-system: "uv"))
+
+
+ // nodes and edges whose uv coordinates can be resolved without knowing the grid
+ let rects-affecting-grid = nodes
+ .filter(node => not is-nan-vector(node.pos.uv))
+ .map(node => (center: node.pos.uv, size: node.size))
+
+ let vertices-affecting-grid = (edges
+ .map(edge => resolve-edge-vertices(edge, nodes, ctx: ctx-with-uv-anchors + (target-system: "uv")))
+ .join() + ()) // coerce none to ()
+ .filter(vert => not is-nan-vector(vert))
+
+
+ // PHASE 2: Determine elastic grid (row/column sizes) and resolve xy coordinates
+
+ // determine diagram's elastic grid layout
+ let grid = compute-grid(rects-affecting-grid, vertices-affecting-grid, options)
+
+ let ctx-with-xyz-anchors
+
+ // we run multiple passes so that anchors on enclose nodes
+ // have a chance to resolve
+ // (a better way would be to resolve coordinates and enclose nodes together)
+ for i in range(5) {
+ // now with grid determined, compute final (physical) coordinates for nodes and edges
+ (ctx-with-xyz-anchors, nodes) = resolve-node-coordinates(
+ nodes, ctx: (target-system: "xyz", grid: grid))
+
+ // resolve enclosing nodes
+ nodes = resolve-node-enclosures(nodes, ctx-with-xyz-anchors)
+ }
+
+ // resolve edges
+ edges = edges.map(edge => {
+ edge.final-vertices = resolve-edge-vertices(
+ edge, ctx: ctx-with-xyz-anchors + (target-system: "xyz", grid: grid), nodes
+ )
+
+ edge = convert-edge-corner-to-poly(edge)
+ edge = apply-edge-shift(grid, edge)
+ edge
+ })
+
+
+ render(grid, nodes, edges, options)
+ })
+}
\ No newline at end of file
diff --git a/render/packages/preview/fletcher/0.5.8/src/draw.typ b/render/packages/preview/fletcher/0.5.8/src/draw.typ
new file mode 100644
index 0000000..89c2930
--- /dev/null
+++ b/render/packages/preview/fletcher/0.5.8/src/draw.typ
@@ -0,0 +1,905 @@
+#import "utils.typ": *
+#import "marks.typ": *
+#import "coords.typ": uv-to-xy
+
+#let DEBUG_COLOR = rgb("f008")
+#let DEBUG_COLOR2 = rgb("0f08")
+
+#let draw-debug(objs) = {
+ cetz.draw.floating(objs)
+}
+
+#let draw-node-outline(node) = {
+ cetz.draw.group({
+ cetz.draw.translate(node.pos.xyz)
+ (node.shape)(node, node.outset)
+ })
+}
+
+#let draw-node(node, debug: 0) = {
+
+ let result = {
+ if node.stroke != none or node.fill != none or not node.auto-shape {
+ cetz.draw.group({
+ cetz.draw.translate(node.pos.xyz)
+ for (i, extrude) in node.extrude.enumerate() {
+ cetz.draw.set-style(
+ fill: if i == 0 { node.fill },
+ stroke: node.stroke,
+ )
+ (node.shape)(node, extrude)
+ }
+ })
+ }
+
+ if node.label != none {
+ let ε = 1e-10pt // temp fix for https://github.com/Jollywatt/typst-fletcher/issues/64
+ cetz.draw.content(
+ node.pos.xyz,
+ box(
+ // wrapping label in a box allows user to control its alignment
+ align(center + horizon, node.label),
+ stroke: if debug >= 3 { DEBUG_COLOR2 + 0.25pt },
+ width: node.size.at(0) - 2*node.inset + ε,
+ height: node.size.at(1) - 2*node.inset,
+ ),
+ anchor: "center",
+ )
+ }
+ }
+
+ if node.layer != 0 { result = cetz.draw.on-layer(node.layer, result) }
+
+ (node.post)(result) // post-process (e.g., hide)
+
+ // Draw debug stuff
+ if debug >= 1 {
+ // dot at node anchor
+ draw-debug(cetz.draw.circle(
+ node.pos.xyz,
+ radius: 0.5pt,
+ fill: DEBUG_COLOR,
+ stroke: none,
+ ))
+ }
+
+ if debug >= 2 and node.radius != 0pt {
+ // node bounding rectangle
+ draw-debug({
+ cetz.draw.rect(
+ ..rect-at(node.pos.xyz, node.size),
+ stroke: DEBUG_COLOR + .1pt,
+ )
+
+ // node anchoring outline (what edges snap to)
+ cetz.draw.set-style(stroke: DEBUG_COLOR2 + 0.25pt)
+ draw-node-outline(node)
+ })
+ }
+
+ if debug >= 3 and "enclosed-vertices" in node {
+ draw-debug(node.enclosed-vertices.map(pos => {
+ cetz.draw.circle(pos, radius: node.inset, stroke: 0.1pt + blue)
+ }).join())
+ }
+}
+
+
+/// Draw an edge label at point along a curve.
+///
+/// Label is drawn near the point `curve(edge.label-pos)`, respecting the label
+/// options of `edge()` such as #param[edge][label-side] and
+/// #param[edge][label-angle].
+///
+/// - edge (dictionary): Edge object. Must include:
+/// - `label-pos`
+/// - `label-sep`
+/// - `label-side`
+/// - `label-anchor`
+/// - `label-angle`
+/// - `label-wrapper`
+/// - curve (function): Parametric curve $RR -> RR^2$ describing the shape of
+/// the edge in $x y$ coordinates.
+#let place-edge-label-on-curve(edge, curve, debug: 0) = {
+
+ let curve-point = curve(edge.label-pos.position)
+ let curve-point-ε = curve(edge.label-pos.position + 1e-3%)
+
+ let θ = wrap-angle-180(angle-between(curve-point, curve-point-ε))
+ let θ-normal = θ + if edge.label-side == right { +90deg } else { -90deg }
+
+ if type(edge.label-angle) == alignment {
+ edge.label-angle = θ - (
+ right: 0deg,
+ top: 90deg,
+ left: 180deg,
+ bottom: 270deg,
+ ).at(repr(edge.label-angle))
+
+ } else if edge.label-angle == auto {
+ edge.label-angle = θ
+ if calc.abs(edge.label-angle) > 90deg {
+ edge.label-angle += 180deg
+ }
+ }
+
+ if edge.label-anchor == auto {
+ edge.label-anchor = angle-to-anchor(θ-normal - edge.label-angle)
+ }
+
+ let label-pos = (to: curve-point, rel: (θ-normal, -edge.label-sep))
+
+ cetz.draw.content(
+ label-pos,
+ box(
+ {
+ set text(edge.label-size)
+ (edge.label-wrapper)(edge)
+ },
+ stroke: if debug >= 2 { DEBUG_COLOR2 + 0.25pt },
+ ),
+ angle: edge.label-angle,
+ anchor: if edge.label-anchor != auto { edge.label-anchor },
+ )
+
+ if debug >= 2 {
+ draw-debug(cetz.draw.circle(
+ label-pos,
+ radius: 0.75pt,
+ stroke: none,
+ fill: DEBUG_COLOR2,
+ ))
+ }
+}
+
+
+// Get the arrow head adjustment for a given extrusion distance.
+//
+// Returns a pair `(from, to)` of distances.
+// If `from < 0pt` and `to > 0pt`, the path length of the edge increases.
+#let cap-offsets(edge, y) = {
+ (0, 1).map(pos => {
+ let mark = edge.marks.find(mark => calc.abs(mark.pos - pos) < 1e-3)
+ if mark == none { return 0pt }
+
+ let is-tip = (pos == 0) == mark.rev
+ let sign = if mark.rev { -1 } else { +1 }
+
+ let x = cap-offset(
+ mark + (tip: is-tip),
+ sign*y/edge.stroke.thickness,
+ )
+
+ let origin = if is-tip { mark.tip-origin } else { mark.tail-origin }
+ x -= origin*float(mark.scale)
+
+ sign*x*edge.stroke.thickness
+ })
+}
+
+#let with-decorations(edge, path) = {
+ if edge.decorations == none { return path }
+
+ let has-mark-at(t) = edge.marks.find(mark => calc.abs(mark.pos - t) < 1e-3 ) != none
+
+ let decor = edge.decorations.with(stroke: edge.stroke)
+
+ // TODO: should this be an absolute offset, not 10% the path length?
+ let ε = 1e-3 // cetz assertions sometimes fail from floating point errors
+ decor = decor.with(
+ start: if has-mark-at(0) { 0.1 } else { ε } * 100%,
+ stop: if has-mark-at(1) { 0.9 } else { 1 - ε } * 100%,
+ )
+
+ decor(path)
+}
+
+/// Draw a straight edge.
+///
+/// - edge (dictionary): The edge object, a dictionary, containing:
+/// - `vertices`: an array of two points, the line's start and end points.
+/// - `extrude`: An array of extrusion lengths to apply a multi-stroke effect
+/// with.
+/// - `stroke`: The stroke style.
+/// - `marks`: An array of marks to draw along the edge.
+/// - `label`: Content for label.
+/// - `label-side`, `label-pos`, `label-sep`, and `label-anchor`.
+/// - debug (int): Level of debug details to draw.
+#let draw-edge-line(edge, debug: 0) = {
+ let (from, to) = edge.final-vertices
+ let θ = angle-between(from, to)
+
+ // Draw line(s), one for each extrusion shift
+ for shift in edge.extrude {
+
+ let offsets = cap-offsets(edge, shift)
+ let points = (from, to).zip(offsets)
+ .map(((point, offset)) => {
+ // Shift line sideways (for multi-stroke effect)
+ point = (rel: (θ + 90deg, shift), to: point)
+ // Shift end points lengthways depending on marks
+ point = (rel: (θ, offset), to: point)
+ point
+ })
+
+ let obj = cetz.draw.line(
+ ..points,
+ stroke: edge.stroke,
+ )
+
+ with-decorations(edge, obj)
+ }
+
+ // Draw marks
+ let total-path-len = vector-len(vector.sub(from, to))
+ let curve(t) = {
+ if calc.abs(total-path-len) > 1e-3pt {
+ t = relative-to-float(t, len: total-path-len)
+ vector.lerp(from, to, t)
+ } else { from }
+ }
+
+ for mark in edge.marks {
+ place-mark-on-curve(mark, curve, stroke: edge.stroke, debug: debug >= 3)
+ }
+
+ // Draw label
+ // This edge only has a single segment, so don't draw the label unless it's
+ // placed on segment 0. This means that when calling this function for the
+ // individual segments of an edge (`draw-edge-polyline`), the `segment` field
+ // of `label-pos` must be set to 0.
+ if edge.label != none and edge.label-pos.segment == 0 {
+
+ // Choose label anchor based on edge direction,
+ // preferring to place labels above the edge
+ if edge.label-side == auto {
+ edge.label-side = if calc.abs(θ) < 90deg { left } else { right }
+ }
+
+ place-edge-label-on-curve(edge, curve, debug: debug)
+ }
+
+}
+
+
+/// Draw a bent edge.
+///
+/// - edge (dictionary): The edge object, a dictionary, containing:
+/// - `vertices`: an array of two points, the arc's start and end points.
+/// - `bend`: The angle of the arc.
+/// - `extrude`: An array of extrusion lengths to apply a multi-stroke effect
+/// with.
+/// - `stroke`: The stroke style.
+/// - `marks`: An array of marks to draw along the edge.
+/// - `label`: Content for label.
+/// - `label-side`, `label-pos`, `label-sep`, and `label-anchor`.
+/// - debug (int): Level of debug details to draw.
+#let draw-edge-arc(edge, debug: 0) = {
+ let (from, to) = edge.final-vertices
+
+ // Determine the arc from the stroke end points and bend angle
+ let (center, radius, start, stop) = get-arc-connecting-points(from, to, edge.bend)
+
+ let bend-dir = if edge.bend > 0deg { +1 } else { -1 }
+
+ // Draw arc(s), one for each extrusion shift
+ for shift in edge.extrude {
+
+ // Adjust arc angles to accommodate for cap offsets
+ let (δ-start, δ-stop) = cap-offsets(edge, shift)
+ .map(arclen => -bend-dir*arclen/radius*1rad)
+
+ let obj = cetz.draw.arc(
+ center,
+ radius: radius + shift,
+ start: start + δ-start,
+ stop: stop + δ-stop,
+ anchor: "origin",
+ stroke: edge.stroke,
+ )
+
+ with-decorations(edge, obj)
+ }
+
+ // Draw marks
+ let total-path-len = calc.abs(stop - start)/1rad*radius
+ let curve(t) = {
+ t = relative-to-float(t, len: total-path-len)
+ vector.add(center, vector-polar(radius, lerp(start, stop, t)))
+ }
+ for mark in edge.marks {
+ place-mark-on-curve(mark, curve, stroke: edge.stroke, debug: debug >= 3)
+ }
+
+ // Draw label
+ if edge.label != none and edge.label-pos.segment == 0 {
+
+ if edge.label-side == auto {
+ // Choose label side to be on outside of arc
+ edge.label-side = if edge.bend > 0deg { left } else { right }
+ }
+
+ place-edge-label-on-curve(edge, curve, debug: debug)
+
+ }
+}
+
+
+
+/// Draw a multi-segment edge
+///
+/// - edge (dictionary): The edge object, a dictionary, containing:
+/// - `vertices`: an array of at least two points to draw segments between.
+/// - `corner-radius`: Radius of curvature between segments.
+/// - `extrude`: An array of extrusion lengths to apply a multi-stroke effect
+/// with.
+/// - `stroke`: The stroke style.
+/// - `marks`: An array of marks to draw along the edge.
+/// - `label`: Content for label.
+/// - `label-side`, `label-pos`, `label-sep`, and `label-anchor`.
+/// - debug (int): Level of debug details to draw.
+#let draw-edge-polyline(edge, debug: 0) = {
+
+ let verts = edge.final-vertices
+ let n-segments = verts.len() - 1
+
+ // angles of each segment
+ let θs = range(n-segments).map(i => {
+ let (vert, vert-next) = (verts.at(i), verts.at(i + 1))
+ assert(vert != vert-next, message: "Adjacent vertices must be distinct.")
+ angle-between(vert, vert-next)
+ })
+
+
+ // round corners
+ let calculate-rounded-corner(i) = {
+ let pt = verts.at(i)
+ let Δθ = wrap-angle-180(θs.at(i) - θs.at(i - 1))
+ let dir = if Δθ > 0deg { +1 } else { -1 } // +1 if ccw, -1 if cw
+
+
+ let θ-normal = θs.at(i - 1) + Δθ/2 + 90deg // direction to center of curvature
+
+ let radius = edge.corner-radius
+ // radius *= 90deg/calc.max(calc.abs(Δθ), 45deg) // visual adjustment so that tighter bends have smaller radii
+ radius *= 1 + calc.cos(Δθ)
+ // skip correcting the corner radius for extruded strokes if there's no stroke at all
+ if edge.extrude != () {
+ radius += if dir > 0 { calc.max(..edge.extrude) } else { -calc.min(..edge.extrude) }
+ }
+ radius *= dir // ??? makes math easier or something
+
+ if calc.abs(Δθ) > 179deg {
+ // singular line; skip arc
+ (
+ arc-center: pt,
+ arc-radius: 0*radius,
+ start: θs.at(i - 1) - 90deg,
+ delta: wrap-angle-180(Δθ),
+ line-shift: 0*radius, // distance from vertex to beginning of arc
+ )
+ } else {
+
+ // distance from vertex to center of curvature
+ let dist = radius/calc.cos(Δθ/2)
+
+ (
+ arc-center: vector.add(pt, vector-polar(dist, θ-normal)),
+ arc-radius: radius,
+ start: θs.at(i - 1) - 90deg,
+ delta: wrap-angle-180(Δθ),
+ line-shift: radius*calc.tan(Δθ/2), // distance from vertex to beginning of arc
+ )
+ }
+
+ }
+
+ let rounded-corners
+ if edge.corner-radius != none {
+ rounded-corners = range(1, θs.len()).map(calculate-rounded-corner)
+ }
+
+ let lerp-scale(t, i) = {
+ if type(t) in (int, float) {
+ let τ = t*n-segments - i
+ if (0 < τ and τ <= 1 or
+ i == 0 and τ <= 0 or
+ i == n-segments - 1 and 1 < τ) { τ }
+ } else {
+ t = as-relative(t)
+ let τ = lerp-scale(float(t.ratio), i)
+ if τ != none {τ *100% + t.length }
+ }
+ }
+
+ let debug-stroke = edge.stroke.thickness/4 + DEBUG_COLOR2
+
+ // phase keeps track of how to offset dash patterns
+ // to ensure continuity between segments
+ let phase = 0pt
+ let stroke-with-phase(phase) = stroke-to-dict(edge.stroke) + (
+ dash: if type(edge.stroke.dash) == dictionary {
+ (array: edge.stroke.dash.array, phase: phase)
+ }
+ )
+
+ // draw each segment
+ for i in range(n-segments) {
+ let (from, to) = (verts.at(i), verts.at(i + 1))
+ let marks = ()
+
+ let Δphase = 0pt
+
+ if edge.corner-radius == none {
+
+ // add phantom marks to ensure segment joins are clean
+ if i > 0 {
+ let Δθ = θs.at(i) - θs.at(i - 1)
+ marks.push((
+ inherit: "bar",
+ pos: 0,
+ angle: 90deg - Δθ/2,
+ hide: true,
+ ))
+ }
+ if i < θs.len() - 1 {
+ let Δθ = θs.at(i + 1) - θs.at(i)
+ marks.push((
+ inherit: "bar",
+ pos: 1,
+ angle: 90deg + Δθ/2,
+ hide: true,
+ ))
+ }
+
+ Δphase += vector-len(vector.sub(from, to))
+
+ } else { // rounded corners
+
+ if i > 0 {
+ // offset start of segment to give space for previous arc
+ let (line-shift,) = rounded-corners.at(i - 1)
+ from = vector.add(from, vector-polar(line-shift, θs.at(i)))
+ }
+
+ if i < θs.len() - 1 {
+
+ let (arc-center, arc-radius, start, delta, line-shift) = rounded-corners.at(i)
+ to = vector.add(to, vector-polar(-line-shift, θs.at(i)))
+
+ Δphase += vector-len(vector.sub(from, to))
+
+ for d in edge.extrude {
+ if calc.abs(delta) > 1deg {
+ cetz.draw.arc(
+ arc-center,
+ radius: arc-radius - d,
+ start: start,
+ delta: delta,
+ anchor: "origin",
+ stroke: stroke-with-phase(phase + Δphase),
+ )
+ }
+
+ if debug >= 4 {
+ cetz.draw.on-layer(1, cetz.draw.circle(
+ arc-center,
+ radius: arc-radius - d,
+ stroke: debug-stroke,
+ ))
+
+ }
+ }
+
+ Δphase += delta/1rad*arc-radius
+ }
+ }
+
+ marks = marks.map(resolve-mark)
+
+ // distribute original marks across segments
+ marks += edge.marks.map(mark => {
+ mark.pos = lerp-scale(mark.pos, i)
+ mark
+ }).filter(mark => mark.pos != none)
+
+ // If the current segment is the one where the label is placed, keep the
+ // label (but change its segment to 0 because `draw-edge-line` will consider
+ // this segment a single-segment edge and only draw labels on segment 0).
+ // Otherwise, draw no label.
+ let label-options = if i == edge.label-pos.segment {
+ (label-pos: edge.label-pos + (segment: 0), label: edge.label)
+ } else {
+ (label: none)
+ }
+
+
+ draw-edge-line(
+ edge + (
+ kind: "line",
+ final-vertices: (from, to),
+ marks: marks,
+ stroke: stroke-with-phase(phase),
+ ) + label-options,
+ debug: debug,
+ )
+
+ phase += Δphase
+
+ }
+
+
+ if debug >= 4 {
+ cetz.draw.line(
+ ..verts,
+ stroke: debug-stroke,
+ )
+ }
+}
+
+
+
+/// Of all the intersection points within a set of CeTZ objects, find the one
+/// which is farthest from a target point and pass it to a callback.
+///
+/// If no intersection points are found, use the target point itself.
+///
+/// - objects (cetz array, none): Objects to search within for intersections. If
+/// `none`, callback is immediately called with `target`.
+/// - target (point): Target point to sort intersections by proximity with, and
+/// to use as a fallback if no intersections are found.
+#let find-farthest-intersection(objects, target, callback) = {
+
+ if objects == none { return callback(target) }
+
+ let node-name = "intersection-finder"
+ cetz.draw.hide(cetz.draw.intersections(node-name, objects))
+
+ cetz.draw.get-ctx(ctx => {
+
+ let calculate-anchors = ctx.nodes.at(node-name).anchors
+ let anchor-names = calculate-anchors(())
+ let anchor-points = anchor-names.map(calculate-anchors)
+ .map(point => {
+ point.at(1) *= -1 // CETZ Y AXIS
+ vector-2d(vector.scale(point, 1cm))
+ }).sorted(key: point => vector-len(vector.sub(point, target)))
+
+ let anchor = anchor-points.at(-1, default: target)
+
+ callback(anchor)
+
+ })
+
+}
+
+#let find-anchor-pair((from-group, to-group), (from-point, to-point), callback) = {
+ find-farthest-intersection(from-group, from-point, from-anchor => {
+ find-farthest-intersection(to-group, to-point, to-anchor => {
+ callback((from-anchor, to-anchor))
+ })
+ })
+
+}
+
+/// Get the anchor point around a node outline at a certain angle.
+#let get-node-anchor(node, θ, callback) = {
+ let outline = cetz.draw.group({
+ cetz.draw.translate(node.pos.xyz)
+ (node.shape)(node, node.outset)
+ })
+ let dummy-line = cetz.draw.line(
+ node.pos.xyz,
+ (rel: (θ, 10*node.radius))
+ )
+
+ find-farthest-intersection(outline + dummy-line, node.pos.xyz, callback)
+}
+
+/// Return the anchor point for an edge connecting to a node with the "defocus"
+/// adjustment.
+///
+/// Basically, for very long/wide nodes, don't make edges coming in from all
+/// angles go to the exact node center, but "spread them out" a bit.
+///
+/// See https://www.desmos.com/calculator/irt0mvixky.
+#let defocus-adjustment(node, θ) = {
+ if node == none { return (0pt, 0pt) }
+ let μ = calc.pow(node.aspect, node.defocus)
+ (
+ calc.max(0pt, node.size.at(0)/2*(1 - 1/μ))*calc.cos(θ),
+ calc.max(0pt, node.size.at(1)/2*(1 - μ/1))*calc.sin(θ),
+ )
+
+}
+
+
+
+#let draw-anchored-line(edge, nodes, debug: 0) = {
+ let (from, to) = edge.final-vertices
+ let θ = angle-between(from, to) + 90deg
+
+ // TODO: do defocus adjustment sensibly
+ if nodes.at(0).len() == 1 {
+ from = vector.add(from, defocus-adjustment(nodes.at(0).at(0), θ - 90deg))
+ }
+ if nodes.at(1).len() == 1 {
+ to = vector.add(to, defocus-adjustment(nodes.at(1).at(0), θ + 90deg))
+
+ }
+
+
+ let dummy-line = cetz.draw.line(from, to)
+
+ let intersection-objects = nodes.map(nodes => {
+ cetz.draw.group(nodes.map(draw-node-outline).join())
+ dummy-line
+ })
+
+
+ find-anchor-pair(intersection-objects, (from, to), anchors => {
+ let obj = draw-edge-line(edge + (
+ final-vertices: anchors,
+ ), debug: debug)
+ (edge.post)(obj) // post-process (e.g., hide)
+ })
+
+}
+
+
+#let draw-anchored-arc(edge, nodes, debug: 0) = {
+ let (from, to) = edge.final-vertices
+ let θ = angle-between(from, to)
+ let θs = (θ + edge.bend, θ - edge.bend + 180deg)
+
+ let dummy-lines = (from, to).zip(θs, nodes)
+ .map(((point, φ, node)) => cetz.draw.line(
+ point,
+ vector.add(point, vector-polar(10cm, φ)), // ray emanating from node
+ ))
+
+ let intersection-objects = nodes.zip(dummy-lines).map(((nodes, dummy-line)) => {
+ cetz.draw.group(nodes.map(draw-node-outline).join())
+ dummy-line
+ })
+
+ find-anchor-pair(intersection-objects, (from, to), anchors => {
+ let obj = draw-edge-arc(edge + (final-vertices: anchors), debug: debug)
+ (edge.post)(obj) // post-process (e.g., hide)
+ })
+}
+
+
+#let draw-anchored-polyline(edge, nodes, debug: 0) = {
+ assert(edge.vertices.len() >= 2, message: "Polyline requires at least two vertices")
+ let verts = edge.final-vertices
+ let (from, to) = (edge.final-vertices.at(0), edge.final-vertices.at(-1))
+
+ let end-segments = (
+ edge.final-vertices.slice(0, 2), // first two vertices
+ edge.final-vertices.slice(-2), // last two vertices
+ )
+
+ let dummy-lines = end-segments.map(points => cetz.draw.line(..points))
+
+ let intersection-objects = nodes.zip(dummy-lines).map(((nodes, dummy-line)) => {
+ cetz.draw.group(nodes.map(draw-node-outline).join())
+ dummy-line
+ })
+
+ find-anchor-pair(intersection-objects, (from, to), anchors => {
+ let edge = edge
+ edge.final-vertices.at(0) = anchors.at(0)
+ edge.final-vertices.at(-1) = anchors.at(1)
+ let obj = draw-edge-polyline(edge, debug: debug)
+ (edge.post)(obj) // post-process (e.g., hide)
+ })
+
+}
+
+
+#let draw-edge(edge, ..args) = {
+ let obj = if edge.kind == "line" {
+ draw-anchored-line(edge, ..args)
+ } else if edge.kind == "arc" {
+ draw-anchored-arc(edge, ..args)
+ } else if edge.kind == "poly" {
+ draw-anchored-polyline(edge, ..args)
+ } else { error("Invalid edge kind #0.", edge.kind) }
+
+ if edge.layer != 0 { obj = cetz.draw.on-layer(edge.layer, obj)}
+
+ obj
+}
+
+
+
+/// Draw diagram coordinate axes.
+///
+/// - grid (dictionary): Dictionary specifying the diagram's grid, containing:
+/// - `origin: (u-min, v-min)`, the minimum values of elastic coordinates,
+/// - `flip: (x, y, xy)`, the axes orientation (see `interpret-axes()`),
+/// - `centers: (x-centers, y-centers)`, the physical offsets of each row and each column,
+/// - `cell-sizes: (x-sizes, y-sizes)`, the physical sizes of each row and
+/// each column.
+#let draw-debug-axes(grid, debug: false, floating: true) = {
+
+ let (x-lims, y-lims) = range(2).map(axis => (
+ grid.centers.at(axis).at( 0) - grid.cell-sizes.at(axis).at( 0)/2,
+ grid.centers.at(axis).at(-1) + grid.cell-sizes.at(axis).at(-1)/2,
+ ))
+
+ let (u-min, v-min) = grid.origin
+
+ let (u-len, v-len) = grid.centers.map(array.len)
+ if grid.flip.xy { (u-len, v-len) = (v-len, u-len) }
+ let v-range = range(v-min, v-min + v-len)
+ let u-range = range(u-min, u-min + u-len)
+
+ if grid.flip.x { u-range = u-range.rev() }
+ if grid.flip.y { v-range = v-range.rev() }
+ if grid.flip.xy { (u-range, v-range) = (v-range, u-range) }
+
+ import cetz.draw
+ let objs = draw.group({
+ let (a, b) = array.zip(x-lims, y-lims)
+ if a == b { b = vector.add(b, (1e-3pt, 1e-3pt)) }
+ draw.rect(a, b, stroke: DEBUG_COLOR + .5pt)
+
+ draw.set-style(stroke: (
+ paint: DEBUG_COLOR,
+ thickness: .3pt,
+ dash: "densely-dotted",
+ ))
+
+ for axis in range(2) {
+ let swap(a, b) = if axis != 1 { (a, b) } else { (b, a) }
+ let x-range = (u-range, v-range).at(axis)
+ let (min, max) = (y-lims, x-lims).at(axis)
+ for (i, x) in x-range.enumerate() {
+ // coordinate line
+ draw.line(
+ swap(grid.centers.at(axis).at(i), min),
+ swap(grid.centers.at(axis).at(i), max),
+ )
+ // size bracket
+ let size = grid.cell-sizes.at(axis).at(i)
+ draw.rect(
+ (to: swap(grid.centers.at(axis).at(i), min), rel: swap(-size/2, 0)),
+ (to: swap(grid.centers.at(axis).at(i), min), rel: swap(+size/2, -1pt)),
+ fill: DEBUG_COLOR,
+ stroke: none,
+ )
+ // coordinate label
+ draw.content(
+ (to: swap(grid.centers.at(axis).at(i), min), rel: swap(0, -.2em)),
+ text(fill: DEBUG_COLOR, size: .7em)[#x],
+ anchor: if axis == 0 { "north" } else { "east" },
+ )
+ }
+ }
+
+ if debug {
+ let (u-label, v-label) = if grid.flip.xy { ($arrow$, $arrow.t.twohead$) } else { ($u$, $v$) }
+
+ let dir-to-arrow(dir) = {
+ if dir == ltr { $arrow.r$ }
+ else if dir == rtl { $arrow.l$ }
+ else if dir == ttb { $arrow.b$ }
+ else if dir == btt { $arrow.t$ }
+ }
+
+ draw.content(
+ (x-lims.at(0), y-lims.at(0)),
+ pad(0.2em, text(0.5em, DEBUG_COLOR, $(#grid.axes.map(dir-to-arrow).join($,$))$)),
+ anchor: "north-east"
+ )
+ }
+
+ })
+
+ if floating {
+ cetz.draw.floating(objs)
+ } else {
+ objs
+ }
+}
+
+// Find candidate nodes that an edge should snap to
+//
+// Returns an array of zero or more nodes. False positives are acceptable.
+#let find-snapping-nodes(grid, nodes, key) = {
+ if type(key) == label {
+ return nodes.filter(node => node.name == key)
+ }
+
+ if type(key) == array and key.len() == 2 {
+
+ let xy-pos = key
+ let candidates = nodes.filter(node => {
+ if node.snap == false { return false }
+ point-is-in-rect(xy-pos, (
+ center: node.pos.xyz,
+ size: node.size,
+ ))
+ })
+
+ if candidates.len() > 0 {
+ // filter out nodes with lower snap priority
+ let max-snap-priority = calc.max(..candidates.map(node => node.snap))
+ candidates = candidates.filter(node => node.snap == max-snap-priority)
+ }
+
+ return candidates
+ }
+
+ error("Couldn't find node corresponding to #0 in diagram.", key)
+}
+
+
+// return a pair of arrays of nodes to which the edge should snap
+#let find-nodes-for-edge(grid, nodes, edge) = {
+ let select-nodes = find-snapping-nodes.with(grid, nodes)
+ let first-last(x) = (x.at(0), x.at(-1))
+ array.zip(
+ edge.snap-to,
+ first-last(edge.vertices),
+ first-last(edge.final-vertices),
+ ).map(((given, vertex, xy)) => {
+ if given == none { return () } // user explicitly disabled snapping
+ let key = if type(vertex) == label { vertex } else { xy }
+ select-nodes(map-auto(given, key))
+ })
+}
+
+#let draw-diagram(
+ grid,
+ nodes,
+ edges,
+ debug: 0,
+) = {
+
+ for edge in edges {
+ let nodes = find-nodes-for-edge(grid, nodes, edge)
+ draw-edge(edge, nodes, debug: debug)
+ }
+
+ for node in nodes {
+ draw-node(node, debug: debug)
+ }
+
+ if debug >= 1 {
+ draw-debug-axes(grid, debug: debug >= 2)
+ }
+
+}
+
+/// Make diagram contents invisible, with or without affecting layout. Works by
+/// wrapping final drawing objects in `cetz.draw.hide`.
+///
+/// #example(```
+/// rect(diagram({
+/// fletcher.hide({
+/// node((0,0), [Can't see me])
+/// edge("->")
+/// })
+/// node((1,1), [Can see me])
+/// }))
+/// ```)
+///
+/// - objects (content, array): Diagram objects to hide.
+/// - bounds (bool): If `false`, layout is as if the objects were never there;
+/// if `true`, the layout treats the objects is present but invisible.
+#let hide(objects, bounds: true) = {
+ if type(objects) == array { objects = objects.join() }
+ let seq = objects + []
+ seq.children.map(child => {
+ if child.func() == metadata {
+ let value = child.value
+ value.post = cetz.draw.hide.with(bounds: bounds)
+ metadata(value)
+ } else {
+ child
+ }
+ }).join()
+}
diff --git a/render/packages/preview/fletcher/0.5.8/src/edge.typ b/render/packages/preview/fletcher/0.5.8/src/edge.typ
new file mode 100644
index 0000000..a83de3e
--- /dev/null
+++ b/render/packages/preview/fletcher/0.5.8/src/edge.typ
@@ -0,0 +1,1173 @@
+#import "utils.typ": *
+#import "marks.typ": *
+#import "coords.typ": vector-polar-with-xy-or-uv-length, resolve, default-ctx
+
+#let EDGE_FLAGS = (
+ "dashed": (dash: "dashed"),
+ "dotted": (dash: "dotted"),
+ "double": (extrude: (-2, +2)),
+ "triple": (extrude: (-4, 0, +4)),
+ "crossing": (crossing: true),
+ "wave": (decorations: "wave"),
+ "zigzag": (decorations: "zigzag"),
+ "coil": (decorations: "coil"),
+)
+
+#let LINE_ALIASES = (
+ "-": (:),
+ "=": EDGE_FLAGS.double,
+ "==": EDGE_FLAGS.triple,
+ "--": EDGE_FLAGS.dashed,
+ "..": EDGE_FLAGS.dotted,
+ "~": EDGE_FLAGS.wave,
+ " ": (extrude: ()),
+)
+
+#let MARK_SYMBOL_ALIASES = (
+ (sym.arrow.r): "->",
+ (sym.arrow.l): "<-",
+ (sym.arrow.r.l): "<->",
+ (sym.arrow.long.r): "->",
+ (sym.arrow.long.l): "<-",
+ (sym.arrow.long.r.l): "<->",
+ (sym.arrow.double.r): "=>",
+ (sym.arrow.double.l): "<=",
+ (sym.arrow.double.r.l): "<=>",
+ (sym.arrow.double.long.r): "=>",
+ (sym.arrow.double.long.l): "<=",
+ (sym.arrow.double.long.r.l): "<=>",
+ (sym.arrow.r.tail): ">->",
+ (sym.arrow.l.tail): "<-<",
+ (sym.arrow.twohead): "->>",
+ (sym.arrow.twohead.r): "->>",
+ (sym.arrow.twohead.l): "<<-",
+ (sym.arrow.bar): "|->",
+ (sym.arrow.bar.double): "|=>",
+ (sym.arrow.hook.r): "hook->",
+ (sym.arrow.hook.l): "<-hook'",
+ (sym.arrow.squiggly.r): "~>",
+ (sym.arrow.squiggly.l): "<~",
+ (sym.arrow.long.squiggly.r): "~>",
+ (sym.arrow.long.squiggly.l): "<~",
+)
+
+
+#let interpret-marks(marks) = {
+ marks = marks.enumerate().map(((i, mark)) => {
+ resolve-mark(mark, defaults: (
+ pos: i/calc.max(1, marks.len() - 1),
+ rev: i == 0,
+ ))
+ }).filter(mark => mark != none) // drop empty marks
+
+ marks = marks.map(mark => {
+ mark.tip = (mark.pos == 0) == mark.rev
+ if (mark.pos not in (0, 1)) { mark.tip = none }
+ mark
+ })
+
+ marks
+}
+
+
+
+/// Parse and interpret the marks argument provided to `edge()`. Returns a
+/// dictionary of processed `edge()` arguments.
+///
+/// - arg (string, array):
+/// Can be a string, (e.g. `"->"`, `"<=>"`), etc, or an array of marks.
+/// A mark can be a string (e.g., `">"` or `"head"`, `"x"` or `"cross"`) or a dictionary containing the keys:
+/// - `kind` (required) the mark name, e.g. `"solid"` or `"bar"`
+/// - `pos` the position along the edge to place the mark, from 0 to 1
+/// - `rev` whether to reverse the direction
+/// - parameters specific to the kind of mark, e.g., `size` or `sharpness`
+/// -> dictiony
+#let interpret-marks-arg(arg) = {
+ if type(arg) == array { return (marks: interpret-marks(arg)) }
+
+ if type(arg) == symbol {
+ if str(arg) in MARK_SYMBOL_ALIASES { arg = MARK_SYMBOL_ALIASES.at(arg) }
+ else { error("Unrecognised marks symbol #0.", arg) }
+ }
+
+ assert(type(arg) == str)
+ let text = arg
+
+ let mark-names = MARKS.get().keys().sorted(key: i => -i.len())
+ let LINES = LINE_ALIASES.keys().sorted(key: i => -i.len())
+
+ let eat(arg, options) = {
+ for option in options {
+ if arg.starts-with(option) {
+ return (arg.slice(option.len()), option)
+ }
+ }
+ return (arg, none)
+ }
+
+ let marks = ()
+ let lines = ()
+
+ let mark
+ let line
+ let flip
+
+ // first mark, [<]-x->>
+ (text, mark) = eat(text, mark-names)
+
+ // flip modifier, hook[']
+ (text, flip) = eat(text, ("'",))
+ if flip != none { mark += flip }
+
+ marks.push(mark)
+
+ let parse-error(suggestion) = error("Invalid marks shorthand #0. Try #1.", arg, suggestion)
+
+ while true {
+ // line, <[-]x->>
+ (text, line) = eat(text, LINES)
+ if line == none {
+ let suggestion = arg.slice(0, -text.len()) + "-" + text
+ parse-error(suggestion)
+ }
+ lines.push(line)
+
+ // subsequent mark, <-[x]->>
+ (text, mark) = eat(text, mark-names)
+
+ // flip modifier, hook[']
+ (text, flip) = eat(text, ("'",))
+ if flip != none { mark += flip }
+
+ marks.push(mark)
+
+ if text == "" { break }
+ if mark == none {
+ // text remains that was not recognised as mark
+ let suggestion = marks.intersperse(lines.at(0)).join()
+ parse-error(suggestion)
+ }
+ }
+
+
+ if lines.dedup().len() > 1 {
+ // different line styles were mixed
+ let suggestion = marks.intersperse(lines.at(0)).join()
+ parse-error(suggestion)
+ }
+ let line = lines.at(0)
+
+
+ // make classic math arrows slightly larger on double/triple stroked lines
+ if line == "=" {
+ marks = marks.map(mark => {
+ if mark == none { return }
+ (
+ ">": (inherit: "doublehead", rev: false),
+ "<": (inherit: "doublehead", rev: true),
+ ).at(mark, default: mark)
+ })
+ } else if line == "==" {
+ marks = marks.map(mark => {
+ if mark == ">" { (inherit: "triplehead", rev: false) }
+ else if mark == "<" { (inherit: "triplehead", rev: true) }
+ else {mark}
+ })
+ }
+
+ return (
+ marks: interpret-marks(marks),
+ ..LINE_ALIASES.at(lines.at(0))
+ )
+}
+
+
+
+/// Interpret the positional arguments given to an `edge()`
+///
+/// Tries to intelligently distinguish the `from`, `to`, `marks`, and `label`
+/// arguments based on the argument types.
+///
+/// Generally, the following combinations are allowed:
+///
+/// ```
+/// edge(..<coords>, ..<marklabel>, ..<options>)
+/// <coords> = () or (to) or (from, to) or (from, ..vertices, to)
+/// <marklabel> = (marks, label) or (label, marks) or (marks) or (label) or ()
+/// <options> = any number of options specified as strings
+/// ```
+#let interpret-edge-args(args, options) = {
+ if args.named().len() > 0 {
+ error("Unexpected named argument(s) #..0.", args.named().keys())
+ }
+
+ let new-options = (:)
+ let pos = args.pos()
+
+ // predicates to detect the kind of a positional argument
+ let is-coord(arg) = type(arg) in (array, dictionary, label) or arg == auto
+ let is-rel-coord(arg) = is-coord(arg) or (
+ type(arg) == str and arg.match(regex("^[utdblrnsew,]+$")) != none
+ )
+ let is-arrow-symbol(arg) = type(arg) == symbol and str(arg) in MARK_SYMBOL_ALIASES
+ let is-edge-flag(arg) = type(arg) == str and arg in EDGE_FLAGS
+ let is-label-side(arg) = type(arg) == alignment
+
+ let maybe-marks(arg) = type(arg) == str and not is-edge-flag(arg) or is-arrow-symbol(arg)
+ let maybe-label(arg) = type(arg) != str and not is-arrow-symbol(arg) and not is-coord(arg)
+
+ let peek(x, ..predicates) = {
+ let preds = predicates.pos()
+ x.len() >= preds.len() and x.zip(preds).all(((arg, pred)) => pred(arg))
+ }
+
+ let assert-not-set(key, default, ..value) = {
+ if options.at(key) == default { return }
+ error(
+ "#0 specified twice with positional argument(s) #..pos and named argument #named.",
+ key, pos: value.pos().map(repr), named: repr(options.at(key)),
+ )
+ }
+
+ let coords = ()
+ let has-first-coord = false
+ let has-tail-coords = false
+
+ // First argument(s) are coordinates
+ // (<coord>, <rel-coord>*) => (<coord>, <rel-coord>*)
+ // (<rel-coord>*) => (auto, <rel-coord>*)
+ if peek(pos, is-coord) {
+ coords.push(pos.remove(0))
+ has-first-coord = true
+ }
+ while peek(pos, is-rel-coord) {
+ if type(pos.at(0)) == str {
+ coords += pos.remove(0).split(",")
+ } else {
+ coords.push(pos.remove(0))
+ }
+ has-tail-coords = true
+ }
+
+ // Allow marks argument to be in between two coordinates
+ // (<coord>, <marks>, <rel-coord>)
+ // (<marks>, <rel-coord>) => (auto, <marks>, <rel-coord>)
+ if not has-tail-coords and peek(pos, maybe-marks, is-rel-coord) {
+ new-options.marks = pos.remove(0)
+ assert-not-set("marks", (), new-options.marks)
+
+ coords.push(pos.remove(0))
+ has-tail-coords = true
+
+ if peek(pos, is-rel-coord) {
+ error("Marks argument #0 must appear after edge vertices (or between them if there are only two).", repr(new-options.marks))
+ }
+ }
+ if coords.len() > 0 or options.vertices.len() == 0 {
+ assert-not-set("vertices", (), ..coords)
+ if not has-tail-coords { coords = (auto, ..coords) }
+ if not has-first-coord { coords = (auto, ..coords) }
+ new-options.vertices = coords
+ }
+
+
+ // Allow label side argument anywhere after coordinates
+ let i = pos.position(is-label-side)
+ if i != none {
+ new-options.label-side = pos.remove(i)
+ assert-not-set("label-side", auto, new-options.label-side)
+ }
+
+
+ // Accept marks and labels after vertices
+ // (.., <marks>, <label>)
+ // (.., <label>, <marks>)
+ let marks
+ let label
+ if peek(pos, maybe-marks, maybe-label) {
+ marks = pos.remove(0)
+ label = pos.remove(0)
+ } else if peek(pos, maybe-label, maybe-marks) {
+ label = pos.remove(0)
+ marks = pos.remove(0)
+ } else if peek(pos, maybe-label) {
+ label = pos.remove(0)
+ } else if peek(pos, maybe-marks) {
+ marks = pos.remove(0)
+ }
+
+ if marks != none {
+ if "marks" in new-options {
+ error("Marks argument passed to `edge()` twice; found #0 and #1.", repr(new-options.marks), repr(marks))
+ }
+ assert-not-set("marks", (), marks)
+ new-options.marks = marks
+ }
+ if label != none {
+ assert-not-set("label", none, label)
+ new-options.label = label
+ }
+
+ // Accept any trailing positional strings as option shorthands
+ while peek(pos, is-edge-flag) {
+ new-options += EDGE_FLAGS.at(pos.remove(0))
+ }
+
+ if pos.len() > 0 {
+ error("Couldn't interpret `edge()` arguments #..0. Try using named arguments. Interpreted previous arguments as #1", pos, new-options)
+ }
+
+ new-options
+}
+
+
+
+
+// Convert to `(segment, pos)`, where `segment` is an `int` and `pos` is a
+// `relative`. `pos` is relative to segment `segment`.
+//
+// Possible inputs:
+// * `(segment, pos)`, where `segment` is an int and `pos` is accepted by
+// `as-relative`. `pos` will be interpreted as relative to segment
+// `segment`.
+// * `pos`, where `pos` is accepted by `as-relative`. `pos` will be
+// interpreted as relative to the whole edge.
+#let normalize-label-pos(pos, n-segments) = {
+ // panic(pos, n-segments)
+
+ let segment
+ let position
+
+ if type(pos) == array and type(pos.at(0)) == int {
+ // Segment specified
+ segment = pos.at(0)
+ position = as-relative(pos.at(1))
+
+ } else {
+ // No segment specified
+ pos = as-relative(pos)
+ pos = pos.ratio*n-segments + pos.length
+
+ // Which segment does the position refer to?
+ // Use ceil-1 instead of floor to put positions that fall on the boundary
+ // between two segment on the end of the first, not the beginning of the
+ // second. There's no particular reason to do it like this, other than
+ // compatibility.
+ segment = calc.ceil(float(pos.ratio)) - 1
+ segment = calc.clamp(segment, 0, n-segments - 1)
+
+ // Make the position relative to the selected segment. This applies only to
+ // the `ratio` part of the `relative` position, not to the `length` part.
+ position = (pos.ratio - 100% * segment) + pos.length
+ }
+
+ if segment < 0 or segment >= n-segments {
+ error("segment of `label-pos` must be at least zero and less than number of segments (#1); got #0.", segment, n-segments)
+ }
+
+ (segment: segment, position: position)
+}
+
+
+
+
+/// Draw a connecting edge in a diagram.
+///
+///
+/// - ..args (any): An edge's positional arguments may specify:
+/// - the edge's #param[edge][vertices], each specified with a CeTZ-style coordinate
+/// - the #param[edge][label] content
+/// - arrow #param[edge][marks], like `"=>"` or `"<<-|-o"`
+/// - other style flags, like `"double"` or `"wave"`
+///
+/// Vertex coordinates must come first, and are optional:
+///
+/// ```typc
+/// edge(from, to, ..) // explicit start and end nodes
+/// edge(to, ..) == edge(auto, to, ..) // start snaps to previous node
+/// edge(..) == edge(auto, auto, ..) // snaps to previous and next nodes
+/// edge(from, v1, v2, ..vs, to, ..) // a multi-segmented edge
+/// edge(from, "->", to) // for two vertices, the marks style can come in between
+/// ```
+///
+/// All vertices except the start point can be shorthand relative coordinate
+/// string containing the characters
+/// ${#"lrudtbnesw".clusters().map(raw).join($, $)}$ or commas.
+///
+/// If given as positional arguments, an edge's #param[edge][marks] and
+/// #param[edge][label] are disambiguated by guessing based on the types. For
+/// example, the following are equivalent:
+///
+/// ```typc
+/// edge((0,0), (1,0), $f$, "->")
+/// edge((0,0), (1,0), "->", $f$)
+/// edge((0,0), (1,0), $f$, marks: "->")
+/// edge((0,0), (1,0), "->", label: $f$)
+/// edge((0,0), (1,0), label: $f$, marks: "->")
+/// ```
+///
+/// Additionally, some common options are given flags that may be given as
+/// string positional arguments. These are
+/// #fletcher.EDGE_FLAGS.keys().map(repr).map(raw).join([, ], last: [, and ]).
+/// For example, the following are equivalent:
+///
+/// ```typc
+/// edge((0,0), (1,0), $f$, "wave", "crossing")
+/// edge((0,0), (1,0), $f$, decorations: "wave", crossing: true)
+/// ```
+///
+/// - vertices (array): Array of (at least two) coordinates for the edge.
+///
+/// Vertices can also be specified as leading positional arguments, but if so,
+/// the `vertices` option must be empty. If the number of vertices is greater
+/// than two, #param[edge][kind] defaults to `"poly"`.
+///
+/// - kind (string): The kind of the edge, one of `"line"`, `"arc"`, or `"poly"`.
+/// This is chosen automatically based on the presence of other options
+/// (#param[edge][bend] implies `"arc"`, #param[edge][corner] or additional
+/// vertices implies `"poly"`).
+///
+/// - corner (none, left, right): Whether to create a right-angled corner,
+/// turning `left` or `right`.
+/// (Bending right means the corner sticks out to the left, and vice versa.)
+///
+/// #diagram(
+/// node((0,1), `from`),
+/// node((1,0), `to`),
+/// edge((0,1), (1,0), `right`, "->", corner: right),
+/// edge((0,1), (1,0), `left`, "->", corner: left),
+/// )
+///
+/// - bend (angle): Edge curvature. If `0deg`, the connector is a straight line;
+/// positive angles bend clockwise.
+///
+/// #diagram(debug: 0, {
+/// node((0,0), $A$)
+/// node((1,1), $B$)
+/// let N = 4
+/// range(N + 1)
+/// .map(x => (x/N - 0.5)*2*100deg)
+/// .map(θ => edge((0,0), (1,1), θ, bend: θ, ">->", label-side: center))
+/// .join()
+/// })
+///
+/// - loop-angle (angle): Angle around the node at which edge loops stick out at. Loops are arcs
+/// with the same start/end point and a large #param[edge][bend] angle (e.g.,
+/// `120deg`). This value has no effect for non-loop edges.
+///
+/// #diagram(debug: 0, {
+/// node((0,0), $O$)
+/// for θ in (0deg, -90deg, 135deg) {
+/// edge((), "->", (), bend: 125deg, loop-angle: θ, label: θ)
+/// }
+/// })
+///
+/// - label (content): Content for the edge label. See the
+/// #param[edge][label-pos] and #param[edge][label-side] options to control
+/// the position (and #param[edge][label-sep] and #param[edge][label-anchor]
+/// for finer control).
+///
+/// - label-side (left, right, center): Which side of the edge to place the
+/// label on, viewed as you walk along it from base to tip.
+///
+/// If `center`, then the label is placed directly on the edge and
+/// #param[edge][label-fill] defaults to `true`. When `auto`, a value of
+/// `left` or `right` is automatically chosen so that the label is:
+/// - roughly above the connector, in the case of straight lines; or
+/// - on the outside of the curve, in the case of arcs.
+///
+/// - label-pos (float, ratio, relative length, array): Position of the label along the
+/// edge, from the start to end.
+///
+/// A number or ratio between zero and one is interpreted as a fraction of the
+/// edge length. Physical and relative relative lengths work too. For example,
+/// `100% - 1em` means `1em` from the end.
+///
+/// #stack(
+/// dir: ltr,
+/// spacing: 1fr,
+/// ..(0, 0.25, 0.5, 0.75, 1).map(p => fletcher.diagram(
+/// cell-size: 1cm,
+/// edge((0,0), (1,0), p, "->", label-pos: p))
+/// ),
+/// )
+///
+/// For `"poly"` edges (see @edge-types), a number does not specify a fraction
+/// of the path length; instead, the $k$th vertex is at position $k/n$ where
+/// $n$ is the number of vertices. Each midpoint is then at $k/n + 0.5$.
+///
+/// As an alternative, the position can be specified by an array
+/// `(segment, position)`, where `segment` is an integer that indicates which
+/// segment the label is placed on (segment $s$ is the one between vertices
+/// $s$ and $s+1$). `position` is then relative to the specified segment; the
+/// segment midpoint is at `(s, 50%)`.
+///
+/// - label-sep (length): Separation between the connector and the label anchor.
+///
+/// With the default anchor (automatically set to `"south"` in this case):
+///
+/// #diagram(
+/// debug: 2,
+/// cell-size: 8mm,
+/// {
+/// for (i, s) in (-5pt, 0pt, .4em, .8em).enumerate() {
+/// edge((2*i,0), (2*i + 1,0), s, "->", label-sep: s)
+/// }
+/// })
+///
+/// With #param[edge][label-anchor] set to `"center"`:
+///
+/// #diagram(
+/// debug: 2,
+/// cell-size: 8mm,
+/// {
+/// for (i, s) in (-5pt, 0pt, .4em, .8em).enumerate() {
+/// edge((2*i,0), (2*i + 1,0), s, "->", label-sep: s, label-anchor: "center")
+/// }
+/// })
+///
+/// Set #param[diagram][debug] to `2` or higher to see label anchors and
+/// outlines as seen here.
+///
+/// Default: #the-param[diagram][label-sep]
+///
+/// - label-angle (angle, left, right, top, bottom, auto): Angle to rotate the
+/// label (counterclockwise).
+///
+/// If a direction is given, the label is rotated so that the edge travels in
+/// that direction relative to the label. If `auto`, the best of `right` or
+/// `left` is chosen.
+///
+/// #for angle in (0deg, 90deg, auto, right, top, left) {
+/// diagram(edge((0,1), (2,0), "->", [#angle], label-angle: angle))
+/// }
+///
+/// - label-anchor (anchor): The CeTZ-style anchor point of the label to use for
+/// placement (e.g., `"north-east"` or `"center"`). If `auto`, the best anchor
+/// is chosen based on #param[edge][label-side], #param[edge][label-angle],
+/// and the edge's direction.
+///
+/// - label-fill (bool, paint): The background fill for the label. If `true`,
+/// defaults to the value of #param[edge][crossing-fill]. If `false` or
+/// `none`, no fill is used. If `auto`, then defaults to `true` if the label
+/// is covering the edge (#param[edge][label-side]`: center`).
+///
+/// - label-size (auto, length): The default text size to apply to edge labels.
+///
+/// Default: #the-param[diagram][label-size]
+///
+/// - label-wrapper (auto, function): Callback function accepting a node
+/// dictionary and returning the label content. This is used to add a label
+/// background (see #param[edge][crossing-fill]), and can be used to adjust
+/// the label's padding, outline, and so on.
+///
+/// ```example
+/// #diagram(edge($f$, label-wrapper: e =>
+/// circle(e.label, fill: e.label-fill)))
+/// ```
+///
+/// Default: #the-param[diagram][label-wrapper]
+///
+/// - stroke (stroke): Stroke style of the edge. Arrows/marks scale with the
+/// stroke thickness (and with #param[edge][mark-scale]).
+///
+/// - dash (string): The stroke's dash style. This is also set by some mark
+/// styles. For example, setting `marks: "<..>"` applies `dash: "dotted"`.
+///
+/// - decorations (none, string, function): Apply a CeTZ path decoration to the
+/// stroke. Preset options are `"wave"`, `"zigzag"`, and `"coil"` (which may
+/// also be passed as convenience positional arguments), but a decoration
+/// function may also be specified.
+///
+/// ```example
+/// #diagram(
+/// $
+/// A edge("wave") &
+/// B edge("zigzag") &
+/// C edge("coil") & D \
+/// alpha &&& omega
+/// $,
+/// edge((0,1), (3,1), "<->", decorations:
+/// cetz.decorations.wave
+/// .with(amplitude: .4)
+/// )
+/// )
+/// ```
+///
+/// - marks (array): The marks (arrowheads) to draw along an edge's stroke. This
+/// may be:
+///
+/// - A shorthand string such as `"->"` or `"hook'-/->>"`. Specifically,
+/// shorthand strings are of the form $M_1 L M_2$ or $M_1 L M_2 L M_3$, etc,
+/// where
+///
+/// $ M_i in #`fletcher.MARKS` = #context math.mat(..fletcher.MARKS.get().keys().map(i => $#raw(lang: none, i),$).chunks(6), delim: "{") $
+/// is a mark name and
+/// $ L in #`fletcher.LINE_ALIASES` = {#fletcher.LINE_ALIASES.keys().map(raw.with(lang: none)).join($,$)} $
+/// is the line style.
+///
+/// - An array of mark names as strings or _mark objects_ (dictionaries of
+/// parameters with a `draw` entry).
+///
+/// Shorthands are expanded into other arguments. For example,
+/// `edge(p1, p2, "=>")` is short for `edge(p1, p2, marks: (none, "head"), "double")`, or more precisely, the result of `edge(p1, p2, ..fletcher.interpret-marks-arg("=>"))`.
+///
+/// #table(
+/// columns: (1fr, 4fr),
+/// align: (center + horizon, horizon),
+/// [Result], [Value of `marks`],
+/// ..(
+/// "->",
+/// ">>-->",
+/// "<=>",
+/// "==>",
+/// "->>-",
+/// "x-/-@",
+/// "|..|",
+/// "hook->>",
+/// "hook'->>",
+/// "||-*-harpoon'",
+/// ("X", (inherit: "head", size: 15, sharpness: 40deg),), ((inherit:
+/// "circle", pos: 0.5, fill: auto),),
+/// ).map(arg => (
+/// fletcher.diagram(edge((0,0), (1,0), marks: arg, stroke: 0.8pt)),
+/// raw(repr(arg)),
+/// )).join()
+/// )
+///
+/// - mark-scale (percent): Scale factor for marks or arrowheads, relative to
+/// the #param[edge][stroke] thickness. See also #the-param[diagram][mark-scale].
+///
+/// #diagram(
+/// label-sep: 10pt,
+/// edge-stroke: 1pt,
+/// for i in range(3) {
+/// let s = (1 + i/2)*100%
+/// edge((2*i,0), (2*i + 1,0), label: s, "->", mark-scale: s)
+/// }
+/// )
+///
+/// Note that the default arrowheads scale automatically with double and
+/// triple strokes:
+///
+/// #diagram(
+/// label-sep: 10pt,
+/// edge-stroke: 1pt,
+/// for (i, s) in ("->", "=>", "==>").enumerate() {
+/// edge((2*i,0), (2*i + 1,0), s, label: raw(s, lang: none))
+/// }
+/// )
+///
+/// - extrude (array): Draw a separate stroke for each extrusion offset to
+/// obtain a multi-stroke effect. Offsets may be numbers (specifying multiples
+/// of the stroke's thickness) or lengths.
+///
+/// #diagram({
+/// (
+/// (0,),
+/// (-1.5,+1.5),
+/// (-2,0,+2),
+/// (-.5em,),
+/// (0, 5pt,),
+/// ).enumerate().map(((i, e)) => {
+/// edge(
+/// (2*i, 0), (2*i + 1, 0), [#e], "|->",
+/// extrude: e, stroke: 1pt, label-sep: 1em)
+/// }).join()
+/// })
+///
+/// Notice how the ends of the line need to shift a little depending on the
+/// mark. This offset is computed with `cap-offset()`.
+///
+/// See also #the-param[node][extrude].
+///
+/// - crossing (bool): If `true`, draws a backdrop of color
+/// #param[edge][crossing-fill] to give the illusion of lines crossing each
+/// other.
+///
+/// #diagram({
+/// edge((0,1), (1,0), stroke: 1pt)
+/// edge((0,0), (1,1), stroke: 1pt)
+/// edge((2,1), (3,0), stroke: 1pt)
+/// edge((2,0), (3,1), stroke: 1pt, crossing: true)
+/// })
+///
+/// You can also pass `"crossing"` as a positional argument as a shorthand for
+/// `crossing: true`.
+///
+/// - crossing-thickness (number): Thickness of the "crossing" background stroke
+/// (applicable if #param[edge][crossing] is `true`) in multiples of the
+/// normal stroke's thickness.
+///
+/// #diagram({
+/// (1, 2, 4, 8).enumerate().map(((i, x)) => {
+/// edge((2*i, 1), (2*i + 1, 0), stroke: 1pt, label-sep: 1em)
+/// edge((2*i, 0), (2*i + 1, 1), raw(str(x)), stroke: 1pt, label-sep:
+/// 2pt, label-pos: 0.3, crossing: true, crossing-thickness: x)
+/// }).join()
+/// })
+///
+/// Default: #the-param[diagram][crossing-thickness]
+///
+/// - crossing-fill (paint): Color to use behind connectors or labels to give
+/// the illusion of crossing over other objects.
+///
+/// #let cross(x, fill) = {
+/// edge((2*x + 0,1), (2*x + 1,0), stroke: 1pt)
+/// edge((2*x + 0,0), (2*x + 1,1), $f$, stroke: 1pt, crossing: true, crossing-fill: fill, label-fill: true)
+/// }
+/// #diagram(crossing-thickness: 5, {
+/// cross(0, white)
+/// cross(1, blue.lighten(50%))
+/// })
+///
+/// Default: #the-param[diagram][crossing-fill]
+///
+/// - corner-radius (length, none): Radius of rounded corners for edges with
+/// multiple segments. Note that `none` is distinct from `0pt`.
+///
+/// #for (i, r) in (none, 0pt, 5pt).enumerate() {
+/// if i > 0 { h(1fr) }
+/// fletcher.diagram(
+/// edge-stroke: 1pt,
+/// edge((3*i, 0), "r,t,rd,r", "=>", raw(repr(r)), label-pos: 0.6, corner-radius: r)
+/// )
+/// }
+///
+/// This length specifies the corner radius for right-angled bends. The actual
+/// radius is smaller for acute angles and larger for obtuse angles to balance
+/// things visually. (Trust me, it looks naff otherwise!)
+///
+/// Default: #the-param[diagram][edge-corner-radius]
+///
+/// - shift (length, number, pair): Amount to shift the edge sideways by,
+/// perpendicular to its direction. A pair `(from, to)` controls the shifts at
+/// each end of the edge independently, and a single shift `s` is short for
+/// `(s, s)`. Shifts can absolute lengths (e.g., `5pt`) or coordinate
+/// differences (e.g., `0.1`).
+///
+/// #diagram(
+/// node((0,0), $A$), node((1,0), $B$),
+/// edge((0,0), (1,0), "->", `3pt`, shift: 3pt),
+/// edge((0,0), (1,0), "->", `-3pt`, shift: -3pt, label-side: right),
+/// )
+///
+/// If an edge has many vertices, the shifts only affect the first and last
+/// segments of the edge.
+///
+/// ```example
+/// #diagram(
+/// node-fill: luma(70%),
+/// node((0,0), [Hello]),
+/// edge("u,r,d", "->"),
+/// edge("u,r,d", "-->", shift: 8pt),
+/// node((1,0), [World]),
+/// )
+/// ```
+///
+/// - snap-to (pair): The nodes the start and end of an edge should snap to.
+/// Each node can be a position or node #param[node][name], or `none` to disable
+/// snapping. See also #the-param[node][snap].
+///
+/// By default, an edge's first and last #param[edge][vertices] snap to nearby
+/// nodes. This option can be used in case automatic snapping fails (if there
+/// are many nodes close together, for example.)
+///
+/// - layer (number): Layer on which to draw the edge.
+///
+/// Objects on a higher `layer` are drawn on top of objects on a lower
+/// `layer`. Objects on the same layer are drawn in the order they are passed
+/// to `diagram()`.
+///
+/// - floating (bool): Whether the edge should be _floating_ so as not to affect
+/// the diagram's bounding box.
+///
+/// When `floating: true`, the edge is wrapped in `cetz.draw.floating(..)` which
+/// prevents the objects from affecting the canvas' bounding box.
+///
+/// ```example
+/// An inline #diagram($
+/// A edge(->, bend: #45deg, floating: #true) & B
+/// $) diagram.
+///
+/// #rect(width: 7cm, align(center, diagram(
+/// node((0,1), $A$),
+/// edge("->", floating: true, [centered despite label]),
+/// node((0,0), $B$),
+/// )))
+/// ```
+///
+/// - post (function): Callback function to intercept `cetz` objects before they
+/// are drawn to the canvas.
+///
+/// This can be used to hide elements without affecting layout (for use with
+/// #link("https://github.com/touying-typ/touying")[Touying], for example).
+/// The `hide()` function also helps for this purpose.
+///
+#let edge(
+ ..args,
+ vertices: (),
+ label: none,
+ label-side: auto,
+ label-pos: 50%,
+ label-sep: auto,
+ label-angle: 0deg,
+ label-anchor: auto,
+ label-fill: auto,
+ label-size: auto,
+ label-wrapper: auto,
+ stroke: auto,
+ dash: none,
+ decorations: none,
+ extrude: (0,),
+ shift: 0pt,
+ kind: auto,
+ bend: 0deg,
+ loop-angle: none,
+ corner: none,
+ corner-radius: auto,
+ marks: (),
+ mark-scale: 100%,
+ crossing: false,
+ crossing-thickness: auto,
+ crossing-fill: auto,
+ snap-to: (auto, auto),
+ layer: 0,
+ floating: false,
+ post: x => x,
+) = {
+
+ let options = (
+ vertices: vertices,
+ label: label,
+ label-pos: label-pos,
+ label-sep: label-sep,
+ label-angle: label-angle,
+ label-anchor: label-anchor,
+ label-side: label-side,
+ label-fill: label-fill,
+ label-size: label-size,
+ label-wrapper: label-wrapper,
+ stroke: stroke,
+ dash: dash,
+ decorations: decorations,
+ kind: kind,
+ bend: bend,
+ loop-angle: pass-none(as-angle)(loop-angle),
+ corner: corner,
+ corner-radius: corner-radius,
+ extrude: extrude,
+ shift: shift,
+ marks: marks,
+ mark-scale: mark-scale,
+ crossing: crossing,
+ crossing-thickness: crossing-thickness,
+ crossing-fill: crossing-fill,
+ snap-to: as-pair(snap-to),
+ layer: layer,
+ post: post,
+ floating: as-bool(floating, message: "`floating` must be boolean"),
+ )
+
+ options += interpret-edge-args(args, options)
+
+ // relative coordinate shorthands
+ let interpret-coord-str(coord) = {
+ if type(coord) != str { return coord }
+ let rel = (0, 0)
+ let dirs = (
+ "t": ( 0,-1), "n": ( 0,-1), "u": ( 0,-1),
+ "b": ( 0,+1), "s": ( 0,+1), "d": ( 0,+1),
+ "l": (-1, 0), "w": (-1, 0),
+ "r": (+1, 0), "e": (+1, 0),
+ )
+ for char in coord.clusters() {
+ rel = vector.add(rel, dirs.at(char))
+ }
+ (rel: rel)
+ }
+ options.vertices = options.vertices.map(interpret-coord-str)
+
+ // guess the number of segments
+ let n-segments = options.vertices.len() - 1
+ if options.corner != none { n-segments += 1 }
+ options.label-pos = normalize-label-pos(options.label-pos, n-segments)
+
+
+ if options.label-side not in (left, center, right, auto) {
+ error("`label-side` must be one of `left`, `center`, `right`, or `auto`; got #0.", options.label-side)
+ }
+ if options.label-side == center {
+ options.label-anchor = "center"
+ options.label-sep = 0pt
+ }
+
+ if type(options.shift) != array { options.shift = (options.shift, options.shift) }
+
+
+ let obj = (
+ class: "edge",
+ ..options,
+ is-crossing-background: false,
+ )
+
+ // for the crossing effect, add another edge underneath
+ if options.crossing {
+ metadata((
+ ..obj,
+ is-crossing-background: true
+ ))
+ }
+
+ metadata(obj)
+}
+
+
+#let resolve-edge-options(edge, options) = {
+ // let to-pt(len) = to-abs-length(len, options.em-size)
+
+ edge += interpret-marks-arg(edge.marks)
+
+ if edge.stroke == none {
+ // hack: for no stroke, it's easier to do the following.
+ // then we have the guarantee that edge.stroke is actually
+ // a stroke, not possibly none
+ edge.extrude = ()
+ edge.marks = ()
+ edge.stroke = stroke((:))
+ }
+
+ edge.stroke = (
+ (
+ cap: "round",
+ dash: edge.dash,
+ thickness: 0.048em, // guarantees thickness is a length, not auto
+ ) +
+ stroke-to-dict(options.edge-stroke) +
+ stroke-to-dict(map-auto(edge.stroke, (:)))
+ )
+ edge.stroke.thickness = edge.stroke.thickness.to-absolute()
+
+ edge.extrude = as-array(edge.extrude).map(as-number-or-length.with(
+ message: "`extrude` must be a number, length, or an array of those"
+ )).map(d => {
+ if type(d) == length { d.to-absolute() }
+ else { d*edge.stroke.thickness }
+ })
+
+ if type(edge.decorations) == str {
+ edge.decorations = (
+ "wave": cetz.decorations.wave.with(
+ amplitude: .12,
+ segment-length: .2,
+ ),
+ "zigzag": cetz.decorations.zigzag.with(
+ amplitude: .12,
+ segment-length: .2,
+ ),
+ "coil": cetz.decorations.coil.with(
+ amplitude: .15,
+ segment-length: .15,
+ factor: 140%,
+ ),
+ ).at(edge.decorations)
+ }
+
+ edge.crossing-fill = map-auto(edge.crossing-fill, options.crossing-fill)
+ edge.crossing-thickness = map-auto(edge.crossing-thickness, options.crossing-thickness)
+ edge.corner-radius = map-auto(edge.corner-radius, options.edge-corner-radius)
+
+ if edge.is-crossing-background {
+ edge.stroke = (
+ thickness: edge.crossing-thickness*edge.stroke.thickness,
+ paint: edge.crossing-fill,
+ cap: "round",
+ )
+ edge.marks = ()
+ edge.extrude = edge.extrude.map(e => e/edge.crossing-thickness)
+ }
+
+ edge.stroke = as-stroke(edge.stroke)
+
+ if edge.kind == auto {
+ if edge.vertices.len() > 2 { edge.kind = "poly" }
+ else if edge.corner != none { edge.kind = "corner" }
+ else if edge.bend != 0deg { edge.kind = "arc" }
+ else { edge.kind = "line" }
+ }
+
+ // Scale marks
+ edge.mark-scale *= options.mark-scale
+ edge.marks = edge.marks.map(mark => {
+ mark.scale *= edge.mark-scale
+ mark
+ })
+
+ edge.label-sep = map-auto(edge.label-sep, options.label-sep).to-absolute()
+ edge.label-size = map-auto(edge.label-size, options.label-size)
+
+ edge.label-fill = map-auto(edge.label-fill, edge.label-side == center)
+ if edge.label-fill == true { edge.label-fill = edge.crossing-fill }
+ if edge.label-fill == false { edge.label-fill = none }
+
+ edge.label-wrapper = map-auto(edge.label-wrapper, options.label-wrapper)
+
+ if edge.floating {
+ edge.post = x => cetz.draw.floating((edge.post)(x))
+ }
+
+ edge
+}
+
+
+#let resolve-edge-vertices(edge, ctx: (:), nodes) = {
+
+ let adjacent-node-pos(forward, default) = {
+ if edge.node-index == none { return default }
+ let indices = if forward {
+ range(edge.node-index, nodes.len())
+ } else {
+ range(0, edge.node-index).rev()
+ }
+ for i in indices {
+ if nodes.at(i).snap != false {
+ return nodes.at(i).pos.at(ctx.target-system)
+ }
+ }
+ return default
+ }
+
+ let prev-pos = adjacent-node-pos(false, (0, 0))
+ let next-pos = adjacent-node-pos(true, (rel: (1, 0)))
+
+ let ctx = default-ctx + ctx + (
+ prev: (pt: prev-pos),
+ )
+
+ edge.vertices.at(0) = map-auto(edge.vertices.at(0), prev-pos)
+ edge.vertices.at(-1) = map-auto(edge.vertices.at(-1), next-pos)
+
+ let (ctx, ..verts) = resolve(ctx, ..edge.vertices)
+ verts.map(vector-2d)
+
+}
+
+
+
+#let convert-edge-corner-to-poly(edge) = {
+ if edge.kind != "corner" { return edge }
+
+ let (from, to) = edge.final-vertices
+ let θ = angle-between(from, to)
+
+ let bend-dir = (
+ if edge.corner == right { true }
+ else if edge.corner == left { false }
+ else { error("Edge `corner` option must be `left` or `right`.") }
+ )
+
+ let θ-floor = calc.floor(θ/90deg)*90deg
+ let θ-ceil = calc.ceil(θ/90deg)*90deg
+ let θs = if bend-dir {
+ (θ-ceil, θ-floor + 180deg)
+ } else {
+ (θ-floor, θ-ceil + 180deg)
+ }
+
+ let corner-point = if calc.even(calc.floor(θ/90deg) + int(bend-dir)) {
+ (to.at(0), from.at(1))
+ } else {
+ (from.at(0), to.at(1))
+ }
+
+ let label-side = map-auto(edge.label-side, if bend-dir { left } else { right })
+
+ edge + (
+ kind: "poly",
+ final-vertices: (from, corner-point, to),
+ label-side: label-side,
+ )
+}
+
+
+
+
+// For straight edges, `shift` translates the line laterally
+#let apply-edge-shift-line(grid, edge) = {
+ let (from-xy, to-xy) = edge.final-vertices
+ let θ = angle-between(from-xy, to-xy) + 90deg
+
+ let (δ-from, δ-to) = edge.shift
+ let δ⃗-from = vector-polar-with-xy-or-uv-length(grid, from-xy, δ-from, θ)
+ let δ⃗-to = vector-polar-with-xy-or-uv-length(grid, to-xy, δ-to, θ)
+
+ edge.final-vertices.at( 0) = vector.add(from-xy, δ⃗-from)
+ edge.final-vertices.at(-1) = vector.add(to-xy, δ⃗-to)
+
+ edge
+}
+
+// For arc edges, `shift` grows/shrinks the arc concentrically
+#let apply-edge-shift-arc(grid, edge) = {
+ let (from-xy, to-xy) = edge.final-vertices
+
+ let θ = angle-between(from-xy, to-xy) + 90deg
+ let (θ-from, θ-to) = (θ + edge.bend, θ - edge.bend)
+
+ let (δ-from, δ-to) = edge.shift
+ let δ⃗-from = vector-polar-with-xy-or-uv-length(grid, from-xy, δ-from, θ-from)
+ let δ⃗-to = vector-polar-with-xy-or-uv-length(grid, to-xy, δ-to, θ-to)
+
+ edge.final-vertices.at( 0) = vector.add(from-xy, δ⃗-from)
+ edge.final-vertices.at(-1) = vector.add(to-xy, δ⃗-to)
+
+ if edge.loop-angle != none {
+ let a = edge.loop-angle + 90deg
+ edge.final-vertices.at( 0) = vector.add(edge.final-vertices.at( 0), vector-polar(+1e-4pt, a))
+ edge.final-vertices.at(-1) = vector.add(edge.final-vertices.at(-1), vector-polar(-1e-4pt, a))
+ }
+
+ edge
+}
+
+// For poly edges, `shift` affects the first/last line segments
+#let apply-edge-shift-poly(grid, edge) = {
+ let end-segments = (
+ edge.final-vertices.slice(0, 2), // first two vertices
+ edge.final-vertices.slice(-2), // last two vertices
+ )
+
+ let θs = (
+ angle-between(..end-segments.at(0)) + 180deg,
+ angle-between(..end-segments.at(1)) + 180deg,
+ )
+
+ let ends = (edge.final-vertices.at(0), edge.final-vertices.at(-1))
+ let δs = edge.shift.zip(ends, θs).map(((d, xy, θ)) => {
+ vector-polar-with-xy-or-uv-length(grid, xy, d, θ + 90deg)
+ })
+
+ // the `shift` option is nicer if it shifts the entire segment, not just the first vertex
+ // first segment
+ edge.final-vertices.at(0) = vector.add(edge.final-vertices.at(0), δs.at(0))
+ edge.final-vertices.at(1) = vector.add(edge.final-vertices.at(1), δs.at(0))
+ // last segment
+ edge.final-vertices.at(-2) = vector.add(edge.final-vertices.at(-2), δs.at(1))
+ edge.final-vertices.at(-1) = vector.add(edge.final-vertices.at(-1), δs.at(1))
+
+ edge
+}
+
+
+/// Apply #the-param[edge][shift] by translating edge vertices.
+///
+/// - grid (dictionary): Representation of the grid layout. This is needed to
+/// support shifts specified as coordinate lengths.
+/// - edge (dictionary): The edge with a `shift` entry.
+#let apply-edge-shift(grid, edge) = {
+ if edge.kind == "line" { apply-edge-shift-line(grid, edge) }
+ else if edge.kind == "arc" { apply-edge-shift-arc(grid, edge) }
+ else if edge.kind == "poly" { apply-edge-shift-poly(grid, edge) }
+ else { edge }
+}
+
diff --git a/render/packages/preview/fletcher/0.5.8/src/exports.typ b/render/packages/preview/fletcher/0.5.8/src/exports.typ
new file mode 100644
index 0000000..22e4ec5
--- /dev/null
+++ b/render/packages/preview/fletcher/0.5.8/src/exports.typ
@@ -0,0 +1,10 @@
+#import "deps.typ": cetz
+
+#import "marks.typ": *
+#import "draw.typ": *
+#import "shapes.typ"
+#import "node.typ": *
+#import "edge.typ": *
+#import "diagram.typ": *
+#import "coords.typ": *
+#import "utils.typ"
diff --git a/render/packages/preview/fletcher/0.5.8/src/marks.typ b/render/packages/preview/fletcher/0.5.8/src/marks.typ
new file mode 100644
index 0000000..2f123cd
--- /dev/null
+++ b/render/packages/preview/fletcher/0.5.8/src/marks.typ
@@ -0,0 +1,441 @@
+#import "utils.typ": *
+#import "deps.typ": cetz
+#import cetz.draw
+#import "default-marks.typ": *
+
+#let MARK_REQUIRED_DEFAULTS = (
+ rev: false,
+ flip: false,
+ scale: 100%,
+ extrude: (0,),
+ tip-end: 0,
+ tail-end: 0,
+ tip-origin: 0,
+ tail-origin: 0,
+)
+
+
+/// For a given mark, determine where that the stroke should terminate at,
+/// relative to the mark's origin point, as a function of the shift.
+///
+/// Imagine the tip-origin of the mark is at $(x, y) = (0, 0)$. A stroke along
+/// the line $y = "shift"$ coming from $x = -oo$ terminates at $x = "offset"$, where
+/// $"offset"$ is the result of this function.
+/// Units are in multiples of stroke thickness.
+///
+/// This is used to correctly implement multi-stroke marks, e.g.,
+/// #diagram(edge("<==>")). The function `mark-debug()` can help visualise a
+/// mark's cap offset.
+///
+/// ```example
+/// #fletcher.mark-debug("O")
+/// ```
+///
+/// The dashed green line shows the stroke tip end as a function of $y$, and the
+/// dashed red line shows where the stroke ends if the mark is acting as a tail.
+#let cap-offset(mark, shift) = {
+ let o = 0
+ let scale = float(mark.scale)
+ if "cap-offset" in mark {
+ o = (mark.cap-offset)(mark, shift/scale)
+ }
+ o += if mark.tip { mark.tip-end } else { mark.tail-end }
+ o*scale
+}
+
+
+#let apply-mark-inheritances(mark) = {
+ let marks = MARKS.get()
+ while "inherit" in mark {
+
+ if mark.inherit.at(-1) == "'" {
+ mark.flip = not mark.at("flip", default: false)
+ mark.inherit = mark.inherit.slice(0, -1)
+ }
+
+ if mark.inherit not in marks {
+ error("Mark inherits from #0 which is not defined.", repr(mark.inherit))
+ }
+
+ let parent = marks.at(mark.remove("inherit"))
+ mark = parent + mark
+ }
+ mark
+}
+
+
+
+/// Resolve a mark dictionary by applying inheritance, adding any required
+/// entries, and evaluating any closure entries.
+///
+/// ```example
+/// #context fletcher.resolve-mark((
+/// a: 1,
+/// b: 2,
+/// c: mark => mark.a + mark.b,
+/// ))
+/// ```
+///
+#let resolve-mark(mark, defaults: (:)) = {
+ if mark == none { return none }
+
+ if type(mark) == str { mark = (inherit: mark) }
+
+ mark = apply-mark-inheritances(mark)
+
+ // be careful to preserve the insertion order of mark
+ // as this defines the evaluation order of mark parameters
+ for (k, v) in MARK_REQUIRED_DEFAULTS + defaults {
+ if k not in mark {
+ mark.insert(k, v)
+ }
+ }
+
+ for (key, value) in mark {
+ if key == "cap-offset" { continue }
+
+ if type(value) == function {
+ mark.at(key) = value(mark)
+ }
+ }
+
+ mark
+}
+
+
+/// Draw a mark at a given position and angle
+///
+/// - mark (dictionary): Mark object to draw. Must contain a `draw` entry.
+/// - stroke (stroke): Stroke style for the mark. The stroke's paint is used as
+/// the default fill style.
+/// - origin (point): Coordinate of the mark's origin (as defined by
+/// `tip-origin` or `tail-origin`).
+/// - angle (angle): Angle of the mark, `0deg` being $->$, counterclockwise.
+/// - debug (bool): Whether to draw the origin points.
+#let draw-mark(
+ mark,
+ stroke: 1pt,
+ origin: (0,0),
+ angle: 0deg,
+ debug: false
+) = {
+ mark = resolve-mark(mark)
+ stroke = as-stroke(stroke)
+
+ let thickness = stroke.thickness
+
+ let fill = mark.at("fill", default: auto)
+ fill = map-auto(fill, stroke.paint)
+ fill = map-auto(fill, black)
+
+ let stroke = stroke-to-dict(stroke)
+ stroke.dash = none
+
+ if "stroke" in mark {
+ if mark.stroke == none { stroke = none }
+ else if mark.stroke == auto { }
+ else { stroke += stroke-to-dict(mark.stroke) }
+ }
+
+ if "draw" not in mark {
+ error("Mark object must contain `draw` or `inherit`; resolved to #0.", mark)
+ }
+
+ draw.group({
+ draw.set-style(
+ stroke: stroke,
+ fill: fill,
+ )
+
+ draw.translate(origin)
+ draw.rotate(angle)
+ draw.scale(thickness/1cm*float(mark.scale))
+
+ if mark.at("rev", default: false) {
+ draw.translate(x: mark.tail-origin)
+ draw.scale(x: -1)
+ if debug {
+ draw.content((0,10), text(0.25em, red)[rev])
+ }
+ } else {
+ draw.translate(x: -mark.tip-origin)
+ }
+
+ if mark.flip {
+ draw.scale(y: -1)
+ }
+
+ for e in mark.extrude {
+ draw.group({
+ draw.translate(x: e)
+ mark.draw
+ })
+ }
+
+ if debug {
+ let tip = mark.at("tip", default: none)
+ if tip == true {
+ draw.content((0,-10), text(0.25em, green)[tip])
+ } else if tip == false {
+ draw.content((0,-10), text(0.25em, orange)[tail])
+ }
+ }
+
+ })
+}
+
+/// Visualise a mark's anatomy.
+///
+/// ```example
+/// #context {
+/// let mark = fletcher.MARKS.get().stealth
+/// // make a wide stealth arrow
+/// mark += (angle: 45deg)
+/// fletcher.mark-debug(mark)
+/// }
+/// ```
+///
+/// - Green/left stroke: the edge's stroke when the mark is at the tip.
+/// - Red/right stroke: edge's stroke if the mark is at the start acting as a
+/// tail.
+/// - Blue-white dot: the origin point $(0, 0)$ in the mark's coordinate frame.
+/// - `tip-origin`: the $x$-coordinate of the point of the mark's tip.
+/// - `tail-origin`: the $x$-coordinate of the mark's tip when it is acting as a
+/// reversed tail mark.
+/// - `tip-end`: The $x$-coordinate of the end point of the edge's stroke (green
+/// stroke).
+/// - `tail-end`: The $x$-coordinate of the end point of the edge's stroke when
+/// acting as a tail mark (red stroke).
+/// - Dashed green/red lines: The stroke end points as a function of $y$. This
+/// is controlled by the special `cap-offset` mark property and is used for
+/// multi-stroke effects like #diagram(edge(">==>")). See `cap-offset()`.
+///
+/// This is mainly useful for designing your own marks.
+///
+/// - mark (string, dictionary): The mark name or dictionary.
+/// - stroke (stroke): The stroke style, whose paint and thickness applies both
+/// to the stroke and the mark itself.
+///
+/// - show-labels (bool): Whether to label the tip/tail origin/end points.
+/// - show-offsets (bool): Whether to visualise the `cap-offset()` values.
+/// - offset-range (number): The span above and below the stroke line to plot
+/// the cap offsets, in multiples of the stroke's thickness.
+#let mark-debug(
+ mark,
+ stroke: 5pt,
+ show-labels: true,
+ show-offsets: true,
+ offset-range: 6,
+) = context {
+ let mark = resolve-mark(mark)
+ let stroke = as-stroke(stroke)
+
+ let t = stroke.thickness
+ let scale = float(mark.scale)
+
+
+ cetz.canvas({
+
+ draw-mark(mark, stroke: stroke)
+
+ if mark.at("rev", default: false) {
+ draw.scale(x: -1)
+ draw.translate(x: -t*mark.tail-origin*scale)
+ } else {
+ draw.translate(x: -t*mark.tip-origin*scale)
+ }
+
+
+ if show-offsets {
+
+ let samples = 100
+ let ys = range(samples + 1)
+ .map(n => n/samples)
+ .map(y => (2*y - 1)*offset-range)
+
+ let tip-points = ys.map(y => {
+ let o = cap-offset(mark + (tip: true), y)
+ (o*t, y*t)
+ })
+
+ let tail-points = ys.map(y => {
+ let o = cap-offset(mark + (tip: false), y)
+ (o*t, y*t)
+ })
+
+ draw.line(
+ ..tip-points,
+ stroke: (
+ paint: rgb("0f0"),
+ thickness: 0.4pt,
+ dash: (array: (3pt, 3pt), phase: 0pt),
+ ),
+ )
+ draw.line(
+ ..tail-points,
+ stroke: (
+ paint: rgb("f00"),
+ thickness: 0.4pt,
+ dash: (array: (3pt, 3pt), phase: 3pt),
+ ),
+ )
+
+
+ }
+
+ if show-labels {
+ for (i, (item, y, color)) in (
+ ("tip-end", +1.00, "0f0"),
+ ("tail-end", -1.00, "f00"),
+ ("tip-origin", +0.75, "0ff"),
+ ("tail-origin", -0.75, "f0f"),
+ ).enumerate() {
+ let x = mark.at(item)*float(mark.scale)
+ let c = rgb(color)
+ draw.line((t*x, 0), (t*x, y), stroke: 0.5pt + c)
+ draw.content(
+ (t*x, y),
+ pad(2pt, text(0.75em, fill: c, raw(item))),
+ anchor: if y < 0 { "north" } else { "south" },
+ )
+ }
+ }
+
+ // draw tip/tail stroke previews
+ let (min, max) = min-max((
+ "tip-end",
+ "tail-end",
+ "tip-origin",
+ "tail-origin",
+ ).map(i => mark.at(i)))
+
+ let l = calc.max(5, max - min)
+
+ draw.line(
+ (t*mark.tip-end, 0),
+ (t*(min - l), 0),
+ stroke: rgb("0f06") + t,
+ )
+ draw.line(
+ (t*mark.tail-end, 0),
+ (t*(max + l), 0),
+ stroke: rgb("f006") + t,
+ )
+
+ // draw true origin dot
+ draw.circle(
+ (0, 0),
+ radius: t/4,
+ stroke: rgb("00f") + 1pt,
+ fill: white,
+ )
+ })
+}
+
+#let mark-demo(
+ mark,
+ stroke: 2pt,
+ width: 3cm,
+ height: 1cm,
+) = context {
+ let mark = resolve-mark(mark)
+ let stroke = as-stroke(stroke)
+
+ let t = stroke.thickness*float(mark.scale)
+
+ cetz.canvas({
+
+ for x in (0, width) {
+ draw.line(
+ (x, +0.5*height),
+ (x, -1.5*height),
+ stroke: red.transparentize(50%) + 0.5pt,
+ )
+ }
+
+ let x = t*(mark.tip-origin - mark.tip-end)
+ draw.line(
+ (x, 0),
+ (rel: (-x, 0), to: (width, 0)),
+ stroke: stroke,
+ )
+
+ let mark-length = t*(mark.tip-origin - mark.tail-origin)
+ draw-mark(
+ mark + (rev: true),
+ stroke: stroke,
+ origin: (mark-length, 0),
+ angle: 0deg,
+ )
+ draw-mark(
+ mark + (rev: false),
+ stroke: stroke,
+ origin: (width, 0),
+ angle: 0deg,
+ )
+
+ draw.translate((0, -height))
+
+ let x = t*(mark.tail-end - mark.tail-origin)
+ draw.line(
+ (x, 0),
+ (rel: (-x, 0), to: (width, 0)),
+ stroke: stroke,
+ )
+
+ draw-mark(
+ mark + (rev: true),
+ stroke: stroke,
+ origin: (0, 0),
+ angle: 180deg,
+ )
+ draw-mark(
+ mark + (rev: false),
+ stroke: stroke,
+ origin: (width - mark-length, 0),
+ angle: 180deg,
+ )
+
+ })
+}
+
+
+#let place-mark-on-curve(mark, path, stroke: 1pt + black, debug: false) = {
+ if mark.at("hide", default: false) { return }
+
+ let ε = 1e-4
+
+ // calculate velocity of parametrised path at point
+ let point = path(mark.pos)
+ let point-plus-ε = path(mark.pos + ε)
+ let grad = vector-len(vector.sub(point-plus-ε, point))/ε
+ if grad == 0pt { grad = ε*1pt }
+
+ let mark-length = mark.at("tip-origin", default: 0) - mark.at("tail-origin", default: 0)
+ mark-length *= float(mark.scale)
+ let Δt = mark-length*stroke.thickness/grad
+ if Δt == 0 { Δt = ε } // avoid Δt = 0 so the two points are distinct
+
+ let t = lerp(Δt, 1, mark.pos)
+ let tip-point = path(t)
+ let tail-point = path(t - Δt)
+ let θ = angle-between(tail-point, tip-point)
+
+ draw-mark(mark, origin: tip-point, angle: θ, stroke: stroke)
+
+ if debug {
+ draw.circle(
+ tip-point,
+ radius: .2pt,
+ fill: rgb("0f0"),
+ stroke: none
+ )
+ draw.circle(
+ tail-point,
+ radius: .2pt,
+ fill: rgb("f00"),
+ stroke: none
+ )
+ }
+
+}
diff --git a/render/packages/preview/fletcher/0.5.8/src/node.typ b/render/packages/preview/fletcher/0.5.8/src/node.typ
new file mode 100644
index 0000000..b8379f5
--- /dev/null
+++ b/render/packages/preview/fletcher/0.5.8/src/node.typ
@@ -0,0 +1,585 @@
+#import "utils.typ": *
+#import "coords.typ": uv-to-xy, default-ctx, resolve, NAN_COORD, resolve-system
+#import "shapes.typ"
+
+
+/// Draw a labelled node in a diagram which can connect to edges.
+///
+/// - ..args (any): The first positional argument is #param[node][pos] and the
+/// second, if given, is #param[node][label].
+///
+/// - pos (coordinate): Position of the node, or its center coordinate. This may
+/// be an elastic (row/column) coordinate like `(2, 1)`, or a CeTZ-style
+/// coordinate expression like `(rel: (30deg, 1cm), to: (2, 1))`.
+///
+/// See the options of `diagram()` to control the physical scale of elastic
+/// coordinates.
+///
+/// - name (label, string, none): An optional name to give the node.
+///
+/// Names can sometimes be used in place of coordinates. For example:
+///
+/// ```example
+/// #diagram(
+/// node((0,0), $A$, name: <A>),
+/// node((1,0.6), $B$, name: <B>),
+/// edge(<A>, <B>, "->"),
+/// node((rel: (1, 0), to: <B>), $C$)
+/// )
+/// ```
+///
+/// Node names are _labels_ (instead of strings like in CeTZ) to disambiguate
+/// them from other positional string arguments given to `edge()`. If a string
+/// is given, it is converted. (Since these labels are never inserted into the
+/// final document, they cannot interfere with other document labels.)
+///
+/// - label (content): Content to display inside the node.
+///
+/// If a node is larger than its label, you can wrap the label in `align()` to
+/// control the label alignment within the node.
+///
+/// ```example
+/// #diagram(
+/// node((0,0), align(bottom + left)[¡Hola!],
+/// width: 3cm, height: 2cm, fill: yellow),
+/// )
+/// ```
+///
+/// - inset (length): Padding between the node's content and its outline.
+///
+/// In debug mode, the inset is visualised by a thin green outline.
+///
+/// ```example
+/// #diagram(
+/// debug: 3,
+/// node-stroke: 1pt,
+/// node((0,0), [Hello,]),
+/// edge(),
+/// node((1,0), [World!], inset: 10pt),
+/// )
+/// ```
+///
+/// Defaults to #the-param[diagram][node-inset].
+///
+/// - outset (length): Margin between the node's bounds to the anchor
+/// points for connecting edges.
+///
+/// This does not affect node layout, only how closely edges connect to the
+/// node.
+///
+/// In debug mode, the outset is visualised by a thin green outline.
+///
+/// ```example
+/// #diagram(
+/// debug: 3,
+/// node-stroke: 1pt,
+/// node((0,0), [Hello,]),
+/// edge(),
+/// node((1,0), [World!], outset: 10pt),
+/// )
+/// ```
+///
+/// Defaults to #the-param[diagram][node-outset].
+///
+/// - width (length, auto): Width of the node. If `auto`, the node's width is
+/// the width of the node #param[node][label], plus twice the
+/// #param[node][inset].
+///
+/// If the width is not `auto`, you can use `align` to control the placement of the node's #param[node][label].
+///
+/// - height (length, auto): Height of the node. If `auto`, the node's height is the height of the node #param[node][label], plus twice the #param[node][inset].
+///
+/// If the height is not `auto`, you can use `align` to control the placement of the node's #param[node][label].
+///
+/// - enclose (array): Positions or names of other nodes to enclose by enlarging
+/// this node.
+///
+/// If given, causes the node to resize so that its bounding rectangle
+/// surrounds the given nodes. The center #param[node][pos] does not affect
+/// the node's position if `enclose` is given, but still affects connecting
+/// edges.
+///
+/// ```example
+/// #diagram(
+/// node-stroke: 1pt,
+/// node((0,0), [ABC], name: <A>),
+/// node((1,1), [XYZ], name: <Z>),
+/// node(
+/// text(teal)[Node group], stroke: teal,
+/// enclose: (<A>, <Z>), name: <group>),
+/// edge(<group>, (3,0.5), stroke: teal),
+/// )
+/// ```
+///
+/// - shape (rect, circle, function): Shape of the node's outline. If `auto`,
+/// one of `rect` or `circle` is chosen depending on the aspect ratio of the
+/// node's label.
+///
+/// Other shapes are defined in the `fletcher.shapes`
+/// submodule, including
+/// #{
+/// fletcher.shapes.ALL_SHAPES.pairs()
+/// .filter(((k, v)) => type(v) != module)
+/// .map(((k, v)) => [#raw(k)])
+/// .join(last: [, and ])[, ]
+/// }.
+///
+/// Custom shapes should be specified as a function `(node, extrude, ..parameters) => (..)`
+/// which returns `cetz` objects.
+/// - The `node` argument is a dictionary containing the node's attributes,
+/// including its dimensions (`node.size`), and other options (such as
+/// `node.corner-radius`).
+/// - The `extrude` argument is a length which the shape outline should be
+/// extruded outwards by. This serves two functions: to support automatic
+/// edge anchoring with a non-zero node `outset`, and to create multi-stroke
+/// effects using the `extrude` node option.
+/// See the ```plain src/shapes.typ``` source file for example shape
+/// implementations.
+///
+/// Defaults to #the-param[diagram][node-shape].
+///
+/// - stroke (stroke): Stroke style for the node outline.
+///
+/// Defaults to #the-param[diagram][node-stroke].
+///
+/// - fill (paint): Fill style of the node. The fill is drawn within the node
+/// outline as defined by the first #param(full: false)[node][extrude] value.
+///
+/// Defaults to #the-param[diagram][node-fill].
+///
+/// - defocus (number): Strength of the "defocus" adjustment for connectors
+/// incident with this node.
+///
+/// This affects how connectors attach to non-square nodes. If `0`, the
+/// adjustment is disabled and connectors are always directed at the node's
+/// exact center.
+///
+/// #stack(
+/// dir: ltr,
+/// spacing: 1fr,
+/// ..(0.2, 0, -1).enumerate().map(((i, defocus)) => {
+/// fletcher.diagram(spacing: 8mm, {
+/// node((i, 0), raw("defocus: "+str(defocus)), stroke: black, defocus: defocus)
+/// for y in (-1, +1) {
+/// edge((i - 1, y), (i, 0))
+/// edge((i, y), (i, 0))
+/// edge((i + 1, y), (i, 0))
+/// }
+/// })
+/// })
+/// )
+///
+/// Defaults to #the-param[diagram][node-defocus].
+///
+/// - extrude (array): Draw strokes around the node at the given offsets to
+/// obtain a multi-stroke effect. Offsets may be numbers (specifying multiples
+/// of the stroke's thickness) or lengths.
+///
+/// The node's fill is drawn within the boundary defined by the first offset in
+/// the array.
+///
+/// #diagram(
+/// node-stroke: 1pt,
+/// node-fill: red.lighten(70%),
+/// node((0,0), `(0,)`),
+/// node((1,0), `(0, 2)`, extrude: (0, 2)),
+/// node((2,0), `(2, 0)`, extrude: (2, 0)),
+/// node((3,0), `(0, -2.5, 2mm)`, extrude: (0, -2.5, 2mm)),
+/// )
+///
+/// See also #the-param[edge][extrude].
+///
+/// - corner-radius (length): Radius of rounded corners, if supported by the
+/// node #param[node][shape].
+///
+/// Defaults to #the-param[diagram][node-corner-radius].
+///
+/// - layer (number): Layer on which to draw the node.
+///
+/// Objects on a higher `layer` are drawn on top of objects on a lower
+/// `layer`. Objects on the same layer are drawn in the order they are passed
+/// to `diagram()`.
+///
+/// Defaults to layer `0` unless the node #param[node][enclose]s
+/// points, in which case `layer` defaults to `-1`.
+///
+/// - snap (number, false): The snapping priority for edges connecting to this
+/// node. A higher priority means edges will automatically snap to this node
+/// over other overlapping nodes. If `false`, edges only snap to this node if
+/// manually set with #the-param[edge][snap-to].
+///
+/// Setting a lower value is useful if the node #param[node][enclose]s other
+/// nodes that you want to snap to first.
+///
+/// - post (function): Callback function to intercept `cetz` objects before they
+/// are drawn to the canvas.
+///
+/// This can be used to hide elements without affecting layout (for use with
+/// #link("https://github.com/touying-typ/touying")[Touying], for example).
+/// The `hide()` function also helps for this purpose.
+///
+#let node(
+ ..args,
+ pos: auto,
+ name: none,
+ label: none,
+ inset: auto,
+ outset: auto,
+ fill: auto,
+ stroke: auto,
+ extrude: (0,),
+ width: auto,
+ height: auto,
+ radius: auto,
+ enclose: (),
+ corner-radius: auto,
+ shape: auto,
+ defocus: auto,
+ snap: 0,
+ layer: auto,
+ post: x => x,
+) = {
+ if args.named().len() > 0 { error("Unexpected named argument(s) #..0.", args.named().keys()) }
+ if args.pos().len() > 2 { error("`node()` can have up to two positional arguments; the position and label.") }
+
+ // interpret first two positional arguments
+ if args.pos().len() == 2 {
+ (pos, label) = args.pos()
+ } else if args.pos().len() == 1 {
+ let arg = args.pos().at(0)
+ // one positional argument may be the coordinate or the label
+ if type(arg) in (array, dictionary, label) {
+ pos = arg
+ label = none
+ } else {
+ pos = if enclose.len() > 0 { auto } else { () }
+ label = arg
+ }
+ }
+
+ let extrude = as-array(extrude).map(as-number-or-length.with(
+ message: "`extrude` must be a number, length, or an array of those"
+ ))
+
+ if not (type(snap) in (int, float) or snap == false) {
+ error("`snap` must be a number specifying priority or `false` to disable; got #0.", repr(snap))
+ }
+
+ metadata((
+ class: "node",
+ pos: (raw: pos),
+ name: pass-none(as-label)(name),
+ label: label,
+ inset: inset,
+ outset: outset,
+ enclose: as-array(enclose),
+ size: (width, height),
+ radius: radius,
+ shape: shape,
+ stroke: stroke,
+ fill: fill,
+ corner-radius: corner-radius,
+ defocus: defocus,
+ extrude: extrude,
+ layer: layer,
+ snap: snap,
+ post: post,
+ ))
+}
+
+
+
+#let resolve-node-options(node, options) = {
+
+ node.stroke = map-auto(node.stroke, options.node-stroke)
+ if node.stroke != none {
+ let base-stroke = pass-none(stroke-to-dict)(options.node-stroke)
+ node.stroke = base-stroke + stroke-to-dict(node.stroke)
+ }
+ node.stroke = pass-none(stroke)(node.stroke) // guarantee stroke or none
+
+ node.fill = map-auto(node.fill, options.node-fill)
+ node.corner-radius = map-auto(node.corner-radius, options.node-corner-radius)
+ node.inset = map-auto(node.inset, options.node-inset).to-absolute()
+ node.outset = map-auto(node.outset, options.node-outset).to-absolute()
+ node.defocus = map-auto(node.defocus, options.node-defocus)
+
+ node.size = node.size.map(pass-auto(length.to-absolute))
+ node.radius = pass-auto(length.to-absolute)(node.radius)
+
+ node.shape = map-auto(node.shape, options.node-shape)
+
+ node.auto-shape = node.shape == auto
+ if node.shape == auto and node.enclose == () {
+ if node.radius != auto { node.shape = shapes.circle }
+ if node.size != (auto, auto) { node.shape = shapes.rect }
+ }
+
+ let thickness = if node.stroke == none { 1pt } else {
+ map-auto(node.stroke.thickness, 1pt)
+ }
+
+ node.extrude = node.extrude.map(d => {
+ if type(d) == length { d }
+ else { d*thickness }
+ }).map(length.to-absolute)
+
+ if type(node.outset) in (int, float) {
+ node.outset *= thickness
+ }
+
+ let default-layer = if node.enclose.len() > 0 { -1 } else { 0 }
+ node.layer = map-auto(node.layer, default-layer)
+
+ node
+}
+
+
+/// Measure node labels with the style context and resolve node shapes.
+///
+/// Widths and heights that are `auto` are determined by measuring the size of
+/// the node's label.
+#let measure-node-size(node) = {
+
+ // Width and height explicitly given
+ if auto not in node.size {
+ let (width, height) = node.size
+ node.radius = vector-len((width/2, height/2))
+ node.aspect = width/height
+
+ // Radius explicitly given
+ } else if node.radius != auto {
+ node.size = (2*node.radius, 2*node.radius)
+ node.aspect = 1
+
+ // Width and/or height set to auto
+ } else {
+
+ let inner-size = node.size.map(pass-auto(i => i - 2*node.inset))
+
+ // Determine physical size of node content
+ let (width, height) = measure(box(
+ node.label,
+ width: inner-size.at(0),
+ height: inner-size.at(1),
+ ))
+
+ // let (width, height) = node.inner-size
+ let radius = vector-len((width/2, height/2)) // circumcircle
+
+ node.aspect = if width == 0pt or height == 0pt { 1 } else { width/height }
+
+ // automatically choose a node shape
+ if node.shape == auto {
+ if node.enclose.len() > 0 {
+ node.shape = rect
+ } else {
+ let is-roundish = calc.max(node.aspect, 1/node.aspect) < 1.5
+ node.shape = if is-roundish { "circle" } else { "rect" }
+ }
+ }
+
+ // Add node inset
+ if radius != 0pt { radius += node.inset }
+ if width != 0pt and height != 0pt {
+ width += 2*node.inset
+ height += 2*node.inset
+ }
+
+ // If width/height/radius is auto, set to measured width/height/radius
+ node.size = node.size.zip((width, height))
+ .map(((given, measured)) => map-auto(given, measured))
+ node.radius = map-auto(node.radius, radius)
+
+ }
+
+ if node.shape in (circle, "circle") { node.shape = shapes.circle }
+ if node.shape in (rect, "rect") { node.shape = shapes.rect }
+
+ node
+}
+
+
+/// Process the `enclose` options of an array of nodes.
+#let resolve-node-enclosures(nodes, ctx) = {
+
+ let nodes = nodes.map(node => {
+ // not an enclose node, leave as is
+ if node.enclose.len() == 0 { return node }
+
+ let enclosed-vertices = node.enclose.map(key => {
+ let near-node = find-node(nodes, key)
+
+ // if near-node == none or near-node.pos.raw == auto {
+ if near-node == none {
+ // if enclosed point doesn't resolve to a node
+ // enclose the point itself
+ let (_, coord) = resolve(ctx, key)
+ (coord,)
+ } else {
+ // if enclosed point resolves to a node
+ // enclose its bounding box
+ let (x, y) = near-node.pos.xyz
+ if "bounding-center" in near-node {
+ (x, y) = near-node.bounding-center
+ }
+ let (w, h) = near-node.size
+ (
+ (x - w/2, y - h/2),
+ (x - w/2, y + h/2),
+ (x + w/2, y - h/2),
+ (x + w/2, y + h/2),
+ )
+ }
+ }).join()
+
+ let (center, size) = bounding-rect(enclosed-vertices)
+
+ node.pos.xyz = center
+ node.bounding-center = center
+ node.size = vector-max(
+ size.map(d => d + node.inset*2),
+ node.size,
+ )
+ node.resolved-enclose = true
+ assert(node.shape != auto)
+
+ node
+ })
+
+ nodes
+}
+
+
+#let register-node-anchors(ctx, node) = {
+ if node.name == none { return ctx }
+ let calculate-anchors
+
+ if ctx.target-system == "uv" {
+ // anchors don't make sense in elastic coordinates
+ // so just give access to the origin, but make
+ // everything else indeterminate (NAN_COORD)
+ calculate-anchors = (a) => {
+ if a == () {
+ ("default",)
+ } else {
+ if a == "default" {
+ node.pos.uv
+ } else {
+ NAN_COORD
+ }
+ }
+ }
+ } else if ctx.target-system == "xyz" {
+ // get node center, taking care for enclose nodes
+ let physical-origin = node.at("bounding-center", default: node.pos.xyz)
+ let uv-origin = node.pos.xyz
+ // enclose nodes are a bit confusing because they have two 'centers'...
+ // the physical center of the shape which is drawn is node.bounding-center,
+ // whereas node.pos.xyz is the uv-space midpoint (which can be different to the xyz
+ // midpoint for irregular grids.)
+ // This is a deliberate design decision - often, edges connecting to enclose
+ // nodes should be nice and straight, not angled toward the exact centre.
+
+ if is-nan-vector(physical-origin) { return ctx }
+
+ // do not compute anchors for enclose nodes before they have been resolved
+ if node.enclose.len() > 0 and "resolved-enclose" not in node {
+ // we should return NAN_COORD to indicate the anchors are not yet resolvable
+ // however, units must be length (float.nan + length panics) but there is
+ // so such thing as nan length (float.nan*1pt == 0pt, interestingly)
+ calculate-anchors = (k) => (0pt, 0pt)
+ // so we just return zero, hoping it doesn't cause incorrect anchors --
+ // it's better than crashing -- and they might get resolved properly later
+ } else {
+ let cetz-obj = (node.shape)(node, node.outset).at(0)
+ calculate-anchors = (k) => {
+ if k == "default" { return uv-origin }
+ let a = ((cetz-obj)(ctx).anchors)(k)
+ if not is-number-vector(a) { return a }
+ a.at(1) *= -1 // CETZ Y AXIS
+ vector.add(
+ physical-origin, // node center
+ vector-2d(vector.scale(a, ctx.length)),
+ )
+ }
+ }
+ }
+
+ ctx.nodes.insert(str(node.name), (anchors: calculate-anchors))
+ ctx
+
+}
+
+/// Resolve node positions to a target coordinate system in sequence.
+///
+/// CeTZ-style coordinate expressions work, with the previous coordinate `()`
+/// referring to the resolved position of the previous node.
+///
+/// The resolved coordinates are added to each node's `pos` dictionary.
+///
+/// - nodes (array): Array of nodes, each a dictionary containing a `pos` entry,
+/// which should be a CeTZ-compatible coordinate expression.
+/// - ctx (dictionary): CeTZ-style context to be passed to `resolve(ctx, ..)`.
+/// This must contain `target-system`, and optionally `grid`.
+/// -> array
+#let resolve-node-coordinates(nodes, ctx: (:)) = {
+ let ctx = default-ctx + ctx
+ let system = ctx.target-system
+
+ // nodes which enclose other points are allowed to have
+ // position `auto`; they are placed after normal nodes
+ let auto-placed-nodes = ()
+
+ let coord
+ for (i, node) in nodes.enumerate() {
+
+ if node.pos.raw == auto {
+ // this node encloses other nodes
+ if ctx.target-system == "xyz" {
+ // resolve center from uv coords, if possible
+ if not is-nan-vector(node.pos.uv) {
+ (ctx, coord) = resolve(ctx, node.pos.uv)
+ }
+ } else {
+ // otherwise, we must find bounding box center later
+ auto-placed-nodes.push(i)
+ coord = NAN_COORD
+ }
+ } else {
+ // this node has a center that may be resolvable
+ (ctx, coord) = resolve(ctx, node.pos.raw)
+ }
+
+ node.pos.insert(ctx.target-system, coord)
+ nodes.at(i) = node
+ ctx = register-node-anchors(ctx, node)
+ }
+
+ for i in auto-placed-nodes {
+ let node = nodes.at(i)
+
+ // the center of enclosing nodes defaults to the center
+ // of the bounding rect of the points they enclose
+ let enclosed-points = node.enclose.map(key => {
+ let node = find-node(nodes, key)
+ if node == none {
+ // enclose key doesn't correspond to node
+ // interpret key as real coordinate
+ let (_, coord) = resolve(ctx, key)
+ coord
+ } else {
+ node.pos.at(ctx.target-system)
+ }
+ }).filter(coord => not is-nan-vector(coord))
+
+ let coord = if enclosed-points.len() > 0 {
+ bounding-rect(enclosed-points).center
+ } else { NAN_COORD }
+
+ nodes.at(i).pos.insert(ctx.target-system, coord)
+
+ }
+
+ (ctx, nodes)
+}
diff --git a/render/packages/preview/fletcher/0.5.8/src/shapes.typ b/render/packages/preview/fletcher/0.5.8/src/shapes.typ
new file mode 100644
index 0000000..2d93484
--- /dev/null
+++ b/render/packages/preview/fletcher/0.5.8/src/shapes.typ
@@ -0,0 +1,761 @@
+#import "deps.typ": cetz
+#import cetz: draw, vector
+#import "utils.typ": dir-to-anchor
+
+/// The standard rectangle node shape.
+///
+/// A string `"rect"` or the element function `rect` given to
+/// #the-param[node][shape] are interpreted as this shape.
+///
+/// #diagram(
+/// node-stroke: green,
+/// node-fill: green.lighten(90%),
+/// node((0,0), `rect`, shape: fletcher.shapes.rect)
+/// )
+///
+#let rect(node, extrude) = {
+ let r = node.corner-radius
+ let (w, h) = node.size.map(i => i/2 + extrude)
+ draw.rect(
+ (-w, -h), (+w, +h),
+ radius: if r != none { r + extrude },
+ )
+}
+
+/// The standard circle node shape.
+///
+/// A string `"circle"` or the element function `circle` given to
+/// #the-param[node][shape] are interpreted as this shape.
+///
+/// #diagram(
+/// node-stroke: red,
+/// node-fill: red.lighten(90%),
+/// node((0,0), `circle`, shape: fletcher.shapes.circle)
+/// )
+///
+#let circle(node, extrude) = draw.circle((0, 0), radius: node.radius + extrude)
+
+/// An elliptical node shape.
+///
+/// #diagram(
+/// node-stroke: orange,
+/// node-fill: orange.lighten(90%),
+/// node((0,0), `ellipse`, shape: fletcher.shapes.ellipse)
+/// )
+///
+/// - scale (number): Scale factor for ellipse radii.
+#let ellipse(node, extrude, scale: 1) = {
+ draw.circle(
+ (0, 0),
+ radius: vector.scale(node.size, 0.5).map(x => x*scale + extrude),
+ )
+}
+
+
+/// A capsule node shape.
+///
+/// #diagram(
+/// node-stroke: teal,
+/// node-fill: teal.lighten(90%),
+/// node((0,0), `pill`, shape: fletcher.shapes.pill)
+/// )
+///
+#let pill(node, extrude) = {
+ let size = node.size.map(i => i + 2*extrude)
+ draw.rect(
+ vector.scale(size, -0.5),
+ vector.scale(size, +0.5),
+ radius: calc.min(..size)/2,
+ )
+}
+
+
+/// A slanted rectangle node shape.
+///
+/// #diagram(
+/// node-stroke: olive,
+/// node-fill: olive.lighten(90%),
+/// node((0,0), `parallelogram`, shape: fletcher.shapes.parallelogram)
+/// )
+///
+/// - angle (angle): Angle of the slant, `0deg` is a rectangle. Don't set to
+/// `90deg` unless you want your document to be larger than the solar system.
+///
+/// - fit (number): Adjusts how comfortably the parallelogram fits the label's bounding box.
+///
+/// #for (i, fit) in (0, 0.5, 1).enumerate() {
+/// let s = fletcher.shapes.parallelogram.with(fit: fit, angle: 35deg)
+/// let l = box(
+/// stroke: (dash: "dashed", thickness: 0.5pt),
+/// inset: 10pt,
+/// raw("fit: " + repr(fit)),
+/// )
+/// diagram(node((i, 0), l,
+/// inset: 0pt,
+/// shape: s,
+/// stroke: olive,
+/// fill: olive.lighten(90%),
+/// ))
+/// h(5mm)
+/// }
+#let parallelogram(node, extrude, flip: false, angle: 20deg, fit: 0.8) = {
+ let (w, h) = node.size
+ if flip { (w, h) = (h, w) }
+
+ let (x, y) = (w/2 + extrude*calc.cos(angle), h/2 + extrude)
+ let δ = h/2*calc.tan(angle)
+ let μ = extrude*calc.tan(angle)
+ x += δ*fit
+
+ let verts = (
+ (-x - μ, -y),
+ (+x - δ, -y),
+ (+x + μ, +y),
+ (-x + δ, +y),
+ )
+
+ if flip { verts = verts.map(((i, j)) => (j, i)) }
+
+ let obj = draw.line(..verts, close: true)
+ draw.group(obj) // enables cetz border anchors
+}
+
+
+/// An isosceles trapezium node shape.
+///
+/// #diagram(
+/// node-stroke: green,
+/// node-fill: green.lighten(90%),
+/// node((0,0), `trapezium`, shape: fletcher.shapes.trapezium)
+/// )
+///
+/// - angle (angle): Angle of the slant, `0deg` is a rectangle. Don't set to
+/// `90deg` unless you want your document to be larger than the solar system.
+///
+/// - fit (number): Adjusts how comfortably the trapezium fits the label's bounding box.
+///
+/// #for (i, fit) in (0, 0.5, 1).enumerate() {
+/// let s = fletcher.shapes.trapezium.with(fit: fit, angle: 35deg)
+/// let l = box(
+/// stroke: (dash: "dashed", thickness: 0.5pt),
+/// inset: 10pt,
+/// raw("fit: " + repr(fit)),
+/// )
+/// diagram(node((i, 0), l,
+/// inset: 0pt,
+/// shape: s,
+/// stroke: green,
+/// fill: green.lighten(90%),
+/// ))
+/// h(5mm)
+/// }
+///
+/// - dir (top, bottom, left, right): The side the shorter parallel edge is on.
+#let trapezium(node, extrude, dir: top, angle: 20deg, fit: 0.8) = {
+ assert(dir in (top, bottom, left, right))
+
+ let flip = dir in (right, left) // flip along diagonal line x = y
+ let rotate = dir in (bottom, left) // rotate 180deg
+
+ let (w, h) = node.size
+ if flip { (w, h) = (h, w) }
+
+ let (x, y) = (w/2 + extrude*calc.cos(angle), h/2 + extrude)
+ let δ = h/2*calc.tan(angle)
+ let μ = extrude*calc.tan(angle)
+ x += δ*fit
+
+ let verts = (
+ (-x - μ, -y),
+ (+x + μ, -y),
+ (+x - δ, +y),
+ (-x + δ, +y),
+ )
+
+ if flip { verts = verts.map(((i, j)) => (j, i)) }
+ if rotate { verts = verts.map(((i, j)) => (-i, -j)) }
+
+ let obj = draw.line(..verts, close: true)
+ draw.group(obj) // enables cetz border anchors
+}
+
+/// A rhombus node shape.
+///
+/// #diagram(
+/// node-stroke: purple,
+/// node-fill: purple.lighten(90%),
+/// node((0,0), `diamond`, shape: fletcher.shapes.diamond)
+/// )
+///
+/// - fit (number): Adjusts how comfortably the diamond fits the label's bounding box.
+///
+/// #for (i, fit) in (0, 0.5, 1).enumerate() {
+/// let s = fletcher.shapes.diamond.with(fit: fit)
+/// let l = box(
+/// stroke: (dash: "dashed", thickness: 0.5pt),
+/// inset: 10pt,
+/// raw("fit: " + repr(fit)),
+/// )
+/// diagram(node((i, 0), l,
+/// inset: 0pt,
+/// shape: s,
+/// stroke: purple,
+/// fill: purple.lighten(90%),
+/// ))
+/// h(5mm)
+/// }
+#let diamond(node, extrude, fit: 0.5) = {
+ let (w, h) = node.size
+ let φ = calc.atan2(w/1pt, h/1pt)
+ let x = w/2*(1 + fit) + extrude/calc.sin(φ)
+ let y = h/2*(1 + fit) + extrude/calc.cos(φ)
+ let obj = draw.line(
+ (-x, 0pt),
+ (0pt, -y),
+ (+x, 0pt),
+ (0pt, +y),
+ close: true,
+ )
+ draw.group(obj) // enables cetz border anchors
+}
+
+/// An isosceles triangle node shape.
+///
+/// One of #param[triangle][angle] or #param[triangle][aspect] may be given, but
+/// not both. The triangle's base coincides with the label's base and widens to
+/// enclose the label; see https://www.desmos.com/calculator/i4i9svunj4.
+///
+/// #diagram(
+/// node-stroke: fuchsia,
+/// node-fill: fuchsia.lighten(90%),
+/// node((0,0), `triangle`, shape: fletcher.shapes.triangle)
+/// )
+///
+/// - dir (top, bottom, left, right): Direction the triangle points.
+/// - aspect (number, auto): Aspect ratio of triangle, or the ratio of its base
+/// to its height.
+/// - angle (angle, auto): Angle of the triangle opposite the base.
+/// - fit (number): Adjusts how comfortably the triangle fits the label's bounding box.
+///
+/// #for (i, fit) in (0, 0.5, 1).enumerate() {
+/// let s = fletcher.shapes.triangle.with(fit: fit, angle: 120deg)
+/// let l = box(
+/// stroke: (dash: "dashed", thickness: 0.5pt),
+/// inset: 10pt,
+/// raw("fit: " + repr(fit)),
+/// )
+/// diagram(node((i, 0), l,
+/// inset: 0pt,
+/// shape: s,
+/// stroke: fuchsia,
+/// fill: fuchsia.lighten(90%),
+/// ))
+/// h(5mm)
+/// }
+#let triangle(node, extrude, dir: top, angle: auto, aspect: auto, fit: 0.8) = {
+ assert(dir in (top, bottom, left, right))
+
+ let flip = dir in (right, left) // flip along diagonal line x = y
+ let rotate = dir in (bottom, left) // rotate 180deg
+
+ let (w, h) = node.size
+ if flip { (w, h) = (h, w) }
+
+ if angle == auto and aspect == auto { aspect = w/h }
+ if angle == auto { angle = 2*calc.atan(aspect/2) }
+ if aspect == auto { aspect = 2*calc.tan(angle/2) }
+
+ let a = aspect*h/2 + fit*w/2
+ let b = (a + fit*w/2)/aspect
+
+ a += extrude*calc.tan(45deg + angle/4)
+ b += extrude/calc.cos(90deg - angle/2)
+
+ let verts = (
+ (-a, -h/2 - extrude),
+ (+a, -h/2 - extrude),
+ (0, +b),
+ )
+
+ if flip { verts = verts.map(((i, j)) => (j, i)) }
+ if rotate { verts = verts.map(((i, j)) => (-i, -j)) }
+
+ let obj = draw.line(..verts, close: true)
+ draw.group(obj) // enables cetz border anchors
+}
+
+
+/// A pentagonal house-like node shape.
+///
+/// #diagram(
+/// node-stroke: eastern,
+/// node-fill: eastern.lighten(90%),
+/// node((0,0), `house`, shape: fletcher.shapes.house)
+/// )
+///
+/// - dir (top, bottom, left, right): Direction of the roof of the house.
+/// - angle (angle): The slant of the roof. A plain rectangle is `0deg`, and
+/// `90deg` is a sky scraper stretching past Pluto.
+#let house(node, extrude, dir: top, angle: 10deg) = {
+ let flip = dir in (right, left) // flip along diagonal line x = y
+ let rotate = dir in (bottom, left) // rotate 180deg
+
+ let (w, h) = node.size
+ if flip { (w, h) = (h, w) }
+
+ let (x, y) = (w/2 + extrude, h/2 + extrude)
+ let a = h/2 + extrude*calc.tan(45deg - angle/2)
+ let b = h/2 + w/2*calc.tan(angle) + extrude/calc.cos(angle)
+
+ let verts = (
+ (-x, -y),
+ (-x, a),
+ (0pt, b),
+ (+x, a),
+ (+x, -y),
+ )
+
+ if flip { verts = verts.map(((i, j)) => (j, i)) }
+ if rotate { verts = verts.map(((i, j)) => (-i, -j)) }
+
+ let obj = draw.line(..verts, close: true)
+ draw.group(obj) // enables cetz border anchors
+}
+
+
+
+
+/// A chevron node shape.
+///
+/// #diagram(
+/// node-stroke: yellow,
+/// node-fill: yellow.lighten(90%),
+/// node((0,0), `chevron`, shape: fletcher.shapes.chevron)
+/// )
+///
+/// - dir (top, bottom, left, right): Direction the chevron points.
+/// - angle (angle): The slant of the arrow. A plain rectangle is `0deg`.
+/// - fit (number): Adjusts how comfortably the chevron fits the label's bounding box.
+///
+/// #for (i, fit) in (0, 0.5, 1).enumerate() {
+/// let s = fletcher.shapes.chevron.with(fit: fit)
+/// let l = box(
+/// stroke: (dash: "dashed", thickness: 0.5pt),
+/// inset: 10pt,
+/// raw("fit: " + repr(fit)),
+/// )
+/// diagram(node((i, 0), l,
+/// inset: 0pt,
+/// shape: s,
+/// stroke: yellow,
+/// fill: yellow.lighten(90%),
+/// ))
+/// h(5mm)
+/// }
+#let chevron(node, extrude, dir: right, angle: 30deg, fit: 0.8) = {
+ let flip = dir in (right, left) // flip along diagonal line x = y
+ let rotate = dir in (bottom, left) // rotate 180deg
+
+ let (w, h) = node.size
+ if flip { (w, h) = (h, w) }
+
+ let (x, y) = (w/2 + extrude, h/2 + extrude)
+ let c = w/2*calc.tan(angle)
+ let α = extrude*calc.tan(45deg - angle/2)
+ let β = extrude*calc.tan(45deg + angle/2)
+ let ɣ = extrude/calc.cos(angle) - c
+ let δ = c*fit
+ let y = h/2 + c*fit
+
+ let verts = (
+ (-x, +y + α - c),
+ (0pt, +y + ɣ + c),
+ (+x, +y + α - c),
+
+ (+x, -y - β),
+ (0pt, -y - ɣ),
+ (-x, -y - β),
+ )
+
+ if flip { verts = verts.map(((i, j)) => (j, i)) }
+ if rotate { verts = verts.map(((i, j)) => (-i, -j)) }
+
+
+ let obj = draw.line(..verts, close: true)
+ draw.group(obj) // enables cetz border anchors
+}
+
+
+
+
+
+/// An (irregular) hexagon node shape.
+///
+/// #diagram(
+/// node-stroke: aqua,
+/// node-fill: aqua.lighten(90%),
+/// node((0,0), `hexagon`, shape: fletcher.shapes.hexagon)
+/// )
+///
+/// - angle (angle): Half the exterior angle, `0deg` being a rectangle.
+/// - fit (number): Adjusts how comfortably the hexagon fits the label's bounding box.
+///
+/// #for (i, fit) in (0, 0.5, 1).enumerate() {
+/// let s = fletcher.shapes.hexagon.with(fit: fit)
+/// let l = box(
+/// stroke: (dash: "dashed", thickness: 0.5pt),
+/// inset: 10pt,
+/// raw("fit: " + repr(fit)),
+/// )
+/// diagram(node((i, 0), l,
+/// inset: 0pt,
+/// shape: s,
+/// stroke: aqua,
+/// fill: aqua.lighten(90%),
+/// ))
+/// h(5mm)
+/// }
+#let hexagon(node, extrude, angle: 30deg, fit: 0.8) = {
+ let (w, h) = node.size
+ let f = h/2*calc.tan(angle)*(1 - fit)
+ let x = w/2 + extrude*calc.tan(45deg - angle/2) - f
+ let y = h/2 + extrude
+ let z = y*calc.tan(angle)
+ let obj = draw.line(
+ (+x, -y),
+ (+x + z, 0pt),
+ (+x, +y),
+
+ (-x, +y),
+ (-x - z, 0pt),
+ (-x, -y),
+
+ close: true,
+ )
+ draw.group(obj) // enables cetz border anchors
+}
+
+
+/// A truncated rectangle node shape.
+///
+/// #diagram(
+/// node-stroke: maroon,
+/// node-fill: maroon.lighten(90%),
+/// node((0,0), `octagon`, shape: fletcher.shapes.octagon)
+/// )
+///
+/// - truncate (number, length): Size of the truncated corners. A number is
+/// interpreted as a multiple of the smaller of the node's width or height.
+#let octagon(node, extrude, truncate: 0.5) = {
+ let (w, h) = node.size
+ let (x, y) = (w/2 + extrude, h/2 + extrude)
+
+ let d
+ if type(truncate) == length { d = truncate }
+ else { d = truncate*calc.min(w/2, h/2)}
+ d += extrude*0.5857864376 // (1 - calc.tan(calc.pi/8))
+
+ let obj = draw.line(
+ (-x + d, -y ),
+ (-x , -y + d),
+ (-x , +y - d),
+ (-x + d, +y ),
+ (+x - d, +y ),
+ (+x , +y - d),
+ (+x , -y + d),
+ (+x - d, -y ),
+ close: true,
+ )
+ draw.group(obj) // enables cetz border anchors
+}
+
+
+/// A 3D cylinder node shape.
+///
+/// #diagram(
+/// node-stroke: gray,
+/// node-fill: gray.lighten(90%),
+/// node((0,0), `cylinder`, shape: fletcher.shapes.cylinder)
+/// )
+///
+/// - fit (number): Adjusts how exactly the cylinder fits around the label's bounding box.
+///
+/// #for (i, fit) in (0, 0.5, 1).enumerate() {
+/// let s = fletcher.shapes.cylinder.with(fit: fit)
+/// let l = box(
+/// stroke: (dash: "dashed", thickness: 0.5pt),
+/// inset: 10pt,
+/// raw("fit: " + repr(fit)),
+/// )
+/// diagram(node((i, 0), l,
+/// inset: 0pt,
+/// shape: s,
+/// stroke: gray,
+/// fill: gray.lighten(90%),
+/// ))
+/// h(5mm)
+/// }
+///
+/// - tilt (angle): Controls the perspective tilt: `0deg` is side on.
+///
+/// #for (i, tilt) in (10deg, 5deg, 0deg, -2deg).enumerate() {
+/// let s = fletcher.shapes.cylinder.with(tilt: tilt)
+/// let l = box(
+/// inset: 10pt,
+/// raw("tilt: " + repr(tilt)),
+/// )
+/// diagram(node((i, 0), l,
+/// inset: 0pt,
+/// shape: s,
+/// stroke: gray,
+/// fill: gray.lighten(90%),
+/// ))
+/// h(5mm)
+/// }
+///
+/// - rings (length, array): Array of vertical positions to draw arcs around the body.
+/// Often used to represent databases.
+///
+/// #for (i, rings) in ((), 4pt, 100% - 4pt, (10%, 20%)).enumerate() {
+/// let s = fletcher.shapes.cylinder.with(rings: rings)
+/// let l = box(
+/// inset: 10pt,
+/// raw("rings:\n" + repr(rings)),
+/// )
+/// diagram(node((i, 0), l,
+/// inset: 0pt,
+/// width: 3cm,
+/// shape: s,
+/// stroke: gray,
+/// fill: gray.lighten(90%),
+/// ))
+/// h(5mm)
+/// }
+#let cylinder(node, extrude, fit: 0.6, tilt: 8deg, rings: ()) = {
+ if type(rings) != array { rings = (rings,) }
+
+ let sign = if tilt >= 0deg { +1 } else {
+ rings = rings.map(ring => 100% - ring)
+ -1
+ }
+
+ let (w, h) = node.size
+ let (x, y) = (w/2, sign*h/2)
+ let ry = sign*x*calc.abs(calc.sin(tilt))
+ x += extrude
+ ry += sign*extrude
+
+ let obj = {
+ draw.translate(y: ry*fit)
+ draw.merge-path({
+ draw.arc((-x, +y), radius: (x, ry), start: 180deg, stop: 0deg)
+ draw.arc((+x, -y), radius: (x, ry), start: 0deg, stop: -180deg)
+ }, close: true)
+ if true {
+ for ring in (0%, ..rings) {
+ ring = ring + 0pt + 0%
+ let t = float(ring.ratio) + sign*ring.length.to-absolute()/(2*y)
+ let yt = y*(1 - t) - y*t
+ draw.arc((+x, yt), radius: (x, ry), start: 0deg, stop: -180deg, fill: none)
+ }
+ }
+ }
+ draw.group(obj)
+}
+
+
+/// A stretched glyph along one side of a node.
+/// See also `shapes.brace`, `shapes.bracket`, and `shapes.paren`, which are implemented using this shape.
+///
+/// #diagram(node((0,0), [Like this!], shape: fletcher.shapes.brace))
+///
+/// This is especially useful when used with #param[node][enclose] nodes.
+///
+/// ```example
+/// #import fletcher.shapes: brace, bracket
+/// #diagram(
+/// spacing: 1cm,
+/// node-stroke: teal,
+/// node((0,0), $A$, name: <A>),
+/// node((1,0), $B$, name: <B>),
+/// node((1,1), $C$, name: <C>),
+/// node(enclose: (<A>, <B>), shape: bracket.with(
+/// dir: top, size: 2em)),
+/// node(enclose: (<B>, <C>), shape: brace.with(
+/// dir: right, length: 100% - 1em,
+/// sep: 10pt, label: $B C$)),
+/// )
+/// ```
+///
+/// - dir (direction): The side of the node to place the glyph across.
+/// Note that the glyph must be chosen to match the direction.
+///
+/// #for (i, dir) in (top, bottom, left, right).enumerate() {
+/// let s = fletcher.shapes.brace.with(dir: dir)
+/// let l = box(
+/// stroke: (dash: "dashed", thickness: 0.5pt),
+/// inset: 10pt,
+/// raw("dir: " + repr(dir)),
+/// )
+/// diagram(node((i, 0), l,
+/// inset: 0pt,
+/// shape: s,
+/// stroke: aqua,
+/// fill: aqua.lighten(90%),
+/// ))
+/// h(5mm)
+/// }
+///
+/// - sep (length): Extra distance between the glyph and the node's edge.
+///
+/// #for (i, sep) in (-5pt, 0pt, 5pt).enumerate() {
+/// let s = fletcher.shapes.brace.with(sep: sep)
+/// let l = box(
+/// stroke: (dash: "dashed", thickness: 0.5pt),
+/// inset: 10pt,
+/// raw("sep: " + repr(sep)),
+/// )
+/// diagram(node((i, 0), l,
+/// inset: 0pt,
+/// shape: s,
+/// stroke: aqua,
+/// fill: aqua.lighten(90%),
+/// ))
+/// h(5mm)
+/// }
+///
+/// - length (relative): Size of the glyph. A relative length such as `100% + 5pt` means `5pt` more than the size of the node. This is ultimately given to the `stretch()` function.
+///
+/// #for (i, length) in (100%, 100% - 2em, 150%).enumerate() {
+/// let s = fletcher.shapes.brace.with(length: length)
+/// let l = box(
+/// stroke: (dash: "dashed", thickness: 0.5pt),
+/// inset: 10pt,
+/// raw("length: " + repr(length)),
+/// )
+/// diagram(node((i, 0), l,
+/// inset: 0pt,
+/// shape: s,
+/// stroke: teal,
+/// fill: teal.lighten(90%),
+/// ))
+/// h(5mm)
+/// }
+///
+/// - glyph (symbol, content): The glyph to use. This works best with glyphs that can be stretched with the #link("https://typst.app/docs/reference/math/stretch/")[`stretch()` function], but any glyph or equation can be used.
+///
+/// #for (i, glyphtxt) in ("brace.b", "bracket.b", "paren.b", "arrow.l.r", "sqrt(pi)").enumerate() {
+/// let s = fletcher.shapes.stretched-glyph.with(glyph: eval(glyphtxt, mode: "math"))
+/// let l = box(
+/// stroke: (dash: "dashed", thickness: 0.5pt),
+/// inset: 10pt,
+/// raw(glyphtxt),
+/// )
+/// diagram(node((i, 0), l,
+/// inset: 0pt,
+/// shape: s,
+/// stroke: teal,
+/// fill: teal.lighten(90%),
+/// ))
+/// h(5mm)
+/// }
+///
+/// - ..args (any): Arguments given to the `text()` element containing the glyph.
+/// Useful for changing color or the font size (defining overall scale without affecting its stretch length).
+///
+/// #diagram({
+/// let l(key, value) = box(
+/// stroke: (dash: "dashed", thickness: 0.5pt),
+/// inset: 10pt,
+/// raw(key + ": " + value)
+/// )
+/// let n(i, key, value) = node((i, 0), l(key, value),
+/// shape: fletcher.shapes.brace.with(..((key): eval(value))))
+/// n(1, "size", "3em")
+/// n(2, "fill", "red")
+/// })
+///
+/// - label (content): Content to be placed at the top/bottom/left/right of the glyph, depending on #param[stretched-glyph][dir].
+///
+/// #for (i, dir) in (top, bottom, left, right).enumerate() {
+/// let s = fletcher.shapes.brace.with(dir: dir, label: emph[label])
+/// diagram(node((i, 0), strong[NODE],
+/// inset: 4pt,
+/// shape: s,
+/// stroke: aqua,
+/// fill: aqua.lighten(90%),
+/// ))
+/// h(5mm)
+/// }
+///
+/// - label-sep (length): Separation between label and glyph.
+///
+/// #for (i, sep) in (-5pt, 0pt, 5pt, 10pt).enumerate() {
+/// let s = fletcher.shapes.brace.with(dir: top, label: [#sep], label-sep: sep)
+/// diagram(node((i, 0), strong[NODE],
+/// inset: 4pt,
+/// shape: s,
+/// stroke: aqua,
+/// fill: aqua.lighten(90%),
+/// ))
+/// h(5mm)
+/// }
+///
+#let stretched-glyph(node, extrude, glyph: sym.brace.b, dir: bottom, sep: 0pt, length: 100%, label: none, label-sep: 0.25em, ..args) = {
+ assert(type(dir) == alignment, message: "Expected direction, got " + repr(type(dir)))
+
+ let (w, h) = node.size
+
+ let (span, pos) = (
+ top: (w, (0, +h/2 + sep)),
+ bottom: (w, (0, -h/2 - sep)),
+ left: (h, (-w/2 - sep, 0)),
+ right: (h, (+w/2 + sep, 0)),
+ ).at(repr(dir))
+
+ if type(length) == ratio { length = length + 0pt }
+ if type(length) == type(1pt) { length = length + 0% }
+
+ length = span*float(length.ratio) + length.length
+
+ let obj = {
+ let stretched = text($ stretch(glyph, size: #length) $, ..args)
+ draw.content(pos, stretched, anchor: dir-to-anchor(dir.inv()), name: "content")
+
+ if label != none {
+ let label-pos = (name: "content", anchor: dir-to-anchor(dir))
+ let padded = pad(..(repr(dir.inv()): label-sep), label)
+ draw.content(label-pos, padded, anchor: dir-to-anchor(dir.inv()))
+ }
+ }
+ draw.group(obj)
+}
+
+#let (brace, bracket, paren) = (
+ (top: math.brace.t, bottom: math.brace.b, left: math.brace.l, right: math.brace.r),
+ (top: math.bracket.t, bottom: math.bracket.b, left: math.bracket.l, right: math.bracket.r),
+ (top: math.paren.t, bottom: math.paren.b, left: math.paren.l, right: math.paren.r),
+).map(glyphs => {
+ (..args, dir: bottom) => {
+ stretched-glyph(..args, glyph: glyphs.at(repr(dir)), dir: dir)
+ }
+})
+
+#let ALL_SHAPES = (
+ rect: rect,
+ circle: circle,
+ ellipse: ellipse,
+ pill: pill,
+ parallelogram: parallelogram,
+ trapezium: trapezium,
+ diamond: diamond,
+ triangle: triangle,
+ house: house,
+ chevron: chevron,
+ hexagon: hexagon,
+ octagon: octagon,
+ cylinder: cylinder,
+ brace: brace,
+ bracket: bracket,
+ paren: paren,
+)
diff --git a/render/packages/preview/fletcher/0.5.8/src/utils.typ b/render/packages/preview/fletcher/0.5.8/src/utils.typ
new file mode 100644
index 0000000..d16afe0
--- /dev/null
+++ b/render/packages/preview/fletcher/0.5.8/src/utils.typ
@@ -0,0 +1,326 @@
+#import "deps.typ": cetz
+#import cetz: vector
+
+#let error(message, ..args) = {
+ let pairs = args.pos().enumerate() + args.named().pairs()
+ let ticks(x) = "`" + if type(x) == str { x } else { repr(x) } + "`"
+ for (k, v) in pairs {
+ if type(v) == array {
+ let replacement = if v.len() > 0 {
+ v.map(ticks).join(", ")
+ } else { "()" }
+ message = message.replace("#.." + str(k), replacement)
+ }
+ if type(v) != str { v = repr(v) }
+ message = message.replace("#" + str(k), ticks(v))
+ }
+ assert(false, message: message)
+}
+
+
+// Replace `auto` with a value
+#let map-auto(value, fallback) = if value == auto { fallback } else { value }
+
+// Make a function propagate `auto`
+#let pass-auto(f) = x => if x == auto { x } else { f(x) }
+
+// Make a function propagage `none`
+#let pass-none(f) = x => if x == none { x } else { f(x) }
+
+#let as-bool(obj, message: "Expected boolean") = {
+ if type(obj) == bool { obj }
+ else { error(message + "; got #0.", repr(obj)) }
+}
+
+// for when `stroke` is already in namespace
+#let as-stroke(x) = stroke(x)
+
+#let as-label(x) = {
+ if type(x) == label { x }
+ else if type(x) == str { label(x) }
+ else { error("Expected label or string; got #0.", repr(x)) }
+}
+
+#let as-pair(obj) = {
+ if type(obj) == array {
+ if obj.len() == 2 { obj }
+ else { error("Expected a pair (array of length 2); got #0.", repr(obj))}
+ } else { (obj, obj) }
+}
+
+#let as-array(obj) = if type(obj) == array { obj } else { (obj,) }
+
+#let as-number-or-length(obj, message: "Expected a number or length") = {
+ if type(obj) in (int, float, length) { obj }
+ else { error(message + "; got #0.", repr(obj)) }
+}
+
+#let as-relative(obj, message: "Expected float or relative length") = {
+ if type(obj) == relative { obj }
+ else if type(obj) in (int, float) { obj*100% + 0pt }
+ else if type(obj) in (ratio, length) { obj + 0% + 0pt }
+ else { error(message + "; got #0.", repr(obj)) }
+}
+
+#let relative-to-float(t, len: float("inf")*1pt) = {
+ len = len.to-absolute()
+ if type(t) in (int, float, ratio) { float(t) }
+ else if type(t) == length { t.to-absolute()/len }
+ else if type(t) == relative { float(t.ratio) + t.length.to-absolute()/len }
+ else { error("Cannot convert #0 to float.", t) }
+}
+
+
+#let as-length(obj, message: "Expected a length") = {
+ if type(obj) == length { obj }
+ else { error(message + "; got #0.", repr(obj)) }
+}
+
+#let as-angle(obj, message: "Expected an angle") = {
+ if type(obj) == angle { obj }
+ else { error(message + "; got #0.", repr(obj)) }
+}
+
+#let stroke-to-dict(s) = {
+ let s = as-stroke(s)
+ let d = (
+ paint: s.paint,
+ thickness: s.thickness,
+ cap: s.cap,
+ join: s.join,
+ dash: s.dash,
+ miter-limit: s.miter-limit,
+ )
+
+ // remove auto entries to allow folding strokes by joining dicts
+ for (key, value) in d {
+ if value == auto {
+ let _ = d.remove(key)
+ }
+ }
+
+ d
+}
+
+
+#let min-max(array) = (calc.min(..array), calc.max(..array))
+#let cumsum(array) = {
+ let sum = array.at(0)
+ for i in range(1, array.len()) {
+ sum += array.at(i)
+ array.at(i) = sum
+ }
+ array
+}
+
+#let vector-len((x, y)) = 1pt*calc.sqrt((x/1pt)*(x/1pt) + (y/1pt)*(y/1pt))
+#let vector-set-len(len, v) = vector.scale(v, len/vector-len(v))
+#let vector-unitless(v) = v.map(x => if type(x) == length { x.pt() } else { x })
+#let vector-2d((x, y, ..z)) = (x, y)
+#let vector-max(a, b) = array.zip(a, b).map(vals => calc.max(..vals))
+
+#let vector-polar(r, θ) = (r*calc.cos(θ), r*calc.sin(θ))
+#let vector-angle(v) = calc.atan2(..vector-unitless(v))
+#let angle-between(from, to) = vector-angle(vector.sub(to, from))
+
+// Ensure angle is in range 0deg <= θ < 360deg
+#let wrap-angle-360(θ) = calc.rem-euclid(θ/360deg, 1)*360deg
+
+// Ensure angle is in range -180deg <= θ <= 180deg
+#let wrap-angle-180(θ) = (θ/360deg - calc.round(θ/360deg))*360deg
+
+#let dir-to-anchor(dir) = {
+ (
+ repr(top): "north",
+ repr(top + right): "north-east",
+ repr(right): "east",
+ repr(bottom + right): "south-east",
+ repr(bottom): "south",
+ repr(bottom + left): "south-west",
+ repr(left): "west",
+ repr(top + left): "north-west",
+ ).at(repr(dir))
+}
+
+#let angle-to-anchor(θ) = {
+ let i = calc.rem(8*θ/1rad/calc.tau, 8)
+ (
+ "east",
+ "north-east",
+ "north",
+ "north-west",
+ "west",
+ "south-west",
+ "south",
+ "south-east",
+ ).at(int(calc.round(i)))
+}
+
+
+#let is-length-vector(v) = v.all(x => type(x) == length)
+#let is-number-vector(v) = v.all(x => type(x) in (int, float))
+#let is-nan-vector(v) = is-number-vector(v) and v.any(x => float(x).is-nan())
+
+
+#let lerp(a, b, t) = a*(1 - t) + b*t
+
+/// Linearly interpolate an array with linear behaviour outside bounds
+///
+/// - values (array): Array of lengths defining interpolation function.
+/// - index (int, float): Index-coordinate to sample.
+/// - spacing (length): Gradient for linear extrapolation beyond array bounds.
+#let interp(values, index, spacing: 0pt) = {
+ let max-index = values.len() - 1
+ if index < 0 {
+ values.at(0) + spacing*index
+ } else if index > max-index {
+ values.at(-1) + spacing*(index - max-index)
+ } else {
+ lerp(
+ values.at(calc.floor(index)),
+ values.at(calc.ceil(index)),
+ calc.fract(index),
+ )
+ }
+}
+
+
+/// Inverse of `interp()`.
+///
+/// - values (array): Array of lengths defining interpolation function.
+/// - value: Value to find the interpolated index of.
+/// - spacing (length): Gradient for linear extrapolation beyond array bounds.
+#let interp-inv(values, value, spacing: 0pt) = {
+ let i = 0
+ while i < values.len() {
+ if values.at(i) >= value { break }
+ i += 1
+ }
+ let (first, last) = (values.at(0), values.at(-1))
+
+ // avoids division by zero when numerator and denominator both vanish
+ let div(a, b) = if calc.abs(a) < 1e-3pt { 0 } else { a/b }
+
+ if value < first {
+ div(value - first, spacing)
+ } else if value >= last {
+ values.len() - 1 + div(value - last, spacing)
+ } else {
+ let (prev, nearest) = (values.at(i - 1), values.at(i))
+ i - 1 + div(value - prev, nearest - prev)
+ }
+}
+
+
+#let rect-at(center, size) = (-1, +1).map(dir => {
+ vector.add(center, vector.scale(size, dir/2))
+})
+
+#let point-is-in-rect(point, (center, size)) = {
+ point.zip(center, size).all(((x, o, s)) => {
+ calc.abs(x - o) <= s/2
+ })
+}
+
+#let bounding-rect(points) = {
+ let (xs, ys) = array.zip(..points)
+ let p1 = (calc.min(..xs), calc.min(..ys))
+ let p2 = (calc.max(..xs), calc.max(..ys))
+ (
+ center: vector.scale(vector.add(p1, p2), 0.5),
+ size: vector.sub(p2, p1)
+ )
+}
+
+
+/// Determine arc between two points with a given bend angle
+///
+/// The bend angle is the angle between chord of the arc (line connecting the
+/// points) and the tangent to the arc and the first point.
+///
+/// Returns a dictionary containing:
+/// - `center`: the center of the arc's curvature
+/// - `radius`
+/// - `start`: the start angle of the arc
+/// - `stop`: the end angle of the arc
+///
+/// - from (point): 2D vector of initial point.
+/// - to (point): 2D vector of final point.
+/// - angle (angle): The bend angle between chord of the arc (line connecting the
+/// points) and the tangent to the arc and the first point.
+/// -> dictionary
+///
+/// #diagram(spacing: 2cm, {
+/// for (i, θ) in (0deg, 45deg, -90deg).enumerate() {
+/// edge((2*i, 0), (2*i + 1, 0), marks: (none, "head"), bend: θ)
+/// edge((2*i, 0), (2*i + 1, 0), [#θ], label-side: center, dash:
+/// "dotted")
+/// }
+/// })
+#let get-arc-connecting-points(from, to, angle) = {
+ // TODO: properly handle trivial arcs
+ if from == to { to = vector.add(to, (0pt, 1e-4pt)) }
+
+ let mid = vector.scale(vector.add(from, to), 0.5)
+ let (dx, dy) = vector.sub(to, from)
+ let perp = (dy, -dx)
+
+ let center = vector.add(mid, vector.scale(perp, 0.5/calc.tan(angle)))
+
+ let radius = vector-len(vector.sub(to, center))
+
+ let start = angle-between(center, from)
+ let stop = angle-between(center, to)
+
+ if start < stop and angle > 0deg { start += 360deg }
+ if start > stop and angle < 0deg { start -= 360deg }
+
+ (center: center, radius: radius, start: start, stop: stop)
+}
+
+/// Return true if a content element is a space or sequence of spaces
+#let is-space(el) = {
+ if el == none { return true }
+ if repr(el.func()) == "space" { return true }
+ if repr(el.func()) == "sequence" { return el.children.all(is-space) }
+ return false
+}
+
+#let is-sequence(it) = {
+ type(it) == content and repr(it.func()) == "sequence"
+}
+
+#let flatten-sequence-to-array(it) = {
+ if is-sequence(it) {
+ it.children.map(flatten-sequence-to-array).join() + ()
+ } else { (it,) }
+}
+
+
+// find a node near a given uv coordinate
+#let find-node-at(nodes, uv, snap: true) = {
+ nodes.filter(node => {
+ if is-nan-vector(node.pos.uv) { return false }
+
+ if snap {
+ // node must be within a one-unit block around pos
+ vector.sub(node.pos.uv, uv).all(Δ => calc.abs(Δ) < 0.1)
+ } else {
+ node.pos.uv == uv
+ }
+ })
+ .sorted(key: node => vector.len(vector.sub(node.pos.uv, uv)))
+ .at(0, default: none)
+}
+
+#let find-node(nodes, key, snap: true) = {
+ if type(key) == label {
+ let node = nodes.find(node => node.name == key)
+ assert(node != none, message: "Couldn't find node with name " + repr(key))
+ node
+ } else if type(key) == array and is-number-vector(key) {
+ find-node-at(nodes, key, snap: snap)
+ } else {
+ none
+ }
+}
diff --git a/render/packages/preview/fletcher/0.5.8/typst.toml b/render/packages/preview/fletcher/0.5.8/typst.toml
new file mode 100644
index 0000000..3c2e56e
--- /dev/null
+++ b/render/packages/preview/fletcher/0.5.8/typst.toml
@@ -0,0 +1,25 @@
+[package]
+name = "fletcher"
+version = "0.5.8"
+compiler = "0.13.0"
+entrypoint = "src/exports.typ"
+authors = ["Joseph Wilson (Jollywatt)"]
+license = "MIT"
+description = "Draw diagrams with nodes and arrows."
+repository = "https://github.com/Jollywatt/typst-fletcher"
+categories = ["visualization", "components"]
+keywords = [
+ "commutative",
+ "commuting",
+ "commute",
+ "diagram",
+ "category",
+ "flowchart",
+ "DAG",
+ "graph",
+ "finite state",
+ "network",
+ "node",
+ "arrow",
+]
+exclude = ["docs/", "tests/"]
diff --git a/render/packages/preview/mitex/0.2.7/CHANGELOG.md b/render/packages/preview/mitex/0.2.7/CHANGELOG.md
new file mode 100644
index 0000000..92111b2
--- /dev/null
+++ b/render/packages/preview/mitex/0.2.7/CHANGELOG.md
@@ -0,0 +1,69 @@
+# CHANGELOG
+
+## 0.2.7
+
+feat: support color-related optional arguments for commands
+feat: support missing commands
+feat: implement \smash command
+
+Thanks to [Shichien](https://github.com/Shichien).
+
+
+
+## 0.2.6
+
+- Fix: fix "kai is deprecated" warning for Typst v0.14.0 (https://github.com/mitex-rs/mitex/pull/201)
+
+
+## 0.2.5
+
+- Fix: assign correct class for lvert and rvert (https://github.com/mitex-rs/mitex/pull/172)
+- Fix: convert `bf` to `bold(upright(..))` (https://github.com/mitex-rs/mitex/pull/183)
+- Fix: remove xarrow and use stretch in typst v0.12.0 (https://github.com/mitex-rs/mitex/pull/184)
+- Fix: fix some symbols `\not`, `\gtreqqless` and `\gtrapprox` (https://github.com/mitex-rs/mitex/pull/185)
+
+
+## 0.2.4
+
+- Fix `\boxed` command.
+- Support basic figure and tabular environments.
+- Add escape symbols for plus, minus and percent.
+- Fix `\left` and `\right`: size of lr use em.
+
+
+## 0.2.3
+
+- Support nesting math equation like `\text{$x$}`.
+- Fix broken `\left` and `\right` commands. #143
+- Correct the symbol mapping for `\varphi`, `phi`, `\epsilon` and `\varepsilon`.
+
+
+## 0.2.2
+
+### Text Mode
+
+- Add `\(\)` and `\[\]` support.
+- Add `\footnote` and `\cite`.
+
+### Fixes
+
+- Remove duplicate keys for error when a dict has duplicate keys in Typst 0.11.
+- Fix bracket/paren group parsing.
+- Remove extra spacing for ceiling symbols.
+
+
+## 0.2.1
+
+- Remove unnecessary zws.
+
+
+## 0.2.0
+
+- Add more symbols for equations.
+- Basic macro support.
+- Basic text mode support.
+
+
+## 0.1.0
+
+- LaTeX support for Typst, powered by Rust and WASM. We can now render LaTeX equations in real-time in Typst.
\ No newline at end of file
diff --git a/render/packages/preview/mitex/0.2.7/LICENSE b/render/packages/preview/mitex/0.2.7/LICENSE
new file mode 100644
index 0000000..a7e77cb
--- /dev/null
+++ b/render/packages/preview/mitex/0.2.7/LICENSE
@@ -0,0 +1,176 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+END OF TERMS AND CONDITIONS
\ No newline at end of file
diff --git a/render/packages/preview/mitex/0.2.7/README.md b/render/packages/preview/mitex/0.2.7/README.md
new file mode 100644
index 0000000..1041f65
--- /dev/null
+++ b/render/packages/preview/mitex/0.2.7/README.md
@@ -0,0 +1,154 @@
+# [MiTeX](https://github.com/mitex-rs/mitex)
+
+**[LaTeX](https://www.latex-project.org/) support for [Typst](https://typst.app/), powered by [Rust](https://www.rust-lang.org/) and [WASM](https://webassembly.org/).**
+
+[MiTeX](https://github.com/mitex-rs/mitex) processes LaTeX code into an abstract syntax tree (AST). Then it transforms the AST into Typst code and evaluates code into Typst content by `eval` function.
+
+MiTeX has been proved to be practical on a large project. It has already correctly converted 32.5k equations from [OI Wiki](https://github.com/OI-wiki/OI-wiki). Compared to [texmath](https://github.com/jgm/texmath), MiTeX has a better display effect and performance in that wiki project. It is also more easy to use, since importing MiTeX to Typst is just one line of code, while texmath is an external program.
+
+In addition, MiTeX is not only **SMALL** but also **FAST**! MiTeX has a size of just about 185 KB, comparing that texmath has a size of 17 MB. A not strict but intuitive comparison is shown below. To convert 32.5k equations from OI Wiki, texmath takes about 109s, while MiTeX WASM takes only 2.28s and MiTeX x86 takes merely 0.085s.
+
+Thanks to [@Myriad-Dreamin](https://github.com/Myriad-Dreamin), he completed the most complex development work: developing the parser for generating AST.
+
+## MiTeX as a Typst Package
+
+- Use `mitex-convert` to convert LaTeX code into Typst code in string.
+- Use `mi` to render an inline LaTeX equation in Typst.
+- Use `mitex(numbering: none, supplement: auto, ..)` or `mimath` to render a block LaTeX equation in Typst.
+- Use `mitext` to render a LaTeX text in Typst.
+
+PS: `#set math.equation(numbering: "(1)")` is also valid for MiTeX.
+
+Following is [a simple example](examples/example.typ) of using MiTeX in Typst:
+
+```typst
+#import "@preview/mitex:0.2.7": *
+
+#assert.eq(mitex-convert("\alpha x"), "alpha x ")
+
+Write inline equations like #mi("x") or #mi[y].
+
+Also block equations (this case is from #text(blue.lighten(20%), link("https://katex.org/")[katex.org])):
+
+#mitex(`
+ \newcommand{\f}[2]{#1f(#2)}
+ \f\relax{x} = \int_{-\infty}^\infty
+ \f\hat\xi\,e^{2 \pi i \xi x}
+ \,d\xi
+`)
+
+We also support text mode (in development):
+
+#mitext(`
+ \iftypst
+ #set math.equation(numbering: "(1)", supplement: "equation")
+ \fi
+
+ \section{Title}
+
+ A \textbf{strong} text, a \emph{emph} text and inline equation $x + y$.
+
+ Also block \eqref{eq:pythagoras}.
+
+ \begin{equation}
+ a^2 + b^2 = c^2 \label{eq:pythagoras}
+ \end{equation}
+`)
+```
+
+![MiTeX example showing LaTeX equations rendered in Typst](examples/example.png)
+
+## MiTeX as a CLI Tool
+
+### Installation
+
+Install latest nightly version by `cargo install --git https://github.com/mitex-rs/mitex mitex-cli`.
+
+### Usage
+
+```bash
+mitex compile main.tex
+# or (same as above)
+mitex compile main.tex mitex.typ
+```
+
+## MiTeX as a Web App
+
+### MiTeX Online Math Converter
+
+We can convert LaTeX equations to Typst equations in web by wasm. https://mitex-rs.github.io/mitex/
+
+### Underleaf
+
+We made a proof of concept online tex editor to show our conversion speed in text mode. The PoC loads files from a git repository and then runs typst compile in browser. As you see, each keystroking get response in preview quickly.
+
+https://mitex-rs.github.io/mitex/tools/underleaf.html
+
+https://github.com/mitex-rs/mitex/assets/34951714/0ce77a2c-0a7d-445f-b26d-e139f3038f83
+
+## Implemented Features
+
+- [x] User-defined TeX (macro) commands, such as `\newcommand{\mysym}{\alpha}`.
+- [x] LaTeX equations support.
+ - [x] Coloring commands (`\color{red} text`, `\textcolor{red}{text}`).
+ - [x] Support for various environments, such as aligned, matrix, cases.
+- [x] Basic text mode support, you can use it to write LaTeX drafts.
+ - [x] `\section`, `\textbf`, `\emph`.
+ - [x] Inline and block math equations.
+ - [x] `\ref`, `\eqref` and `\label`.
+ - [x] `itemize` and `enumerate` environments.
+
+## Features to Implement
+
+- [ ] Pass command specification to MiTeX plugin dynamically. With that you can define a typst function `let myop(it) = op(upright(it))` and then use it by `\myop{it}`.
+- [ ] Package support, which means that you can change set of commands by telling MiTeX to use a list of packages.
+- [ ] Better text mode support, such as figure, algorithm and description environments.
+
+To achieve the latter two goals, we need a well-structured architecture for the text mode, along with intricate work. Currently, we don't have very clear ideas yet. If you are willing to contribute by discussing in the issues or even submitting pull requests, your contribution is highly welcome.
+
+## Differences between MiTeX and other solutions
+
+MiTeX has different objectives compared to [texmath](https://github.com/jgm/texmath) (a.k.a. [pandoc](https://pandoc.org/)):
+
+- MiTeX focuses on rendering LaTeX content correctly within Typst, leveraging the powerful programming capabilities of WASM and typst to achieve results that are essentially consistent with LaTeX display.
+- texmath aims to be general-purpose converters and generate strings that are more human-readable.
+
+For example, MiTeX transforms `\frac{1}{2}_3` into `frac(1, 2)_3`, while texmath converts it into `1 / 2_3`. The latter's display is not entirely correct, whereas the former ensures consistency in display.
+
+Another example is that MiTeX transforms `(\frac{1}{2})` into `\(frac(1, 2)\)` instead of `(frac(1, 2))`, avoiding the use of automatic Left/Right to achieve consistency with LaTeX rendering.
+
+**Certainly, the greatest advantage is that you can directly write LaTeX content in Typst without the need for manual conversion!**
+
+## Submitting Issues
+
+If you find missing commands or bugs of MiTeX, please feel free to submit an issue [here](https://github.com/mitex-rs/mitex/issues).
+
+## Contributing to MiTeX
+
+Currently, MiTeX maintains following three parts of code:
+
+- A TeX parser library written in **Rust**, see [mitex-lexer](https://github.com/mitex-rs/mitex/tree/main/crates/mitex-lexer) and [mitex-parser](https://github.com/mitex-rs/mitex/tree/main/crates/mitex-parser).
+- A TeX to Typst converter library written in **Rust**, see [mitex](https://github.com/mitex-rs/mitex/tree/main/crates/mitex).
+- A list of TeX packages and comamnds written in **Typst**, which then used by the typst package, see [MiTeX Command Specification](https://github.com/mitex-rs/mitex/tree/main/packages/mitex/specs).
+
+For a translation process, for example, we have:
+
+```
+\frac{1}{2}
+
+===[parser]===> AST ===[converter]===>
+
+#eval("$frac(1, 2)$", scope: (frac: (num, den) => $(num)/(den)$))
+```
+
+You can use the `#mitex-convert()` function to get the Typst Code generated from LaTeX Code.
+
+### Add missing TeX commands
+
+Even if you don't know Rust at all, you can still add missing TeX commands to MiTeX by modifying [specification files](https://github.com/mitex-rs/mitex/tree/main/packages/mitex/specs), since they are written in typst! You can open an issue to acquire the commands you want to add, or you can edit the files and submit a pull request.
+
+In the future, we will provide the ability to customize TeX commands, which will make it easier for you to use the commands you create for yourself.
+
+### Develop the parser and the converter
+
+See [CONTRIBUTING.md](https://github.com/mitex-rs/mitex/blob/main/CONTRIBUTING.md).
diff --git a/render/packages/preview/mitex/0.2.7/lib.typ b/render/packages/preview/mitex/0.2.7/lib.typ
new file mode 100644
index 0000000..3e33673
--- /dev/null
+++ b/render/packages/preview/mitex/0.2.7/lib.typ
@@ -0,0 +1 @@
+#import "mitex.typ": mitex-wasm, mitex-convert, mitex-scope, mitex, mitext, mimath, mi
\ No newline at end of file
diff --git a/render/packages/preview/mitex/0.2.7/mitex.typ b/render/packages/preview/mitex/0.2.7/mitex.typ
new file mode 100644
index 0000000..d22d04d
--- /dev/null
+++ b/render/packages/preview/mitex/0.2.7/mitex.typ
@@ -0,0 +1,45 @@
+#import "specs/mod.typ": mitex-scope
+#let mitex-wasm = plugin("./mitex.wasm")
+
+#let get-elem-text(it) = {
+ {
+ if type(it) == str {
+ it
+ } else if type(it) == content and it.has("text") {
+ it.text
+ } else {
+ panic("Unsupported type: " + str(type(it)))
+ }
+ }
+}
+
+#let mitex-convert(it, mode: "math", spec: bytes(())) = {
+ if mode == "math" {
+ str(mitex-wasm.convert_math(bytes(get-elem-text(it)), spec))
+ } else {
+ str(mitex-wasm.convert_text(bytes(get-elem-text(it)), spec))
+ }
+}
+
+// Math Mode
+#let mimath(it, block: true, ..args) = {
+ let res = mitex-convert(mode: "math", it)
+ let eval-res = eval("$" + res + "$", scope: mitex-scope)
+ math.equation(block: block, eval-res, ..args)
+}
+
+// Text Mode
+#let mitext(it) = {
+ let res = mitex-convert(mode: "text", it)
+ eval(res, mode: "markup", scope: mitex-scope)
+}
+
+#let mitex(it, mode: "math", ..args) = {
+ if mode == "math" {
+ mimath(it, ..args)
+ } else {
+ mitext(it, ..args)
+ }
+}
+
+#let mi = mimath.with(block: false)
diff --git a/render/packages/preview/mitex/0.2.7/mitex.wasm b/render/packages/preview/mitex/0.2.7/mitex.wasm
new file mode 100755
index 0000000..8260ace
Binary files /dev/null and b/render/packages/preview/mitex/0.2.7/mitex.wasm differ
diff --git a/render/packages/preview/mitex/0.2.7/specs/README.md b/render/packages/preview/mitex/0.2.7/specs/README.md
new file mode 100644
index 0000000..891ab0d
--- /dev/null
+++ b/render/packages/preview/mitex/0.2.7/specs/README.md
@@ -0,0 +1,250 @@
+# MiTeX Command Specification
+
+This includes ways to define specs, which can be used to define everything in the existing standard packages [latex-std](./latex/standard.typ).
+
+Even if you don't know Rust at all, you can still add missing TeX commands to MiTeX by modifing [latex-std](./latex/standard.typ), since they are written in typst! You can open an issue to acquire the commands you want to add, or you can edit the files and submit a pull request.
+
+
+## Introduce
+
+For a translation process, for example, we have:
+
+```
+\frac{1}{2}
+
+===[parser]===> AST ===[converter]===>
+
+#eval("$frac(1, 2)$", scope: (frac: (num, den) => $(num)/(den)$))
+```
+
+You can use the `#mitex-convert()` function to get the Typst Code generated from LaTeX Code.
+
+To achieve this, we need to define four components for LaTeX commands:
+
+- `cmd`: The name of the LaTeX command. Since LaTeX commands all start with `\`, we remove the leading `\` and use the command name as the key in the dictionary.
+ - There is also the concept of environments, for example, `\begin{pmatrix} 1 & 2 \\ 3 & 4 \end{pmatrix}` is a matrix environment.
+- `args`: The argument pattern of the LaTeX command. For example:
+ - `\alpha` has no arguments;
+ - `\hat{x}` matches one argument on the right;
+ - `\frac{1}{2}` matches two arguments on the right;
+ - `\sqrt[3]{2}` includes optional arguments;
+ - `\sum\limits` has `limits` matching one argument on the left;
+ - `\displaystyle` greedily matches all arguments on the right;
+ - `x \over y` as an infix operator greedily matches all arguments on both sides.
+- `alias`: The alias of the LaTeX command in Typst.
+ - The alias can be an existing symbol or function, for example, `alpha` and `binom(n, k)`;
+ - It can also be a key in the `mitex-scope` for `eval`, for example, our self-defined `frac`.
+- `handle`: The value in the `mitex-scope`, which is our self-defined symbol or processing function.
+ - For example, the `frac` key corresponds to the value `(num, den) => $(num)/(den)$`.
+
+MiTeX would need them for converting your TeX commands into typst code.
+
+At the Typst level, we need `alias` and `handle`, which are then combined into the `mitex-scope` passed to the `eval` function as the `scope` parameter.
+
+In short, currently a command spec is a typst dict, with its keys are name of the tex command, and its values are opaque spec item, which contains necessary information for MiTeX.
+
+In [specification file for standard latex](./latex/standard.typ), It constructs and exports a such command spec.
+
+Next, we provides a bunch of convenient functions for constructing opaque spec items.
+
+
+## Reference
+
+### `define-sym`
+
+Define a normal symbol, as no-argument commands like `\alpha`.
+
+```typst
+#let define-sym(s, sym: none) = { .. }
+```
+
+**Arguments:**
+- s (str): Alias command for typst handler.
+ For example, alias `\prod` to typst's `product`.
+- sym (content): The specific content, as the value of alias in mitex-scope.
+ For example, there is no direct alias for \negthinspace symbol in typst,
+ but we can add `h(-(3/18) * 1em)` ourselves
+
+**Return:** A opaque spec item and a scope item (none for no scope item)
+
+
+### `define-greedy-cmd`
+
+Define a greedy command, like `\displaystyle`.
+
+```typst
+#let define-greedy-cmd(s, handle: none) = { .. }
+```
+
+**Arguments:**
+- s (str): Alias command for typst handler.
+ For example, alias `\displaystyle` to typst's `mitexdisplay`, as the key in mitex-scope.
+- handle (function): The handler function, as the value of alias in mitex-scope.
+ It receives a content argument as all greedy matches to the content
+ For example, we define `mitexdisplay` to `math.display`
+
+**Return:** A opaque spec item and a scope item (none for no scope item)
+
+
+### `define-infix-cmd`
+
+Define an infix command, like `\over`.
+
+```typst
+#let define-infix-cmd(s, handle: none) = { .. }
+```
+
+**Arguments:**
+- s (str): Alias command for typst handler.
+ For example, alias `\over` to typst's `frac`, as the key in mitex-scope.
+- handle (function): The handler function, as the value of alias in mitex-scope.
+ It receives two content arguments, as (prev, after) arguments.
+ For example, we define `\over` to `frac: (num, den) => $(num)/(den)$`
+
+**Return:** A opaque spec item and a scope item (none for no scope item)
+
+
+### `define-glob-cmd`
+
+Define a glob (Global Wildcard) match command with a specified pattern for matching args
+Kind of item to match:
+
+- Bracket/b: []
+- Parenthesis/p: ()
+- Term/t: any rest of terms, typically {} or single char
+
+```typst
+#let define-glob-cmd(pat, s, handle: none) = { .. }
+```
+
+**Arguments:**
+- pat (pattern): The pattern for glob-cmd
+ For example, `{,b}t` for `\sqrt` to support `\sqrt{2}` and `\sqrt[3]{2}`
+- s (str): Alias command for typst handler.
+ For example, alias `\sqrt` to typst's `mitexsqrt`, as the key in mitex-scope.
+- handle (function): The handler function, as the value of alias in mitex-scope.
+ It receives variable length arguments, for example `(2,)` or `([3], 2)` for sqrt.
+ Therefore you need to use `(.. arg) = > {..}` to receive them.
+
+**Return:** A opaque spec item and a scope item (none for no scope item)
+
+
+### `define-cmd`
+
+Define a command with a fixed number of arguments, like `\hat{x}` and `\frac{1}{2}`.
+
+```typst
+#let define-cmd(num, alias: none, handle: none) = { .. }
+```
+
+**Arguments:**
+- num (int): The number of arguments for the command.
+- alias (str): Alias command for typst handler.
+ For example, alias `\frac` to typst's `frac`, as the key in mitex-scope.
+- handle (function): The handler function, as the value of alias in mitex-scope.
+ It receives fixed number of arguments, for example `frac(1, 2)` for `\frac{1}{2}`.
+
+**Return:** A opaque spec item and a scope item (none for no scope item)
+
+
+### `define-env`
+
+Define an environment with a fixed number of arguments, like `\begin{array}{lr}`.
+
+```typst
+#let define-env(num, alias: none, handle: none) = { .. }
+```
+
+**Arguments:**
+- num (int): The number of arguments as environment options for the environment.
+- alias (str): Alias command for typst handler.
+ For example, alias `\begin{array}{lr}` to typst's `mitexarray`,
+ and alias `\begin{aligned}` to typst's `aligned`, as the key in mitex-scope.
+- kind (str): environment kind, it could be "is-math", "is-cases", "is-matrix",
+ "is-itemize", "is-enumerate"
+- handle (function): The handler function, as the value of alias in mitex-scope.
+ It receives fixed number of named arguments as environment options,
+ for example `array(arg0: ..)` or `array(arg0: .., arg1: ..)`.
+ And it receives variable length arguments as environment body,
+ Therefore you need to use `(.. arg) = > {..}` to receive them.
+
+**Return:** A opaque spec item and a scope item (none for no scope item)
+
+
+### `sym`
+
+Define a symbol without alias and without handler function, like \alpha => alpha
+
+```typst
+#let sym = ((kind: "sym"), none)
+```
+
+**Return:** A opaque spec item and no scope item (none for no scope item)
+
+
+### `of-sym`
+
+```typst
+#let of-sym(handle) = ((kind: "sym"), (handle: handle))
+```
+
+Define a symbol without alias and with handler function,
+like \negthinspace => h(-(3/18) * 1em)
+
+**Arguments:**
+
+- handle (function): The handler function, as the value of alias in mitex-scope.
+ For example, define `negthinspace` to handle `h(-(3/18) * 1em)` in mitex-scope
+
+**Return:** A symbol spec and a scope item
+
+
+### `left1-op`
+
+Define a left1-op command without handler, like `\limits` for `\sum\limits`
+
+```typst
+#let left1-op(alias) = ((kind: "cmd", args: ( kind: "left1" ), alias: alias), none)
+```
+
+**Arguments:**
+
+- alias (str): Alias command for typst handler.
+ For example, alias `\limits` to typst's `limits`
+ and alias `\nolimits` to typst's `scripts`
+
+**Return:** A cmd spec and no scope item (none for no scope item)
+
+
+### `cmd1`
+
+Define a cmd1 command like \hat{x} => hat(x)
+
+```typst
+#let cmd1 = ((kind: "cmd1"), none)
+```
+
+**Return:** A cmd1 spec and a scope item (none for no scope item)
+
+
+### `cmd2`
+
+Define a cmd2 command like \binom{1}{2} => binom(1, 2)
+
+```typst
+#let cmd2 = ((kind: "cmd2"), none)
+```
+
+**Return:** A cmd2 spec and a scope item (none for no scope item)
+
+
+### `matrix-env`
+
+Define a matrix environment without handler
+
+```typst
+#let matrix-env = ((kind: "matrix-env"), none)
+```
+
+**Return:** A matrix-env spec and a scope item (none for no scope item)
+
diff --git a/render/packages/preview/mitex/0.2.7/specs/latex/standard.typ b/render/packages/preview/mitex/0.2.7/specs/latex/standard.typ
new file mode 100644
index 0000000..f451b13
--- /dev/null
+++ b/render/packages/preview/mitex/0.2.7/specs/latex/standard.typ
@@ -0,0 +1,1187 @@
+#import "../prelude.typ": *
+
+// 0. Some useful internal variables or functions
+#let mitex-color-map = (
+ "red": rgb(255, 0, 0),
+ "green": rgb(0, 255, 0),
+ "blue": rgb(0, 0, 255),
+ "cyan": rgb(0, 255, 255),
+ "magenta": rgb(255, 0, 255),
+ "yellow": rgb(255, 255, 0),
+ "black": rgb(0, 0, 0),
+ "white": rgb(255, 255, 255),
+ "gray": rgb(128, 128, 128),
+ "lightgray": rgb(192, 192, 192),
+ "darkgray": rgb(64, 64, 64),
+ "brown": rgb(165, 42, 42),
+ "orange": rgb(255, 165, 0),
+ "pink": rgb(255, 182, 193),
+ "purple": rgb(128, 0, 128),
+ "teal": rgb(0, 128, 128),
+ "olive": rgb(128, 128, 0),
+)
+#let get-tex-str-from-arr(arr) = arr.filter(it => it != [ ] and it != [#math.zws]).map(it => it.text).sum()
+#let get-tex-str(tex) = if tex.has("children") {
+ get-tex-str-from-arr(tex.children)
+} else {
+ tex.text
+}
+#let get-tex-color-from-arr(arr) = {
+ mitex-color-map.at(lower(get-tex-str-from-arr(arr)), default: none)
+}
+#let get-tex-color(model, spec) = {
+ let model = if type(model) == content and model.has("text") {
+ model.text
+ } else if type(model) == str {
+ model
+ } else {
+ model
+ }
+
+ let s = if type(spec) == str {
+ spec
+ } else if type(spec) == content and spec.has("text") {
+ spec.text
+ } else if (
+ type(spec) == content and spec.has("children")
+ ) {
+ spec.children.map(it => if it.has("text") { it.text } else { "" }).join("")
+ } else {
+ ""
+ }
+
+ if model == none {
+ mitex-color-map.at(lower(s), default: none)
+ } else if model == "gray" {
+ luma(float(s) * 100%)
+ } else if model == "rgb" {
+ rgb(..s.split(",").map(x => float(x) * 100%))
+ } else if model == "RGB" {
+ rgb(..s.split(",").map(x => int(x)))
+ } else if model == "HTML" {
+ rgb("#" + s)
+ } else if model == "cmyk" {
+ cmyk(..s.split(",").map(x => float(x) * 100%))
+ } else {
+ none
+ }
+}
+
+// 1. functions created to make it easier to define a spec
+#let operatornamewithlimits(it) = math.op(limits: true, math.upright(it))
+#let arrow-handle(arrow-sym) = define-cmd(1, handle: it => $limits(stretch(#arrow-sym)^#it)$)
+#let _greedy-handle(fn) = (..args) => $fn(#args.pos().sum())$
+#let greedy-handle(alias, fn) = define-greedy-cmd(alias, handle: _greedy-handle(fn))
+#let limits-handle(alias, wrap) = define-cmd(1, alias: alias, handle: it => math.limits(wrap(it)))
+#let matrix-handle(delim: none, handle: none) = define-env(
+ none,
+ kind: "is-matrix",
+ alias: none,
+ handle: math.mat.with(delim: delim),
+)
+#let call-or-ignore(fn) = (..args) => if args.pos().len() > 0 {
+ fn(..args)
+} else {
+ math.zws
+}
+#let ignore-me = (..args) => { }
+#let ignore-sym = define-sym("")
+
+// 2. Standard package definitions, generate specs and scopes,
+// for parser/convert and typst respectively
+#let (
+ spec,
+ scope,
+) = process-spec((
+ // Text mode
+ section: define-cmd(1, alias: "#heading(level: 1)"),
+ subsection: define-cmd(1, alias: "#heading(level: 2)"),
+ subsubsection: define-cmd(1, alias: "#heading(level: 3)"),
+ footnote: define-cmd(1, alias: "#footnote"),
+ cite: define-cmd(1, alias: "#mitexcite", handle: it => cite(label(get-tex-str(it)))),
+ emph: define-cmd(1, alias: "#emph"),
+ label: define-cmd(1, alias: "mitexlabel", handle: ignore-me),
+ tag: define-cmd(1, alias: "mitexlabel", handle: ignore-me),
+ ref: define-cmd(1, alias: "#mitexref", handle: it => ref(label(get-tex-str(it)))),
+ eqref: define-cmd(1, alias: "#mitexref"),
+ item: ignore-sym,
+ // environments for text mode
+ itemize: define-env(none, kind: "is-itemize"),
+ enumerate: define-env(none, kind: "is-enumerate"),
+ quote: define-env(none, alias: "quote(block: true)"),
+ abstract: define-env(none, alias: "quote(block: true)"),
+ figure: define-glob-env("{,b}", kind: "is-figure", alias: "figure"),
+ table: define-glob-env("{,b}", kind: "is-figure", alias: "figure"),
+ tabular: define-env(1, kind: "is-table", alias: "table"),
+ // commands for figure
+ centering: ignore-sym,
+ textwidth: sym,
+ caption: define-cmd(1, alias: "mitexcaption", handle: ignore-me),
+ includegraphics: define-glob-cmd("{,b}t", "#miteximage", handle: ignore-me),
+ // commands for tabular
+ toprule: define-glob-cmd("{,b}", "toprule"),
+ midrule: define-glob-cmd("{,b}", "midrule"),
+ bottomrule: define-glob-cmd("{,b}", "bottomrule"),
+ hline: ignore-sym,
+ vline: ignore-sym,
+ // Spaces: \! \, \> \: \; \ \quad \qquad
+ "!": define-sym("negthinspace", sym: h(-(3/18) * 1em)),
+ negthinspace: of-sym(h(-(3/18) * 1em)),
+ negthinmedspace: of-sym(h(-(3/18) * 1em)),
+ negmedspace: of-sym(h(-(4/18) * 1em)),
+ negthickspace: of-sym(h(-(5/18) * 1em)),
+ ",": define-sym("thin"),
+ thinspace: define-sym("thin"),
+ ">": define-sym("med"),
+ ":": define-sym("med"),
+ medspace: define-sym("med"),
+ ";": define-sym("thick"),
+ "": define-sym("thick"),
+ thickspace: define-sym("thick"),
+ enspace: of-sym(h((1/2) * 1em)),
+ nobreakspace: define-sym("space.nobreak"),
+ space: sym,
+ quad: sym,
+ qquad: define-sym("wide"),
+ phantom: define-cmd(1, handle: hide),
+ hphantom: define-cmd(1, handle: it => box(height: 0pt, hide(it))),
+ vphantom: define-cmd(1, handle: it => box(width: 0pt, hide(it))),
+ smash: define-cmd(1, handle: it => box(height: 0pt, align(bottom, $#it$))),
+ // Escape symbols
+ "_": define-sym("\\_"),
+ "^": define-sym("hat"),
+ "*": define-sym(""),
+ "|": define-sym("||"),
+ "&": define-sym("amp"),
+ "#": define-sym("hash"),
+ "%": define-sym("%"),
+ "-": define-sym("-"),
+ "+": define-sym("+"),
+ "$": define-sym("dollar"),
+ "{": define-sym("\\{"),
+ "}": define-sym("\\}"),
+ vert: define-sym("|"),
+ lvert: of-sym(math.class("opening", "|")),
+ rvert: of-sym(math.class("closing", "|")),
+ Vert: define-sym("||"),
+ lVert: of-sym(math.class("opening", "||")),
+ rVert: of-sym(math.class("closing", "||")),
+ lparen: define-sym("paren.l"),
+ rparen: define-sym("paren.r"),
+ lceil: define-sym("⌈"),
+ rceil: define-sym("⌉"),
+ lfloor: define-sym("⌊"),
+ rfloor: define-sym("⌋"),
+ // Sizes and styles
+ displaystyle: greedy-handle("mitexdisplay", math.display),
+ textstyle: greedy-handle("mitexinline", math.inline),
+ scriptstyle: greedy-handle("mitexscript", math.script),
+ scriptscriptstyle: greedy-handle("mitexsscript", math.sscript),
+ bf: greedy-handle("mitexbold", it => math.bold(math.upright(it))),
+ rm: greedy-handle("mitexupright", math.upright),
+ it: greedy-handle("mitexitalic", math.italic),
+ sf: greedy-handle("mitexsans", math.sans),
+ frak: greedy-handle("mitexfrak", math.frak),
+ tt: greedy-handle("mitexmono", math.mono),
+ cal: greedy-handle("mitexcal", math.cal),
+ bold: define-cmd(1, alias: "bold"),
+ mathbf: define-cmd(1, alias: "mitexmathbf", handle: it => math.bold(math.upright(it))),
+ bm: define-cmd(1, alias: "bold"),
+ boldsymbol: define-cmd(1, alias: "bold"),
+ pmb: define-cmd(1, alias: "bold"),
+ mathrm: define-cmd(1, alias: "upright"),
+ mathit: define-cmd(1, alias: "italic"),
+ mathnormal: define-cmd(1, alias: "italic"),
+ mathsf: define-cmd(1, alias: "sans"),
+ mathfrak: define-cmd(1, alias: "frak"),
+ mathtt: define-cmd(1, alias: "mono"),
+ Bbb: define-cmd(1, alias: "bb"),
+ mathbb: define-cmd(1, alias: "bb"),
+ mathcal: define-cmd(1, alias: "cal"),
+ mathscr: define-cmd(1, handle: it => {
+ let s = get-tex-str(it)
+ s.clusters().map(x => $scr(#x)$).join()
+ }),
+ mathbin: define-cmd(1, handle: it => math.class("binary", it)),
+ mathclose: define-cmd(1, handle: it => math.class("closing", it)),
+ mathinner: define-cmd(1, handle: it => math.class("fence", it)),
+ mathop: define-cmd(1, handle: it => math.class("unary", it)),
+ mathopen: define-cmd(1, handle: it => math.class("opening", it)),
+ mathord: define-cmd(1, handle: it => math.class("normal", it)),
+ mathpunct: define-cmd(1, handle: it => math.class("punctuation", it)),
+ mathrel: define-cmd(1, handle: it => math.class("relation", it)),
+ big: define-cmd(1, handle: it => math.lr(size: 1.2em, it)),
+ Big: define-cmd(1, handle: it => math.lr(size: 1.8em, it)),
+ bigg: define-cmd(1, handle: it => math.lr(size: 2.4em, it)),
+ Bigg: define-cmd(1, handle: it => math.lr(size: 3em, it)),
+ bigl: define-cmd(1, alias: "big"),
+ Bigl: define-cmd(1, alias: "Big"),
+ biggl: define-cmd(1, alias: "bigg"),
+ Biggl: define-cmd(1, alias: "Bigg"),
+ bigm: define-cmd(1, alias: "big"),
+ Bigm: define-cmd(1, alias: "Big"),
+ biggm: define-cmd(1, alias: "bigg"),
+ Biggm: define-cmd(1, alias: "Bigg"),
+ bigr: define-cmd(1, alias: "big"),
+ Bigr: define-cmd(1, alias: "Big"),
+ biggr: define-cmd(1, alias: "bigg"),
+ Biggr: define-cmd(1, alias: "Bigg"),
+ // todo: size, especially multi-line, ignore it for now.
+ Huge: ignore-sym,
+ normalsize: ignore-sym,
+ huge: ignore-sym,
+ small: ignore-sym,
+ footnotesize: ignore-sym,
+ Large: ignore-sym,
+ LARGE: ignore-sym,
+ scriptsize: ignore-sym,
+ large: ignore-sym,
+ tiny: ignore-sym,
+ // Colors
+ color: define-greedy-cmd("#mitexcolor", handle: (model, texcolor, ..args) => {
+ let color = get-tex-color(model, texcolor)
+ if color != none {
+ text(fill: color, args.pos().sum())
+ } else {
+ args.pos().sum()
+ }
+ }),
+ textcolor: define-glob-cmd("{,b}tt", "#colortext", handle: (model, texcolor, body) => {
+ let color = get-tex-color(model, texcolor)
+ if color != none {
+ text(fill: color, body)
+ } else {
+ body
+ }
+ }),
+ colorbox: define-glob-cmd("{,b}tt", "#mitexcolorbox", handle: (model, texcolor, body) => {
+ let color = get-tex-color(model, texcolor)
+ if color != none {
+ box(fill: color, inset: (x: 3pt), outset: (y: 3pt), radius: 2pt, body)
+ } else {
+ body
+ }
+ }),
+ // Limits
+ limits: left1-op("limits"),
+ nolimits: left1-op("scripts"),
+ // Commands
+ frac: define-cmd(2, handle: (num, den) => $(num)/(den)$),
+ // todo: cfrac, dfrac are same?
+ cfrac: define-cmd(2, handle: (num, den) => $display((num)/(den))$),
+ dfrac: define-cmd(2, handle: (num, den) => $display((num)/(den))$),
+ tfrac: define-cmd(2, handle: (num, den) => $inline((num)/(den))$),
+ binom: define-cmd(2),
+ dbinom: define-cmd(2, handle: (n, k) => $display(binom(#n, #k))$),
+ tbinom: define-cmd(2, handle: (n, k) => $inline(binom(#n, #k))$),
+ stackrel: define-cmd(2, handle: (sup, base) => $limits(base)^(sup)$),
+ substack: define-cmd(1, handle: it => it),
+ overset: define-cmd(2, handle: (sup, base) => $limits(base)^(sup)$),
+ underset: define-cmd(2, handle: (sub, base) => $limits(base)_(sub)$),
+ // Accents
+ "not": define-cmd(1, alias: "mitexnot", handle: it => math.cancel(angle: 20deg, it)),
+ cancel: define-cmd(1),
+ xcancel: define-cmd(1, handle: math.cancel),
+ bcancel: define-cmd(1, handle: math.cancel.with(inverted: true)),
+ sout: define-cmd(1, handle: math.cancel.with(angle: 90deg)),
+ grave: define-cmd(1, alias: "grave"),
+ acute: define-cmd(1, alias: "acute"),
+ hat: define-cmd(1, alias: "hat"),
+ widehat: define-cmd(1, alias: "hat"),
+ tilde: define-cmd(1, alias: "tilde"),
+ widetilde: define-cmd(1, alias: "tilde"),
+ bar: define-cmd(1, alias: "macron"),
+ breve: define-cmd(1, alias: "breve"),
+ dot: define-cmd(1, alias: "dot"),
+ ddot: define-cmd(1, alias: "dot.double"),
+ dddot: define-cmd(1, alias: "dot.triple"),
+ ddddot: define-cmd(1, alias: "dot.quad"),
+ H: define-cmd(1, alias: "acute.double"),
+ check: define-cmd(1, alias: "caron"),
+ widecheck: define-cmd(1, alias: "caron"),
+ u: define-cmd(1, alias: "breve"),
+ v: define-cmd(1, alias: "caron"),
+ r: define-cmd(1, alias: "circle"),
+ vec: define-cmd(1, alias: "arrow"),
+ overrightarrow: define-cmd(1, alias: "arrow"),
+ overleftarrow: define-cmd(1, alias: "arrow.l"),
+ overline: cmd1,
+ underline: cmd1,
+ overbrace: limits-handle("mitexoverbrace", math.overbrace),
+ underbrace: limits-handle("mitexunderbrace", math.underbrace),
+ overbracket: limits-handle("mitexoverbracket", math.overbracket),
+ underbracket: limits-handle("mitexunderbracket", math.underbracket),
+ boxed: define-cmd(1, handle: it => box(stroke: 0.5pt, inset: 6pt, $it$)),
+ // Greeks
+ alpha: sym,
+ beta: sym,
+ gamma: sym,
+ delta: sym,
+ epsilon: define-sym("epsilon.alt"),
+ zeta: sym,
+ eta: sym,
+ theta: sym,
+ iota: sym,
+ kappa: sym,
+ lambda: sym,
+ mu: sym,
+ nu: sym,
+ xi: sym,
+ omicron: sym,
+ pi: sym,
+ rho: sym,
+ sigma: sym,
+ tau: sym,
+ upsilon: sym,
+ phi: define-sym("phi.alt"),
+ chi: sym,
+ psi: sym,
+ omega: sym,
+ Alpha: sym,
+ Beta: sym,
+ Gamma: sym,
+ Delta: sym,
+ Epsilon: sym,
+ Zeta: sym,
+ Eta: sym,
+ Theta: sym,
+ Iota: sym,
+ Kappa: sym,
+ Lambda: sym,
+ Mu: sym,
+ Nu: sym,
+ Xi: sym,
+ Omicron: sym,
+ Pi: sym,
+ Rho: sym,
+ Sigma: sym,
+ Tau: sym,
+ Upsilon: sym,
+ Phi: sym,
+ Chi: sym,
+ Psi: sym,
+ Omega: sym,
+ varbeta: define-sym("beta.alt"),
+ varepsilon: define-sym("epsilon"),
+ varkappa: define-sym("kappa.alt"),
+ varphi: define-sym("phi"),
+ varpi: define-sym("pi.alt"),
+ varrho: define-sym("rho.alt"),
+ varsigma: define-sym("sigma.alt"),
+ vartheta: define-sym("theta.alt"),
+ ell: sym,
+ // Function symbols
+ sin: sym,
+ cos: sym,
+ tan: sym,
+ cot: sym,
+ sec: sym,
+ csc: sym,
+ arcsin: sym,
+ arccos: sym,
+ arctan: sym,
+ sinh: sym,
+ cosh: sym,
+ tanh: sym,
+ coth: sym,
+ ln: sym,
+ log: sym,
+ lg: sym,
+ lim: sym,
+ limsup: sym,
+ liminf: sym,
+ hom: sym,
+ det: sym,
+ exp: sym,
+ deg: sym,
+ gcd: sym,
+ lcm: sym,
+ dim: sym,
+ ker: sym,
+ arg: sym,
+ Pr: sym,
+ // Limits
+ max: sym,
+ min: sym,
+ argmax: sym,
+ argmin: sym,
+ sup: sym,
+ inf: sym,
+ sum: sym,
+ prod: define-sym("product"),
+ int: define-sym("integral"),
+ iint: define-sym("integral.double"),
+ iiint: define-sym("integral.triple"),
+ oint: define-sym("integral.cont"),
+ oiint: define-sym("integral.surf"),
+ oiiint: define-sym("integral.vol"),
+ // Symbols
+ mod: define-sym("mod"),
+ bmod: define-sym("mod"),
+ cdot: define-sym("dot.c"),
+ cdotp: define-sym("dot.c"),
+ sdot: define-sym("dot.c"),
+ times: define-sym("times"),
+ oplus: define-sym("plus.o"),
+ ominus: define-sym("minus.o"),
+ pm: define-sym("plus.minus"),
+ plusmn: define-sym("plus.minus"),
+ mp: define-sym("minus.plus"),
+ div: define-sym("div"),
+ star: define-sym("star"),
+ cap: define-sym("inter"),
+ cup: define-sym("union"),
+ "in": define-sym("in"),
+ isin: define-sym("in"),
+ notin: define-sym("in.not"),
+ subset: define-sym("subset"),
+ subseteq: define-sym("subset.eq"),
+ subsetneqq: define-sym("⫋"),
+ ne: define-sym("!="),
+ neq: define-sym("!="),
+ lt: define-sym("<"),
+ gt: define-sym(">"),
+ le: define-sym("<="),
+ ge: define-sym(">="),
+ leq: define-sym("<="),
+ geq: define-sym(">="),
+ leqslant: define-sym("lt.eq.slant"),
+ geqslant: define-sym("gt.eq.slant"),
+ eqslantgtr: define-sym("⪖"),
+ eqslantless: define-sym("⪕"),
+ approx: define-sym("approx"),
+ leftarrow: define-sym("<-"),
+ rightarrow: define-sym("->"),
+ leftrightarrow: define-sym("<->"),
+ Leftarrow: define-sym("arrow.l.double"),
+ Rightarrow: define-sym("=>"),
+ Leftrightarrow: define-sym("<=>"),
+ larr: define-sym("<-"),
+ rarr: define-sym("->"),
+ lrarr: define-sym("<->"),
+ lArr: define-sym("arrow.l.double"),
+ rArr: define-sym("=>"),
+ lrArr: define-sym("<=>"),
+ Larr: define-sym("arrow.l.double"),
+ Rarr: define-sym("=>"),
+ Lrarr: define-sym("<=>"),
+ longleftarrow: define-sym("<--"),
+ longrightarrow: define-sym("-->"),
+ longleftrightarrow: define-sym("<-->"),
+ Longleftarrow: define-sym("<=="),
+ Longrightarrow: define-sym("==>"),
+ Longleftrightarrow: define-sym("<==>"),
+ to: define-sym("->"),
+ implies: define-sym("==>"),
+ impliedby: define-sym("<=="),
+ gets: define-sym("<-"),
+ mapsto: define-sym("|->"),
+ infty: define-sym("oo"),
+ lbrack: define-sym("bracket.l"),
+ rbrack: define-sym("bracket.r"),
+ lgroup: define-sym("⟮"),
+ rgroup: define-sym("⟯"),
+ llbracket: define-sym("bracket.stroked.l"),
+ rrbracket: define-sym("bracket.stroked.r"),
+ angle: define-sym("angle"),
+ lang: define-sym("chevron.l"),
+ rang: define-sym("chevron.r"),
+ langle: define-sym("chevron.l"),
+ rangle: define-sym("chevron.r"),
+ measuredangle: define-sym("angle.arc"),
+ sphericalangle: define-sym("angle.spheric"),
+ ast: define-sym("ast"),
+ checkmark: define-sym("checkmark"),
+ circledast: define-sym("convolve.o"),
+ backslash: define-sym("backslash"),
+ dagger: define-sym("dagger"),
+ ddagger: define-sym("dagger.double"),
+ circleddash: define-sym("dash.o"),
+ odot: define-sym("dot.o"),
+ bigodot: define-sym("dot.o.big"),
+ boxdot: define-sym("dot.square"),
+ dots: define-sym("dots.h"),
+ cdots: define-sym("dots.h.c"),
+ ldots: define-sym("dots.h"),
+ vdots: define-sym("dots.v"),
+ ddots: define-sym("dots.down"),
+ dotsb: define-sym("dots.h.c"),
+ dotsc: define-sym("dots.h"),
+ dotsi: define-sym("dots.h.c"),
+ dotsm: define-sym("dots.h.c"),
+ dotso: define-sym("dots.h"),
+ sim: define-sym("tilde"),
+ simeq: define-sym("tilde.eq"),
+ backsimeq: define-sym("tilde.eq.rev"),
+ cong: define-sym("tilde.equiv"),
+ ncong: define-sym("tilde.equiv.not"),
+ nsim: define-sym("tilde.not"),
+ backsim: define-sym("tilde.rev"),
+ prime: define-sym("prime"),
+ backprime: define-sym("prime.rev"),
+ bigoplus: define-sym("plus.o.big"),
+ dotplus: define-sym("plus.dot"),
+ boxplus: define-sym("plus.square"),
+ boxminus: define-sym("minus.square"),
+ eqsim: define-sym("minus.tilde"),
+ otimes: define-sym("times.o"),
+ bigotimes: define-sym("times.o.big"),
+ divideontimes: define-sym("times.div"),
+ leftthreetimes: define-sym("times.three.l"),
+ rightthreetimes: define-sym("times.three.r"),
+ ltimes: define-sym("times.l"),
+ rtimes: define-sym("times.r"),
+ boxtimes: define-sym("times.square"),
+ triangleq: define-sym("eq.delta"),
+ curlyeqprec: define-sym("eq.prec"),
+ curlyeqsucc: define-sym("eq.succ"),
+ gtrdot: define-sym("gt.dot"),
+ gg: define-sym("gt.double"),
+ gtreqless: define-sym("gt.eq.lt"),
+ gtreqqless: define-sym("⪌"),
+ gtrapprox: define-sym("gt.approx"),
+ ngeq: define-sym("gt.eq.not"),
+ geqq: define-sym("gt.equiv"),
+ ngeqq: of-sym(math.cancel(angle: 20deg, "\u{2267}")),
+ gtrless: define-sym("gt.lt"),
+ gneqq: define-sym("gt.nequiv"),
+ ngtr: define-sym("gt.not"),
+ gnsim: define-sym("gt.ntilde"),
+ gtrsim: define-sym("gt.tilde"),
+ vartriangleright: define-sym("gt.tri"),
+ trianglerighteq: define-sym("gt.tri.eq"),
+ ntrianglerighteq: define-sym("gt.tri.eq.not"),
+ ntriangleright: define-sym("gt.tri.not"),
+ ggg: define-sym("gt.triple"),
+ lessdot: define-sym("lt.dot"),
+ ll: define-sym("lt.double"),
+ lesseqgtr: define-sym("lt.eq.gt"),
+ nleq: define-sym("lt.eq.not"),
+ nleqslant: of-sym(math.cancel(angle: 20deg, length: 1em, math.lt.eq.slant)),
+ leqq: define-sym("lt.equiv"),
+ nleqq: of-sym(math.cancel(angle: 20deg, "\u{2266}")),
+ lessgtr: define-sym("lt.gt"),
+ lneqq: define-sym("lt.nequiv"),
+ nless: define-sym("lt.not"),
+ lnsim: define-sym("lt.ntilde"),
+ lesssim: define-sym("lt.tilde"),
+ vartriangleleft: define-sym("lt.tri"),
+ trianglelefteq: define-sym("lt.tri.eq"),
+ ntrianglelefteq: define-sym("lt.tri.eq.not"),
+ ntriangleleft: define-sym("lt.tri.not"),
+ lll: define-sym("lt.triple"),
+ approxeq: define-sym("approx.eq"),
+ prec: define-sym("prec"),
+ precapprox: define-sym("prec.approx"),
+ preceq: define-sym("prec.eq"),
+ preccurlyeq: define-sym("prec.eq"),
+ npreceq: define-sym("prec.eq.not"),
+ precnapprox: define-sym("prec.napprox"),
+ nprec: define-sym("prec.not"),
+ precnsim: define-sym("prec.ntilde"),
+ precsim: define-sym("prec.tilde"),
+ succ: define-sym("succ"),
+ succapprox: define-sym("succ.approx"),
+ succeq: define-sym("succ.eq"),
+ succcurlyeq: define-sym("succ.eq"),
+ nsucceq: define-sym("succ.eq.not"),
+ succnapprox: define-sym("succ.napprox"),
+ nsucc: define-sym("succ.not"),
+ succnsim: define-sym("succ.ntilde"),
+ succsim: define-sym("succ.tilde"),
+ equiv: define-sym("equiv"),
+ propto: define-sym("prop"),
+ empty: define-sym("nothing"),
+ emptyset: define-sym("nothing"),
+ varnothing: define-sym("nothing"),
+ o: define-sym("nothing"),
+ O: define-sym("nothing"),
+ osplash: define-sym("⊘"),
+ setminus: define-sym("without"),
+ And: define-sym("amp"),
+ bigcirc: define-sym("circle.stroked.big"),
+ smallsetminus: define-sym("without"),
+ complement: define-sym("complement"),
+ ni: define-sym("in.rev"),
+ notni: define-sym("in.rev.not"),
+ Subset: define-sym("subset.double"),
+ nsubseteq: define-sym("subset.eq.not"),
+ nsubseteqq: of-sym(math.cancel(angle: 20deg, length: 1em, "\u{2AC5}")),
+ sqsubseteq: define-sym("subset.eq.sq"),
+ subsetneq: define-sym("subset.neq"),
+ supset: define-sym("supset"),
+ Supset: define-sym("supset.double"),
+ supseteq: define-sym("supset.eq"),
+ nsupseteq: define-sym("supset.eq.not"),
+ nsupseteqq: of-sym(math.cancel(angle: 20deg, length: 1em, "\u{2AC6}")),
+ sqsupseteq: define-sym("supset.eq.sq"),
+ supsetneq: define-sym("supset.neq"),
+ bigcup: define-sym("union.big"),
+ Cup: define-sym("union.double"),
+ uplus: define-sym("union.plus"),
+ biguplus: define-sym("union.plus.big"),
+ sqcup: define-sym("union.sq"),
+ bigsqcup: define-sym("union.sq.big"),
+ bigcap: define-sym("inter.big"),
+ Cap: define-sym("inter.double"),
+ sqcap: define-sym("inter.sq"),
+ partial: define-sym("partial"),
+ nabla: define-sym("nabla"),
+ coprod: define-sym("product.co"),
+ forall: define-sym("forall"),
+ exist: define-sym("exists"),
+ exists: define-sym("exists"),
+ nexists: define-sym("exists.not"),
+ top: define-sym("top"),
+ bot: define-sym("bot"),
+ neg: define-sym("not"),
+ lnot: define-sym("not"),
+ land: define-sym("and"),
+ wedge: define-sym("and"),
+ lor: define-sym("or"),
+ bigwedge: define-sym("and.big"),
+ curlywedge: define-sym("and.curly"),
+ vee: define-sym("or"),
+ bigvee: define-sym("or.big"),
+ curlyvee: define-sym("or.curly"),
+ models: define-sym("models"),
+ therefore: define-sym("therefore"),
+ because: define-sym("because"),
+ blacksquare: define-sym("qed"),
+ circ: define-sym("compose"),
+ multimap: define-sym("multimap"),
+ mid: define-sym("divides"),
+ nmid: define-sym("divides.not"),
+ wr: define-sym("wreath"),
+ parallel: define-sym("parallel"),
+ shortparallel: define-sym("parallel"),
+ nparallel: define-sym("parallel.not"),
+ perp: define-sym("perp"),
+ Join: define-sym("join"),
+ pounds: define-sym("pound"),
+ clubsuit: define-sym("suit.club"),
+ spadesuit: define-sym("suit.spade"),
+ bull: define-sym("bullet"),
+ bullet: define-sym("bullet"),
+ circledcirc: define-sym("compose.o"),
+ rhd: define-sym("triangle.stroked.r"),
+ lhd: define-sym("triangle.stroked.l"),
+ triangle: define-sym("triangle.stroked.t"),
+ bigtriangleup: define-sym("triangle.stroked.t"),
+ bigtriangledown: define-sym("triangle.stroked.b"),
+ triangleright: define-sym("triangle.stroked.small.r"),
+ triangledown: define-sym("triangle.stroked.small.b"),
+ triangleleft: define-sym("triangle.stroked.small.l"),
+ vartriangle: define-sym("triangle.stroked.small.t"),
+ square: define-sym("square.stroked"),
+ Diamond: define-sym("diamond.stroked"),
+ diamond: define-sym("diamond.stroked.small"),
+ diamonds: define-sym("diamond.stroked"),
+ diamondsuit: define-sym("diamond.stroked"),
+ lozenge: define-sym("lozenge.stroked"),
+ blacklozenge: define-sym("lozenge.filled"),
+ bigstar: define-sym("star.stroked"),
+ longmapsto: define-sym("arrow.r.long.bar"),
+ nRightarrow: define-sym("arrow.r.double.not"),
+ hookrightarrow: define-sym("arrow.r.hook"),
+ looparrowright: define-sym("arrow.r.loop"),
+ nrightarrow: define-sym("arrow.r.not"),
+ rightsquigarrow: define-sym("arrow.r.squiggly"),
+ rightarrowtail: define-sym("arrow.r.tail"),
+ Rrightarrow: define-sym("arrow.r.triple"),
+ twoheadrightarrow: define-sym("arrow.r.twohead"),
+ nLeftarrow: define-sym("arrow.l.double.not"),
+ hookleftarrow: define-sym("arrow.l.hook"),
+ looparrowleft: define-sym("arrow.l.loop"),
+ nleftarrow: define-sym("arrow.l.not"),
+ leftarrowtail: define-sym("arrow.l.tail"),
+ Lleftarrow: define-sym("arrow.l.triple"),
+ twoheadleftarrow: define-sym("arrow.l.twohead"),
+ uparrow: define-sym("arrow.t"),
+ Uparrow: define-sym("arrow.t.double"),
+ downarrow: define-sym("arrow.b"),
+ Downarrow: define-sym("arrow.b.double"),
+ iff: define-sym("arrow.l.r.double.long"),
+ nLeftrightarrow: define-sym("arrow.l.r.double.not"),
+ nleftrightarrow: define-sym("arrow.l.r.not"),
+ leftrightsquigarrow: define-sym("arrow.l.r.wave"),
+ updownarrow: define-sym("arrow.t.b"),
+ Updownarrow: define-sym("arrow.t.b.double"),
+ nearrow: define-sym("arrow.tr"),
+ searrow: define-sym("arrow.br"),
+ nwarrow: define-sym("arrow.tl"),
+ swarrow: define-sym("arrow.bl"),
+ circlearrowleft: define-sym("arrow.ccw"),
+ curvearrowleft: define-sym("arrow.ccw.half"),
+ circlearrowright: define-sym("arrow.cw"),
+ curvearrowright: define-sym("arrow.cw.half"),
+ rightrightarrows: define-sym("arrows.rr"),
+ leftleftarrows: define-sym("arrows.ll"),
+ upuparrows: define-sym("arrows.tt"),
+ downdownarrows: define-sym("arrows.bb"),
+ leftrightarrows: define-sym("arrows.lr"),
+ rightleftarrows: define-sym("arrows.rl"),
+ rightharpoonup: define-sym("harpoon.rt"),
+ rightharpoondown: define-sym("harpoon.rb"),
+ leftharpoonup: define-sym("harpoon.lt"),
+ leftharpoondown: define-sym("harpoon.lb"),
+ upharpoonleft: define-sym("harpoon.tl"),
+ upharpoonright: define-sym("harpoon.tr"),
+ downharpoonleft: define-sym("harpoon.bl"),
+ downharpoonright: define-sym("harpoon.br"),
+ leftrightharpoons: define-sym("harpoons.ltrb"),
+ rightleftharpoons: define-sym("harpoons.rtlb"),
+ vdash: define-sym("tack.r"),
+ nvdash: define-sym("tack.r.not"),
+ vDash: define-sym("tack.r.double"),
+ nvDash: define-sym("tack.r.double.not"),
+ dashv: define-sym("tack.l"),
+ hbar: define-sym("planck"),
+ hslash: define-sym("planck"),
+ Re: define-sym("Re"),
+ Im: define-sym("Im"),
+ AA: define-sym("circle(A)"),
+ aa: define-sym("circle(A)"),
+ Box: define-sym("ballot"),
+ N: define-sym("NN"),
+ natnums: define-sym("NN"),
+ natural: define-sym("♮"),
+ P: define-sym("pilcrow"),
+ Q: define-sym("QQ"),
+ R: define-sym("RR"),
+ Z: define-sym("ZZ"),
+ S: define-sym("section"),
+ sect: define-sym("section"),
+ AE: define-sym("Æ"),
+ ae: define-sym("æ"),
+ alef: define-sym("aleph"),
+ alefsym: define-sym("aleph"),
+ aleph: define-sym("aleph"),
+ amalg: define-sym("product.co"),
+ arctg: of-sym(math.op("arctg")),
+ asymp: define-sym("≍"),
+ ch: of-sym(math.op("ch")),
+ circeq: define-sym("≗"),
+ colon: define-sym("colon"),
+ cth: of-sym(math.op("cth")),
+ dag: define-sym("dagger"),
+ Dagger: define-sym("dagger.double"),
+ ddag: define-sym("dagger.double"),
+ daleth: define-sym("ℸ"),
+ sharp: define-sym("♯"),
+ flat: define-sym("♭"),
+ i: define-sym("dotless.i"),
+ j: define-sym("dotless.j"),
+ imath: define-sym("dotless.i"),
+ jmath: define-sym("dotless.j"),
+ smallsmile: define-sym("⌣"),
+ smile: define-sym("⌣"),
+ ss: define-sym("ß"),
+ surd: define-sym("\√"),
+ tg: define-sym("tg"),
+ th: of-sym(math.op("th")),
+ weierp: define-sym("℘"),
+ wp: define-sym("℘"),
+ lbrace: define-sym("\\{"),
+ rbrace: define-sym("\\}"),
+ doteq: define-sym("≐"),
+ Vdash: define-sym("⊩"),
+ Doteq: define-sym("≑"),
+ Vvdash: define-sym("⊪"),
+ gnapprox: define-sym("⪊"),
+ ngeqslant: define-sym("gt.eq.not"),
+ precneqq: define-sym("prec.nequiv"),
+ gneq: define-sym("⪈"),
+ approxcolon: define-sym("approx:"),
+ approxcoloncolon: define-sym("approx::"),
+ backepsilon: define-sym("in.rev.small"),
+ barwedge: define-sym("⊼"),
+ beth: define-sym("beth"),
+ between: define-sym("≬"),
+ bigdot: define-sym("dot.o.big"),
+ bigplus: define-sym("plus.o.big"),
+ bigtimes: define-sym("times.o.big"),
+ blacktriangle: define-sym("triangle.filled.t"),
+ blacktriangledown: define-sym("triangle.filled.b"),
+ blacktriangleleft: define-sym("triangle.filled.l"),
+ blacktriangleright: define-sym("triangle.filled.r"),
+ bowtie: define-sym("⋈"),
+ Bumpeq: define-sym("≎"),
+ bumpeq: define-sym("≏"),
+ centerdot: define-sym("dot.op"),
+ circledR: define-sym("®"),
+ circledS: define-sym("Ⓢ"),
+ clubs: define-sym("suit.club"),
+ cnums: define-sym("CC"),
+ Colonapprox: define-sym("::approx"),
+ colonapprox: define-sym(":approx"),
+ coloncolon: define-sym("::"),
+ coloncolonapprox: define-sym("::approx"),
+ coloncolonequals: define-sym("::="),
+ coloncolonminus: define-sym("::−"),
+ coloncolonsim: define-sym("::tilde.op"),
+ Coloneq: define-sym("::−"),
+ coloneq: define-sym(":−"),
+ colonequals: define-sym(":="),
+ Coloneqq: define-sym("::="),
+ coloneqq: define-sym(":="),
+ colonminus: define-sym(":−"),
+ Colonsim: define-sym("::tilde.op"),
+ colonsim: define-sym(":tilde.op"),
+ Complex: define-sym("CC"),
+ copyright: define-sym("copyright"),
+ ctg: define-sym("ctg"),
+ Darr: define-sym("arrow.b.double"),
+ dArr: define-sym("arrow.b.double"),
+ darr: define-sym("arrow.b"),
+ dashleftarrow: define-sym("arrow.l.dash"),
+ dashrightarrow: define-sym("arrow.r.dash"),
+ dbcolon: define-sym("::"),
+ degree: define-sym("degree"),
+ digamma: define-sym("ϝ"),
+ diagdown: define-sym("╲"),
+ diagup: define-sym("╱"),
+ doteqdot: define-sym("≑"),
+ doublebarwedge: define-sym("⩞"),
+ doublecap: define-sym("inter.double"),
+ doublecup: define-sym("union.double"),
+ eqcirc: define-sym("≖"),
+ Eqcolon: define-sym("−::"),
+ eqcolon: define-sym("dash.colon"),
+ Eqqcolon: define-sym("=::"),
+ eqqcolon: define-sym("=:"),
+ equalscolon: define-sym("=:"),
+ equalscoloncolon: define-sym("=::"),
+ eth: define-sym("ð"),
+ fallingdotseq: define-sym("≒"),
+ Finv: define-sym("Ⅎ"),
+ frown: define-sym("⌢"),
+ Game: define-sym("⅁"),
+ gggtr: define-sym(">>>"),
+ gimel: define-sym("gimel"),
+ Harr: define-sym("<=>"),
+ hArr: define-sym("<=>"),
+ harr: define-sym("<->"),
+ hearts: define-sym("♡"),
+ heartsuit: define-sym("♡"),
+ image: define-sym("Im"),
+ imageof: define-sym("⊷"),
+ infin: define-sym("infinity"),
+ intercal: define-sym("⊺"),
+ intop: define-sym("integral"),
+ lBrace: define-sym("⦃"),
+ ldotp: define-sym("."),
+ leadsto: define-sym("arrow.r.squiggly"),
+ lessapprox: define-sym("⪅"),
+ lesseqqgtr: define-sym("⪋"),
+ llcorner: define-sym("⌞"),
+ llless: define-sym("<<<"),
+ lnapprox: define-sym("⪉"),
+ lneq: define-sym("⪇"),
+ lrcorner: define-sym("⌟"),
+ lq: define-sym("quote.l.single"),
+ Lsh: define-sym("↰"),
+ maltese: define-sym("maltese"),
+ mathellipsis: define-sym("..."),
+ mathsterling: define-sym("pound"),
+ mho: define-sym("Omega.inv"),
+ minuscolon: define-sym("dash.colon"),
+ minuscoloncolon: define-sym("−::"),
+ minuso: define-sym("⦵"),
+ newline: define-sym("\\"),
+ nVDash: define-sym("⊯"),
+ nVdash: define-sym("⊮"),
+ OE: define-sym("Œ"),
+ oe: define-sym("œ"),
+ origof: define-sym("⊶"),
+ oslash: define-sym("⊘"),
+ owns: define-sym("in.rev"),
+ pitchfork: define-sym("⋔"),
+ ratio: define-sym(":"),
+ rBrace: define-sym("⦄"),
+ real: define-sym("Re"),
+ Reals: define-sym("RR"),
+ reals: define-sym("RR"),
+ restriction: define-sym("harpoon.tr"),
+ risingdotseq: define-sym("≓"),
+ rmoustache: define-sym("⎱"),
+ rq: define-sym("'"),
+ Rsh: define-sym("↱"),
+ simcolon: define-sym("tilde.op:"),
+ simcoloncolon: define-sym("tilde.op::"),
+ spades: define-sym("suit.spade"),
+ sqsubset: define-sym("subset.sq"),
+ sqsupset: define-sym("supset.sq"),
+ sub: define-sym("subset"),
+ sube: define-sym("subset.eq"),
+ subseteqq: define-sym("⫅"),
+ succneqq: define-sym("succ.nequiv"),
+ supe: define-sym("supset.eq"),
+ supseteqq: define-sym("⫆"),
+ supsetneqq: define-sym("⫌"),
+ textasciitilde: define-sym("~"),
+ textasciicircum: define-sym("\\^"),
+ textbackslash: define-sym("\\\\"),
+ textbar: define-sym("\\|"),
+ textbardbl: define-sym("‖"),
+ textbraceleft: define-sym("{"),
+ textbraceright: define-sym("}"),
+ textdagger: define-sym("dagger"),
+ textdaggerdbl: define-sym("dagger.double"),
+ textdegree: define-sym("degree"),
+ textdollarsign: define-sym("\\$"),
+ textellipsis: define-sym("..."),
+ textemdash: define-sym("---"),
+ textendash: define-sym("--"),
+ textgreater: define-sym("gt"),
+ textless: define-sym("lt"),
+ textquotedblleft: define-sym("quote.l.double"),
+ textquotedblright: define-sym("quote.r.double"),
+ textquoteleft: define-sym("quote.l.single"),
+ textquoteright: define-sym("quote.r.single"),
+ textregistered: define-sym("®"),
+ textsterling: define-sym("pound"),
+ textunderscore: define-sym("\\_"),
+ thetasym: define-sym("theta.alt"),
+ Uarr: define-sym("arrow.t.double"),
+ uArr: define-sym("arrow.t.double"),
+ uarr: define-sym("arrow.t"),
+ ulcorner: define-sym("⌜"),
+ unlhd: define-sym("lt.tri.eq"),
+ unrhd: define-sym("gt.tri.eq"),
+ urcorner: define-sym("⌝"),
+ varpropto: define-sym("prop"),
+ varsubsetneq: define-sym("subset.neq"),
+ varsubsetneqq: define-sym("⫋"),
+ varsupsetneq: define-sym("supset.neq"),
+ varsupsetneqq: define-sym("⫌"),
+ vcentcolon: define-sym(":"),
+ veebar: define-sym("⊻"),
+ yen: define-sym("yen"),
+ arcctg: of-sym(math.op("arcctg")),
+ begingroup: ignore-sym,
+ cosec: of-sym(math.op("cosec")),
+ cotg: of-sym(math.op("cotg")),
+ injlim: of-sym(math.op("inj\u{2009}lim", limits: true)),
+ mathclap: define-cmd(1, handle: it => box(width: 0pt, $it$)),
+ mathring: define-cmd(1, handle: it => math.circle(it)),
+ nobreak: ignore-sym,
+ noexpand: ignore-sym,
+ overgroup: define-cmd(1, handle: it => $accent(it, \u{0311})$),
+ undergroup: define-cmd(1, handle: it => $accent(it, \u{032e})$),
+ overleftharpoon: define-cmd(1, handle: it => $accent(it, \u{20d0})$),
+ overleftrightarrow: define-cmd(1, handle: it => $accent(it, \u{20e1})$),
+ overlinesegment: define-cmd(1, handle: it => $accent(it, \u{20e9})$),
+ overrightharpoon: define-cmd(1, handle: it => $accent(it, \u{20d1})$),
+ underbar: define-cmd(1, handle: it => $underline(it)$),
+ plim: of-sym(math.op("plim", limits: true)),
+ projlim: of-sym(math.op("proj\u{2009}lim", limits: true)),
+ raisebox: define-cmd(2, handle: (sp, it) => text(baseline: -eval(get-tex-str(sp)), it)),
+ sh: of-sym(math.op("sh")),
+ smallint: of-sym($inline(integral)$),
+ thickapprox: of-sym($bold(approx)$),
+ thicksim: of-sym($bold(tilde)$),
+ varDelta: of-sym($italic(Delta)$),
+ varGamma: of-sym($italic(Gamma)$),
+ varLambda: of-sym($italic(Lambda)$),
+ varOmega: of-sym($italic(Omega)$),
+ varPhi: of-sym($italic(Phi)$),
+ varPi: of-sym($italic(Pi)$),
+ varPsi: of-sym($italic(Psi)$),
+ varSigma: of-sym($italic(Sigma)$),
+ varTheta: of-sym($italic(Theta)$),
+ varUpsilon: of-sym($italic(Upsilon)$),
+ varXi: of-sym($italic(Xi)$),
+ xleftarrow: arrow-handle(math.arrow.l),
+ xrightarrow: arrow-handle(math.arrow.r),
+ xLeftarrow: arrow-handle(math.arrow.l.double),
+ xRightarrow: arrow-handle(math.arrow.r.double),
+ xleftrightarrow: arrow-handle(math.arrow.l.r),
+ xLeftrightarrow: arrow-handle(math.arrow.l.r.double),
+ xhookleftarrow: arrow-handle(math.arrow.l.hook),
+ xhookrightarrow: arrow-handle(math.arrow.r.hook),
+ xtwoheadleftarrow: arrow-handle(math.arrow.l.twohead),
+ xtwoheadrightarrow: arrow-handle(math.arrow.r.twohead),
+ xleftharpoonup: arrow-handle(math.harpoon.lt),
+ xrightharpoonup: arrow-handle(math.harpoon.rt),
+ xleftharpoondown: arrow-handle(math.harpoon.lb),
+ xrightharpoondown: arrow-handle(math.harpoon.rb),
+ xleftrightharpoons: arrow-handle(math.harpoons.ltrb),
+ xrightleftharpoons: arrow-handle(math.harpoons.rtlb),
+ xtofrom: arrow-handle(math.arrows.rl),
+ xmapsto: arrow-handle(math.arrow.r.bar),
+ xlongequal: arrow-handle(math.eq),
+ pmod: define-cmd(1, handle: it => $quad (mod thick it)$),
+ pod: define-cmd(1, handle: it => $quad (it)$),
+ "set": define-cmd(1, handle: it => $\{it\}$),
+ Set: define-cmd(1, handle: it => $lr(\{it\})$),
+ bra: define-cmd(1, handle: it => $chevron.l it|$),
+ Bra: define-cmd(1, handle: it => $lr(chevron.l it|)$),
+ ket: define-cmd(1, handle: it => $|it chevron.r$),
+ Ket: define-cmd(1, handle: it => $lr(|it chevron.r)$),
+ braket: define-cmd(1, handle: it => $chevron.l it chevron.r$),
+ Braket: define-cmd(1, handle: it => $lr(chevron.l it chevron.r)$),
+ fbox: define-cmd(1, handle: it => box(stroke: 0.5pt, $it$)),
+ hbox: define-cmd(1, handle: it => it),
+ // Matrices
+ matrix: matrix-handle(delim: none),
+ pmatrix: matrix-handle(delim: "("),
+ bmatrix: matrix-handle(delim: "["),
+ Bmatrix: matrix-handle(delim: "{"),
+ vmatrix: matrix-handle(delim: "|"),
+ Vmatrix: matrix-handle(delim: "||"),
+ smallmatrix: matrix-handle(handle: (..args) => math.inline(math.mat.with(delim: none, ..args))),
+ array: define-env(1, kind: "is-matrix", alias: "mitexarray", handle: (arg0: ("l",), ..args) => {
+ if args.pos().len() == 0 {
+ return
+ }
+ if type(arg0) != str {
+ if arg0.has("children") {
+ arg0 = arg0.children.filter(it => it != [ ] and it != [#math.zws])
+ .map(it => it.text)
+ .filter(it => it == "l" or it == "c" or it == "r")
+ } else {
+ arg0 = (arg0.text,)
+ }
+ }
+ let matrix = args.pos().map(row => if type(row) == array { row } else { (row,) } )
+ let n = matrix.len()
+ let m = calc.max(..matrix.map(row => row.len()))
+ matrix = matrix.map(row => row + (m - row.len()) * (none,))
+ let array-at(arr, pos) = {
+ arr.at(calc.min(pos, arr.len() - 1))
+ }
+ let align-map = ("l": left, "c": center, "r": right)
+ set align(align-map.at(array-at(arg0, 0)))
+ pad(y: 0.2em, grid(
+ columns: m,
+ column-gutter: 0.5em,
+ row-gutter: 0.5em,
+ ..matrix.flatten().map(it => $it$)
+ ))
+ }),
+ subarray: define-env(1, kind: "is-matrix", alias: "mitexarray"),
+ // Environments
+ aligned: define-env(none, kind: "is-math", alias: "aligned", handle: call-or-ignore(it => pad(y: 0.2em, block(math.op(math.display(it)))))),
+ alignedat: define-env(1, kind: "is-math", alias: "alignedat", handle: (arg0: none, it) => pad(y: 0.2em, block(math.op(it)))),
+ align: define-env(none, kind: "is-math", alias: "aligned"),
+ "align*": define-env(none, kind: "is-math", alias: "aligned"),
+ equation: define-env(none, kind: "is-math", alias: "aligned"),
+ "equation*": define-env(none, kind: "is-math", alias: "aligned"),
+ split: define-env(none, kind: "is-math", alias: "aligned"),
+ gather: define-env(none, kind: "is-math", alias: "aligned"),
+ gathered: define-env(none, kind: "is-math", alias: "aligned"),
+ cases: define-env(none, kind: "is-cases", alias: "cases"),
+ rcases: define-env(none, kind: "is-cases", alias: "rcases", handle: math.cases.with(reverse: true)),
+ // Specials
+ notag: ignore-sym,
+ relax: ignore-sym,
+ cr: ignore-sym,
+ expandafter: ignore-sym,
+ hskip: ignore-sym,
+ mskip: ignore-sym,
+ kern: ignore-sym,
+ mkern: ignore-sym,
+ mathstrut: ignore-sym,
+ nonumber: ignore-sym,
+ KaTeX: of-sym(math.upright($K A T E X$)),
+ LaTeX: of-sym(math.upright($L A T E X$)),
+ TeX: of-sym(math.upright($T E X$)),
+ middle: define-cmd(1, handle: it => math.mid(it)),
+ operatorname: define-cmd(1, handle: it => math.op(math.upright(it))),
+ operatornamewithlimits: define-cmd(1, alias: "operatornamewithlimits", handle: operatornamewithlimits),
+ "operatorname*": define-cmd(1, alias: "operatornamewithlimits", handle: operatornamewithlimits),
+ vspace: define-cmd(1, handle: it => v(eval(get-tex-str(it)))),
+ hspace: define-cmd(1, handle: it => h(eval(get-tex-str(it)))),
+ text: define-cmd(1, alias: "#textmath", handle: it => it),
+ textmd: define-cmd(1, alias: "#textmd", handle: it => it),
+ textnormal: define-cmd(1, alias: "#textnormal", handle: it => it),
+ textbf: define-cmd(1, alias: "#textbf", handle: math.bold),
+ textit: define-cmd(1, alias: "#textit", handle: math.italic),
+ textrm: define-cmd(1, alias: "#textrm", handle: math.upright),
+ textup: define-cmd(1, alias: "#textup", handle: math.upright),
+ textsf: define-cmd(1, alias: "#textsf", handle: math.sans),
+ texttt: define-cmd(1, alias: "#texttt", handle: math.mono),
+ over: define-infix-cmd("frac"),
+ atop: define-infix-cmd("atop", handle: (a, b) => $mat(delim: #none, #a; #b)$),
+ choose: define-infix-cmd("binom", handle: math.binom),
+ brace: define-infix-cmd("brace", handle: (n, k) => $mat(delim: "{", #n;; #k)$),
+ brack: define-infix-cmd("brack", handle: (n, k) => $mat(delim: "[", #n;; #k)$),
+ sqrt: define-glob-cmd("{,b}t", "mitexsqrt", handle: (..args) => {
+ if args.pos().len() == 1 {
+ $sqrt(#args.pos().at(0))$
+ } else if args.pos().len() == 2 {
+ $root(
+ #args.pos().at(0).children.filter(it => it != [\[] and it != [\]]).sum(),
+ #args.pos().at(1)
+ )$
+ } else {
+ panic("unexpected args in sqrt")
+ }
+ }),
+ // todo: macros
+ def: ignore-sym,
+ newcommand: ignore-sym,
+ "newcommand*": ignore-sym,
+ renewcommand: ignore-sym,
+ "renewcommand*": ignore-sym,
+ DeclareRobustCommand: ignore-sym,
+ "DeclareRobustCommand*": ignore-sym,
+ DeclareTextCommand: ignore-sym,
+ DeclareTextCommandDefault: ignore-sym,
+ ProvideTextCommand: ignore-sym,
+ ProvideTextCommandDefault: ignore-sym,
+ providecommand: ignore-sym,
+ "providecommand*": ignore-sym,
+ newenvironment: ignore-sym,
+ "newenvironment*": ignore-sym,
+ renewenvironment: ignore-sym,
+ "renewenvironment*": ignore-sym,
+ AtEndOfClass: ignore-sym,
+ AtEndOfPackage: ignore-sym,
+ AtBeginDocument: ignore-sym,
+ AtEndDocument: ignore-sym,
+ "@ifstar": ignore-sym,
+ "if": ignore-sym,
+ ifdim: ignore-sym,
+ iffalse: ignore-sym,
+ ifnum: ignore-sym,
+ ifodd: ignore-sym,
+ iftrue: ignore-sym,
+ ifx: ignore-sym,
+ DeclareOption: ignore-sym,
+ "DeclareOption*": ignore-sym,
+ CurrentOption: ignore-sym,
+ ProcessOptions: ignore-sym,
+ ExecuteOptions: ignore-sym,
+ RequirePackage: ignore-sym,
+ RequirePackageWithOptions: ignore-sym,
+ documentclass: ignore-sym,
+ PassOptionsToClass: ignore-sym,
+ PassOptionsToPackage: ignore-sym,
+ IfFileExists: ignore-sym,
+ InputIfFileExists: ignore-sym,
+ ProvidesFile: ignore-sym,
+ ignorespaces: ignore-sym,
+ ignorespacesafterend: ignore-sym,
+ ifvoid: ignore-sym,
+ ifinner: ignore-sym,
+ ifhbox: ignore-sym,
+ ifvbox: ignore-sym,
+ ifhmode: ignore-sym,
+ ifmmode: ignore-sym,
+ ifvmode: ignore-sym,
+ CheckCommand: ignore-sym,
+ "CheckCommand*": ignore-sym,
+ newcounter: ignore-sym,
+ newlength: ignore-sym,
+ newsavebox: ignore-sym,
+ newtheorem: ignore-sym,
+ newfont: ignore-sym,
+ ProvidesClass: ignore-sym,
+ LoadClass: ignore-sym,
+ LoadClassWithOptions: ignore-sym,
+))
+
+// export: include package name, spec and scope
+#let package = (name: "latex-std", spec: (commands: spec), scope: scope)
diff --git a/render/packages/preview/mitex/0.2.7/specs/mod.typ b/render/packages/preview/mitex/0.2.7/specs/mod.typ
new file mode 100644
index 0000000..6b5d957
--- /dev/null
+++ b/render/packages/preview/mitex/0.2.7/specs/mod.typ
@@ -0,0 +1,12 @@
+
+#import "prelude.typ": *
+#import "latex/standard.typ": package as latex-std
+
+// 1. import all the packages and form a mitex-scope for mitex to use
+#let packages = (latex-std,)
+#let mitex-scope = packages.map(pkg => pkg.scope).sum()
+
+// 2. export all packages with specs by metadata and <mitex-packages> label,
+// mitex-cli can fetch them by
+// `typst query --root . ./packages/mitex/specs/mod.typ "<mitex-packages>"`
+#metadata(packages) <mitex-packages>
diff --git a/render/packages/preview/mitex/0.2.7/specs/prelude.typ b/render/packages/preview/mitex/0.2.7/specs/prelude.typ
new file mode 100644
index 0000000..70789f0
--- /dev/null
+++ b/render/packages/preview/mitex/0.2.7/specs/prelude.typ
@@ -0,0 +1,230 @@
+/// Define a normal symbol, as no-argument commands like \alpha
+///
+/// Arguments:
+/// - s (str): Alias command for typst handler.
+/// For example, alias `\prod` to typst's `product`.
+/// - sym (content): The specific content, as the value of alias in mitex-scope.
+/// For example, there is no direct alias for \negthinspace symbol in typst,
+/// but we can add `h(-(3/18) * 1em)` ourselves
+///
+/// Return: A spec item and a scope item (none for no scope item)
+#let define-sym(s, sym: none) = {
+ (
+ (kind: "alias-sym", alias: s),
+ if sym != none {
+ (alias: s, handle: sym)
+ } else {
+ none
+ },
+ )
+}
+
+/// Define a greedy command, like \displaystyle
+///
+/// Arguments:
+/// - s (str): Alias command for typst handler.
+/// For example, alias `\displaystyle` to typst's `mitexdisplay`, as the key in mitex-scope.
+/// - handle (function): The handler function, as the value of alias in mitex-scope.
+/// It receives a content argument as all greedy matches to the content
+/// For example, we define `mitexdisplay` to `math.display`
+///
+/// Return: A spec item and a scope item (none for no scope item)
+#let define-greedy-cmd(s, handle: none) = {
+ (
+ (kind: "greedy-cmd", alias: s),
+ if handle != none {
+ (alias: s, handle: handle)
+ } else {
+ none
+ },
+ )
+}
+
+/// Define an infix command, like \over
+///
+/// Arguments:
+/// - s (str): Alias command for typst handler.
+/// For example, alias `\over` to typst's `frac`, as the key in mitex-scope.
+/// - handle (function): The handler function, as the value of alias in mitex-scope.
+/// It receives two content arguments, as (prev, after) arguments.
+/// For example, we define `\over` to `frac: (num, den) => $(num)/(den)$`
+///
+/// Return: A spec item and a scope item (none for no scope item)
+#let define-infix-cmd(s, handle: none) = {
+ (
+ (kind: "infix-cmd", alias: s),
+ if handle != none {
+ (alias: s, handle: handle)
+ } else {
+ none
+ },
+ )
+}
+
+/// Define a glob (Global Wildcard) match command with a specified pattern for matching args
+/// Kind of item to match:
+/// - Bracket/b: []
+/// - Parenthesis/p: ()
+/// - Term/t: any rest of terms, typically {} or single char
+///
+/// Arguments:
+/// - pat (pattern): The pattern for glob-cmd
+/// For example, `{,b}t` for `\sqrt` to support `\sqrt{2}` and `\sqrt[3]{2}`
+/// - s (str): Alias command for typst handler.
+/// For example, alias `\sqrt` to typst's `mitexsqrt`, as the key in mitex-scope.
+/// - handle (function): The handler function, as the value of alias in mitex-scope.
+/// It receives variable length arguments, for example `(2,)` or `([3], 2)` for sqrt.
+/// Therefore you need to use `(.. arg) = > {..}` to receive them.
+///
+/// Return: A spec item and a scope item (none for no scope item)
+#let define-glob-cmd(pat, s, handle: none) = {
+ (
+ (kind: "glob-cmd", pattern: pat, alias: s),
+ if handle != none {
+ (alias: s, handle: handle)
+ } else {
+ none
+ },
+ )
+}
+
+/// Define a command with a fixed number of arguments, like \hat{x} and \frac{1}{2}
+///
+/// Arguments:
+/// - num (int): The number of arguments for the command.
+/// - alias (str): Alias command for typst handler.
+/// For example, alias `\frac` to typst's `frac`, as the key in mitex-scope.
+/// - handle (function): The handler function, as the value of alias in mitex-scope.
+/// It receives fixed number of arguments, for example `frac(1, 2)` for `\frac{1}{2}`.
+///
+/// Return: A spec item and a scope item (none for no scope item)
+#let define-cmd(num, alias: none, handle: none) = {
+ (
+ (
+ kind: "cmd",
+ args: ("kind": "right", "pattern": (kind: "fixed-len", len: num)),
+ alias: alias,
+ ),
+ if handle != none {
+ (alias: alias, handle: handle)
+ } else {
+ none
+ },
+ )
+}
+
+/// Define an environment with a fixed number of arguments, like \begin{alignedat}{2}
+///
+/// Arguments:
+/// - num (int): The number of arguments as environment options for the environment.
+/// - alias (str): Alias command for typst handler.
+/// For example, alias `\begin{alignedat}{2}` to typst's `alignedat`,
+/// and alias `\begin{aligned}` to typst's `aligned`, as the key in mitex-scope.
+/// - kind (str): environment kind, it could be "is-math", "is-cases", "is-matrix",
+/// "is-itemize", "is-enumerate"
+/// - handle (function): The handler function, as the value of alias in mitex-scope.
+/// It receives fixed number of named arguments as environment options,
+/// for example `alignedat(arg0: ..)` or `alignedat(arg0: .., arg1: ..)`.
+/// And it receives variable length arguments as environment body,
+/// Therefore you need to use `(.. arg) = > {..}` to receive them.
+///
+/// Return: A spec item and a scope item (none for no scope item)
+#let define-env(num, kind: "none", alias: none, handle: none) = {
+ (
+ (
+ kind: "env",
+ args: if num != none {
+ (kind: "fixed-len", len: num)
+ } else {
+ (kind: "none")
+ },
+ ctx_feature: (kind: kind),
+ alias: alias,
+ ),
+ if handle != none {
+ (alias: alias, handle: handle)
+ } else {
+ none
+ },
+ )
+}
+
+#let define-glob-env(pat, kind: "none", alias: none, handle: none) = {
+ (
+ (
+ kind: "glob-env",
+ pattern: pat,
+ ctx_feature: (kind: kind),
+ alias: alias,
+ ),
+ if handle != none {
+ (alias: alias, handle: handle)
+ } else {
+ none
+ },
+ )
+}
+
+/// Define a symbol without alias and without handler function, like \alpha => alpha
+///
+/// Return: A spec item and no scope item (none for no scope item)
+#let sym = ((kind: "sym"), none)
+
+/// Define a symbol without alias and with handler function,
+/// like \negthinspace => h(-(3/18) * 1em)
+///
+/// Arguments:
+/// - handle (function): The handler function, as the value of alias in mitex-scope.
+/// For example, define `negthinspace` to handle `h(-(3/18) * 1em)` in mitex-scope
+///
+/// Return: A symbol spec and a scope item
+#let of-sym(handle) = ((kind: "sym"), (handle: handle))
+
+/// Define a left1-op command without handler, like `\limits` for `\sum\limits`
+///
+/// Arguments:
+/// - alias (str): Alias command for typst handler.
+/// For example, alias `\limits` to typst's `limits`
+/// and alias `\nolimits` to typst's `scripts`
+///
+/// Return: A cmd spec and no scope item (none for no scope item)
+#let left1-op(alias) = ((kind: "cmd", args: (kind: "left1"), alias: alias), none)
+
+/// Define a cmd1 command like \hat{x} => hat(x)
+///
+/// Return: A cmd1 spec and a scope item (none for no scope item)
+#let cmd1 = ((kind: "cmd1"), none)
+
+/// Define a cmd2 command like \binom{1}{2} => binom(1, 2)
+///
+/// Return: A cmd2 spec and a scope item (none for no scope item)
+#let cmd2 = ((kind: "cmd2"), none)
+
+/// Define a matrix environment without handler
+///
+/// Return: A matrix-env spec and a scope item (none for no scope item)
+#let matrix-env = ((kind: "matrix-env"), none)
+
+/// Receives a list of definitions composed of the above functions, and processes them to return a dictionary containing spec and scope.
+#let process-spec(definitions) = {
+ let spec = (:)
+ let scope = (:)
+ for (key, value) in definitions.pairs() {
+ let spec-item = value.at(0)
+ let scope-item = value.at(1)
+ spec.insert(key, spec-item)
+ if scope-item != none {
+ if "alias" in scope-item and type(scope-item.alias) == str {
+ let key = if scope-item.alias.starts-with("#") {
+ scope-item.alias.slice(1)
+ } else {
+ scope-item.alias
+ }
+ scope.insert(key, scope-item.handle)
+ } else {
+ scope.insert(key, scope-item.handle)
+ }
+ }
+ }
+ (spec: spec, scope: scope)
+}
diff --git a/render/packages/preview/mitex/0.2.7/typst.toml b/render/packages/preview/mitex/0.2.7/typst.toml
new file mode 100644
index 0000000..d19dc4b
--- /dev/null
+++ b/render/packages/preview/mitex/0.2.7/typst.toml
@@ -0,0 +1,12 @@
+[package]
+name = "mitex"
+version = "0.2.7"
+entrypoint = "lib.typ"
+authors = ["Myriad-Dreamin", "OrangeX4", "Enter-tainer", "Shichien"]
+license = "Apache-2.0"
+description = "LaTeX support for Typst, powered by Rust and WASM."
+
+repository = "https://github.com/mitex-rs/mitex"
+categories = ["utility"]
+keywords = ["wasm", "rust", "LaTeX", "equation"]
+exclude = ["examples"]
\ No newline at end of file
diff --git a/render/packages/preview/oxifmt/0.2.1/LICENSE b/render/packages/preview/oxifmt/0.2.1/LICENSE
new file mode 100644
index 0000000..a9cb23f
--- /dev/null
+++ b/render/packages/preview/oxifmt/0.2.1/LICENSE
@@ -0,0 +1,16 @@
+MIT No Attribution
+
+Copyright (c) 2023 Pg Biel
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this
+software and associated documentation files (the "Software"), to deal in the Software
+without restriction, including without limitation the rights to use, copy, modify,
+merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/render/packages/preview/oxifmt/0.2.1/README.md b/render/packages/preview/oxifmt/0.2.1/README.md
new file mode 100644
index 0000000..4782894
--- /dev/null
+++ b/render/packages/preview/oxifmt/0.2.1/README.md
@@ -0,0 +1,237 @@
+# typst-oxifmt (v0.2.1)
+
+A Typst library that brings convenient string formatting and interpolation through the `strfmt` function. Its syntax is taken directly from Rust's `format!` syntax, so feel free to read its page for more information (https://doc.rust-lang.org/std/fmt/); however, this README should have enough information and examples for all expected uses of the library. Only a few things aren't supported from the Rust syntax, such as the `p` (pointer) format type, or the `.*` precision specifier.
+
+A few extras (beyond the Rust-like syntax) will be added over time, though (feel free to drop suggestions at the repository: https://github.com/PgBiel/typst-oxifmt). The first "extra" so far is the `fmt-decimal-separator: "string"` parameter, which lets you customize the decimal separator for decimal numbers (floats) inserted into strings. E.g. `strfmt("Result: {}", 5.8, fmt-decimal-separator: ",")` will return the string `"Result: 5,8"` (comma instead of dot). See more below.
+
+**Compatible with:** [Typst](https://github.com/typst/typst) v0.4.0+
+
+## Table of Contents
+
+- [Usage](#usage)
+ - [Formatting options](#formatting-options)
+ - [Examples](#examples)
+ - [Grammar](#grammar)
+- [Issues and Contributing](#issues-and-contributing)
+- [Testing](#testing)
+- [Changelog](#changelog)
+- [License](#license)
+
+## Usage
+
+You can use this library through Typst's package manager (for Typst v0.6.0+):
+
+```typ
+#import "@preview/oxifmt:0.2.1": strfmt
+```
+
+For older Typst versions, download the `oxifmt.typ` file either from Releases or directly from the repository. Then, move it to your project's folder, and write at the top of your Typst file(s):
+
+```typ
+#import "oxifmt.typ": strfmt
+```
+
+Doing the above will give you access to the main function provided by this library (`strfmt`), which accepts a format string, followed by zero or more replacements to insert in that string (according to `{...}` formats inserted in that string), an optional `fmt-decimal-separator` parameter, and returns the formatted string, as described below.
+
+Its syntax is almost identical to Rust's `format!` (as specified here: https://doc.rust-lang.org/std/fmt/). You can escape formats by duplicating braces (`{{` and `}}` become `{` and `}`). Here's an example (see more examples in the file `tests/strfmt-tests.typ`):
+
+```typ
+#import "@preview/oxifmt:0.2.1": strfmt
+
+#let s = strfmt("I'm {}. I have {num} cars. I'm {0}. {} is {{cool}}.", "John", "Carl", num: 10)
+#assert.eq(s, "I'm John. I have 10 cars. I'm John. Carl is {cool}.")
+```
+
+Note that `{}` extracts positional arguments after the string sequentially (the first `{}` extracts the first one, the second `{}` extracts the second one, and so on), while `{0}`, `{1}`, etc. will always extract the first, the second etc. positional arguments after the string. Additionally, `{bananas}` will extract the named argument "bananas".
+
+### Formatting options
+
+You can use `{:spec}` to customize your output. See the Rust docs linked above for more info, but a summary is below.
+
+(You may also want to check out the examples at [Examples](#examples).)
+
+- Adding a `?` at the end of `spec` (that is, writing e.g. `{0:?}`) will call `repr()` to stringify your argument, instead of `str()`. Note that this only has an effect if your argument is a string, an integer, a float or a `label()` / `<label>` - for all other types (such as booleans or elements), `repr()` is always called (as `str()` is unsupported for those).
+ - For strings, `?` (and thus `repr()`) has the effect of printing them with double quotes. For floats, this ensures a `.0` appears after it, even if it doesn't have decimal digits. For integers, this doesn't change anything. Finally, for labels, the `<label>` (with `?`) is printed as `<label>` instead of `label`.
+ - **TIP:** Prefer to always use `?` when you're inserting something that isn't a string, number or label, in order to ensure consistent results even if the library eventually changes the non-`?` representation.
+- After the `:`, add e.g. `_<8` to align the string to the left, padding it with as many `_`s as necessary for it to be at least `8` characters long (for example). Replace `<` by `>` for right alignment, or `^` for center alignment. (If the `_` is omitted, it defaults to ' ' (aligns with spaces).)
+ - If you prefer to specify the minimum width (the `8` there) as a separate argument to `strfmt` instead, you can specify `argument$` in place of the width, which will extract it from the integer at `argument`. For example, `_^3$` will center align the output with `_`s, where the minimum width desired is specified by the fourth positional argument (index `3`), as an integer. This means that a call such as `strfmt("{:_^3$}", 1, 2, 3, 4)` would produce `"__1__"`, as `3$` would evaluate to `4` (the value at the fourth positional argument/index `3`). Similarly, `named$` would take the width from the argument with name `named`, if it is an integer (otherwise, error).
+- **For numbers:**
+ - Specify `+` after the `:` to ensure zero or positive numbers are prefixed with `+` before them (instead of having no sign). `-` is also accepted but ignored (negative numbers always specify their sign anyways).
+ - Use something like `:09` to add zeroes to the left of the number until it has at least 9 digits / characters.
+ - The `9` here is also a width, so the same comment from before applies (you can add `$` to take it from an argument to the `strfmt` function).
+ - Use `:.5` to ensure your float is represented with 5 decimal digits of precision (zeroes are added to the right if needed; otherwise, it is rounded, **not truncated**).
+ - Note that floating point inaccuracies can be sometimes observed here, which is an unfortunate current limitation.
+ - Similarly to `width`, the precision can also be specified via an argument with the `$` syntax: `.5$` will take the precision from the integer at argument number 5 (the sixth one), while `.test$` will take it from the argument named `test`.
+ - **Integers only:** Add `x` (lowercase hex) or `X` (uppercase) at the end of the `spec` to convert the number to hexadecimal. Also, `b` will convert it to binary, while `o` will convert to octal.
+ - Specify a hashtag, e.g. `#x` or `#b`, to prepend the corresponding base prefix to the base-converted number, e.g. `0xABC` instead of `ABC`.
+ - Add `e` or `E` at the end of the `spec` to ensure the number is represented in scientific notation (with `e` or `E` as the exponent separator, respectively).
+ - For decimal numbers (floats), you can specify `fmt-decimal-separator: ","` to `strfmt` to have the decimal separator be a comma instead of a dot, for example.
+ - To have this be the default, you can alias `strfmt`, such as using `#let strfmt = strfmt.with(fmt-decimal-separator: ",")`.
+ - Number spec arguments (such as `.5`) are ignored when the argument is not a number, but e.g. a string, even if it looks like a number (such as `"5"`).
+- Note that all spec arguments above **have to be specified in order** - if you mix up the order, it won't work properly!
+ - Check the grammar below for the proper order, but, in summary: fill (character) with align (`<`, `>` or `^`) -> sign (`+` or `-`) -> `#` -> `0` (for 0 left-padding of numbers) -> width (e.g. `8` from `08` or `9` from `-<9`) -> `.precision` -> spec type (`?`, `x`, `X`, `b`, `o`, `e`, `E`)).
+
+Some examples:
+
+```typ
+#import "@preview/oxifmt:0.2.1": strfmt
+
+#let s1 = strfmt("{0:?}, {test:+012e}, {1:-<#8x}", "hi", -74, test: 569.4)
+#assert.eq(s1, "\"hi\", +00005.694e2, -0x4a---")
+
+#let s2 = strfmt("{:_>+11.5}", 59.4)
+#assert.eq(s2, "__+59.40000")
+
+#let s3 = strfmt("Dict: {:!<10?}", (a: 5))
+#assert.eq(s3, "Dict: (a: 5)!!!!")
+```
+
+### Examples
+
+- **Inserting labels, text and numbers into strings:**
+```typ
+#import "@preview/oxifmt:0.2.1": strfmt
+
+#let s = strfmt("First: {}, Second: {}, Fourth: {3}, Banana: {banana} (brackets: {{escaped}})", 1, 2.1, 3, label("four"), banana: "Banana!!")
+#assert.eq(s, "First: 1, Second: 2.1, Fourth: four, Banana: Banana!! (brackets: {escaped})")
+```
+
+- **Forcing `repr()` with `{:?}`** (which adds quotes around strings, and other things - basically represents a Typst value):
+```typ
+#import "@preview/oxifmt:0.2.1": strfmt
+
+#let s = strfmt("The value is: {:?} | Also the label is {:?}", "something", label("label"))
+#assert.eq(s, "The value is: \"something\" | Also the label is <label>")
+```
+
+- **Inserting other types than numbers and strings** (for now, they will always use `repr()`, even without `{...:?}`, although that is more explicit):
+```typ
+#import "@preview/oxifmt:0.2.1": strfmt
+
+#let s = strfmt("Values: {:?}, {1:?}, {stuff:?}", (test: 500), ("a", 5.1), stuff: [a])
+#assert.eq(s, "Values: (test: 500), (\"a\", 5.1), [a]")
+```
+
+- **Padding to a certain width with characters:** Use `{:x<8}`, where `x` is the **character to pad with** (e.g. space or `_`, but can be anything), `<` is the **alignment of the original text** relative to the padding (can be `<` for left aligned (padding goes to the right), `>` for right aligned (padded to its left) and `^` for center aligned (padded at both left and right)), and `8` is the **desired total width** (padding will add enough characters to reach this width; if the replacement string already has this width, no padding will be added):
+```typ
+#import "@preview/oxifmt:0.2.1": strfmt
+
+#let s = strfmt("Left5 {:-<5}, Right6 {:=>6}, Center10 {centered: ^10?}, Left3 {tleft:_<3}", "xx", 539, tleft: "okay", centered: [a])
+#assert.eq(s, "Left5 xx---, Right6 ===539, Center10 [a] , Left3 okay")
+// note how 'okay' didn't suffer any padding at all (it already had at least the desired total width).
+```
+
+- **Padding numbers with zeroes to the left:** It's a similar functionality to the above, however you write `{:08}` for 8 characters (for instance) - note that any characters in the number's representation matter for width (including sign, dot and decimal part):
+```typ
+#import "@preview/oxifmt:0.2.1": strfmt
+
+#let s = strfmt("Left-padded7 numbers: {:07} {:07} {:07} {3:07}", 123, -344, 44224059, 45.32)
+#assert.eq(s, "Left-padded7 numbers: 0000123 -000344 44224059 0045.32")
+```
+
+- **Defining padding-to width using parameters, not literals:** If you want the desired replacement width (the `8` in `{:08}` or `{: ^8}`) to be passed via parameter (instead of being hardcoded into the format string), you can specify `parameter$` in place of the width, e.g. `{:02$}` to take it from the third positional parameter, or `{:a>banana$}` to take it from the parameter named `banana` - note that the chosen parameter **must be an integer** (desired total width):
+```typ
+#import "@preview/oxifmt:0.2.1": strfmt
+
+#let s = strfmt("Padding depending on parameter: {0:02$} and {0:a>banana$}", 432, 0, 5, banana: 9)
+#assert.eq(s, "Padding depending on parameter: 00432 aaaaaa432") // widths 5 and 9
+```
+
+- **Displaying `+` on positive numbers:** Just add a `+` at the "beginning", i.e., before the `#0` (if either is there), or after the custom fill and align (if it's there and not `0` - see [Grammar](#grammar) for the exact positioning), like so:
+```typ
+#import "@preview/oxifmt:0.2.1": strfmt
+
+#let s = strfmt("Some numbers: {:+} {:+08}; With fill and align: {:_<+8}; Negative (no-op): {neg:+}", 123, 456, 4444, neg: -435)
+#assert.eq(s, "Some numbers: +123 +0000456; With fill and align: +4444___; Negative (no-op): -435")
+
+```
+
+- **Converting numbers to bases 2, 8 and 16:** Use one of the following specifier types (i.e., characters which always go at the very end of the format): `b` (binary), `o` (octal), `x` (lowercase hexadecimal) or `X` (uppercase hexadecimal). You can also add a `#` between `+` and `0` (see the exact position at the [Grammar](#grammar)) to display a **base prefix** before the number (i.e. `0b` for binary, `0o` for octal and `0x` for hexadecimal):
+```typ
+#import "@preview/oxifmt:0.2.1": strfmt
+
+#let s = strfmt("Bases (10, 2, 8, 16(l), 16(U):) {0} {0:b} {0:o} {0:x} {0:X} | W/ prefixes and modifiers: {0:#b} {0:+#09o} {0:_>+#9X}", 124)
+#assert.eq(s, "Bases (10, 2, 8, 16(l), 16(U):) 124 1111100 174 7c 7C | W/ prefixes and modifiers: 0b1111100 +0o000174 ____+0x7C")
+```
+
+- **Picking float precision (right-extending with zeroes):** Add, at the end of the format (just before the spec type (such as `?`), if there's any), either `.precision` (hardcoded, e.g. `.8` for 8 decimal digits) or `.parameter$` (taking the precision value from the specified parameter, like with `width`):
+```typ
+#import "@preview/oxifmt:0.2.1": strfmt
+
+#let s = strfmt("{0:.8} {0:.2$} {0:.potato$}", 1.234, 0, 2, potato: 5)
+#assert.eq(s, "1.23400000 1.23 1.23400")
+```
+
+- **Scientific notation:** Use `e` (lowercase) or `E` (uppercase) as specifier types (can be combined with precision):
+```typ
+#import "@preview/oxifmt:0.2.1": strfmt
+
+#let s = strfmt("{0:e} {0:E} {0:+.9e} | {1:e} | {2:.4E}", 124.2312, 50, -0.02)
+#assert.eq(s, "1.242312e2 1.242312E2 +1.242312000e2 | 5e1 | -2.0000E-2")
+```
+
+- **Customizing the decimal separator on floats:** Just specify `fmt-decimal-separator: ","` (comma as an example):
+```typ
+#import "@preview/oxifmt:0.2.1": strfmt
+
+#let s = strfmt("{0} {0:.6} {0:.5e}", 1.432, fmt-decimal-separator: ",")
+#assert.eq(s, "1,432 1,432000 1,43200e0")
+```
+
+### Grammar
+
+Here's the grammar specification for valid format `spec`s (in `{name:spec}`), which is basically Rust's format:
+
+```
+format_spec := [[fill]align][sign]['#']['0'][width]['.' precision]type
+fill := character
+align := '<' | '^' | '>'
+sign := '+' | '-'
+width := count
+precision := count | '*'
+type := '' | '?' | 'x?' | 'X?' | identifier
+count := parameter | integer
+parameter := argument '$'
+```
+
+Note, however, that precision of type `.*` is not supported yet and will raise an error.
+
+## Issues and Contributing
+
+Please report any issues or send any contributions (through pull requests) to the repository at https://github.com/PgBiel/typst-oxifmt
+
+## Testing
+
+If you wish to contribute, you may clone the repository and test this package with the following commands (from the project root folder):
+
+```sh
+git clone https://github.com/PgBiel/typst-oxifmt
+cd typst-oxifmt/tests
+typst c strfmt-tests.typ --root ..
+```
+
+The tests succeeded if you received no error messages from the last command (please ensure you're using a supported Typst version).
+
+## Changelog
+
+### v0.2.1
+
+- Fixed formatting of UTF-8 strings. Before, strings with multi-byte UTF-8 codepoints would cause formatting inconsistencies or even crashes. ([Issue #6](https://github.com/PgBiel/typst-oxifmt/issues/6))
+- Fixed an inconsistency in negative number formatting. Now, it will always print a regular hyphen (e.g. '-2'), which is consistent with Rust's behavior; before, it would occasionally print a minus sign instead (as observed in a comment to [Issue #4](https://github.com/PgBiel/typst-oxifmt/issues/4)).
+- Added compatibility with Typst 0.8.0's new type system.
+
+### v0.2.0
+
+- The package's name is now `oxifmt`!
+- `oxifmt:0.2.0` is now available through Typst's Package Manager! You can now write `#import "@preview/oxifmt:0.2.0": strfmt` to use the library.
+- Greatly improved the README, adding a section for common examples.
+- Fixed negative numbers being formatted with two minus signs.
+- Fixed custom precision of floats not working when they are exact integers.
+
+### v0.1.0
+
+- Initial release, added `strfmt`.
+
+## License
+
+MIT-0 license (see the `LICENSE` file).
diff --git a/render/packages/preview/oxifmt/0.2.1/oxifmt.typ b/render/packages/preview/oxifmt/0.2.1/oxifmt.typ
new file mode 100644
index 0000000..1283f24
--- /dev/null
+++ b/render/packages/preview/oxifmt/0.2.1/oxifmt.typ
@@ -0,0 +1,510 @@
+// oxifmt v0.2.1
+
+// For compatibility with pre-0.8.0 Typst types, which were strings
+#let _int-type = type(0)
+#let _float-type = type(5.5)
+#let _str-type = type("")
+#let _label-type = type(<hello>)
+
+#let _strfmt_formatparser(s) = {
+ if type(s) != _str-type {
+ panic("String format parsing internal error: String format parser given non-string.")
+ }
+ let result = ()
+ let codepoints = s.codepoints()
+
+ // -- parsing state --
+ let current-fmt-span = none
+ let current-fmt-name = none
+ // if the last character was an unescaped {
+ let last-was-lbracket = false
+ // if the last character was an unescaped }
+ let last-was-rbracket = false
+
+ // -- procedures --
+ let write-format-span(last-i, result, current-fmt-span, current-fmt-name) = {
+ current-fmt-span.at(1) = last-i + 1 // end index
+ result.push((format: (name: current-fmt-name, span: current-fmt-span)))
+ current-fmt-span = none
+ current-fmt-name = none
+ (result, current-fmt-span, current-fmt-name)
+ }
+
+ // -- errors --
+ let excessive-lbracket() = {
+ panic("String format parsing error: Inserted a second, non-escaped { inside a {format specifier}. Did you forget to insert a } somewhere, or to escape the { with {{?")
+ }
+ let excessive-rbracket() = {
+ panic("String format parsing error: Inserted a stray } (doesn't match any { from before). Did you forget to insert a { somewhere, or to escape the } with }}?")
+ }
+ let missing-rbracket() = {
+ panic("String format parsing error: Reached end of string with an open format specifier {, but without a closing }. Did you forget to insert a right bracket, or to escape the { with {{?")
+ }
+
+ // -- parse loop --
+ let last-i = none
+ let i = 0
+ for character in codepoints {
+ if character == "{" {
+ // double l-bracket = escape
+ if last-was-lbracket {
+ last-was-lbracket = false // escape {{
+ last-was-rbracket = false
+ if current-fmt-span.at(0) == last-i {
+ current-fmt-span = none // cancel this span
+ current-fmt-name = none
+ }
+ if current-fmt-name != none {
+ // if in the middle of a larger span ({ ... {{ <-):
+ // add the escaped character to the format name
+ current-fmt-name += character
+ } else {
+ // outside a span ({...} {{ <-) => emit an 'escaped' token
+ result.push((escape: (escaped: "{", span: (last-i, i + 1))))
+ }
+
+ last-i = i
+ i += 1 // '{' is ASCII, so 1 byte
+ continue
+ }
+ if last-was-rbracket {
+ // { ... }{ <--- ok, close the previous span
+ (result, current-fmt-span, current-fmt-name) = write-format-span(last-i, result, current-fmt-span, current-fmt-name)
+ last-was-rbracket = false
+ }
+ if current-fmt-span == none {
+ // begin span
+ current-fmt-span = (i, none)
+ current-fmt-name = ""
+ }
+ last-was-lbracket = true
+ } else if character == "}" {
+ last-was-lbracket = false
+ if last-was-rbracket {
+ last-was-rbracket = false // escape }}
+ if current-fmt-name != none {
+ current-fmt-name += character
+ } else {
+ result.push((escape: (escaped: "}", span: (last-i, i + 1))))
+ }
+
+ last-i = i
+ i += 1 // '}' is ASCII, so 1 byte
+ continue
+ }
+ // delay closing the span to the next iteration
+ // in case this is an escaped }
+ last-was-rbracket = true
+ } else {
+ // { ... {A <--- non-escaped { inside larger {}
+ if last-was-lbracket and (current-fmt-span != none and current-fmt-span.at(0) != last-i) {
+ excessive-lbracket()
+ }
+ if last-was-rbracket {
+ if current-fmt-span == none {
+ // {...} }A <--- non-escaped } with no matching {
+ excessive-rbracket()
+ } else {
+ // { ... }A <--- ok, close the previous span
+ (result, current-fmt-span, current-fmt-name) = write-format-span(last-i, result, current-fmt-span, current-fmt-name)
+ }
+ }
+ // {abc <--- add character to the format name
+ if current-fmt-name != none {
+ current-fmt-name += character
+ }
+ last-was-lbracket = false
+ last-was-rbracket = false
+ }
+
+ last-i = i
+ i += character.len() // index must be in bytes, and a UTF-8 codepoint can have more than one byte
+ }
+ // { ...
+ if current-fmt-span != none {
+ if last-was-rbracket {
+ // ... } <--- ok, close span
+ (result, current-fmt-span, current-fmt-name) = write-format-span(last-i, result, current-fmt-span, current-fmt-name)
+ } else {
+ // {abcd| <--- string ended with unclosed span
+ missing-rbracket()
+ }
+ }
+
+ result
+}
+
+#let _strfmt_parse-fmt-name(name) = {
+ // {a:b} => separate 'a' from 'b'
+ // (also accepts {a}, {}, {0}, {:...})
+ let subparts = name.match(regex("^([^:]*)(?::(.*))?$")).captures
+ let name = subparts.at(0)
+ let extras = subparts.at(1)
+ let name = if type(name) != _str-type {
+ name
+ } else if name == "" {
+ none
+ } else if regex("^\\d+$") in name {
+ int(name)
+ } else {
+ name
+ }
+ (name, extras)
+}
+
+#let _strfmt_is-numeric-type(obj) = {
+ type(obj) in (_int-type, _float-type)
+}
+
+#let _strfmt_stringify(obj) = {
+ if type(obj) in (_int-type, _float-type) {
+ // Fix negative sign not being a hyphen
+ // for consistency with our rich formatting output
+ str(obj).replace("\u{2212}", "-")
+ } else if type(obj) in (_label-type, _str-type) {
+ str(obj)
+ } else {
+ repr(obj)
+ }
+}
+
+#let _strfmt_display-radix(num, radix, signed: true, lowercase: false) = {
+ let num = int(num)
+ if type(radix) != _int-type or num == 0 or radix <= 1 {
+ return "0"
+ }
+ let sign = if num < 0 and signed { "-" } else { "" }
+ let num = calc.abs(num)
+ let radix = calc.min(radix, 16)
+ let digits = if lowercase {
+ ("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f")
+ } else {
+ ("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F")
+ }
+ let result = ""
+
+ while (num > 0) {
+ let quot = calc.quo(num, radix)
+ let rem = calc.floor(calc.rem(num, radix))
+ let digit = digits.at(rem)
+ result = digit + result
+ num = quot
+ }
+
+ sign + result
+}
+
+#let _strfmt_with-precision(num, precision) = {
+ if precision == none {
+ return _strfmt_stringify(num)
+ }
+ let result = _strfmt_stringify(calc.round(float(num), digits: calc.min(50, precision)))
+ let digits-match = result.match(regex("^\\d+\\.(\\d+)$"))
+ let digits-len-diff = 0
+ if digits-match != none and digits-match.captures.len() > 0 {
+ // get the digits capture group; its length will be digit amount
+ let digits = digits-match.captures.first()
+ digits-len-diff = precision - digits.len()
+ } else if "." not in result { // 5.0 or something
+ // 0 digits! Difference will be exactly 'precision'
+ digits-len-diff = precision
+ }
+
+ // add missing zeroes for precision
+ if digits-len-diff > 0 {
+ if "." not in result {
+ result += "." // decimal separator missing
+ }
+ result += "0" * digits-len-diff
+ }
+
+ result
+}
+
+#let _strfmt_exp-format(num, exponent-sign: "e", base: 10, precision: none) = {
+ assert(_strfmt_is-numeric-type(num), message: "String formatter internal error: Cannot convert '" + repr(num) + "' to a number to obtain its scientific notation representation.")
+ let f = float(num)
+ let exponent = if f == 0 { 1 } else { calc.floor(calc.log(calc.abs(f), base: base)) }
+ let mantissa = f / calc.pow(10, exponent)
+ let mantissa = _strfmt_with-precision(mantissa, precision)
+
+ mantissa + exponent-sign + _strfmt_stringify(exponent)
+}
+
+// Parses {format:specslikethis}.
+// Rust's format spec grammar:
+/*
+format_spec := [[fill]align][sign]['#']['0'][width]['.' precision]type
+fill := character
+align := '<' | '^' | '>'
+sign := '+' | '-'
+width := count
+precision := count | '*'
+type := '' | '?' | 'x?' | 'X?' | identifier
+count := parameter | integer
+parameter := argument '$'
+*/
+#let _generate-replacement(fullname, extras, replacement, pos-replacements: (), named-replacements: (:), fmt-decimal-separator: auto) = {
+ if extras == none {
+ if not _strfmt_is-numeric-type(replacement) {
+ fmt-decimal-separator = auto
+ }
+ replacement = _strfmt_stringify(replacement)
+ if fmt-decimal-separator not in (auto, none) {
+ replacement = replacement.replace(".", _strfmt_stringify(fmt-decimal-separator))
+ }
+ return replacement
+ }
+ let extras = _strfmt_stringify(extras)
+ // note: usage of [\s\S] in regex to include all characters, incl. newline
+ // (dot format ignores newline)
+ let extra-parts = extras.match(
+ // fill align sign # 0 width(from param) width precision(from param) precision spectype
+ regex("^(?:([\\s\\S])?([<^>]))?([+-])?(#)?(0)?(?:(?:(\\d+)|([^.$]+))\$|(\\d+))?(?:\\.(?:(?:(\\d+)|([^$]+))\$|(\\d+|\*)))?([^\\s]*)\\s*$")
+ )
+ if extra-parts == none {
+ panic("String formatter error: Invalid format spec '" + extras + "', from '{" + fullname.replace("{", "{{").replace("}", "}}") + "}'. Try escaping the braces { } with {{ }} if you wanted to insert literal braces.")
+ }
+
+ let (fill, align, sign, hashtag, zero, width-posarg, width-namedarg, width-lit, precision-posarg, precision-namedarg, precision-lit, spectype) = extra-parts.captures
+
+ // 'count' type parameters in the spec (width, precision) can be either a literal number (123),
+ // a number referring to a positional argument (123$), or some text referring to a named argument (abc$).
+ // The final $ is mandatory for the last two cases.
+ let parse-count(lit, pos, named, spec-part-name: "unknown") = {
+ if lit != none {
+ int(lit)
+ } else if pos != none {
+ let i = int(pos)
+ assert(
+ pos-replacements.len() > 0,
+ message: "String formatter error: Attempted to use positional argument " + str(i) + " for " + spec-part-name + ", but no positional arguments were given (from '{" + fullname.replace("{", "{{").replace("}", "}}") + "}')."
+ )
+ assert(
+ i >= 0 and i < pos-replacements.len(),
+ message: "String formatter error: Attempted to use positional argument " + str(i) + " for " + spec-part-name + ", but there is no argument at that position (from '{" + fullname.replace("{", "{{").replace("}", "}}") + "}'). Please note that positional arguments start at position 0, and are specified in order after the format string in the 'strfmt' call."
+ )
+ let arg = pos-replacements.at(i)
+ assert(
+ type(arg) == _int-type,
+ message: "String formatter error: Attempted to use positional argument " + str(i) + " for " + spec-part-name + ", but it was a(n) '" + type(arg) + "', not an integer (from '{" + fullname.replace("{", "{{").replace("}", "}}") + "}')."
+ )
+
+ int(arg)
+ } else if named != none {
+ assert(
+ named-replacements.len() > 0,
+ message: "String formatter error: Attempted to use named argument '" + named + "' for " + spec-part-name + ", but no named arguments were given (from '{" + fullname.replace("{", "{{").replace("}", "}}") + "}')."
+ )
+ assert(
+ named in named-replacements,
+ message: "String formatter error: Attempted to use named argument '" + named + "' for " + spec-part-name + ", but there is no argument associated to that name (from '{" + fullname.replace("{", "{{").replace("}", "}}") + "}'). Ensure you pass that argument in the 'strfmt' call, e.g. strfmt(\"string {:.myarg$}\", 5.823, myarg: 10)."
+ )
+ let arg = named-replacements.at(named)
+ assert(
+ type(arg) == _int-type,
+ message: "String formatter error: Attempted to use named argument '" + named + "' for " + spec-part-name + ", but it was a(n) '" + type(arg) + "', not an integer (from '{" + fullname.replace("{", "{{").replace("}", "}}") + "}')."
+ )
+
+ int(arg)
+ } else {
+ none
+ }
+ }
+
+ if precision-lit == "*" {
+ panic("String formater error: Precision specification of type `.*` is not supported yet (from '{" + fullname.replace("{", "{{").replace("}", "}}") + "}'). Try specifying your desired precision directly on the format spec, e.g. `.5`, or through some argument, e.g. `.name$` to take it from the 'name' named argument.")
+ }
+
+ let align = if align == "" {
+ none
+ } else if align == "<" {
+ left
+ } else if align == ">" {
+ right
+ } else if align == "^" {
+ center
+ } else if align != none {
+ panic("String formatter error: Invalid alignment in the format spec: '" + align + "' (must be either '<', '^' or '>').")
+ }
+ let width = parse-count(width-lit, width-posarg, width-namedarg, spec-part-name: "width")
+ let width = if width == none { 0 } else { int(width) }
+ let precision = parse-count(precision-lit, precision-posarg, precision-namedarg, spec-part-name: "precision")
+ let hashtag = hashtag == "#"
+ let zero = zero == "0"
+ let hashtag-prefix = ""
+
+ let valid-specs = ("", "?", "b", "x", "X", "o", "x?", "X?", "e", "E")
+ let spec-error() = {
+ panic(
+ "String formatter error: Unknown spec type '" + spectype + "', from '{" + fullname.replace("{", "{{").replace("}", "}}") + "}'. Valid options include: '" + valid-specs.join("', '") + "'. Maybe you specified some invalid formatting spec syntax (after the ':'), which can also prompt this error. Check the oxifmt docs for more information.")
+ }
+ if spectype not in valid-specs {
+ spec-error()
+ }
+
+ let is-numeric = _strfmt_is-numeric-type(replacement)
+ if is-numeric {
+ if zero {
+ // disable fill, we will be prefixing with zeroes if necessary
+ fill = none
+ } else if fill == none {
+ fill = " "
+ zero = false
+ }
+ // default number alignment to right
+ if align == none {
+ align = right
+ }
+
+ // if + is specified, + will appear before all numbers >= 0.
+ if sign == "+" and replacement >= 0 {
+ sign = "+"
+ } else if replacement < 0 {
+ sign = "-"
+ } else {
+ sign = ""
+ }
+
+ // we'll add the sign back later!
+ replacement = calc.abs(replacement)
+
+ if spectype in ("e", "E") {
+ let exponent-sign = if spectype == "E" { "E" } else { "e" }
+ replacement = _strfmt_exp-format(calc.abs(replacement), exponent-sign: exponent-sign, precision: precision)
+ } else if type(replacement) != _int-type and precision != none {
+ replacement = _strfmt_with-precision(replacement, precision)
+ } else if type(replacement) == _int-type and spectype in ("x", "X", "b", "o", "x?", "X?") {
+ let radix-map = (x: 16, X: 16, "x?": 16, "X?": 16, b: 2, o: 8)
+ let radix = radix-map.at(spectype)
+ let lowercase = spectype.starts-with("x")
+ replacement = _strfmt_stringify(_strfmt_display-radix(replacement, radix, lowercase: lowercase, signed: false))
+ if hashtag {
+ let hashtag-prefix-map = ("16": "0x", "2": "0b", "8": "0o")
+ hashtag-prefix = hashtag-prefix-map.at(str(radix))
+ }
+ } else {
+ precision = none
+ replacement = if spectype.ends-with("?") {
+ repr(replacement)
+ } else {
+ _strfmt_stringify(replacement)
+ }
+ }
+ if fmt-decimal-separator not in (auto, none) {
+ replacement = replacement.replace(".", _strfmt_stringify(fmt-decimal-separator))
+ }
+ if zero {
+ let width-diff = width - (replacement.len() + sign.len() + hashtag-prefix.len())
+ if width-diff > 0 { // prefix with the appropriate amount of zeroes
+ replacement = ("0" * width-diff) + replacement
+ }
+ }
+ } else {
+ sign = ""
+ hashtag-prefix = ""
+ hashtag = false
+ zero = false
+ replacement = if spectype.ends-with("?") {
+ repr(replacement)
+ } else {
+ _strfmt_stringify(replacement)
+ }
+ if fill == none {
+ fill = " "
+ }
+ if align == none {
+ align = left
+ }
+ if precision != none and replacement.len() > precision {
+ replacement = replacement.slice(0, precision)
+ }
+ }
+
+ // use number prefixes parsed above
+ replacement = sign + hashtag-prefix + replacement
+
+ if fill != none {
+ // perform fill/width adjustments: "x" ---> " x" if width is 4
+ let width-diff = width - replacement.len() // number prefixes are also considered for width
+ if width-diff > 0 {
+ if align == left {
+ replacement = replacement + (fill * width-diff)
+ } else if align == right {
+ replacement = (fill * width-diff) + replacement
+ } else if align == center {
+ let width-fill = fill * (calc.ceil(float(width-diff) / 2))
+ replacement = width-fill + replacement + width-fill
+ }
+ }
+ }
+
+ replacement
+}
+
+#let strfmt(format, ..replacements) = {
+ if format == "" { return "" }
+ let formats = _strfmt_formatparser(format)
+ let num-replacements = replacements.pos()
+ let named-replacements = replacements.named()
+ let unnamed-format-index = 0
+ let fmt-decimal-separator = if "fmt-decimal-separator" in named-replacements { named-replacements.at("fmt-decimal-separator") } else { auto }
+
+ let parts = ()
+ let last-span-end = 0
+ for f in formats {
+ let replace-by = none
+ let replace-span = none
+ if "escape" in f {
+ replace-by = f.escape.escaped
+ replace-span = f.escape.span
+ } else if "format" in f {
+ let f = f.format
+ let (name, extras) = _strfmt_parse-fmt-name(f.name)
+ if name == none {
+ let fmt-index = unnamed-format-index
+ let amount-pos-replacements = num-replacements.len()
+ if amount-pos-replacements == 0 {
+ panic("String formatter error: Specified a {} (or similar) format to extract positional replacements, but none were given. Try specifying them sequentially after the format string, e.g. strfmt(\"{}, {}\", 5, 1+1) would become \"5, 2\".")
+ }
+ if amount-pos-replacements <= fmt-index {
+ let were-was = if amount-pos-replacements == 1 { "was" } else { "were" }
+ panic("String formatter error: Specified more {} (or similar) formats than positional replacements (only " + str(amount-pos-replacements) + " of them " + were-was + " given!). Please specify the missing positional arguments sequentially after the format string in the 'strfmt' call.")
+ }
+ replace-by = num-replacements.at(fmt-index)
+ unnamed-format-index += 1
+ } else if type(name) == _int-type {
+ let fmt-index = name
+ let amount-pos-replacements = num-replacements.len()
+ if amount-pos-replacements == 0 {
+ panic("String formatter error: format key '" + str(name) + "' would attempt to get a positional replacement, but none were given after the string. Try specifying positional replacements after the format string in the 'strfmt' call, e.g. strfmt(\"{1}, {0}\", 2, 3) would become \"3, 2\".")
+ }
+ if amount-pos-replacements <= fmt-index {
+ let were-was = if amount-pos-replacements == 1 { "was" } else { "were" }
+ panic("String formatter error: format key '" + str(name) + "', from '{" + f.name.replace("{", "{{").replace("}", "}}") + "}', is not a valid positional replacement position (only " + str(amount-pos-replacements) + " of them " + were-was + " given). Note that the first position is 0. For example, strfmt(\"{1}, {0}\", 2, 3) would become \"3, 2\".")
+ }
+ replace-by = num-replacements.at(fmt-index)
+ } else { // named replacement
+ if name not in named-replacements {
+ panic("String formatter error: format key '" + name + "', from '{" + f.name.replace("{", "{{").replace("}", "}}") + "}', does not match any given named replacement. Try specifying it after the format string, e.g. like so: strfmt(\"Test: {myarg}\", myarg: 1 + 1) would become \"Test: 2\".")
+ }
+ replace-by = named-replacements.at(name)
+ }
+ replace-by = _generate-replacement(f.name, extras, replace-by, pos-replacements: num-replacements, named-replacements: named-replacements, fmt-decimal-separator: fmt-decimal-separator)
+ replace-span = f.span
+ } else {
+ panic("String formatter error: Internal error (unexpected format received).")
+ }
+ // {...}ABCABCABC{...} <--- push ABCABCABC to parts
+ parts.push(format.slice(last-span-end, replace-span.at(0)))
+ // push the replacement string instead of the {...} at the end
+ parts.push(replace-by)
+ last-span-end = replace-span.at(1)
+ }
+ if last-span-end < format.len() {
+ parts.push(format.slice(last-span-end, format.len()))
+ }
+
+ // join all the string parts (constant parts + formatted parts + escaped parts)
+ parts.join()
+}
diff --git a/render/packages/preview/oxifmt/0.2.1/typst.toml b/render/packages/preview/oxifmt/0.2.1/typst.toml
new file mode 100644
index 0000000..6f680c1
--- /dev/null
+++ b/render/packages/preview/oxifmt/0.2.1/typst.toml
@@ -0,0 +1,8 @@
+[package]
+name = "oxifmt"
+version = "0.2.1"
+authors = ["PgBiel <https://github.com/PgBiel>"]
+license = "MIT-0"
+description = "Convenient Rust-like string formatting in Typst"
+entrypoint = "oxifmt.typ"
+repository = "https://github.com/PgBiel/typst-oxifmt"
diff --git a/render/packages/preview/oxifmt/1.0.0/LICENSE b/render/packages/preview/oxifmt/1.0.0/LICENSE
new file mode 100644
index 0000000..03f646f
--- /dev/null
+++ b/render/packages/preview/oxifmt/1.0.0/LICENSE
@@ -0,0 +1 @@
+MIT OR Apache-2.0
diff --git a/render/packages/preview/oxifmt/1.0.0/LICENSE-APACHE b/render/packages/preview/oxifmt/1.0.0/LICENSE-APACHE
new file mode 100644
index 0000000..71b8799
--- /dev/null
+++ b/render/packages/preview/oxifmt/1.0.0/LICENSE-APACHE
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright 2024 PgBiel
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/render/packages/preview/oxifmt/1.0.0/LICENSE-MIT b/render/packages/preview/oxifmt/1.0.0/LICENSE-MIT
new file mode 100644
index 0000000..869be70
--- /dev/null
+++ b/render/packages/preview/oxifmt/1.0.0/LICENSE-MIT
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2024 PgBiel
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/render/packages/preview/oxifmt/1.0.0/README.md b/render/packages/preview/oxifmt/1.0.0/README.md
new file mode 100644
index 0000000..288a53f
--- /dev/null
+++ b/render/packages/preview/oxifmt/1.0.0/README.md
@@ -0,0 +1,326 @@
+# typst-oxifmt (v1.0.0)
+
+A Typst library that brings convenient string formatting and interpolation through the `strfmt` function. Its syntax is taken directly from Rust's `format!` syntax, so feel free to read its page for more information (https://doc.rust-lang.org/std/fmt/); however, this README should have enough information and examples for all expected uses of the library. Only a few things aren't supported from the Rust syntax, such as the `p` (pointer) format type, or the `.*` precision specifier. Check out the ["Examples" section](#examples) for more.
+
+A few extras (beyond the Rust-like syntax) will be added over time, though (feel free to drop suggestions at the repository: https://github.com/PgBiel/typst-oxifmt). The first "extra" so far is the `fmt-decimal-separator: "string"` parameter, which lets you customize the decimal separator for decimal numbers (floats) inserted into strings. E.g. `strfmt("Result: {}", 5.8, fmt-decimal-separator: ",")` will return the string `"Result: 5,8"` (comma instead of dot). We also provide thousands separator support with `fmt-thousands-separator: "_"` for example. See more at ["Custom options"](#custom-options).
+
+**Compatible with:** [Typst](https://github.com/typst/typst) v0.7.0+
+
+## Quick examples
+
+```typ
+#import "@preview/oxifmt:1.0.0": strfmt
+
+// "User John has 10 apples."
+#strfmt("User {} has {} apples.", "John", 10)
+
+// "if exp > 100 { true }"
+#strfmt("if {var} > {num} {{ true }}", var: "exp", num: 100)
+
+// "1.10e2 meters (**wow**)"
+#strfmt("{:.2e} meters ({:*^7})", 110.0, "wow")
+
+// "20_000 players have more than +002,300 points."
+#strfmt(
+ "{} players have more than {:+08.3} points.",
+ 20000,
+ 2.3,
+ fmt-decimal-separator: ",",
+ fmt-thousands-separator: "_"
+)
+
+// "The byte value is 0x8C or 10001100"
+#strfmt("The byte value is {:#02X} or {0:08b}", 140)
+```
+
+## Table of Contents
+
+- [Usage](#usage)
+ - [Formatting options](#formatting-options)
+ - [Examples](#examples)
+ - [Custom options](#custom-options)
+ - [Grammar](#grammar)
+- [Issues and Contributing](#issues-and-contributing)
+- [Testing](#testing)
+- [Changelog](#changelog)
+- [License](#license)
+
+## Usage
+
+You can use this library through Typst's package manager (for Typst v0.6.0+):
+
+```typ
+#import "@preview/oxifmt:1.0.0": strfmt
+```
+
+For older Typst versions, download the `oxifmt.typ` file either from Releases or directly from the repository. Then, move it to your project's folder, and write at the top of your Typst file(s):
+
+```typ
+#import "oxifmt.typ": strfmt
+```
+
+Doing the above will give you access to the main function provided by this library (`strfmt`), which accepts a format string, followed by zero or more replacements to insert in that string (according to `{...}` formats inserted in that string), an optional `fmt-decimal-separator` parameter, and returns the formatted string, as described below.
+
+Its syntax is almost identical to Rust's `format!` (as specified here: https://doc.rust-lang.org/std/fmt/). You can escape formats by duplicating braces (`{{` and `}}` become `{` and `}`). Here's an example (see more examples in the file `tests/strfmt-tests.typ`):
+
+```typ
+#import "@preview/oxifmt:1.0.0": strfmt
+
+#let s = strfmt("I'm {}. I have {num} cars. I'm {0}. {} is {{cool}}.", "John", "Carl", num: 10)
+#assert.eq(s, "I'm John. I have 10 cars. I'm John. Carl is {cool}.")
+```
+
+Note that `{}` extracts positional arguments after the string sequentially (the first `{}` extracts the first one, the second `{}` extracts the second one, and so on), while `{0}`, `{1}`, etc. will always extract the first, the second etc. positional arguments after the string. Additionally, `{bananas}` will extract the named argument "bananas".
+
+### Formatting options
+
+You can use `{:spec}` to customize your output. See the Rust docs linked above for more info, but a summary is below.
+
+(You may also want to check out the examples at [Examples](#examples).)
+
+- Adding a `?` at the end of `spec` (that is, writing e.g. `{0:?}`) will call `repr()` to stringify your argument, instead of `str()`. Note that this only has an effect if your argument is a string, an integer, a float or a `label()` / `<label>` - for all other types (such as booleans or elements), `repr()` is always called (as `str()` is unsupported for those).
+ - For strings, `?` (and thus `repr()`) has the effect of printing them with double quotes. For floats, this ensures a `.0` appears after it, even if it doesn't have decimal digits. For integers, this doesn't change anything. Finally, for labels, the `<label>` (with `?`) is printed as `<label>` instead of `label`.
+ - **TIP:** Prefer to always use `?` when you're inserting something that isn't a string, number or label, in order to ensure consistent results even if the library eventually changes the non-`?` representation.
+- After the `:`, add e.g. `_<8` to align the string to the left, padding it with as many `_`s as necessary for it to be at least `8` characters long (for example). Replace `<` by `>` for right alignment, or `^` for center alignment. (If the `_` is omitted, it defaults to ' ' (aligns with spaces).)
+ - If you prefer to specify the minimum width (the `8` there) as a separate argument to `strfmt` instead, you can specify `argument$` in place of the width, which will extract it from the integer at `argument`. For example, `_^3$` will center align the output with `_`s, where the minimum width desired is specified by the fourth positional argument (index `3`), as an integer. This means that a call such as `strfmt("{v:_^3$}", 1, 2, 3, 4, v: 88)` would produce `"_88_"`, as `3$` would evaluate to `4` (the value at the fourth positional argument/index `3`). Similarly, `named$` would take the width from the argument with name `named`, if it is an integer (otherwise, error).
+- **For numbers:**
+ - Specify `+` after the `:` to ensure zero or positive numbers are prefixed with `+` before them (instead of having no sign). `-` is also accepted but ignored (negative numbers always specify their sign anyways).
+ - Use something like `:09` to add zeroes to the left of the number until it has at least 9 digits / characters.
+ - The `9` here is also a width, so the same comment from before applies (you can add `$` to take it from an argument to the `strfmt` function).
+ - Use `:.5` to ensure your float is represented with 5 decimal digits of precision (zeroes are added to the right if needed; otherwise, it is rounded, **not truncated**).
+ - Note that floating point inaccuracies can be sometimes observed here, which is an unfortunate current limitation.
+ - Similarly to `width`, the precision can also be specified via an argument with the `$` syntax: `.5$` will take the precision from the integer at argument number 5 (the sixth one), while `.test$` will take it from the argument named `test`.
+ - **Integers only:** Add `x` (lowercase hex) or `X` (uppercase) at the end of the `spec` to convert the number to hexadecimal. Also, `b` will convert it to binary, while `o` will convert to octal.
+ - Specify a hashtag, e.g. `#x` or `#b`, to prepend the corresponding base prefix to the base-converted number, e.g. `0xABC` instead of `ABC`.
+ - Add `e` or `E` at the end of the `spec` to ensure the number is represented in scientific notation (with `e` or `E` as the exponent separator, respectively).
+ - For decimal numbers (floats), you can specify `fmt-decimal-separator: ","` to `strfmt` to have the decimal separator be a comma instead of a dot, for example.
+ - To have this be the default, you can alias `strfmt`, such as using `#let strfmt = strfmt.with(fmt-decimal-separator: ",")`.
+ - You can enable thousands separators for numbers with `fmt-thousands-separator: "_"` to separate with an underscore, for example.
+ - By default, thousands separators are inserted after every third digit from the end of the number. Use `fmt-thousands-count: 2` to change that to every second digit as an example.
+ - Number spec arguments (such as `.5`) are ignored when the argument is not a number, but e.g. a string, even if it looks like a number (such as `"5"`).
+- Note that all spec arguments above **have to be specified in order** - if you mix up the order, it won't work properly!
+ - Check the grammar below for the proper order, but, in summary: fill (character) with align (`<`, `>` or `^`) -> sign (`+` or `-`) -> `#` -> `0` (for 0 left-padding of numbers) -> width (e.g. `8` from `08` or `9` from `-<9`) -> `.precision` -> spec type (`?`, `x`, `X`, `b`, `o`, `e`, `E`)).
+
+Some examples:
+
+```typ
+#import "@preview/oxifmt:1.0.0": strfmt
+
+#let s1 = strfmt("{0:?}, {test:+012e}, {1:-<#8x}", "hi", -74, test: 569.4)
+#assert.eq(s1, "\"hi\", +00005.694e2, -0x4a---")
+
+#let s2 = strfmt("{:_>+11.5}", 59.4)
+#assert.eq(s2, "__+59.40000")
+
+#let s3 = strfmt("Dict: {:!<10?}", (a: 5))
+#assert.eq(s3, "Dict: (a: 5)!!!!")
+```
+
+### Examples
+
+- **Inserting labels, text and numbers into strings:**
+```typ
+#import "@preview/oxifmt:1.0.0": strfmt
+
+#let s = strfmt("First: {}, Second: {}, Fourth: {3}, Banana: {banana} (brackets: {{escaped}})", 1, 2.1, 3, label("four"), banana: "Banana!!")
+#assert.eq(s, "First: 1, Second: 2.1, Fourth: four, Banana: Banana!! (brackets: {escaped})")
+```
+
+- **Forcing `repr()` with `{:?}`** (which adds quotes around strings, and other things - basically represents a Typst value):
+```typ
+#import "@preview/oxifmt:1.0.0": strfmt
+
+#let s = strfmt("The value is: {:?} | Also the label is {:?}", "something", label("label"))
+#assert.eq(s, "The value is: \"something\" | Also the label is <label>")
+```
+
+- **Inserting other types than numbers and strings** (for now, they will always use `repr()`, even without `{...:?}`, although that is more explicit):
+```typ
+#import "@preview/oxifmt:1.0.0": strfmt
+
+#let s = strfmt("Values: {:?}, {1:?}, {stuff:?}", (test: 500), ("a", 5.1), stuff: [a])
+#assert.eq(s, "Values: (test: 500), (\"a\", 5.1), [a]")
+```
+
+- **Padding to a certain width with characters:** Use `{:x<8}`, where `x` is the **character to pad with** (e.g. space or `_`, but can be anything), `<` is the **alignment of the original text** relative to the padding (can be `<` for left aligned (padding goes to the right), `>` for right aligned (padded to its left) and `^` for center aligned (padded at both left and right)), and `8` is the **desired total width** (padding will add enough characters to reach this width; if the replacement string already has this width, no padding will be added):
+```typ
+#import "@preview/oxifmt:1.0.0": strfmt
+
+#let s = strfmt("Left5 {:-<5}, Right6 {:=>6}, Center10 {centered: ^10?}, Left3 {tleft:_<3}", "xx", 539, tleft: "okay", centered: [a])
+#assert.eq(s, "Left5 xx---, Right6 ===539, Center10 [a] , Left3 okay")
+// note how 'okay' didn't suffer any padding at all (it already had at least the desired total width).
+```
+
+- **Padding numbers with zeroes to the left:** It's a similar functionality to the above, however you write `{:08}` for 8 characters (for instance) - note that any characters in the number's representation matter for width (including sign, dot and decimal part):
+```typ
+#import "@preview/oxifmt:1.0.0": strfmt
+
+#let s = strfmt("Left-padded7 numbers: {:07} {:07} {:07} {3:07}", 123, -344, 44224059, 45.32)
+#assert.eq(s, "Left-padded7 numbers: 0000123 -000344 44224059 0045.32")
+```
+
+- **Defining padding-to width using parameters, not literals:** If you want the desired replacement width (the `8` in `{:08}` or `{: ^8}`) to be passed via parameter (instead of being hardcoded into the format string), you can specify `parameter$` in place of the width, e.g. `{:02$}` to take it from the third positional parameter, or `{:a>banana$}` to take it from the parameter named `banana` - note that the chosen parameter **must be an integer** (desired total width):
+```typ
+#import "@preview/oxifmt:1.0.0": strfmt
+
+#let s = strfmt("Padding depending on parameter: {0:02$} and {0:a>banana$}", 432, 0, 5, banana: 9)
+#assert.eq(s, "Padding depending on parameter: 00432 aaaaaa432") // widths 5 and 9
+```
+
+- **Displaying `+` on positive numbers:** Just add a `+` at the "beginning", i.e., before the `#0` (if either is there), or after the custom fill and align (if it's there and not `0` - see [Grammar](#grammar) for the exact positioning), like so:
+```typ
+#import "@preview/oxifmt:1.0.0": strfmt
+
+#let s = strfmt("Some numbers: {:+} {:+08}; With fill and align: {:_<+8}; Negative (no-op): {neg:+}", 123, 456, 4444, neg: -435)
+#assert.eq(s, "Some numbers: +123 +0000456; With fill and align: +4444___; Negative (no-op): -435")
+
+```
+
+- **Converting numbers to bases 2, 8 and 16:** Use one of the following specifier types (i.e., characters which always go at the very end of the format): `b` (binary), `o` (octal), `x` (lowercase hexadecimal) or `X` (uppercase hexadecimal). You can also add a `#` between `+` and `0` (see the exact position at the [Grammar](#grammar)) to display a **base prefix** before the number (i.e. `0b` for binary, `0o` for octal and `0x` for hexadecimal):
+```typ
+#import "@preview/oxifmt:1.0.0": strfmt
+
+#let s = strfmt("Bases (10, 2, 8, 16(l), 16(U):) {0} {0:b} {0:o} {0:x} {0:X} | W/ prefixes and modifiers: {0:#b} {0:+#09o} {0:_>+#9X}", 124)
+#assert.eq(s, "Bases (10, 2, 8, 16(l), 16(U):) 124 1111100 174 7c 7C | W/ prefixes and modifiers: 0b1111100 +0o000174 ____+0x7C")
+```
+
+- **Picking float precision (right-extending with zeroes):** Add, at the end of the format (just before the spec type (such as `?`), if there's any), either `.precision` (hardcoded, e.g. `.8` for 8 decimal digits) or `.parameter$` (taking the precision value from the specified parameter, like with `width`):
+```typ
+#import "@preview/oxifmt:1.0.0": strfmt
+
+#let s = strfmt("{0:.8} {0:.2$} {0:.potato$}", 1.234, 0, 2, potato: 5)
+#assert.eq(s, "1.23400000 1.23 1.23400")
+```
+
+- **Scientific notation:** Use `e` (lowercase) or `E` (uppercase) as specifier types (can be combined with precision):
+```typ
+#import "@preview/oxifmt:1.0.0": strfmt
+
+#let s = strfmt("{0:e} {0:E} {0:+.9e} | {1:e} | {2:.4E}", 124.2312, 50, -0.02)
+#assert.eq(s, "1.242312e2 1.242312E2 +1.242312000e2 | 5e1 | -2.0000E-2")
+```
+
+### Custom options
+
+Oxifmt has some additional formatting options laid on top of Rust's, listed below with examples:
+
+- **Customizing the decimal separator on floats:** Just specify `fmt-decimal-separator: ","` (comma as an example):
+```typ
+#import "@preview/oxifmt:1.0.0": strfmt
+
+#let s = strfmt("{0} {0:.6} {0:.5e}", 1.432, fmt-decimal-separator: ",")
+#assert.eq(s, "1,432 1,432000 1,43200e0")
+```
+
+- **Displaying thousands separators on numbers:** Specify `fmt-thousands-separator: "_"` (underscore as an example - the default is `""` which disables the feature):
+```typ
+#import "@preview/oxifmt:1.0.0": strfmt
+
+#let s = strfmt("{}", 20000, fmt-thousands-separator: "_")
+#assert.eq(s, "20_000")
+```
+
+- **Customizing the distance between thousands separators:** Specify `fmt-thousands-count: 2` (2 as an example - the default is 3):
+```typ
+#import "@preview/oxifmt:1.0.0": strfmt
+
+#let s = strfmt("{}", 20000, fmt-thousands-count: 2, fmt-thousands-separator: "_")
+#assert.eq(s, "2_00_00")
+```
+
+- **Variable distances between thousands separators:** Specify `fmt-thousands-count: (3, 2)`, such that the rightmost (first) thousand will have 3 digits, then the second from the right will have 2 digits, and any further ones will have 2 digits as well (last group size is repeated):
+```typ
+#import "@preview/oxifmt:1.0.0": strfmt
+
+#let s = strfmt("{}", 1000000, fmt-thousands-count: (3, 2), fmt-thousands-separator: ",")
+#assert.eq(s, "10,00,000")
+```
+
+### Grammar
+
+Here's the grammar specification for valid format `spec`s (in `{name:spec}`), which is basically Rust's format:
+
+```
+format_spec := [[fill]align][sign]['#']['0'][width]['.' precision]type
+fill := character
+align := '<' | '^' | '>'
+sign := '+' | '-'
+width := count
+precision := count | '*'
+type := '' | '?' | 'x?' | 'X?' | identifier
+count := parameter | integer
+parameter := argument '$'
+```
+
+Note, however, that precision of type `.*` is not supported yet and will raise an error.
+
+## Issues and Contributing
+
+Please report any issues or send any contributions (through pull requests) to the repository at https://github.com/PgBiel/typst-oxifmt
+
+## Testing
+
+If you wish to contribute, you may clone the repository and test this package with the following commands (from the project root folder):
+
+```sh
+git clone https://github.com/PgBiel/typst-oxifmt
+cd typst-oxifmt/tests
+typst c strfmt-tests.typ --root ..
+```
+
+The tests succeeded if you received no error messages from the last command (please ensure you're using a supported Typst version).
+
+## Changelog
+
+### v1.0.0 (2025-06-04)
+
+`oxifmt` is two years old!
+
+- **Breaking change:** Replacement names can no longer contain braces for consistency with Rust. ([Issue #17](https://github.com/PgBiel/typst-oxifmt/issues/17))
+ - That is, `{a {{ b}` and `{a }} b}` are now errors.
+ - Braces inside replacement names cannot be escaped, and `}` ends the name eagerly.
+ - Leads to less apparent ambiguity in some cases, and is also what Rust does.
+- **Breaking change:** Private symbols are now hidden. This package's entrypoint now only exports the `strfmt` function. ([PR #26](https://github.com/PgBiel/typst-oxifmt/pull/26))
+ - Technically not a breaking change as these weren't intended for public usage, but worth giving some attention to anyway.
+- Added variably-sized thousands for insertion of separators through `fmt-thousands-count: (group 1 size, group 2 size, ..., remaining group sizes)`. This may be useful for certain numbering systems used in India. ([Issue #21](https://github.com/PgBiel/typst-oxifmt/issues/21))
+ - For instance, one may have a digit group of size 3 followed by any amount of size 2 groups using `strfmt("1000000", fmt-thousands-count: (3, 2), fmt-thousands-separator: ",")`, which outputs `10,00,000` (note that groups go from right to left, similarly to the numbers themselves).
+- Fixed an inconsistency with Rust where `{` and `}` would not be valid padding characters in format specifiers. The following is now valid: `{:{<5}` i.e. pad to 5 characters to the left with `{` (similarly for `}`). ([Issue #28](https://github.com/PgBiel/typst-oxifmt/issues/28))
+- Fixed an inconsistency with Rust where center-aligned padding could result in more than the specified width as padding was forced to be equal on both sides for perfect centering. Now, `strfmt("{:_^4}", "a")` will output `"_a__"` (exactly 4 characters, even if not perfectly centered) instead of `"__a__"` (5 characters). ([Issue #29](https://github.com/PgBiel/typst-oxifmt/issues/29))
+- Fixed a bug with scientific notation conversion for fixed-point `decimal` where certain digits would not be displayed. ([Issue #23](https://github.com/PgBiel/typst-oxifmt/issues/23))
+
+### v0.3.0 (2025-05-27)
+
+- **Breaking change:** Named replacements prefixed with `fmt-` are now an error. Those are reserved for future `oxifmt` options. ([Issue #15](https://github.com/PgBiel/typst-oxifmt/issues/15))
+ - For example, instead of `strfmt("{fmt-x}", fmt-x: 10)`, write `strfmt("{_fmt-x}, _fmt-x: 10")` instead (or some other name with a different prefix).
+- Added thousands separator support, configurable with `strfmt(format, fmt-thousands-count: 3, fmt-thousands-separator: "")`. The first option defines how many digits should appear between each separator, and the second option controls the separator itself (default is empty string, disabling it). ([Issue #5](https://github.com/PgBiel/typst-oxifmt/issues/5))
+ - For example, `strfmt("{}", 2000, fmt-thousands-separator: ",")` displays `"2,000"`.
+ - Within the same example, adding `fmt-thousands-count: 2` would display `20,00` instead.
+ - Numeric systems with irregular thousands separator distances will be supported in a future release.
+- Added support for numeric formatting of [fixed-point `decimal` numbers](https://typst.app/docs/reference/foundations/decimal/). They support the same format specifiers as floats, e.g. `{:e}` for exponential notation, `{:.3}` for a fixed precision and so on. ([Issue #11](https://github.com/PgBiel/typst-oxifmt/issues/11))
+- oxifmt is now dual-licensed as MIT or Apache-2.0 (previously just MIT).
+- Fixed some bugs when formatting `inf` and `NaN`.
+- Fixed a rare case of wrong usage of types in strings in internal code, which could cause oxifmt to generate an error in upcoming Typst v0.14. **It is recommended to upgrade oxifmt to avoid this problem.**
+ - However, this was only triggered when a very rare formatting option was used (dynamic precision specifiers, which have a dollar sign `$`, e.g. `{:.prec$}`), so existing code is unlikely to be affected. Still a good idea to upgrade, though.
+- Fixed exponential notation formatting with very large numbers. Note that they might need rounding to look good (e.g. `strfmt("{:.2e}", number)` instead of just `{:e}`), but they will no longer cause an error. ([Issue #16](https://github.com/PgBiel/typst-oxifmt/issues/16))
+
+### v0.2.1 (2024-05-08)
+
+- Fixed formatting of UTF-8 strings. Before, strings with multi-byte UTF-8 codepoints would cause formatting inconsistencies or even crashes. ([Issue #6](https://github.com/PgBiel/typst-oxifmt/issues/6))
+- Fixed an inconsistency in negative number formatting. Now, it will always print a regular hyphen (e.g. '-2'), which is consistent with Rust's behavior; before, it would occasionally print a minus sign instead (as observed in a comment to [Issue #4](https://github.com/PgBiel/typst-oxifmt/issues/4)).
+- Added compatibility with Typst 0.8.0's new type system.
+
+### v0.2.0 (2023-08-02)
+
+- The package's name is now `oxifmt`!
+- `oxifmt:0.2.0` is now available through Typst's Package Manager! You can now write `#import "@preview/oxifmt:0.2.0": strfmt` to use the library.
+- Greatly improved the README, adding a section for common examples.
+- Fixed negative numbers being formatted with two minus signs.
+- Fixed custom precision of floats not working when they are exact integers.
+
+### v0.1.0 (2023-06-04)
+
+- Initial release, added `strfmt`.
+
+## License
+
+Licensed under MIT or Apache-2.0, at your option.
diff --git a/render/packages/preview/oxifmt/1.0.0/lib.typ b/render/packages/preview/oxifmt/1.0.0/lib.typ
new file mode 100644
index 0000000..d2f7329
--- /dev/null
+++ b/render/packages/preview/oxifmt/1.0.0/lib.typ
@@ -0,0 +1 @@
+#import "oxifmt.typ": strfmt
diff --git a/render/packages/preview/oxifmt/1.0.0/oxifmt.typ b/render/packages/preview/oxifmt/1.0.0/oxifmt.typ
new file mode 100644
index 0000000..a26d651
--- /dev/null
+++ b/render/packages/preview/oxifmt/1.0.0/oxifmt.typ
@@ -0,0 +1,769 @@
+// oxifmt v0.2.1
+
+// For compatibility with pre-0.8.0 Typst types, which were strings
+#let _int-type = type(0)
+#let _float-type = type(5.5)
+#let _str-type = type("")
+#let _label-type = type(<hello>)
+#let _arr-type = type(())
+
+#let _minus-sign = "\u{2212}"
+#let using-080 = type(type(5)) != _str-type
+#let using-090 = using-080 and str(-1).codepoints().first() == _minus-sign
+#let using-0110 = using-090 and sys.version >= version(0, 11, 0)
+#let using-0120 = using-090 and sys.version >= version(0, 12, 0)
+
+#let _decimal = if using-0120 { decimal } else { none }
+
+#let _arr-chunks = if using-0110 {
+ array.chunks
+} else {
+ (arr, chunks) => {
+ let i = 0
+ let res = ()
+ for element in arr {
+ if i == 0 {
+ res.push(())
+ i = chunks
+ }
+ res.last().push(element)
+ i -= 1
+ }
+ res
+ }
+}
+
+// Splits an array into dynamic chunk sizes.
+// 'chunks' is an array e.g. (1, 2, 3) indicating
+// the sizes of each chunk. The last size is repeated if there
+// are more elements than the chunks combined can cover.
+//
+// For example, if arr = ("a", "b", "c", "d", "e", "f", "g", "h", "i") and
+// chunks = (2, 3), this will return
+// (("a", "b"), ("c", "d", "e"), ("f", "g", "h"), ("i",))
+#let _arr-dyn-chunks(arr, chunks) = {
+ let i = 0
+ let res = ()
+ let chunk-i = 0
+ if chunks == () {
+ return ()
+ }
+
+ for element in arr {
+ if i == 0 {
+ res.push(())
+ i = chunks.at(chunk-i)
+ if i <= 0 {
+ assert(false, message: "String formatter error: internal error: received chunk of invalid size")
+ }
+ if chunk-i + 1 != chunks.len() {
+ chunk-i += 1
+ }
+ }
+ res.last().push(element)
+ i -= 1
+ }
+ res
+}
+
+#let _float-is-nan = if using-0110 {
+ float.is-nan
+} else {
+ x => type(x) == _float-type and "NaN" in repr(x)
+}
+
+#let _float-is-infinite = if using-0110 {
+ float.is-infinite
+} else {
+ x => type(x) == _float-type and "inf" in repr(x)
+}
+
+#let _strfmt_formatparser(s) = {
+ if type(s) != _str-type {
+ panic("String format parsing internal error: String format parser given non-string.")
+ }
+ let result = ()
+ let codepoints = s.codepoints()
+
+ // -- parsing state --
+ let current-fmt-span = none
+ let current-fmt-name = none
+ // if we're at {abc:|, i.e. right after a colon in {}
+ let last-was-fmt-colon = false
+ // if the last character was an unescaped {
+ let last-was-lbracket = false
+ // if the last character was an unescaped }
+ let last-was-rbracket = false
+
+ // -- procedures --
+ let write-format-span(last-i, result, current-fmt-span, current-fmt-name) = {
+ current-fmt-span.at(1) = last-i + 1 // end index
+ result.push((format: (name: current-fmt-name, span: current-fmt-span)))
+ current-fmt-span = none
+ current-fmt-name = none
+ (result, current-fmt-span, current-fmt-name)
+ }
+
+ // -- errors --
+ let excessive-lbracket() = {
+ panic("String format parsing error: Inserted a second, non-escaped { inside a {format specifier}. Did you forget to insert a } somewhere, or to escape the { with {{?")
+ }
+ let excessive-rbracket() = {
+ panic("String format parsing error: Inserted a stray } (doesn't match any { from before). Did you forget to insert a { somewhere, or to escape the } with }}?")
+ }
+ let missing-rbracket() = {
+ panic("String format parsing error: Reached end of string with an open format specifier {, but without a closing }. Did you forget to insert a right bracket, or to escape the { with {{?")
+ }
+
+ // -- parse loop --
+ let last-i = none
+ let i = 0
+ let code-i = 0
+ for character in codepoints {
+ if character == "{" {
+ // double l-bracket = escape
+ if last-was-lbracket {
+ last-was-lbracket = false // escape {{
+ last-was-rbracket = false
+ if current-fmt-span.at(0) == last-i {
+ // outside a span ({...} {{ <-) => emit an 'escaped' token
+ current-fmt-span = none // cancel this span
+ current-fmt-name = none
+ result.push((escape: (escaped: "{", span: (last-i, i + 1))))
+ } else {
+ panic("String formatter error: internal error: invalid left bracket state")
+ }
+ } else if current-fmt-span == none {
+ // begin span
+ current-fmt-span = (i, none)
+ current-fmt-name = ""
+
+ // indicate we just started a span
+ // in case it is escaped right afterwards
+ last-was-lbracket = true
+ } else if last-was-fmt-colon and codepoints.len() > code-i + 1 and codepoints.at(code-i + 1) in ("<", "^", ">") {
+ // don't error on mid-span { if this { might be used for padding
+ // 'escape' it right away
+ // e.g. {a:{<5} => formats "bc" as "{{{bc"
+ current-fmt-name += character
+ last-was-lbracket = false
+ } else {
+ // if in the middle of a larger span ({ ... { <-):
+ // error
+ excessive-lbracket()
+ }
+
+ last-was-fmt-colon = false
+ } else if character == "}" {
+ last-was-lbracket = false
+ if current-fmt-span == none {
+ if last-was-rbracket {
+ last-was-rbracket = false // escape }}
+ result.push((escape: (escaped: "}", span: (last-i, i + 1))))
+ } else {
+ // delay erroring on unmatched } to the next iteration
+ // in case this is an escaped }
+ last-was-rbracket = true
+ }
+ } else if last-was-fmt-colon and codepoints.len() > code-i + 1 and codepoints.at(code-i + 1) in ("<", "^", ">") {
+ // don't close span with } if this } might be used for padding
+ // e.g. {a:}<5} => formats "bc" as "}}}bc"
+ current-fmt-name += character
+ last-was-rbracket = false
+ } else {
+ // { ... } <--- ok, close the previous span
+ // Do this eagerly, escaping } inside { ... } is invalid
+ (result, current-fmt-span, current-fmt-name) = write-format-span(i, result, current-fmt-span, current-fmt-name)
+ }
+
+ last-was-fmt-colon = false
+ } else {
+ if last-was-rbracket {
+ if current-fmt-span == none {
+ // {...} }A <--- non-escaped } with no matching {
+ excessive-rbracket()
+ } else {
+ // { ... }A <--- span should have been eagerly closed already
+ panic("String formatter error: internal error: invalid right bracket state")
+ }
+ }
+
+ if current-fmt-name == none {
+ last-was-fmt-colon = false
+ } else {
+ // {abc <--- add character to the format name
+ current-fmt-name += character
+ last-was-fmt-colon = character == ":"
+ }
+ last-was-lbracket = false
+ last-was-rbracket = false
+ }
+
+ last-i = i
+ i += character.len() // index must be in bytes, and a UTF-8 codepoint can have more than one byte
+ code-i += 1
+ }
+ // { ...
+ if current-fmt-span != none {
+ if last-was-rbracket {
+ // ... } <--- ok, close span
+ (result, current-fmt-span, current-fmt-name) = write-format-span(last-i, result, current-fmt-span, current-fmt-name)
+ last-was-fmt-colon = false
+ } else {
+ // {abcd| <--- string ended with unclosed span
+ missing-rbracket()
+ }
+ } else if last-was-rbracket {
+ // } <--- unmatched and unescaped } at the very end
+ excessive-rbracket()
+ }
+
+ result
+}
+
+#let _strfmt_parse-fmt-name(name) = {
+ // {a:b} => separate 'a' from 'b'
+ // (also accepts {a}, {}, {0}, {:...})
+ let (name, ..extras) = name.split(":")
+ let name = if type(name) != _str-type {
+ name
+ } else if name == "" {
+ none
+ } else if name.codepoints().all(x => x == "0" or x == "1" or x == "2" or x == "3" or x == "4" or x == "5" or x == "6" or x == "7" or x == "8" or x == "9") {
+ int(name)
+ } else {
+ name
+ }
+ (name, extras.join())
+}
+
+#let _strfmt_is-numeric-type(obj) = {
+ type(obj) in (_int-type, _float-type, _decimal)
+}
+
+#let _strfmt_stringify(obj) = {
+ if type(obj) == _float-type {
+ if _float-is-infinite(obj) {
+ // Fix 0.12.0 inf string inconsistency
+ if obj < 0 { "-" } else { "" } + "inf"
+ } else {
+ // Fix negative sign not being a hyphen
+ // for consistency with our rich formatting output
+ str(obj).replace("\u{2212}", "-")
+ }
+ } else if type(obj) == _int-type {
+ str(obj).replace("\u{2212}", "-")
+ } else if type(obj) in (_label-type, _str-type, _decimal) {
+ str(obj)
+ } else {
+ repr(obj)
+ }
+}
+
+#let _strfmt_display-radix(num, radix, signed: true, lowercase: false) = {
+ let num = int(num)
+ if type(radix) != _int-type or num == 0 or radix <= 1 {
+ return "0"
+ }
+
+ // Note: only integers are accepted here, so no need to check for decimal signed zero
+ let sign = if num < 0 and signed { "-" } else { "" }
+ let num = calc.abs(num)
+ let radix = calc.min(radix, 16)
+ let digits = if lowercase {
+ ("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f")
+ } else {
+ ("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F")
+ }
+ let result = ""
+
+ while (num > 0) {
+ let quot = calc.quo(num, radix)
+ let rem = calc.floor(calc.rem(num, radix))
+ let digit = digits.at(rem)
+ result = digit + result
+ num = quot
+ }
+
+ sign + result
+}
+
+#let _strfmt_with-precision(num, precision) = {
+ if precision == none {
+ return _strfmt_stringify(num)
+ }
+ let result = _strfmt_stringify(calc.round(if type(num) == _decimal { num } else { float(num) }, digits: calc.min(50, precision)))
+ let digits-match = result.match(regex("^\\d+\\.(\\d+)$"))
+ let digits-len-diff = 0
+ if digits-match != none and digits-match.captures.len() > 0 {
+ // get the digits capture group; its length will be digit amount
+ let digits = digits-match.captures.first()
+ digits-len-diff = precision - digits.len()
+ } else if "." not in result { // 5.0 or something
+ // 0 digits! Difference will be exactly 'precision'
+ digits-len-diff = precision
+ }
+
+ // add missing zeroes for precision
+ if digits-len-diff > 0 {
+ if "." not in result {
+ result += "." // decimal separator missing
+ }
+ result += "0" * digits-len-diff
+ }
+
+ result
+}
+
+#let _strfmt_exp-format(num, exponent-sign: "e", precision: none) = {
+ assert(_strfmt_is-numeric-type(num), message: "String formatter internal error: Cannot convert '" + repr(num) + "' to a number to obtain its scientific notation representation.")
+
+ if type(num) == _decimal {
+ // Normalize signed zero
+ let num = if num == 0 { _decimal("0") } else { num }
+ let (integral, ..fractional) = str(num).split(".")
+ // Normalize decimals with larger scales than is needed
+ let fractional = fractional.sum(default: "").trim("0", at: end)
+ let (integral, fractional, exponent) = if num > -1 and num < 1 and fractional != "" {
+ let first-non-zero = fractional.codepoints().position(s => s != "0")
+ assert(first-non-zero != none, message: "String formatter internal error: expected non-zero fractional digit")
+
+ // Integral part is zero
+ // Convert 0.00012345 -> 1.2345
+ // Position of first non-zero is the amount of zeroes - 1
+ // (e.g. above, position of 1 is 3 => 3 zeroes,
+ // so exponent is -3 - 1 = -4)
+ (
+ fractional.at(first-non-zero),
+ fractional.slice(first-non-zero + 1),
+ -first-non-zero - 1
+ )
+ } else {
+ // Number has non-zero integral part, or is zero
+ // Convert 12345.6789 -> 1.23456789
+ // Exponent is integral digits - 1
+ (
+ integral.at(0),
+ integral.slice(1) + fractional,
+ integral.len() - 1
+ )
+ }
+ return (
+ // mantissa
+ integral + if fractional != "" { "." + fractional } else { "" },
+ exponent-sign + _strfmt_stringify(exponent)
+ )
+ }
+
+ let f = float(num)
+ let exponent = if f == 0 { 1 } else { calc.floor(calc.log(calc.abs(f), base: 10)) }
+ let mantissa = f / calc.pow(10.0, exponent)
+ let mantissa = _strfmt_with-precision(mantissa, precision)
+
+ (mantissa, exponent-sign + _strfmt_stringify(exponent))
+}
+
+// Parses {format:specslikethis}.
+// Rust's format spec grammar:
+/*
+format_spec := [[fill]align][sign]['#']['0'][width]['.' precision]type
+fill := character
+align := '<' | '^' | '>'
+sign := '+' | '-'
+width := count
+precision := count | '*'
+type := '' | '?' | 'x?' | 'X?' | identifier
+count := parameter | integer
+parameter := argument '$'
+*/
+#let _generate-replacement(
+ fullname, extras, replacement,
+ pos-replacements: (), named-replacements: (:),
+ fmt-decimal-separator: auto,
+ fmt-thousands-count: 3,
+ fmt-thousands-separator: ""
+) = {
+ if extras == none {
+ let is-numeric = _strfmt_is-numeric-type(replacement)
+
+ if is-numeric {
+ let is-nan = type(replacement) == _float-type and _float-is-nan(replacement)
+ let is-inf = type(replacement) == _float-type and _float-is-infinite(replacement)
+ let string-replacement = _strfmt_stringify(calc.abs(replacement))
+ let sign = if (
+ not is-nan and replacement < 0
+ or replacement == 0 and type(replacement) == _decimal and (
+ // Preserve signed zero decimal
+ "-" in str(replacement) or _minus-sign in str(replacement)
+ )
+ ) {
+ "-"
+ } else {
+ ""
+ }
+ let (integral, ..fractional) = string-replacement.split(".")
+ if fmt-thousands-separator != "" and not is-nan and not is-inf {
+ let digit-groups = if type(fmt-thousands-count) == _arr-type {
+ _arr-dyn-chunks(integral.codepoints().rev(), fmt-thousands-count)
+ } else {
+ _arr-chunks(integral.codepoints().rev(), fmt-thousands-count)
+ }
+ integral = digit-groups
+ .join(fmt-thousands-separator.codepoints().rev())
+ .rev()
+ .join()
+ }
+
+ if fractional.len() > 0 {
+ let decimal-separator = if fmt-decimal-separator not in (auto, none) { _strfmt_stringify(fmt-decimal-separator) } else { "." }
+ return sign + integral + decimal-separator + fractional.first()
+ } else {
+ return sign + integral
+ }
+ } else {
+ return _strfmt_stringify(replacement)
+ }
+ }
+ let extras = _strfmt_stringify(extras)
+ // note: usage of [\s\S] in regex to include all characters, incl. newline
+ // (dot format ignores newline)
+ let extra-parts = extras.match(
+ // fill align sign # 0 width(from param) width precision(from param) precision spectype
+ regex("^(?:([\\s\\S])?([<^>]))?([+-])?(#)?(0)?(?:(?:(\\d+)|([^.$]+))\$|(\\d+))?(?:\\.(?:(?:(\\d+)|([^$]+))\$|(\\d+|\*)))?([^\\s]*)\\s*$")
+ )
+ if extra-parts == none {
+ panic("String formatter error: Invalid format spec '" + extras + "', from '{" + fullname.replace("{", "{{").replace("}", "}}") + "}'. Try escaping the braces { } with {{ }} if you wanted to insert literal braces.")
+ }
+
+ let (fill, align, sign, hashtag, zero, width-posarg, width-namedarg, width-lit, precision-posarg, precision-namedarg, precision-lit, spectype) = extra-parts.captures
+
+ // 'count' type parameters in the spec (width, precision) can be either a literal number (123),
+ // a number referring to a positional argument (123$), or some text referring to a named argument (abc$).
+ // The final $ is mandatory for the last two cases.
+ let parse-count(lit, pos, named, spec-part-name: "unknown") = {
+ if lit != none {
+ int(lit)
+ } else if pos != none {
+ let i = int(pos)
+ assert(
+ pos-replacements.len() > 0,
+ message: "String formatter error: Attempted to use positional argument " + str(i) + " for " + spec-part-name + ", but no positional arguments were given (from '{" + fullname.replace("{", "{{").replace("}", "}}") + "}')."
+ )
+ assert(
+ i >= 0 and i < pos-replacements.len(),
+ message: "String formatter error: Attempted to use positional argument " + str(i) + " for " + spec-part-name + ", but there is no argument at that position (from '{" + fullname.replace("{", "{{").replace("}", "}}") + "}'). Please note that positional arguments start at position 0, and are specified in order after the format string in the 'strfmt' call."
+ )
+ let arg = pos-replacements.at(i)
+ assert(
+ type(arg) == _int-type,
+ message: "String formatter error: Attempted to use positional argument " + str(i) + " for " + spec-part-name + ", but it was a(n) '" + str(type(arg)) + "', not an integer (from '{" + fullname.replace("{", "{{").replace("}", "}}") + "}')."
+ )
+
+ int(arg)
+ } else if named != none {
+ assert(
+ named-replacements.len() > 0,
+ message: "String formatter error: Attempted to use named argument '" + named + "' for " + spec-part-name + ", but no named arguments were given (from '{" + fullname.replace("{", "{{").replace("}", "}}") + "}')."
+ )
+ assert(
+ named in named-replacements,
+ message: "String formatter error: Attempted to use named argument '" + named + "' for " + spec-part-name + ", but there is no argument associated to that name (from '{" + fullname.replace("{", "{{").replace("}", "}}") + "}'). Ensure you pass that argument in the 'strfmt' call, e.g. strfmt(\"string {:.myarg$}\", 5.823, myarg: 10)."
+ )
+ let arg = named-replacements.at(named)
+ assert(
+ type(arg) == _int-type,
+ message: "String formatter error: Attempted to use named argument '" + named + "' for " + spec-part-name + ", but it was a(n) '" + str(type(arg)) + "', not an integer (from '{" + fullname.replace("{", "{{").replace("}", "}}") + "}')."
+ )
+
+ int(arg)
+ } else {
+ none
+ }
+ }
+
+ if precision-lit == "*" {
+ panic("String formatter error: Precision specification of type `.*` is not supported yet (from '{" + fullname.replace("{", "{{").replace("}", "}}") + "}'). Try specifying your desired precision directly on the format spec, e.g. `.5`, or through some argument, e.g. `.name$` to take it from the 'name' named argument.")
+ }
+
+ let align = if align == "" {
+ none
+ } else if align == "<" {
+ left
+ } else if align == ">" {
+ right
+ } else if align == "^" {
+ center
+ } else if align != none {
+ panic("String formatter error: Invalid alignment in the format spec: '" + align + "' (must be either '<', '^' or '>').")
+ }
+ let width = parse-count(width-lit, width-posarg, width-namedarg, spec-part-name: "width")
+ let width = if width == none { 0 } else { int(width) }
+ let precision = parse-count(precision-lit, precision-posarg, precision-namedarg, spec-part-name: "precision")
+ let hashtag = hashtag == "#"
+ let zero = zero == "0"
+ let hashtag-prefix = ""
+
+ let valid-specs = ("", "?", "b", "x", "X", "o", "x?", "X?", "e", "E")
+ let spec-error() = {
+ panic(
+ "String formatter error: Unknown spec type '" + spectype + "', from '{" + fullname.replace("{", "{{").replace("}", "}}") + "}'. Valid options include: '" + valid-specs.join("', '") + "'. Maybe you specified some invalid formatting spec syntax (after the ':'), which can also prompt this error. Check the oxifmt docs for more information.")
+ }
+ if spectype not in valid-specs {
+ spec-error()
+ }
+
+ if _strfmt_is-numeric-type(replacement) {
+ let is-nan = type(replacement) == _float-type and _float-is-nan(replacement)
+ let is-inf = type(replacement) == _float-type and _float-is-infinite(replacement)
+ if zero {
+ // disable fill, we will be prefixing with zeroes if necessary
+ fill = none
+ } else if fill == none {
+ fill = " "
+ zero = false
+ }
+ // default number alignment to right
+ if align == none {
+ align = right
+ }
+
+ if replacement == 0 and type(replacement) == _decimal {
+ // Preserve signed zero.
+ if "-" in str(replacement) or _minus-sign in str(replacement) {
+ sign = "-"
+ } else if sign == "+" {
+ sign = "+"
+ } else {
+ sign = ""
+ }
+ } else if sign == "+" and not is-nan and replacement >= 0 {
+ // if + is specified, + will appear before all numbers >= 0.
+ sign = "+"
+ } else if not is-nan and replacement < 0 {
+ sign = "-"
+ } else {
+ sign = ""
+ }
+
+ // we'll add the sign back later!
+ replacement = calc.abs(replacement)
+
+ // Separate integral from fractional parts
+ // We'll recompose them later
+ let integral = ""
+ let fractional = ()
+ let exponent-suffix = ""
+
+ if spectype in ("e", "E") and not is-nan and not is-inf {
+ let exponent-sign = if spectype == "E" { "E" } else { "e" }
+ let (mantissa, exponent) = _strfmt_exp-format(calc.abs(replacement), exponent-sign: exponent-sign, precision: precision)
+ (integral, ..fractional) = mantissa.split(".")
+ exponent-suffix = exponent
+ } else if type(replacement) != _int-type and precision != none and not is-nan and not is-inf {
+ let new-replacement = _strfmt_with-precision(replacement, precision)
+ (integral, ..fractional) = new-replacement.split(".")
+ } else if type(replacement) == _int-type and spectype in ("x", "X", "b", "o", "x?", "X?") {
+ let radix-map = (x: 16, X: 16, "x?": 16, "X?": 16, b: 2, o: 8)
+ let radix = radix-map.at(spectype)
+ let lowercase = spectype.starts-with("x")
+ integral = _strfmt_stringify(_strfmt_display-radix(replacement, radix, lowercase: lowercase, signed: false))
+ if hashtag {
+ let hashtag-prefix-map = ("16": "0x", "2": "0b", "8": "0o")
+ hashtag-prefix = hashtag-prefix-map.at(str(radix))
+ }
+ } else {
+ precision = none
+ let new-replacement = if spectype.ends-with("?") {
+ let repr-res = repr(replacement)
+ if using-090 and not using-0110 and type(replacement) == _float-type and "." not in repr-res {
+ // Workaround for repr inconsistency in Typst 0.9.0 and 0.10.0
+ repr-res + ".0"
+ } else {
+ repr-res
+ }
+ } else {
+ _strfmt_stringify(replacement)
+ }
+ (integral, ..fractional) = new-replacement.split(".")
+ }
+
+ let decimal-separator = if fmt-decimal-separator not in (auto, none) { _strfmt_stringify(fmt-decimal-separator) } else { "." }
+ let replaced-fractional = if fractional.len() > 0 { decimal-separator + fractional.join(decimal-separator) } else { "" }
+ let exponent-suffix = exponent-suffix.replace(".", decimal-separator)
+
+ if zero {
+ let width-diff = width - (integral.len() + replaced-fractional.codepoints().len() + sign.len() + hashtag-prefix.len() + exponent-suffix.codepoints().len())
+ if width-diff > 0 { // prefix with the appropriate amount of zeroes
+ integral = ("0" * width-diff) + integral
+ }
+ }
+
+ // Format with thousands AFTER zeroes, but BEFORE applying textual prefixes
+ if fmt-thousands-separator != "" and not is-nan and not is-inf {
+ let digit-groups = if type(fmt-thousands-count) == _arr-type {
+ _arr-dyn-chunks(integral.codepoints().rev(), fmt-thousands-count)
+ } else {
+ _arr-chunks(integral.codepoints().rev(), fmt-thousands-count)
+ }
+ integral = digit-groups
+ .join(fmt-thousands-separator.codepoints().rev())
+ .rev()
+ .join()
+ }
+
+ replacement = integral + replaced-fractional + exponent-suffix
+ } else {
+ sign = ""
+ hashtag-prefix = ""
+ hashtag = false
+ zero = false
+ replacement = if spectype.ends-with("?") {
+ repr(replacement)
+ } else {
+ _strfmt_stringify(replacement)
+ }
+ if fill == none {
+ fill = " "
+ }
+ if align == none {
+ align = left
+ }
+ if precision != none and replacement.len() > precision {
+ replacement = replacement.slice(0, precision)
+ }
+ }
+
+ // use number prefixes parsed above
+ replacement = sign + hashtag-prefix + replacement
+
+ if fill != none {
+ // perform fill/width adjustments: "x" ---> " x" if width is 4
+ let width-diff = width - replacement.codepoints().len() // number prefixes are also considered for width
+ if width-diff > 0 {
+ if align == left {
+ replacement = replacement + (fill * width-diff)
+ } else if align == right {
+ replacement = (fill * width-diff) + replacement
+ } else if align == center {
+ let half-width = calc.quo(width-diff, 2)
+ let left-fill = fill * half-width // floor div
+ let right-fill = fill * (half-width + calc.rem(width-diff, 2)) // ceil div (if adding odd fill, add 1 to the right)
+ replacement = left-fill + replacement + right-fill
+ }
+ }
+ }
+
+ replacement
+}
+
+#let strfmt(
+ format,
+ ..replacements,
+ fmt-decimal-separator: auto,
+ fmt-thousands-count: 3,
+ fmt-thousands-separator: "",
+) = {
+ if format == "" { return "" }
+ let formats = _strfmt_formatparser(format)
+ let num-replacements = replacements.pos()
+ let named-replacements = replacements.named()
+ let unnamed-format-index = 0
+
+ if fmt-decimal-separator != auto and type(fmt-decimal-separator) != _str-type {
+ assert(
+ false,
+ message: "String formatter error: 'fmt-decimal-separator' must be a string or 'auto', got '" + str(type(fmt-decimal-separator)) + "' instead."
+ )
+ }
+
+ if type(fmt-thousands-count) == _arr-type {
+ assert(
+ fmt-thousands-count.all(c => type(c) == _int-type and c > 0),
+ message: "String formatter error: 'fmt-thousands-count' must be a positive integer or array of positive integers, got an array with at least one element that isn't a positive integer."
+ )
+ assert(fmt-thousands-count != (), message: "String formatter error: 'fmt-thousands-count' must not be an empty array, but an array of positive integers.")
+ } else if type(fmt-thousands-count) == _int-type {
+ if fmt-thousands-count <= 0 {
+ assert(
+ false,
+ message: "String formatter error: 'fmt-thousands-count' must be a positive integer, got " + str(fmt-thousands-count) + " instead."
+ )
+ }
+ } else {
+ assert(
+ false,
+ message: "String formatter error: 'fmt-thousands-count' must be a positive integer or array of positive integers, got '" + str(type(fmt-thousands-count)) + "' instead."
+ )
+ }
+
+ if type(fmt-thousands-separator) != _str-type {
+ assert(
+ false,
+ message: "String formatter error: 'fmt-thousands-separator' must be a string (or empty string, \"\", to disable), got '" + str(type(fmt-thousands-separator)) + "' instead."
+ )
+ }
+
+ for (name, _) in named-replacements {
+ if name.starts-with("fmt-") {
+ assert(false, message: "String formatter error: unknown format option '" + name + "'. Keys prefixed with 'fmt-' are reserved for future oxifmt options. Please use a different key name.")
+ }
+ }
+
+ let parts = ()
+ let last-span-end = 0
+ for f in formats {
+ let replace-by = none
+ let replace-span = none
+ if "escape" in f {
+ replace-by = f.escape.escaped
+ replace-span = f.escape.span
+ } else if "format" in f {
+ let f = f.format
+ let (name, extras) = _strfmt_parse-fmt-name(f.name)
+ if name == none {
+ let fmt-index = unnamed-format-index
+ let amount-pos-replacements = num-replacements.len()
+ if amount-pos-replacements == 0 {
+ panic("String formatter error: Specified a {} (or similar) format to extract positional replacements, but none were given. Try specifying them sequentially after the format string, e.g. strfmt(\"{}, {}\", 5, 1+1) would become \"5, 2\".")
+ }
+ if amount-pos-replacements <= fmt-index {
+ let were-was = if amount-pos-replacements == 1 { "was" } else { "were" }
+ panic("String formatter error: Specified more {} (or similar) formats than positional replacements (only " + str(amount-pos-replacements) + " of them " + were-was + " given!). Please specify the missing positional arguments sequentially after the format string in the 'strfmt' call.")
+ }
+ replace-by = num-replacements.at(fmt-index)
+ unnamed-format-index += 1
+ } else if type(name) == _int-type {
+ let fmt-index = name
+ let amount-pos-replacements = num-replacements.len()
+ if amount-pos-replacements == 0 {
+ panic("String formatter error: format key '" + str(name) + "' would attempt to get a positional replacement, but none were given after the string. Try specifying positional replacements after the format string in the 'strfmt' call, e.g. strfmt(\"{1}, {0}\", 2, 3) would become \"3, 2\".")
+ }
+ if amount-pos-replacements <= fmt-index {
+ let were-was = if amount-pos-replacements == 1 { "was" } else { "were" }
+ panic("String formatter error: format key '" + str(name) + "', from '{" + f.name.replace("{", "{{").replace("}", "}}") + "}', is not a valid positional replacement position (only " + str(amount-pos-replacements) + " of them " + were-was + " given). Note that the first position is 0. For example, strfmt(\"{1}, {0}\", 2, 3) would become \"3, 2\".")
+ }
+ replace-by = num-replacements.at(fmt-index)
+ } else { // named replacement
+ if name not in named-replacements {
+ panic("String formatter error: format key '" + name + "', from '{" + f.name.replace("{", "{{").replace("}", "}}") + "}', does not match any given named replacement. Try specifying it after the format string, e.g. like so: strfmt(\"Test: {myarg}\", myarg: 1 + 1) would become \"Test: 2\".")
+ }
+ replace-by = named-replacements.at(name)
+ }
+ replace-by = _generate-replacement(f.name, extras, replace-by, pos-replacements: num-replacements, named-replacements: named-replacements, fmt-decimal-separator: fmt-decimal-separator, fmt-thousands-count: fmt-thousands-count, fmt-thousands-separator: fmt-thousands-separator)
+ replace-span = f.span
+ } else {
+ panic("String formatter error: Internal error (unexpected format received).")
+ }
+ // {...}ABCABCABC{...} <--- push ABCABCABC to parts
+ parts.push(format.slice(last-span-end, replace-span.at(0)))
+ // push the replacement string instead of the {...} at the end
+ parts.push(replace-by)
+ last-span-end = replace-span.at(1)
+ }
+ if last-span-end < format.len() {
+ parts.push(format.slice(last-span-end, format.len()))
+ }
+
+ // join all the string parts (constant parts + formatted parts + escaped parts)
+ parts.join()
+}
diff --git a/render/packages/preview/oxifmt/1.0.0/typst.toml b/render/packages/preview/oxifmt/1.0.0/typst.toml
new file mode 100644
index 0000000..a1785e3
--- /dev/null
+++ b/render/packages/preview/oxifmt/1.0.0/typst.toml
@@ -0,0 +1,8 @@
+[package]
+name = "oxifmt"
+version = "1.0.0"
+authors = ["PgBiel <https://github.com/PgBiel>"]
+license = "MIT OR Apache-2.0"
+description = "Convenient Rust-like string formatting in Typst"
+entrypoint = "lib.typ"
+repository = "https://github.com/PgBiel/typst-oxifmt"
diff --git a/render/theme.typ b/render/theme.typ
new file mode 100644
index 0000000..67c67a3
--- /dev/null
+++ b/render/theme.typ
@@ -0,0 +1,76 @@
+// md-preview themes: loads the active theme and merges it over the
+// built-in `vscode` theme, so a user theme only lists what it changes.
+//
+// --input theme-dir=<absolute folder that holds theme.json> (optional)
+// --input theme=dark|light
+//
+// A value of the wrong type (or a colour that is not #rgb, #rgba, #rrggbb
+// or #rrggbbaa) is ignored and the vscode value is used, so a bad user
+// theme draws like vscode instead of failing the compile. theme.json itself
+// must be valid JSON (the hooks module checks that before it passes it).
+
+#let base-dir = "themes/vscode"
+#let base = json(base-dir + "/theme.json")
+#let theme-dir = sys.inputs.at("theme-dir", default: "").trim().trim("/", at: end)
+#let user = if theme-dir == "" { (:) } else {
+ let u = json(theme-dir + "/theme.json")
+ if type(u) == dictionary { u } else { (:) }
+}
+
+#let is-colour(v) = type(v) == str and v.match(regex("^#([0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$")) != none
+#let is-num(v) = type(v) in (int, float)
+
+// Is `u` an acceptable replacement for the default `b`?
+#let valid(u, b) = {
+ if u == none { false }
+ else if is-num(b) { is-num(u) }
+ else if type(b) == bool { type(u) == bool }
+ else if type(b) == str { if b.starts-with("#") { is-colour(u) } else { type(u) == str } }
+ else if type(b) == array {
+ type(u) == array and u.len() > 0 and (b.len() == 0 or u.all(x => if is-num(b.first()) { is-num(x) } else { type(x) == type(b.first()) }))
+ } else { type(u) == type(b) }
+}
+
+#let merge(b, u) = {
+ let out = b
+ for (k, v) in u {
+ if k in b {
+ let bv = b.at(k)
+ if type(bv) == dictionary and type(v) == dictionary { out.insert(k, merge(bv, v)) }
+ else if valid(v, bv) or (k == "size" and v == "terminal") { out.insert(k, v) }
+ } else if v != none {
+ out.insert(k, v)
+ }
+ }
+ out
+}
+
+#let T = merge(base, user)
+#let dark = sys.inputs.at("theme", default: "dark") != "light"
+#let mode = if dark { "dark" } else { "light" }
+
+// Colours of the active mode, as Typst colours.
+#let C = {
+ let out = (:)
+ for (k, v) in T.at(mode) { if is-colour(v) { out.insert(k, rgb(v)) } }
+ out
+}
+
+// i-th entry of a per-level array; the last entry repeats.
+#let at-level(arr, i) = arr.at(calc.min(i, arr.len() - 1))
+
+// Syntax colours: the user theme's own tmTheme when theme.json names one,
+// else the vscode one for this mode. A function, so measure.typ (which
+// imports this file through fonts.typ) never reads the file.
+#let syntax() = {
+ let own = user.at("syntax", default: (:))
+ let name = if type(own) == dictionary { own.at(mode, default: none) } else { none }
+ if type(name) == str and name.trim() != "" and theme-dir != "" {
+ let p = if name.starts-with("/") { name } else { theme-dir + "/" + name }
+ read(p, encoding: none)
+ } else {
+ read(base-dir + "/" + base.syntax.at(mode), encoding: none)
+ }
+}
+
+#let fonts = T.fonts
diff --git a/render/themes/README.md b/render/themes/README.md
new file mode 100644
index 0000000..50dcfa0
--- /dev/null
+++ b/render/themes/README.md
@@ -0,0 +1,63 @@
+# md-preview themes
+
+A theme is a folder with a `theme.json`. md-preview ships two:
+
+| Folder | Name | Looks like |
+|---|---|---|
+| `vscode-modern` (default) | VS Code Modern | VS Code's Markdown preview, Dark Modern / Light Modern |
+| `vscode` | VS Code | the same, with the Dark+ / Light+ colours; every theme merges over this one |
+
+Your own themes go in `~/.claude/md-preview/themes/<name>/theme.json`. A theme there with the same folder name as a built-in one is used in its place. It is still merged over the built-in `vscode`, like every theme. Choose a theme with `/md-preview theme <name>`.
+
+## Merging
+
+Every key is optional. The template merges your `theme.json` over `vscode/theme.json`, so you only write what you change. A value of the wrong type (for example a colour that is not `#rgb`, `#rgba`, `#rrggbb` or `#rrggbbaa`, or text where a number belongs) is ignored, and the vscode value is used. The file must be valid JSON; if it is not, md-preview uses the default theme, `vscode-modern`, and tells you.
+
+Example: pink inline code, rounder boxes.
+
+```json
+{
+ "name": "Pink code",
+ "dark": { "inline-code-fg": "#ff79c6", "inline-code-bg": "#ff79c626" },
+ "light": { "inline-code-fg": "#c2185b" },
+ "inline-code": { "radius-px": 8 }
+}
+```
+
+## Units
+
+- `*-px`: CSS pixels of VS Code's preview. Its body text is 14px, so 1px = 11/14 pt (the body is always 11pt; md-preview scales the whole picture to your terminal).
+- `*-em`: em of that element's own text.
+- `size`: a fraction of the body text size. For code, `"terminal"` means the size of your terminal's own text.
+- Colours: `#rgb`, `#rgba`, `#rrggbb` or `#rrggbbaa`. The page is transparent, so a translucent background (for example `#ffffff1a`) looks right on any terminal colour.
+
+## Keys and vscode defaults
+
+| Key | vscode default | What it does |
+|---|---|---|
+| `name`, `description`, `source` | | Shown by `/md-preview theme` |
+| `syntax.dark`, `syntax.light` | `dark.tmTheme`, `light.tmTheme` | Code colours: a TextMate theme file in this folder. If you leave this out, the vscode files are used. If you name a file, it must exist. |
+| `fonts.body` | SF Pro Text, Helvetica Neue, Helvetica, Arial, … | Body font list (first installed one wins, per character) |
+| `fonts.code` | Menlo, SF Mono, DejaVu Sans Mono, … | Code font list |
+| `fonts.use-terminal-font` | `true` | Put the terminal's own font first for code |
+| `dark.*`, `light.*` | see `vscode/theme.json` | Colours: `fg`, `muted`, `link`, `accent` (checked boxes), `bg` (the page colour that live Typst blocks get as `theme.bg`), `border` (h1/h2 rules, hr, table rows), `th-border`, `inline-code-fg`, `inline-code-bg`, `code-fg`, `code-bg`, `code-border`, `quote-bg`, `quote-border`, `check` (tick in a checked box), `red`, `green`, `blue`, `yellow`, `orange`, `purple` (for drawings) |
+| `text.leading-em` / `text.paragraph-em` | `0.38` / `1.2` | Gap between lines / between paragraphs |
+| `heading.size-em` | `[2, 1.5, 1.25, 1, 0.875, 0.85]` | h1–h6 sizes |
+| `heading.weight` | `600` | |
+| `heading.leading-em`, `above-em`, `below-em` | `0.2`, `[1.4, 1.6, 1.5, …]`, `[1.0, 1.0, 0.9, …]` | Spacing (arrays are per level; the last entry repeats) |
+| `heading.rule-levels`, `rule-pad-em` | `2`, `0.3` | Levels that get a rule under them, and the gap above it |
+| `list.markers` | `["disc", "circle", "square"]` | Per nesting level: `disc`, `circle` and `square` are drawn like CSS; any other text is used as the marker |
+| `list.indent-em`, `gap-em` | `1.9`, `0.55` | Bullet indent; gap from bullet to text |
+| `list.number-indent-em`, `number-gap-em` | `1.45`, `0.5` | The same for numbered lists |
+| `list.item-spacing-em` | `0.38` | Gap between items |
+| `inline-code.size` | `1.0` | Code size (VS Code: same as body) |
+| `inline-code.pad-x-px`, `pad-y-px`, `radius-px` | `3`, `1`, `4` | VS Code: `padding: 1px 3px; border-radius: 4px` |
+| `code-block.size`, `line-height` | `1.0`, `1.357` | |
+| `code-block.pad-px`, `radius-px`, `border-px` | `16`, `3`, `1` | |
+| `quote.bar-px`, `radius-px`, `pad-left-px`, `pad-right-px`, `pad-y-em` | `5`, `2`, `10`, `16`, `0.55` | |
+| `table.pad-x-px`, `pad-y-px`, `border-px`, `header-weight` | `10`, `5`, `1`, `700` | |
+| `rule.border-px`, `gap-em` | `1`, `1.5` | Horizontal rule |
+
+## Licence
+
+The `vscode` and `vscode-modern` values come from VS Code (MIT, Copyright (c) 2015 - present Microsoft Corporation). Each of those folders has the `LICENSE` file. Their `source` keys name the files the values come from.
diff --git a/render/themes/vscode-modern/LICENSE b/render/themes/vscode-modern/LICENSE
new file mode 100644
index 0000000..0ac28ee
--- /dev/null
+++ b/render/themes/vscode-modern/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2015 - present Microsoft Corporation
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/render/themes/vscode-modern/theme.json b/render/themes/vscode-modern/theme.json
new file mode 100644
index 0000000..63db8d9
--- /dev/null
+++ b/render/themes/vscode-modern/theme.json
@@ -0,0 +1,32 @@
+{
+ "name": "VS Code Modern",
+ "description": "VS Code's Markdown preview with Dark Modern and Light Modern",
+ "source": "microsoft/vscode (MIT, see LICENSE): extensions/theme-defaults/themes/dark_modern.json and light_modern.json (colours); every other value comes from the vscode theme (markdown.css, highlight.css)",
+ "dark": {
+ "fg": "#cccccc",
+ "muted": "#9d9d9d",
+ "link": "#4daafc",
+ "accent": "#0078d4",
+ "bg": "#1f1f1f",
+ "inline-code-fg": "#d0d0d0",
+ "inline-code-bg": "#ffffff21",
+ "code-fg": "#cccccc",
+ "code-bg": "#ffffff0e",
+ "code-border": "#313131",
+ "quote-bg": "#ffffff0e",
+ "quote-border": "#616161"
+ },
+ "light": {
+ "fg": "#3b3b3b",
+ "muted": "#3b3b3b",
+ "link": "#005fb8",
+ "accent": "#005fb8",
+ "inline-code-fg": "#3b3b3b",
+ "inline-code-bg": "#0000001f",
+ "code-fg": "#3b3b3b",
+ "code-bg": "#00000007",
+ "code-border": "#e5e5e5",
+ "quote-bg": "#00000007",
+ "quote-border": "#e5e5e5"
+ }
+}
diff --git a/render/themes/vscode/LICENSE b/render/themes/vscode/LICENSE
new file mode 100644
index 0000000..0ac28ee
--- /dev/null
+++ b/render/themes/vscode/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2015 - present Microsoft Corporation
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/render/themes/vscode/dark.tmTheme b/render/themes/vscode/dark.tmTheme
new file mode 100644
index 0000000..d80e5ba
--- /dev/null
+++ b/render/themes/vscode/dark.tmTheme
@@ -0,0 +1,41 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<!-- Colours from VS Code (MIT, Copyright (c) 2015 - present Microsoft Corporation):
+ extensions/markdown-language-features/media/highlight.css -->
+<plist version="1.0">
+<dict>
+ <key>name</key><string>VS Code preview dark (hljs vs2015)</string>
+ <key>settings</key>
+ <array>
+ <dict><key>settings</key><dict><key>foreground</key><string>#D4D4D4</string><key>background</key><string>#1E1E1E</string></dict></dict>
+ <dict><key>name</key><string>hljs-operator</string><key>scope</key><string>keyword.operator, storage.type.function.arrow, punctuation.separator.key-value, punctuation.separator, punctuation.accessor, punctuation.terminator, constant.language.import-export-all, keyword.operator.assignment</string><key>settings</key><dict><key>foreground</key><string>#D4D4D4</string></dict></dict>
+ <dict><key>name</key><string>hljs-keyword</string><key>scope</key><string>keyword, storage, storage.type, storage.modifier, keyword.control, keyword.declaration, keyword.other, keyword.operator.new, keyword.operator.expression, keyword.operator.word, keyword.operator.wordlike, keyword.operator.logical.python, keyword.operator.instanceof, keyword.operator.typeof, keyword.operator.sizeof, variable.language, support.type.primitive</string><key>settings</key><dict><key>foreground</key><string>#569CD6</string></dict></dict>
+ <dict><key>name</key><string>hljs-literal</string><key>scope</key><string>constant.language</string><key>settings</key><dict><key>foreground</key><string>#569CD6</string></dict></dict>
+ <dict><key>name</key><string>hljs-built_in</string><key>scope</key><string>support.function.builtin, support.class.builtin, support.type.builtin, support.function.builtin.shell, support.macro, variable.function.macro, support.class, support.type, support.constant.builtin, entity.name.type, storage.type.primitive, storage.type.numeric, storage.type.rust, entity.name.namespace</string><key>settings</key><dict><key>foreground</key><string>#4EC9B0</string></dict></dict>
+ <dict><key>name</key><string>hljs-number</string><key>scope</key><string>constant.numeric</string><key>settings</key><dict><key>foreground</key><string>#B8D7A3</string></dict></dict>
+ <dict><key>name</key><string>hljs-string</string><key>scope</key><string>string, punctuation.definition.string, string punctuation.definition.string</string><key>settings</key><dict><key>foreground</key><string>#D69D85</string></dict></dict>
+ <dict><key>name</key><string>hljs-regexp</string><key>scope</key><string>string.regexp</string><key>settings</key><dict><key>foreground</key><string>#9A5334</string></dict></dict>
+ <dict><key>name</key><string>hljs-template_tag</string><key>scope</key><string>punctuation.definition.template-expression, punctuation.section.embedded</string><key>settings</key><dict><key>foreground</key><string>#9A5334</string></dict></dict>
+ <dict><key>name</key><string>hljs-subst</string><key>scope</key><string>meta.template.expression, meta.interpolation, source.python meta.interpolation</string><key>settings</key><dict><key>foreground</key><string>#DCDCDC</string></dict></dict>
+ <dict><key>name</key><string>hljs-title</string><key>scope</key><string>entity.name.function, variable.function, support.function, meta.function-call.generic, entity.name.class, entity.name.struct, entity.name.enum, entity.name.trait, entity.name.impl, entity.name.interface</string><key>settings</key><dict><key>foreground</key><string>#DCDCDC</string></dict></dict>
+ <dict><key>name</key><string>hljs-params</string><key>scope</key><string>variable.parameter</string><key>settings</key><dict><key>foreground</key><string>#DCDCDC</string></dict></dict>
+ <dict><key>name</key><string>hljs-comment</string><key>scope</key><string>comment, punctuation.definition.comment, comment punctuation.definition.comment</string><key>settings</key><dict><key>foreground</key><string>#57A64A</string><key>fontStyle</key><string>italic</string></dict></dict>
+ <dict><key>name</key><string>hljs-doctag</string><key>scope</key><string>comment.block.documentation storage.type, comment.block.documentation entity.name.tag, comment.block.documentation keyword, comment.line.documentation keyword</string><key>settings</key><dict><key>foreground</key><string>#608B4E</string></dict></dict>
+ <dict><key>name</key><string>hljs-meta</string><key>scope</key><string>meta.preprocessor, entity.name.function.preprocessor, keyword.other.directive, meta.annotation, meta.decorator, entity.name.function.decorator, punctuation.definition.annotation, punctuation.definition.decorator, comment.line.shebang</string><key>settings</key><dict><key>foreground</key><string>#9B9B9B</string></dict></dict>
+ <dict><key>name</key><string>hljs-tag</string><key>scope</key><string>punctuation.definition.tag</string><key>settings</key><dict><key>foreground</key><string>#9B9B9B</string></dict></dict>
+ <dict><key>name</key><string>hljs-name</string><key>scope</key><string>entity.name.tag</string><key>settings</key><dict><key>foreground</key><string>#569CD6</string></dict></dict>
+ <dict><key>name</key><string>hljs-variable</string><key>scope</key><string>variable.other.readwrite.shell, variable.other.normal, variable.other.special, variable.other.positional, variable.other.bracket, punctuation.definition.variable, variable.other.php, variable.other.makefile</string><key>settings</key><dict><key>foreground</key><string>#BD63C5</string></dict></dict>
+ <dict><key>name</key><string>hljs-attr</string><key>scope</key><string>meta.object-literal.key, meta.mapping.key string, meta.mapping.key, support.type.property-name.json, entity.name.tag.yaml, string.unquoted.key, entity.other.attribute-name, meta.structure.dictionary.key.python, meta.toml entity.name.tag, entity.name.tag.toml, meta.tag.toml</string><key>settings</key><dict><key>foreground</key><string>#9CDCFE</string></dict></dict>
+ <dict><key>name</key><string>hljs-attribute</string><key>scope</key><string>support.type.property-name, meta.property-name</string><key>settings</key><dict><key>foreground</key><string>#9CDCFE</string></dict></dict>
+ <dict><key>name</key><string>hljs-symbol</string><key>scope</key><string>constant.other.symbol, constant.character.escape</string><key>settings</key><dict><key>foreground</key><string>#569CD6</string></dict></dict>
+ <dict><key>name</key><string>hljs-bullet</string><key>scope</key><string>punctuation.definition.list.begin.markdown, punctuation.definition.list, markup.list.unnumbered punctuation</string><key>settings</key><dict><key>foreground</key><string>#D7BA7D</string></dict></dict>
+ <dict><key>name</key><string>hljs-link</string><key>scope</key><string>markup.underline.link, string.other.link</string><key>settings</key><dict><key>foreground</key><string>#569CD6</string><key>fontStyle</key><string>underline</string></dict></dict>
+ <dict><key>name</key><string>hljs-section</string><key>scope</key><string>markup.heading, entity.name.section, punctuation.definition.heading</string><key>settings</key><dict><key>foreground</key><string>#FFD700</string></dict></dict>
+ <dict><key>name</key><string>hljs-selector</string><key>scope</key><string>entity.name.tag.css, entity.other.attribute-name.class.css, entity.other.attribute-name.id.css, entity.other.attribute-name.pseudo-class.css, entity.other.pseudo-class, meta.selector</string><key>settings</key><dict><key>foreground</key><string>#D7BA7D</string></dict></dict>
+ <dict><key>name</key><string>hljs-emphasis</string><key>scope</key><string>markup.italic</string><key>settings</key><dict><key>fontStyle</key><string>italic</string></dict></dict>
+ <dict><key>name</key><string>hljs-strong</string><key>scope</key><string>markup.bold</string><key>settings</key><dict><key>fontStyle</key><string>bold</string></dict></dict>
+ <dict><key>name</key><string>hljs-addition</string><key>scope</key><string>markup.inserted</string><key>settings</key><dict><key>foreground</key><string>#9BB955</string></dict></dict>
+ <dict><key>name</key><string>hljs-deletion</string><key>scope</key><string>markup.deleted</string><key>settings</key><dict><key>foreground</key><string>#FF0000</string></dict></dict>
+ </array>
+</dict>
+</plist>
diff --git a/render/themes/vscode/light.tmTheme b/render/themes/vscode/light.tmTheme
new file mode 100644
index 0000000..ea9c298
--- /dev/null
+++ b/render/themes/vscode/light.tmTheme
@@ -0,0 +1,41 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<!-- Colours from VS Code (MIT, Copyright (c) 2015 - present Microsoft Corporation):
+ extensions/markdown-language-features/media/highlight.css -->
+<plist version="1.0">
+<dict>
+ <key>name</key><string>VS Code preview light (hljs vs)</string>
+ <key>settings</key>
+ <array>
+ <dict><key>settings</key><dict><key>foreground</key><string>#000000</string><key>background</key><string>#FFFFFF</string></dict></dict>
+ <dict><key>name</key><string>hljs-operator</string><key>scope</key><string>keyword.operator, storage.type.function.arrow, punctuation.separator.key-value, punctuation.separator, punctuation.accessor, punctuation.terminator, constant.language.import-export-all, keyword.operator.assignment</string><key>settings</key><dict><key>foreground</key><string>#000000</string></dict></dict>
+ <dict><key>name</key><string>hljs-keyword</string><key>scope</key><string>keyword, storage, storage.type, storage.modifier, keyword.control, keyword.declaration, keyword.other, keyword.operator.new, keyword.operator.expression, keyword.operator.word, keyword.operator.wordlike, keyword.operator.logical.python, keyword.operator.instanceof, keyword.operator.typeof, keyword.operator.sizeof, variable.language, support.type.primitive</string><key>settings</key><dict><key>foreground</key><string>#0000FF</string></dict></dict>
+ <dict><key>name</key><string>hljs-literal</string><key>scope</key><string>constant.language</string><key>settings</key><dict><key>foreground</key><string>#A31515</string></dict></dict>
+ <dict><key>name</key><string>hljs-built_in</string><key>scope</key><string>support.function.builtin, support.class.builtin, support.type.builtin, support.function.builtin.shell, support.macro, variable.function.macro, support.class, support.type, support.constant.builtin, entity.name.type, storage.type.primitive, storage.type.numeric, storage.type.rust, entity.name.namespace</string><key>settings</key><dict><key>foreground</key><string>#007ACC</string></dict></dict>
+ <dict><key>name</key><string>hljs-number</string><key>scope</key><string>constant.numeric</string><key>settings</key><dict><key>foreground</key><string>#008000</string></dict></dict>
+ <dict><key>name</key><string>hljs-string</string><key>scope</key><string>string, punctuation.definition.string, string punctuation.definition.string</string><key>settings</key><dict><key>foreground</key><string>#A31515</string></dict></dict>
+ <dict><key>name</key><string>hljs-regexp</string><key>scope</key><string>string.regexp</string><key>settings</key><dict><key>foreground</key><string>#000000</string></dict></dict>
+ <dict><key>name</key><string>hljs-template_tag</string><key>scope</key><string>punctuation.definition.template-expression, punctuation.section.embedded</string><key>settings</key><dict><key>foreground</key><string>#A31515</string></dict></dict>
+ <dict><key>name</key><string>hljs-subst</string><key>scope</key><string>meta.template.expression, meta.interpolation, source.python meta.interpolation</string><key>settings</key><dict><key>foreground</key><string>#2B91AF</string></dict></dict>
+ <dict><key>name</key><string>hljs-title</string><key>scope</key><string>entity.name.function, variable.function, support.function, meta.function-call.generic, entity.name.class, entity.name.struct, entity.name.enum, entity.name.trait, entity.name.impl, entity.name.interface</string><key>settings</key><dict><key>foreground</key><string>#808080</string></dict></dict>
+ <dict><key>name</key><string>hljs-params</string><key>scope</key><string>variable.parameter</string><key>settings</key><dict><key>foreground</key><string>#000000</string></dict></dict>
+ <dict><key>name</key><string>hljs-comment</string><key>scope</key><string>comment, punctuation.definition.comment, comment punctuation.definition.comment</string><key>settings</key><dict><key>foreground</key><string>#008000</string><key>fontStyle</key><string>italic</string></dict></dict>
+ <dict><key>name</key><string>hljs-doctag</string><key>scope</key><string>comment.block.documentation storage.type, comment.block.documentation entity.name.tag, comment.block.documentation keyword, comment.line.documentation keyword</string><key>settings</key><dict><key>foreground</key><string>#808080</string></dict></dict>
+ <dict><key>name</key><string>hljs-meta</string><key>scope</key><string>meta.preprocessor, entity.name.function.preprocessor, keyword.other.directive, meta.annotation, meta.decorator, entity.name.function.decorator, punctuation.definition.annotation, punctuation.definition.decorator, comment.line.shebang</string><key>settings</key><dict><key>foreground</key><string>#2B91AF</string></dict></dict>
+ <dict><key>name</key><string>hljs-tag</string><key>scope</key><string>punctuation.definition.tag</string><key>settings</key><dict><key>foreground</key><string>#0000FF</string></dict></dict>
+ <dict><key>name</key><string>hljs-name</string><key>scope</key><string>entity.name.tag</string><key>settings</key><dict><key>foreground</key><string>#0000FF</string></dict></dict>
+ <dict><key>name</key><string>hljs-variable</string><key>scope</key><string>variable.other.readwrite.shell, variable.other.normal, variable.other.special, variable.other.positional, variable.other.bracket, punctuation.definition.variable, variable.other.php, variable.other.makefile</string><key>settings</key><dict><key>foreground</key><string>#008000</string></dict></dict>
+ <dict><key>name</key><string>hljs-attr</string><key>scope</key><string>meta.object-literal.key, meta.mapping.key string, meta.mapping.key, support.type.property-name.json, entity.name.tag.yaml, string.unquoted.key, entity.other.attribute-name, meta.structure.dictionary.key.python, meta.toml entity.name.tag, entity.name.tag.toml, meta.tag.toml</string><key>settings</key><dict><key>foreground</key><string>#FF0000</string></dict></dict>
+ <dict><key>name</key><string>hljs-attribute</string><key>scope</key><string>support.type.property-name, meta.property-name</string><key>settings</key><dict><key>foreground</key><string>#A31515</string></dict></dict>
+ <dict><key>name</key><string>hljs-symbol</string><key>scope</key><string>constant.other.symbol, constant.character.escape</string><key>settings</key><dict><key>foreground</key><string>#00B0E8</string></dict></dict>
+ <dict><key>name</key><string>hljs-bullet</string><key>scope</key><string>punctuation.definition.list.begin.markdown, punctuation.definition.list, markup.list.unnumbered punctuation</string><key>settings</key><dict><key>foreground</key><string>#00B0E8</string></dict></dict>
+ <dict><key>name</key><string>hljs-link</string><key>scope</key><string>markup.underline.link, string.other.link</string><key>settings</key><dict><key>foreground</key><string>#00B0E8</string></dict></dict>
+ <dict><key>name</key><string>hljs-section</string><key>scope</key><string>markup.heading, entity.name.section, punctuation.definition.heading</string><key>settings</key><dict><key>foreground</key><string>#A31515</string></dict></dict>
+ <dict><key>name</key><string>hljs-selector</string><key>scope</key><string>entity.name.tag.css, entity.other.attribute-name.class.css, entity.other.attribute-name.id.css, entity.other.attribute-name.pseudo-class.css, entity.other.pseudo-class, meta.selector</string><key>settings</key><dict><key>foreground</key><string>#0000FF</string></dict></dict>
+ <dict><key>name</key><string>hljs-emphasis</string><key>scope</key><string>markup.italic</string><key>settings</key><dict><key>fontStyle</key><string>italic</string></dict></dict>
+ <dict><key>name</key><string>hljs-strong</string><key>scope</key><string>markup.bold</string><key>settings</key><dict><key>fontStyle</key><string>bold</string></dict></dict>
+ <dict><key>name</key><string>hljs-addition</string><key>scope</key><string>markup.inserted</string><key>settings</key><dict><key>foreground</key><string>#9BB955</string></dict></dict>
+ <dict><key>name</key><string>hljs-deletion</string><key>scope</key><string>markup.deleted</string><key>settings</key><dict><key>foreground</key><string>#FF0000</string></dict></dict>
+ </array>
+</dict>
+</plist>
diff --git a/render/themes/vscode/theme.json b/render/themes/vscode/theme.json
new file mode 100644
index 0000000..59c88cd
--- /dev/null
+++ b/render/themes/vscode/theme.json
@@ -0,0 +1,111 @@
+{
+ "name": "VS Code",
+ "description": "VS Code's Markdown preview with the default themes, Dark+ and Light+",
+ "source": "microsoft/vscode (MIT, see LICENSE): extensions/markdown-language-features/media/markdown.css (sizes, spacing), media/highlight.css (code colours, in dark.tmTheme and light.tmTheme), src/vs/platform/theme/common/colors/baseColors.ts (textPreformat, textCodeBlock, textBlockQuote, textLink defaults), extensions/theme-defaults/themes/dark_vs.json and light_vs.json (editor and widget colours)",
+ "syntax": { "dark": "dark.tmTheme", "light": "light.tmTheme" },
+ "fonts": {
+ "body": ["SF Pro Text", "Helvetica Neue", "Helvetica", "Arial", "Noto Sans", "DejaVu Sans",
+ "PingFang SC", "Hiragino Sans", "Apple SD Gothic Neo", "Noto Sans CJK SC",
+ "Apple Color Emoji", "Noto Color Emoji"],
+ "code": ["Menlo", "SF Mono", "DejaVu Sans Mono", "Courier New",
+ "PingFang SC", "Apple Color Emoji", "Noto Color Emoji"],
+ "use-terminal-font": true
+ },
+ "dark": {
+ "fg": "#d4d4d4",
+ "muted": "#ccccccb3",
+ "link": "#3794ff",
+ "accent": "#0e639c",
+ "bg": "#1e1e1e",
+ "border": "#ffffff2e",
+ "th-border": "#ffffffb0",
+ "inline-code-fg": "#d7ba7d",
+ "inline-code-bg": "#ffffff1a",
+ "code-fg": "#d4d4d4",
+ "code-bg": "#0a0a0a66",
+ "code-border": "#303031",
+ "quote-bg": "#ffffff05",
+ "quote-border": "#007acc80",
+ "check": "#ffffff",
+ "red": "#f14c4c",
+ "green": "#89d185",
+ "blue": "#3794ff",
+ "yellow": "#cca700",
+ "orange": "#d18616",
+ "purple": "#b180d7"
+ },
+ "light": {
+ "fg": "#000000",
+ "muted": "#717171",
+ "link": "#006ab1",
+ "accent": "#007acc",
+ "bg": "#ffffff",
+ "border": "#0000002e",
+ "th-border": "#000000b0",
+ "inline-code-fg": "#a31515",
+ "inline-code-bg": "#0000001a",
+ "code-fg": "#000000",
+ "code-bg": "#dcdcdc66",
+ "code-border": "#d4d4d4",
+ "quote-bg": "#0000000d",
+ "quote-border": "#007acc80",
+ "check": "#ffffff",
+ "red": "#e51400",
+ "green": "#388a34",
+ "blue": "#1a85ff",
+ "yellow": "#bf8803",
+ "orange": "#d18616",
+ "purple": "#652d90"
+ },
+ "text": {
+ "leading-em": 0.38,
+ "paragraph-em": 1.2
+ },
+ "heading": {
+ "size-em": [2, 1.5, 1.25, 1, 0.875, 0.85],
+ "weight": 600,
+ "leading-em": 0.2,
+ "above-em": [1.4, 1.6, 1.5, 1.5, 1.5, 1.5],
+ "below-em": [1.0, 1.0, 0.9, 0.9, 0.9, 0.9],
+ "rule-levels": 2,
+ "rule-pad-em": 0.3
+ },
+ "list": {
+ "markers": ["disc", "circle", "square"],
+ "indent-em": 1.9,
+ "gap-em": 0.55,
+ "number-indent-em": 1.45,
+ "number-gap-em": 0.5,
+ "item-spacing-em": 0.38
+ },
+ "inline-code": {
+ "size": 1.0,
+ "pad-x-px": 3,
+ "pad-y-px": 1,
+ "radius-px": 4
+ },
+ "code-block": {
+ "size": 1.0,
+ "line-height": 1.357,
+ "pad-px": 16,
+ "radius-px": 3,
+ "border-px": 1
+ },
+ "quote": {
+ "bar-px": 5,
+ "radius-px": 2,
+ "pad-left-px": 10,
+ "pad-right-px": 16,
+ "pad-y-em": 0.55
+ },
+ "table": {
+ "pad-x-px": 10,
+ "pad-y-px": 5,
+ "border-px": 1,
+ "header-weight": 700
+ },
+ "rule": {
+ "border-px": 1,
+ "gap-em": 1.5
+ }
+}
diff --git a/tests/pure.test.ts b/tests/pure.test.ts
new file mode 100644
index 0000000..e0bb63e
--- /dev/null
+++ b/tests/pure.test.ts
@@ -0,0 +1,420 @@
+import { expect, test } from 'claude-code/testing'
+
+import {
+ alignFirstLine, DEFAULT_METRICS, DEFAULT_SIZE, firstLineOf, fontFit, ghosttyFontOf, itermFontOf, parseCommand, parseFontSpec, typstCall,
+ blocksOf, canDrawIn, cellOf, columnsFor, DEFAULT_CELL, hashOf, imagePathOf, isSet, localImages, MAX_COLUMNS,
+ parseOd, plainOf, pngSize, rowsFor, shouldRetrySafe, sizing, splitSegments, themeOf, TYPST_PROMPT,
+ BASE_THEME, DEFAULT_THEME, chooseTheme, isSyntaxPath, isThemeName, measureCall, pickThemes, renderKey, themeEntry, themeFiles, themeListing,
+} from '../hooks/register'
+
+const para = (i: number) => `Paragraph ${i} ${'word '.repeat(40)}`.trim()
+const fence = (info: string, lines: number) => ['```' + info, ...Array.from({ length: lines }, (_, i) => `line ${i}`), '```'].join('\n')
+const words = (s: string) => s.split(/\s+/).filter(Boolean)
+
+test('a short answer is one segment', () => {
+ expect(splitSegments('# Title\n\nSome text.', 100)).toEqual(['# Title\n\nSome text.'])
+ expect(splitSegments(' \n\n', 100)).toEqual([])
+})
+
+test('a long answer is cut at blank lines and keeps every word', () => {
+ const md = Array.from({ length: 120 }, (_, i) => para(i)).join('\n\n')
+ const segments = splitSegments(md, 80)
+ expect(segments.length).toBeGreaterThan(1)
+ expect(words(segments.join('\n\n'))).toEqual(words(md))
+ for (const s of segments) expect(s.startsWith('Paragraph')).toBe(true)
+})
+
+test('a blank line inside a code fence never cuts it', () => {
+ const md = ['Intro', '', '```js', 'a()', '', 'b()', '```', '', 'After'].join('\n')
+ const blocks = blocksOf(md)
+ expect(blocks.length).toBe(3)
+ expect(blocks[1]!.lines).toEqual(['```js', 'a()', '', 'b()', '```'])
+ expect(blocks[1]!.fence?.info).toBe('js')
+})
+
+test('a long code fence is cut into fences of the same language', () => {
+ const md = `Before\n\n${fence('python', 400)}\n\nAfter`
+ const segments = splitSegments(md, 80)
+ expect(segments.length).toBeGreaterThan(2)
+ const fenced = segments.filter(s => s.includes('line '))
+ for (const s of fenced) {
+ const open = (s.match(/^```python$/gm) ?? []).length
+ const shut = (s.match(/^```$/gm) ?? []).length
+ expect(open).toBe(shut)
+ expect(open).toBeGreaterThan(0)
+ }
+ const all = segments.join('\n')
+ for (let i = 0; i < 400; i++) expect(all.includes(`line ${i}\n`) || all.endsWith(`line ${i}`)).toBe(true)
+})
+
+test('a typst fence is never cut, however long', () => {
+ for (const info of ['typst', 'typ']) {
+ const md = `Before\n\n${fence(info, 400)}\n\nAfter`
+ const segments = splitSegments(md, 80)
+ const holding = segments.filter(s => s.includes('line '))
+ expect(holding.length).toBe(1)
+ expect(holding[0]!.includes(fence(info, 400))).toBe(true)
+ }
+})
+
+test('a typst fence with blank lines inside stays whole', () => {
+ const body = ['```typst', '#let a = 1', '', '#a', '```'].join('\n')
+ const md = `${Array.from({ length: 60 }, (_, i) => para(i)).join('\n\n')}\n\n${body}\n\n${para(99)}`
+ const segments = splitSegments(md, 80)
+ expect(segments.some(s => s.includes(body))).toBe(true)
+})
+
+test('an indented continuation never starts a segment', () => {
+ const md = Array.from({ length: 80 }, (_, i) => `- item ${i} ${'word '.repeat(30)}\n\n more of item ${i}`).join('\n\n')
+ for (const s of splitSegments(md, 80)) expect(/^\s/.test(s)).toBe(false)
+})
+
+test('footnotes keep the answer in one segment; link definitions go to every segment', () => {
+ const long = Array.from({ length: 120 }, (_, i) => para(i)).join('\n\n')
+ expect(splitSegments(`${long}\n\nSee[^1].\n\n[^1]: A note.`, 80).length).toBe(1)
+ const segments = splitSegments(`${long}\n\n[docs]: https://example.com`, 80)
+ expect(segments.length).toBeGreaterThan(1)
+ for (const s of segments) expect(s.includes('[docs]: https://example.com')).toBe(true)
+})
+
+test('the hash is stable and tells inputs apart', () => {
+ expect(hashOf(['abc', 100])).toBe(hashOf(['abc', 100]))
+ expect(hashOf(['abc', 100])).not.toBe(hashOf(['abc', 101]))
+ expect(hashOf(['ab', 'c'])).not.toBe(hashOf(['a', 'bc']))
+ expect(hashOf(['x'])).toMatch(/^[0-9a-f]{16}$/)
+})
+
+test('the theme follows the setting', () => {
+ expect(themeOf('light')).toBe('light')
+ expect(themeOf('light-daltonized')).toBe('light')
+ expect(themeOf('dark-ansi')).toBe('dark')
+ expect(themeOf(undefined)).toBe('dark')
+ expect(themeOf(true)).toBe('dark')
+})
+
+const near = (a: number, b: number, eps = 1e-3) => expect(Math.abs(a - b)).toBeLessThan(eps)
+
+const MESLO = { adv: 0.60205, xh: 0.546875, avg: 0.60205 }
+const SF = { adv: 0.62988, xh: 0.526367, avg: 0.482785 }
+
+test('the body font is matched to the terminal font by x-height and width', () => {
+ const fit = fontFit({ term: MESLO, menlo: MESLO, body: SF })
+ // Body text is about 1.14 times the terminal em, so it looks as big.
+ near(fit.ratio, 1.1379, 1e-3)
+ near(fit.code, 1 / fit.ratio, 1e-4)
+ // A column is a terminal cell: 11 pt body / ratio = em; em * advance = cell.
+ near(fit.columnPt, (11 * MESLO.adv) / fit.ratio, 1e-3)
+ // The size setting is on top: 130% narrows the column by 1.3.
+ near(fontFit({ term: MESLO, menlo: MESLO, body: SF }, 130).columnPt, fit.columnPt / 1.3, 1e-3)
+ // No terminal font known: Menlo's metrics stand in.
+ near(fontFit({ term: null, menlo: MESLO, body: SF }).columnPt, fit.columnPt, 1e-9)
+ near(fontFit(DEFAULT_METRICS).ratio, 1.1379, 2e-3)
+ expect(DEFAULT_SIZE).toBe(100)
+})
+
+test('size math: the PNG is exactly as wide as the box', () => {
+ expect(columnsFor(100)).toBe(98)
+ expect(columnsFor(300)).toBe(MAX_COLUMNS)
+ expect(columnsFor(undefined)).toBe(78)
+ const s = sizing(100, { width: 16, height: 32 }, 6.6)
+ expect(s.widthPt).toBe(660)
+ expect(s.widthPx).toBe(1600)
+ expect(Math.round((s.widthPt / 72) * s.ppi)).toBe(1600)
+ near(s.rowPt, 13.2)
+ const odd = sizing(97, { width: 16.6, height: 34 }, 5.8197)
+ expect(Math.round((odd.widthPt / 72) * odd.ppi)).toBe(odd.widthPx)
+ // Example: 120 columns of a 17 x 34 px cell.
+ expect(sizing(120, { width: 17, height: 34 }, 5.82).widthPx).toBe(2040)
+})
+
+test('the size command takes 80 to 200 percent', () => {
+ expect(parseCommand('')).toEqual({ kind: 'show' })
+ expect(parseCommand(' on ')).toEqual({ kind: 'on' })
+ expect(parseCommand('OFF')).toEqual({ kind: 'off' })
+ expect(parseCommand('size 130')).toEqual({ kind: 'size', percent: 130 })
+ expect(parseCommand('size 80%')).toEqual({ kind: 'size', percent: 80 })
+ expect(parseCommand('size 200')).toEqual({ kind: 'size', percent: 200 })
+ expect(parseCommand('size 79')).toEqual({ kind: 'bad' })
+ expect(parseCommand('size 201')).toEqual({ kind: 'bad' })
+ expect(parseCommand('size')).toEqual({ kind: 'bad' })
+ expect(parseCommand('size big')).toEqual({ kind: 'bad' })
+ expect(parseCommand('bigger')).toEqual({ kind: 'bad' })
+})
+
+test('the first line of an answer is told by how it starts', () => {
+ expect(firstLineOf('\n\nSome text')).toBe('para')
+ expect(firstLineOf('# Title')).toBe('h1')
+ expect(firstLineOf('## Part')).toBe('h2')
+ expect(firstLineOf('### Part')).toBe('h3')
+ expect(firstLineOf('###### Small')).toBe('h4')
+ expect(firstLineOf('#hashtag')).toBe('para')
+ expect(firstLineOf('> quote')).toBe('quote')
+ expect(firstLineOf('```js\nx\n```')).toBe('code')
+ expect(firstLineOf('| a | b |')).toBe('table')
+ expect(firstLineOf('- item')).toBe('para')
+})
+
+test('the first line of text is centred on the bullet row', () => {
+ // 11 pt rows: a paragraph fits row 0, pulled up a little.
+ expect(alignFirstLine('para', 11)).toEqual({ topPt: -1.95, bulletRow: 0 })
+ // A big heading is taller than a row: it centres on row 1, its ink not cut.
+ const h1 = alignFirstLine('h1', 11)
+ expect(h1.bulletRow).toBe(1)
+ near(h1.topPt, -3.86, 0.01)
+ const inkTop = { para: 2.55, h1: 5.82, h2: 3.64, h3: 2.55, h4: 2.18, quote: 8.36, code: 12.36, table: 6.18 }
+ for (const kind of ['para', 'h1', 'h2', 'h3', 'h4', 'quote', 'code', 'table'] as const) {
+ for (const rowPt of [9, 11, 13.2, 16]) {
+ const { topPt, bulletRow } = alignFirstLine(kind, rowPt)
+ expect(bulletRow).toBeGreaterThanOrEqual(0)
+ expect(bulletRow).toBeLessThan(3)
+ // No ink above the picture's top.
+ expect(inkTop[kind] + topPt).toBeGreaterThan(0)
+ }
+ }
+})
+
+test('pages are padded to whole rows, so rows round', () => {
+ const px = { width: 16, height: 32 }
+ expect(rowsFor({ width: 1600, height: 320 }, 100, px)).toBe(10)
+ expect(rowsFor({ width: 1600, height: 321 }, 100, px)).toBe(10)
+ expect(rowsFor({ width: 1600, height: 319 }, 100, px)).toBe(10)
+ expect(rowsFor({ width: 1600, height: 10 }, 100, px)).toBe(1)
+ expect(rowsFor({ width: 1600, height: 100000 }, 100, px)).toBe(255)
+ // Drawn at half the width (a narrower window before the new render), half the rows.
+ expect(rowsFor({ width: 1600, height: 640 }, 50, px)).toBe(10)
+ expect(DEFAULT_CELL.height / DEFAULT_CELL.width).toBe(2)
+})
+
+test('the cell comes from the tty in device pixels, with no scale step', () => {
+ // iTerm2 on Retina, 14 pt Meslo: 2040 x 1700 px for 120 x 50 cells.
+ expect(cellOf('50 120 2040 1700')).toEqual({ width: 17, height: 34 })
+ // Ghostty on Retina reports device pixels too.
+ expect(cellOf('40 200 3200 1360')).toEqual({ width: 16, height: 34 })
+ expect(cellOf('50 200 0 0')).toBe(null)
+ expect(cellOf('')).toBe(null)
+ // Not believable: under 4 or over 64 px a cell.
+ expect(cellOf('50 200 600 1700')).toBe(null)
+ expect(cellOf('50 20 1700 1700')).toBe(null)
+})
+
+test('the terminal font is read from iTerm2 and Ghostty settings', () => {
+ expect(parseFontSpec('MesloLGS-NF-Regular 14')).toEqual({ name: 'MesloLGS-NF-Regular', size: 14 })
+ expect(parseFontSpec('Menlo-Regular 12.5')).toEqual({ name: 'Menlo-Regular', size: 12.5 })
+ expect(parseFontSpec('nosize')).toBe(null)
+ const marks = JSON.stringify([
+ { Name: 'Default', Guid: 'G1', 'Normal Font': 'MesloLGS-NF-Regular 14' },
+ { Name: 'Work', Guid: 'G2', 'Normal Font': 'Menlo-Regular 12' },
+ ])
+ expect(itermFontOf(marks, 'Work', 'G1\n')).toBe('Menlo-Regular 12')
+ expect(itermFontOf(marks, undefined, 'G1\n')).toBe('MesloLGS-NF-Regular 14')
+ expect(itermFontOf(marks, 'Gone', 'G1')).toBe('MesloLGS-NF-Regular 14')
+ expect(itermFontOf('not json', 'Work', 'G1')).toBe(null)
+ expect(ghosttyFontOf('theme = x\nfont-family = \nfont-family = "JetBrains Mono"\nfont-family = Menlo')).toBe('JetBrains Mono')
+ expect(ghosttyFontOf('font-size = 13')).toBe(null)
+})
+
+test('typst runs with the network off and its own package cache', () => {
+ const { argv, env } = typstCall({
+ typst: '/opt/homebrew/bin/typst', root: '/mod', cache: '/tmp/c', ppi: 210.5,
+ inputs: { theme: 'dark', width: 698.4, 'term-font': 'MesloLGS NF', doc: '/tmp/c/k/doc.json' },
+ out: '/tmp/c/k/a-{0p}.png',
+ })
+ expect(argv.slice(0, 2)).toEqual(['/opt/homebrew/bin/typst', 'compile'])
+ expect(argv.includes('--package-path')).toBe(true)
+ expect(argv[argv.indexOf('--package-path') + 1]).toBe('/mod/render/packages')
+ expect(argv[argv.indexOf('--ppi') + 1]).toBe('210.5000')
+ expect(argv.includes('term-font=MesloLGS NF')).toBe(true)
+ expect(argv.slice(-2)).toEqual(['/mod/render/md.typ', '/tmp/c/k/a-{0p}.png'])
+ expect(env.HTTPS_PROXY).toBe('http://127.0.0.1:9')
+ expect(env.HTTP_PROXY).toBe('http://127.0.0.1:9')
+ expect(env.ALL_PROXY).toBe('http://127.0.0.1:9')
+ expect(env.TYPST_PACKAGE_CACHE_PATH).toBe('/tmp/c/pkg-cache')
+})
+
+test('PNG headers are read', () => {
+ const od = [
+ ' 89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52',
+ ' 00 00 06 d1 00 00 05 8f',
+ '@',
+ ' 89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52',
+ ' 00 00 00 10 00 00 00 20',
+ '@',
+ '',
+ ].join('\n')
+ const heads = parseOd(od)
+ expect(heads.length).toBe(2)
+ expect(pngSize(heads[0]!)).toEqual({ width: 0x6d1, height: 0x58f })
+ expect(pngSize(heads[1]!)).toEqual({ width: 16, height: 32 })
+ expect(pngSize([1, 2, 3])).toBe(null)
+ expect(pngSize(new Array(24).fill(0))).toBe(null)
+})
+
+test('any failed compile is retried with safe=1', () => {
+ expect(shouldRetrySafe(1)).toBe(true)
+ expect(shouldRetrySafe(2)).toBe(true)
+ expect(shouldRetrySafe(0)).toBe(false)
+})
+
+test('local images are found outside code and resolved as the template does', () => {
+ const md = '![chart](out/a.png)\n\n```md\n![x](gone.png)\n```\n\n![](https://x.dev/i.png) ![b](file:///tmp/b%20c.png) ![c](./d.png "t")'
+ expect(localImages(md)).toEqual(['out/a.png', 'file:///tmp/b%20c.png', './d.png'])
+ expect(imagePathOf('out/a.png', '/repo/')).toBe('/repo/out/a.png')
+ expect(imagePathOf('./d.png', '/repo')).toBe('/repo/d.png')
+ expect(imagePathOf('file:///tmp/b%20c.png', '/repo')).toBe('/tmp/b c.png')
+})
+
+test('the alt is one short plain line', () => {
+ const alt = plainOf('# Hello\n\n- **bold** and `code`\n- [link](https://x.dev)\n\n' + 'more '.repeat(100))
+ expect(alt.startsWith('Hello bold and code link more')).toBe(true)
+ expect(alt.length).toBeLessThanOrEqual(200)
+ expect(alt.includes('\n')).toBe(false)
+ expect(plainOf('')).toBe(' ')
+})
+
+test('pictures draw where Claude Code draws them: kitty and Ghostty, or forced', () => {
+ const base = { program: '', term: 'xterm-256color', kitty: false, tmux: false, ssh: false, engineForced: false, modForced: false }
+ expect(canDrawIn({ ...base, program: 'ghostty' })).toBe(true)
+ expect(canDrawIn({ ...base, term: 'xterm-ghostty' })).toBe(true)
+ expect(canDrawIn({ ...base, term: 'xterm-kitty' })).toBe(true)
+ expect(canDrawIn({ ...base, kitty: true })).toBe(true)
+ expect(canDrawIn({ ...base, program: 'iTerm.app' })).toBe(false)
+ expect(canDrawIn({ ...base, program: 'iTerm.app', engineForced: true })).toBe(true)
+ expect(canDrawIn({ ...base, program: 'WezTerm' })).toBe(false)
+ expect(canDrawIn({ ...base, program: 'WezTerm', engineForced: true })).toBe(true)
+ expect(canDrawIn({ ...base, program: 'WarpTerminal' })).toBe(false)
+ expect(canDrawIn({ ...base, program: 'Apple_Terminal' })).toBe(false)
+ expect(canDrawIn({ ...base, program: 'ghostty', tmux: true })).toBe(false)
+ expect(canDrawIn({ ...base, program: 'ghostty', tmux: true, engineForced: true })).toBe(true)
+ expect(canDrawIn({ ...base, program: 'ghostty', ssh: true })).toBe(false)
+ expect(canDrawIn({ ...base, program: 'iTerm.app', ssh: true, engineForced: true })).toBe(false)
+ expect(canDrawIn({ ...base, ssh: true, modForced: true })).toBe(true)
+ expect(canDrawIn({ ...base, modForced: true })).toBe(true)
+})
+
+test('a flag is set unless empty, 0, false, no or off', () => {
+ expect(isSet('1')).toBe(true)
+ expect(isSet('true')).toBe(true)
+ expect(isSet(undefined)).toBe(false)
+ expect(isSet('')).toBe(false)
+ expect(isSet('0')).toBe(false)
+ expect(isSet('false')).toBe(false)
+})
+
+test('Claude is told about typst blocks', () => {
+ expect(TYPST_PROMPT.includes('```typst')).toBe(true)
+ expect(TYPST_PROMPT.includes('#import "@preview/cetz:0.5.2"')).toBe(true)
+ expect(TYPST_PROMPT.includes('#import "@preview/fletcher:0.5.8" as fletcher: diagram, node, edge')).toBe(true)
+ expect(TYPST_PROMPT.includes('$math$ (LaTeX)')).toBe(true)
+ expect(TYPST_PROMPT.includes('theme.code-bg')).toBe(true)
+ expect(TYPST_PROMPT.endsWith('keep replies readable as plain text too.')).toBe(true)
+})
+
+
+test('the theme command lists, or switches to a name kept as typed', () => {
+ expect(parseCommand('theme')).toEqual({ kind: 'theme' })
+ expect(parseCommand('THEME')).toEqual({ kind: 'theme' })
+ expect(parseCommand('theme vscode')).toEqual({ kind: 'theme', name: 'vscode' })
+ expect(parseCommand('theme My.Dark_Theme-2')).toEqual({ kind: 'theme', name: 'My.Dark_Theme-2' })
+ expect(parseCommand('theme a b')).toEqual({ kind: 'bad' })
+ expect(parseCommand('theme ../up')).toEqual({ kind: 'bad' })
+ expect(parseCommand('theme a/b')).toEqual({ kind: 'bad' })
+ expect(isThemeName('.hidden')).toBe(false)
+ expect(isThemeName('nord')).toBe(true)
+})
+
+test('a theme folder is usable only with a theme.json object', () => {
+ expect(themeEntry('nord', '/u/nord', true, '{"name":"Nord","description":"Cold"}')).toEqual({
+ name: 'nord', dir: '/u/nord', isUser: true, title: 'Nord', description: 'Cold', syntax: {},
+ })
+ expect(themeEntry('bare', '/u/bare', true, '{}')).toMatchObject({ title: 'bare', description: '' })
+ for (const bad of ['{"name":', '[]', '3', 'null', '"x"']) expect('reason' in themeEntry('x', '/u/x', true, bad)).toBe(true)
+ expect('reason' in themeEntry('a b', '/u/a b', true, '{}')).toBe(true)
+})
+
+test('a user theme replaces the built-in one of its name; a broken one is only reported', () => {
+ const found = [
+ themeEntry('nord', '/home/.claude/md-preview/themes/nord', true, '{"description":"mine"}'),
+ themeEntry('vscode', '/mod/render/themes/vscode', false, '{"name":"VS Code"}'),
+ themeEntry('nord', '/mod/render/themes/nord', false, '{"description":"built-in"}'),
+ themeEntry('vscode', '/home/.claude/md-preview/themes/vscode', true, '{not json'),
+ themeEntry('solar', '/home/.claude/md-preview/themes/solar', true, '[1]'),
+ ]
+ const { themes, problems } = pickThemes(found)
+ expect([...themes.keys()].sort()).toEqual(['nord', 'vscode'])
+ expect(themes.get('nord')).toMatchObject({ isUser: true, description: 'mine' })
+ expect(themes.get('vscode')).toMatchObject({ isUser: false, dir: '/mod/render/themes/vscode' })
+ expect(problems.map(p => p.name).sort()).toEqual(['solar', 'vscode'])
+ const listing = themeListing(themes, problems, 'nord', '/home/.claude/md-preview/themes')
+ expect(listing).toContain('* nord (user): mine')
+ expect(listing).toContain('- vscode (built-in)')
+ expect(listing).toContain('skipped solar (user)')
+ expect(listing).toContain('/home/.claude/md-preview/themes/<name>/theme.json')
+})
+
+test('a missing theme falls back to the base theme, even before it is on disk', () => {
+ const { themes } = pickThemes([themeEntry('nord', '/u/nord', true, '{}')])
+ expect(chooseTheme(themes, 'nord', '/mod')).toEqual({ name: 'nord', dir: '/u/nord', isFallback: false })
+ expect(chooseTheme(themes, 'gone', '/mod')).toEqual({ name: BASE_THEME, dir: `/mod/render/themes/${BASE_THEME}`, isFallback: true })
+ expect(chooseTheme(themes, BASE_THEME, '/mod')).toMatchObject({ name: BASE_THEME, isFallback: false })
+})
+
+test('a missing theme falls back to the default theme when it is there', () => {
+ const { themes } = pickThemes([
+ themeEntry(BASE_THEME, `/mod/render/themes/${BASE_THEME}`, false, '{}'),
+ themeEntry(DEFAULT_THEME, `/mod/render/themes/${DEFAULT_THEME}`, false, '{}'),
+ ])
+ expect(DEFAULT_THEME).toBe('vscode-modern')
+ expect(chooseTheme(themes, 'gone', '/mod')).toEqual({ name: DEFAULT_THEME, dir: `/mod/render/themes/${DEFAULT_THEME}`, isFallback: true })
+ expect(chooseTheme(themes, DEFAULT_THEME, '/mod')).toMatchObject({ name: DEFAULT_THEME, isFallback: false })
+ expect(chooseTheme(themes, BASE_THEME, '/mod')).toMatchObject({ name: BASE_THEME, isFallback: false })
+})
+
+test('the picture key changes with the theme, its folder and its files', () => {
+ const base = {
+ textHash: 'abc', columns: 98, cell: { width: 16, height: 32 }, size: 100, mode: 'dark' as const,
+ termFont: 'MesloLGS NF', columnPt: 6.6, templateStamp: '1',
+ look: { name: 'vscode', dir: '/mod/render/themes/vscode', stamp: '1,2,3,1,2,3' },
+ }
+ const key = renderKey(base)
+ expect(renderKey({ ...base })).toBe(key)
+ expect(renderKey({ ...base, look: { ...base.look, name: 'nord' } })).not.toBe(key)
+ expect(renderKey({ ...base, look: { ...base.look, dir: '/u/vscode' } })).not.toBe(key)
+ expect(renderKey({ ...base, look: { ...base.look, stamp: '1,2,4,1,2,3' } })).not.toBe(key)
+ expect(renderKey({ ...base, mode: 'light' })).not.toBe(key)
+})
+
+test('a theme names its syntax files inside its own folder', () => {
+ expect(themeEntry('a', '/u/a', true, '{"syntax":{"dark":"d.tmTheme","light":"sub/l.tmTheme"}}')).toMatchObject({
+ syntax: { dark: 'd.tmTheme', light: 'sub/l.tmTheme' },
+ })
+ expect(themeEntry('a', '/u/a', true, '{"syntax":{"dark":"d.tmTheme"}}')).toMatchObject({ syntax: { dark: 'd.tmTheme' } })
+ for (const bad of ['"x"', '[]', '{"dark":3}', '{"dark":"../x.tmTheme"}', '{"light":"/etc/x.tmTheme"}', '{"dark":""}', '{"dark":"a/../../b"}']) {
+ expect('reason' in themeEntry('a', '/u/a', true, `{"syntax":${bad}}`)).toBe(true)
+ }
+ expect(isSyntaxPath('./dark.tmTheme')).toBe(true)
+ expect(isSyntaxPath('..x.tmTheme')).toBe(true)
+})
+
+test('the stamp follows the syntax files a theme really uses', () => {
+ const vscode = themeEntry('vscode', '/mod/render/themes/vscode', false, '{"syntax":{"dark":"dark.tmTheme","light":"light.tmTheme"}}') as any
+ const modern = themeEntry('vscode-modern', '/mod/render/themes/vscode-modern', false, '{}') as any
+ const half = themeEntry('half', '/u/half', true, '{"syntax":{"light":"mine.tmTheme"}}') as any
+ expect(themeFiles(vscode, vscode, '/mod')).toEqual([
+ '/mod/render/themes/vscode/theme.json', '/mod/render/themes/vscode/theme.json',
+ '/mod/render/themes/vscode/dark.tmTheme', '/mod/render/themes/vscode/light.tmTheme',
+ ])
+ expect(themeFiles(modern, vscode, '/mod')).toEqual([
+ '/mod/render/themes/vscode-modern/theme.json', '/mod/render/themes/vscode/theme.json',
+ '/mod/render/themes/vscode/dark.tmTheme', '/mod/render/themes/vscode/light.tmTheme',
+ ])
+ expect(themeFiles(half, vscode, '/mod').slice(2)).toEqual(['/mod/render/themes/vscode/dark.tmTheme', '/u/half/mine.tmTheme'])
+ expect(themeFiles(undefined, undefined, '/mod')[2]).toBe('/mod/render/themes/vscode/dark.tmTheme')
+})
+
+test('the font measure reads the active theme, with the root at /', () => {
+ const argv = measureCall('typst', '/mod', 'MesloLGS NF', '/u/nord')
+ expect(argv.slice(0, 5)).toEqual(['typst', 'eval', 'query(<m>).first().value', '--in', '/mod/render/measure.typ'])
+ expect(argv[argv.indexOf('--root') + 1]).toBe('/')
+ expect(argv).toContain('theme-dir=/u/nord')
+ expect(argv).toContain('term-font=MesloLGS NF')
+})
diff --git a/tests/render.test.ts b/tests/render.test.ts
new file mode 100644
index 0000000..a338a4f
--- /dev/null
+++ b/tests/render.test.ts
@@ -0,0 +1,31 @@
+import { expect, mock, test } from 'claude-code/testing'
+
+// What the engine would draw: the test stands beneath the plugin.
+const ENGINE = { type: 'Text', props: {}, children: ['engine drawing'] }
+
+const message = (requestId: string, props: Record<string, unknown>) =>
+ ({
+ plugin: 'md-preview',
+ surface: 'terminal',
+ component: 'AssistantMessage',
+ requestId,
+ props: { text: '# Hello\n\nSome **bold** text.', isFirstOfReply: true, ...props },
+ viewport: { columns: 100, rows: 40 },
+ }) as any
+
+test('with the mod off, an answer draws as the engine draws it', async ($, on) => {
+ mock.store(on)
+ on('ui.render', () => ENGINE as any)
+ const ran = await $.command.run({ command: 'md-preview', args: 'off' } as any)
+ expect(ran.text).toBe('md-preview is off.')
+ const mounted = await $.ui.mount(message('off-1', {}))
+ expect(await mounted.drawn()).toMatchObject(ENGINE)
+})
+
+test('a summary block and an empty block draw as the engine draws them', async ($, on) => {
+ on('ui.render', () => ENGINE as any)
+ for (const [id, props] of [['sum-1', { isSummary: true }], ['empty-1', { text: ' \n' }]] as const) {
+ const mounted = await $.ui.mount(message(id, props))
+ expect(await mounted.drawn()).toMatchObject(ENGINE)
+ }
+})
diff --git a/tests/themes.test.ts b/tests/themes.test.ts
new file mode 100644
index 0000000..f86e033
--- /dev/null
+++ b/tests/themes.test.ts
@@ -0,0 +1,85 @@
+import { expect, mock, test } from 'claude-code/testing'
+
+// A theme tree in memory: built-in themes under the mod's render/themes, user
+// themes under $HOME/.claude/md-preview/themes.
+const HOME = '/fake-home'
+const USER = `${HOME}/.claude/md-preview/themes`
+const files: Record<string, string> = {
+ 'render/themes/vscode/theme.json': '{"name":"VS Code","description":"built-in look"}',
+ 'render/themes/vscode-modern/theme.json': '{"name":"VS Code Modern","description":"default look"}',
+ 'render/themes/nord/theme.json': '{"description":"built-in nord"}',
+ [`${USER}/nord/theme.json`]: '{"description":"my nord"}',
+ [`${USER}/Broken/theme.json`]: '{"name":',
+ [`${USER}/Sun.Light/theme.json`]: '{"description":"bright"}',
+ [`${USER}/Lost/theme.json`]: '{"syntax":{"dark":"gone.tmTheme"}}',
+ [`${USER}/Own/theme.json`]: '{"description":"own colours","syntax":{"dark":"own.tmTheme"}}',
+ [`${USER}/Own/own.tmTheme`]: '<plist/>',
+}
+const fileOf = (path: string) => Object.keys(files).find(f => (f.startsWith('/') ? path === f : path.endsWith(`/${f}`)))
+const dirsIn = (path: string) => {
+ const base = path.endsWith('/render/themes') ? 'render/themes' : path === USER ? USER : null
+ if (!base) return null
+ const names = new Set(Object.keys(files).filter(f => f.startsWith(`${base}/`)).map(f => f.slice(base.length + 1).split('/')[0]!))
+ return [...names].map(name => ({ name, kind: 'dir' as const, size: 0, mtimeMs: 0, isLink: false }))
+}
+
+const withThemes = (on: any, stored: Record<string, unknown> = {}) => {
+ mock.env(on, { HOME })
+ on('fs.list', async ($: any, e: any, next: any) => {
+ const entries = dirsIn(e.path)
+ return entries ? { value: entries } : next(e)
+ })
+ on('fs.exists', async ($: any, e: any, next: any) => (e.path.startsWith(`${USER}/`) ? { value: !!fileOf(e.path) } : next(e)))
+ on('fs.read', async ($: any, e: any, next: any) => {
+ const f = fileOf(e.path)
+ return f ? { value: files[f]! } : next(e)
+ })
+ // The mod's store, in memory, for the test to read.
+ const kept: Record<string, unknown> = { ...stored }
+ on('store.get', async ($: any, e: any) => ({ value: kept[e.key] }))
+ on('store.set', async ($: any, e: any) => {
+ kept[e.key] = e.value
+ return { value: undefined }
+ })
+ return kept
+}
+
+test('/md-preview theme lists built-in and user themes; a user theme wins and a broken one is reported', async ($, on) => {
+ withThemes(on)
+ const ran = await $.command.run({ command: 'md-preview', args: 'theme' } as any)
+ expect(ran.text).toContain('* vscode-modern (built-in): default look')
+ expect(ran.text).toContain('- vscode (built-in): built-in look')
+ expect(ran.text).toContain('- nord (user): my nord')
+ expect(ran.text).toContain('- Sun.Light (user): bright')
+ expect(ran.text).toContain('skipped Broken (user): theme.json is not valid JSON')
+ expect(ran.text).toContain(`${USER}/<name>/theme.json`)
+ expect(ran.text).toContain('skipped Lost (user): theme.json names syntax files that do not exist: gone.tmTheme')
+ expect(ran.text).toContain('- Own (user): own colours')
+})
+
+test('/md-preview theme <name> switches and stores the name as typed; an unknown one is refused', async ($, on) => {
+ const store = withThemes(on)
+ const set = await $.command.run({ command: 'md-preview', args: 'theme Sun.Light' } as any)
+ expect(set.text).toContain('md-preview uses the theme Sun.Light.')
+ expect(set.text).toContain('* Sun.Light (user)')
+ expect(store['theme-name']).toBe('Sun.Light')
+ const shown = await $.command.run({ command: 'md-preview', args: '' } as any)
+ expect(shown.text).toContain('theme Sun.Light')
+ const bad = await $.command.run({ command: 'md-preview', args: 'theme sun.light' } as any)
+ expect(bad.text).toContain('No usable theme named sun.light.')
+ const broken = await $.command.run({ command: 'md-preview', args: 'theme Broken' } as any)
+ expect(broken.text).toContain('No usable theme named Broken.')
+ expect(store['theme-name']).toBe('Sun.Light')
+})
+
+test('a stored theme that is gone falls back to vscode-modern, with one toast', async ($, on) => {
+ withThemes(on, { 'theme-name': 'gone' })
+ const toasts: string[] = []
+ on('ui.toast', async ($: any, e: any) => {
+ toasts.push(String(e.text ?? e.message ?? JSON.stringify(e)))
+ return { value: undefined }
+ })
+ const ran = await $.command.run({ command: 'md-preview', args: 'theme' } as any)
+ expect(ran.text).toContain('* vscode-modern (built-in)')
+ expect(toasts.filter(t => t.includes('md-preview: theme gone not found, using vscode-modern')).length).toBe(1)
+})
diff --git a/tsconfig.json b/tsconfig.json
new file mode 100644
index 0000000..8681ec0
--- /dev/null
+++ b/tsconfig.json
@@ -0,0 +1,3 @@
+{
+ "extends": "./.claude-plugin/types/tsconfig.json"
+}
diff --git a/types/index.d.ts b/types/index.d.ts
new file mode 100644
index 0000000..ffbc6ca
--- /dev/null
+++ b/types/index.d.ts
@@ -0,0 +1,14 @@
+// The values md-preview keeps in $.state.
+export type MdPreviewTheme = 'dark' | 'light'
+
+declare module 'claude-code' {
+ interface PluginState {
+ 'md-preview': {
+ // Whether answers are drawn as pictures (also kept in $.store as `enabled`).
+ isOn: boolean
+ // Goes up each time a render finishes or the setup changes, so the
+ // AssistantMessage hooks that read it draw again.
+ done: number
+ }
+ }
+}