Code›Snippet

core

Snippet

Embed a project file as a syntax-highlighted code block — composes inside codegroup, diff, and any future fence-consuming container

Source

import Markdoc from '@markdoc/markdoc';
import type { Node } from '@markdoc/markdoc';
import type { ProjectFiles, PreprocessContext, PreprocessPage } from '@refrakt-md/types';
import { createContentModelSchema } from '../lib/index.js';
import type { AnchorOptions } from '../lib/anchor.js';
import {
	formatHighlight,
	highlightMatchLines,
	parseHighlightMatch,
	reindent,
	shouldReindent,
} from '../lib/present.js';
import { readSnippetFile, SnippetSandboxError } from '../lib/read-file.js';
import { compareMarker, parseMarker } from '../lib/review-marker.js';
import { inferLanguage } from '../lang-map.js';

const { Ast } = Markdoc;

function resolveAttributeValue(
	value: unknown,
	variables: Record<string, unknown> | undefined,
): string {
	if (value === undefined || value === null) return '';
	if (typeof value === 'string') return value;
	if (typeof value === 'number' || typeof value === 'boolean') return String(value);
	if (typeof value === 'object' && '$$mdtype' in (value as Record<string, unknown>)) {
		const node = value as { $$mdtype: string; path?: unknown };
		if (node.$$mdtype === 'Variable' && Array.isArray(node.path)) {
			let current: unknown = variables;
			for (const segment of node.path as string[]) {
				if (current === null || current === undefined) return '';
				current = (current as Record<string, unknown>)[segment];
			}
			return current === null || current === undefined ? '' : String(current);
		}
	}
	return '';
}

function makeErrorFence(pathAttr: string, message: string): Node {
	return new Ast.Node('fence', {
		content: `snippet error: ${message}\n`,
		language: 'text',
		source: pathAttr || '(unresolved)',
		snippet: true,
		'data-snippet-error': message,
	});
}

function resolveSnippetToFence(
	tag: Node,
	page: PreprocessPage,
	ctx: PreprocessContext,
	files: ProjectFiles,
): Node {
	const pathAttr = resolveAttributeValue(tag.attributes.path, ctx.variables);
	const lines =
		tag.attributes.lines !== undefined
			? resolveAttributeValue(tag.attributes.lines, ctx.variables)
			: undefined;
	const langAttr =
		tag.attributes.lang !== undefined
			? resolveAttributeValue(tag.attributes.lang, ctx.variables)
			: undefined;
	const linenumbers = tag.attributes.linenumbers === true;
	const highlight =
		tag.attributes.highlight !== undefined
			? resolveAttributeValue(tag.attributes.highlight, ctx.variables)
			: undefined;

	const str = (name: string): string | undefined =>
		tag.attributes[name] !== undefined
			? resolveAttributeValue(tag.attributes[name], ctx.variables)
			: undefined;

	const anchor = {
		symbol: str('symbol'),
		match: str('match'),
		occurrence:
			tag.attributes.occurrence !== undefined ? Number(tag.attributes.occurrence) : undefined,
		extent: str('extent') as AnchorOptions['extent'],
		until: str('until'),
		through: str('through'),
		doc: tag.attributes.doc === undefined ? undefined : tag.attributes.doc === true,
	};
	const reindentAttr =
		tag.attributes.reindent === undefined ? undefined : tag.attributes.reindent === true;
	const highlightMatch = str('highlight-match');
	const reviewedAttr = str('reviewed');

	if (!pathAttr) {
		const msg =
			'snippet `path` attribute is required (and an unresolvable variable reference resolves to empty)';
		ctx.error(msg, page.url);
		return makeErrorFence('', msg);
	}

	let result;
	try {
		result = readSnippetFile({
			files,
			pathAttr,
			lines: lines || undefined,
			anchor,
			lang: langAttr || undefined,
			referencingPage: page.relativePath,
		});
	} catch (err) {
		if (err instanceof SnippetSandboxError) {
			ctx.error(err.message, page.url);
			return makeErrorFence(pathAttr, err.message);
		}
		const msg = (err as Error).message ?? String(err);
		ctx.error(`snippet "${pathAttr}" failed unexpectedly: ${msg}`, page.url);
		return makeErrorFence(pathAttr, msg);
	}

	for (const warning of result.warnings) {
		ctx.warn(warning, page.url);
	}

	if (reviewedAttr && reviewedAttr.length > 0) {
		const stored = parseMarker(reviewedAttr);
		const comparison = compareMarker(stored.strict, result.content, stored.loose);
		if (comparison.verdict === 'stale') {
			ctx.warn(
				`snippet \`${pathAttr}\` has changed since it was last reviewed. Re-read the prose ` +
					'around it, then run `refrakt snippet review --update` to see the diff and re-stamp.',
				page.url,
			);
		}
	}

	const language = langAttr && langAttr.length > 0 ? langAttr : inferLanguage(result.relativePath);

	// Line coordinates are fixed before `reindent`, which changes columns, not lines.
	const highlightMatchLinesFound = highlightMatch
		? highlightMatchLines(result.content, parseHighlightMatch(highlightMatch))
		: [];

	const content = shouldReindent(result.anchored, reindentAttr)
		? reindent(result.content)
		: result.content;

	const fenceAttrs: Record<string, unknown> = {
		content,
		language,
		source: result.relativePath,
		snippet: true,
	};
	if (lines) fenceAttrs.lines = lines;
	else if (result.anchored && result.start !== undefined && result.end !== undefined) {
		fenceAttrs.lines = `${result.start}-${result.end}`;
	}
	if (linenumbers) fenceAttrs.linenumbers = true;

	if (highlightMatchLinesFound.length > 0) {
		const base = result.start ?? 1;
		fenceAttrs.highlight = formatHighlight(highlightMatchLinesFound.map((n) => n + base - 1));
	} else if (highlight && highlight.length > 0) {
		fenceAttrs.highlight = highlight;
	}

	return new Ast.Node('fence', fenceAttrs);
}

function preprocessSnippet(tag: Node, page: PreprocessPage, ctx: PreprocessContext): Node | void {
	if (!ctx.sandbox) return;
	return resolveSnippetToFence(tag, page, ctx, ctx.sandbox);
}

export const snippet = createContentModelSchema({
	attributes: {
		path: {
			type: String,
			required: true,
			description:
				'Path to the source file, relative to the project root. Rejected if it escapes the root.',
		},
		lines: {
			type: String,
			required: false,
			description:
				'Line range. Formats: "10-25", "10-" (to EOF), "-20" (from start), "10" (single line). 1-indexed, inclusive. A coordinate into a file nobody promised to hold still — prefer `symbol` or `match`, which survive edits above the region. Mutually exclusive with both.',
		},
		symbol: {
			type: String,
			required: false,
			description:
				'Name a declaration instead of a line range: `symbol="SiteConfig"`. The anchor is built from the language\'s keyword table, so a symbol that moves is still found and a symbol that is renamed fails loudly instead of rendering the wrong region. Includes the doc comment by default (see `doc`).',
		},
		match: {
			type: String,
			required: false,
			description:
				'Raw regex anchor, applied per line: `match="^\\\\.rf-hint\\\\s*\\\\{"`. The general form — `symbol` is sugar over it — and the way to address a language whose keywords the table does not carry.',
		},
		occurrence: {
			type: Number,
			required: false,
			description:
				'Which match to take when the anchor is ambiguous, 1-based. An escape hatch, not a naming form: it is a better coordinate than a line number, but it still drifts when another match is inserted above the one addressed. Prefer a more specific `match=`. Out of range refuses rather than clamping.',
		},
		extent: {
			type: String,
			required: false,
			matches: ['auto', 'dedent', 'section', 'paired'],
			description:
				"How far the slice runs. `auto` (default) balances delimiters — TS, CSS, JSON. `dedent` consumes lines indented deeper than the anchor — Python, YAML. `section` runs to the next sibling at the anchor's own level — Markdown headings, TOML tables. `paired` balances a token pair — Markdoc, HTML, Svelte. Never inferred from the file.",
		},
		until: {
			type: String,
			required: false,
			description:
				'Regex ending the extent, excluding the matching line. Overrides `extent`. Refuses if it never matches rather than returning the rest of the file.',
		},
		through: {
			type: String,
			required: false,
			description:
				'As `until`, but including the matching line. Two attributes rather than one flag because `until="^}"` in code wants the brace in and `until="^## "` in Markdown wants the heading out — either default is silently wrong half the time.',
		},
		doc: {
			type: Boolean,
			required: false,
			description:
				'Include the preceding doc comment. Defaults on for `symbol` (which names an entity and delegates the boundary) and off for `match` (which names a line the author already chose). Annotations and decorators attach regardless.',
		},
		reindent: {
			type: Boolean,
			required: false,
			description:
				"Strip the slice's common leading whitespace, so a nested target does not render with a ragged left edge. Defaults on for `symbol`/`match` and off for `lines`, so no existing line-addressed invocation changes how it renders. Relative structure is preserved, so a dedented Python method stays valid.",
		},
		reviewed: {
			type: String,
			required: false,
			description:
				'Records that a human read this version of the slice and confirmed the prose around it matched. Freezes nothing — the snippet still tracks HEAD and re-resolves every build. When the slice changes, a diagnostic asks for a re-read; the page still renders the current code. Written by `refrakt snippet review`, never by hand.',
		},
		'highlight-match': {
			type: String,
			required: false,
			description:
				'Comma-separated regexes; lines matching any of them are emphasized. The anchor-native form of `highlight` — under an anchor the author never saw a line number, so content is the only thing they can point at.',
		},
		lang: {
			type: String,
			required: false,
			description: 'Syntax-highlighting language hint. Overrides the extension-based inference.',
		},
		linenumbers: {
			type: Boolean,
			required: false,
			description:
				'Show line numbers in the gutter. Starting number derives from the `lines` range start (e.g. lines="74-125" → first line is 74), so numbers reflect the file\'s real offsets.',
		},
		highlight: {
			type: String,
			required: false,
			description:
				'Range(s) to emphasize without cropping — Shiki-style format: "74-78", "74-78,82,90-92". Indices are file coordinates (same frame as `lines=`), and stay so under an anchor. Note that a *numeric* highlight under `symbol`/`match` carries the same coordinate exposure anchoring otherwise removes — the resolver chose the region, so the author is guessing at its line numbers. Use `highlight-match` there.',
		},
	},
	contentModel: { type: 'sequence', fields: [] },
	preprocess: preprocessSnippet,
	transform(_resolved, _attrs) {
		throw new Error(
			'{% snippet %} reached the transform phase unresolved.\n\n' +
				'If this file is pulled in with {% partial %}: use {% include %} instead. ' +
				'Markdoc expands partials during the transform, which is after the preprocess ' +
				'phase that resolves `snippet` — so a `snippet` tag inside a partial never gets ' +
				'read. {% include file="..." /%} pastes the file before preprocess, so `snippet` ' +
				'and `data` inside it resolve. Both runes read the same `_partials/` directory ' +
				'and file roots, so only the call site changes.\n\n' +
				'If you are building a custom pipeline: registered `preprocess` hooks must run ' +
				'before `Markdoc.transform` (snippet pre-resolves to a Markdoc `fence` node).',
		);
	},
});

View packages/runes/src/tags/snippet.ts on GitHub

Embed a project file, or part of one, as a syntax-highlighted code block. The file is read on every build, so the page never drifts from the code. A snippet is an ordinary code block once it is read, so it works anywhere a fenced block does, including inside {% codegroup %} and {% diff %}.

Basic usage

path is relative to the project root. With nothing else, the whole file is embedded:

{% snippet path="site/examples/counter/script.js" /%}
<div class="rf-codeblock">
  <pre data-language="javascript" data-source="site/examples/counter/script.js">
    <code data-language="javascript" data-source="site/examples/counter/script.js">let count = 0;
function update(delta) {
	count += delta;
	document.getElementById('count').textContent = count;
}
</code>
  </pre>
</div>
let count = 0;
function update(delta) {
	count += delta;
	document.getElementById('count').textContent = count;
}
<div class="rf-codeblock">
  <pre data-language="javascript" data-source="site/examples/counter/script.js"><code data-language="javascript" data-source="site/examples/counter/script.js">let count = 0;
function update(delta) {
	count += delta;
	document.getElementById('count').textContent = count;
}
</code></pre>
</div>

Paths must stay inside the project: absolute paths, .. that climbs out, symlinks that point out, and directories are build errors, as is a missing file.

Embed part of a file by name

A line range breaks silently when someone edits the file above it. Name the region instead. symbol finds a declaration wherever it has moved to, and fails the build if it is renamed or deleted:

{% snippet path="packages/runes/src/lang-map.ts" symbol="inferLanguage" /%}
<div class="rf-codeblock">
  <pre data-language="typescript" data-source="packages/runes/src/lang-map.ts" data-lines="48-85" style="--rf-start-line: 47">
    <code data-language="typescript" data-source="packages/runes/src/lang-map.ts" data-lines="48-85">/**
 * Infer the highlight-language identifier from a file path or extension.
 *
 * Accepts a full path (`&quot;src/lib/foo.ts&quot;`), a bare extension with the dot
 * (`&quot;.ts&quot;`), or a bare extension without (`&quot;ts&quot;`). Unknown extensions
 * return {@link FALLBACK_LANG}.
 *
 * @example
 * ```ts
 * inferLanguage('src/lib/foo.ts');   // 'typescript'
 * inferLanguage('.svelte');           // 'svelte'
 * inferLanguage('config.unknown');    // 'text'
 * ```
 */
export function inferLanguage(pathOrExt: string): string {
	if (typeof pathOrExt !== 'string' || pathOrExt.length === 0) return FALLBACK_LANG;

	// Reduce to the trailing extension. Three accepted shapes:
	// - `&quot;foo/bar.ts&quot;` → last segment is `bar.ts`; extension is `.ts`
	// - `&quot;.ts&quot;` → already an extension
	// - `&quot;ts&quot;` → bare extension, no dot
	let ext: string;
	const lastSlash = Math.max(pathOrExt.lastIndexOf('/'), pathOrExt.lastIndexOf('\\'));
	const lastSegment = lastSlash &gt;= 0 ? pathOrExt.slice(lastSlash + 1) : pathOrExt;
	const lastDot = lastSegment.lastIndexOf('.');
	if (lastDot === -1) {
		// No dot anywhere — treat the whole string as a bare extension.
		ext = '.' + lastSegment.toLowerCase();
	} else if (lastDot === 0) {
		// Leading dot only — `&quot;.ts&quot;` style.
		ext = lastSegment.toLowerCase();
	} else {
		// Normal `name.ext`.
		ext = lastSegment.slice(lastDot).toLowerCase();
	}

	return LANG_MAP[ext] ?? FALLBACK_LANG;
}</code>
  </pre>
</div>
/**
 * Infer the highlight-language identifier from a file path or extension.
 *
 * Accepts a full path (`"src/lib/foo.ts"`), a bare extension with the dot
 * (`".ts"`), or a bare extension without (`"ts"`). Unknown extensions
 * return {@link FALLBACK_LANG}.
 *
 * @example
 * ```ts
 * inferLanguage('src/lib/foo.ts');   // 'typescript'
 * inferLanguage('.svelte');           // 'svelte'
 * inferLanguage('config.unknown');    // 'text'
 * ```
 */
export function inferLanguage(pathOrExt: string): string {
	if (typeof pathOrExt !== 'string' || pathOrExt.length === 0) return FALLBACK_LANG;

	// Reduce to the trailing extension. Three accepted shapes:
	// - `"foo/bar.ts"` → last segment is `bar.ts`; extension is `.ts`
	// - `".ts"` → already an extension
	// - `"ts"` → bare extension, no dot
	let ext: string;
	const lastSlash = Math.max(pathOrExt.lastIndexOf('/'), pathOrExt.lastIndexOf('\\'));
	const lastSegment = lastSlash >= 0 ? pathOrExt.slice(lastSlash + 1) : pathOrExt;
	const lastDot = lastSegment.lastIndexOf('.');
	if (lastDot === -1) {
		// No dot anywhere — treat the whole string as a bare extension.
		ext = '.' + lastSegment.toLowerCase();
	} else if (lastDot === 0) {
		// Leading dot only — `".ts"` style.
		ext = lastSegment.toLowerCase();
	} else {
		// Normal `name.ext`.
		ext = lastSegment.slice(lastDot).toLowerCase();
	}

	return LANG_MAP[ext] ?? FALLBACK_LANG;
}
<div class="rf-codeblock">
  <pre data-language="typescript" data-source="packages/runes/src/lang-map.ts" data-lines="48-85" style="--rf-start-line: 47"><code data-language="typescript" data-source="packages/runes/src/lang-map.ts" data-lines="48-85">/**
 * Infer the highlight-language identifier from a file path or extension.
 *
 * Accepts a full path (`&quot;src/lib/foo.ts&quot;`), a bare extension with the dot
 * (`&quot;.ts&quot;`), or a bare extension without (`&quot;ts&quot;`). Unknown extensions
 * return {@link FALLBACK_LANG}.
 *
 * @example
 * ```ts
 * inferLanguage('src/lib/foo.ts');   // 'typescript'
 * inferLanguage('.svelte');           // 'svelte'
 * inferLanguage('config.unknown');    // 'text'
 * ```
 */
export function inferLanguage(pathOrExt: string): string {
	if (typeof pathOrExt !== 'string' || pathOrExt.length === 0) return FALLBACK_LANG;

	// Reduce to the trailing extension. Three accepted shapes:
	// - `&quot;foo/bar.ts&quot;` → last segment is `bar.ts`; extension is `.ts`
	// - `&quot;.ts&quot;` → already an extension
	// - `&quot;ts&quot;` → bare extension, no dot
	let ext: string;
	const lastSlash = Math.max(pathOrExt.lastIndexOf('/'), pathOrExt.lastIndexOf('\\'));
	const lastSegment = lastSlash &gt;= 0 ? pathOrExt.slice(lastSlash + 1) : pathOrExt;
	const lastDot = lastSegment.lastIndexOf('.');
	if (lastDot === -1) {
		// No dot anywhere — treat the whole string as a bare extension.
		ext = '.' + lastSegment.toLowerCase();
	} else if (lastDot === 0) {
		// Leading dot only — `&quot;.ts&quot;` style.
		ext = lastSegment.toLowerCase();
	} else {
		// Normal `name.ext`.
		ext = lastSegment.slice(lastDot).toLowerCase();
	}

	return LANG_MAP[ext] ?? FALLBACK_LANG;
}</code></pre>
</div>

match takes a regex applied to each line of the raw source, for anything symbol does not cover: match="^.counter span" picks a CSS rule. Matches inside comments are skipped.

Where the slice ends

extent sets how far the slice runs from the anchor. It is never guessed from the file.

extentEnds atFor
auto (default)a ; or the matching }TypeScript, CSS, JSON
dedentthe first line back at the anchor's indentPython, YAML
sectionthe next sibling at the anchor's own levelMarkdown headings, TOML tables
pairedthe matching close tokenMarkdoc, HTML, Svelte

auto refuses a language without braces and semicolons, and names extent="dedent" instead.

When an anchor is not enough

WriteTo
through="^}"End at a regex, including the matching line
until="^## "End at a regex, excluding the matching line
occurrence=2Take the second match when the anchor matches more than once
lines="10-25"Use a line range

An ambiguous anchor warns and names every line that matched. Prefer a more specific match over occurrence: another match added above the one you meant shifts the count. An occurrence past the last match is an error.

Embed a line range

lines slices by line number, 1-indexed and inclusive, as your editor counts them. Prefer an anchor where you can.

InputMeaning
"10-25"Lines 10 through 25
"10-"Line 10 to the end of the file
"-20"Lines 1 through 20
"10"Line 10 only

An end past the end of the file is clamped, with a warning; a start past it is a build error.

{% snippet path="biome.jsonc" lines="36-41" /%}
<div class="rf-codeblock">
  <pre data-language="jsonc" data-source="biome.jsonc" data-lines="36-41" style="--rf-start-line: 35">
    <code data-language="jsonc" data-source="biome.jsonc" data-lines="36-41">  &quot;formatter&quot;: {
    &quot;enabled&quot;: true,
    &quot;useEditorconfig&quot;: true,
    &quot;indentStyle&quot;: &quot;tab&quot;,
    &quot;lineWidth&quot;: 100
  },</code>
  </pre>
</div>
  "formatter": {
    "enabled": true,
    "useEditorconfig": true,
    "indentStyle": "tab",
    "lineWidth": 100
  },
<div class="rf-codeblock">
  <pre data-language="jsonc" data-source="biome.jsonc" data-lines="36-41" style="--rf-start-line: 35"><code data-language="jsonc" data-source="biome.jsonc" data-lines="36-41">  &quot;formatter&quot;: {
    &quot;enabled&quot;: true,
    &quot;useEditorconfig&quot;: true,
    &quot;indentStyle&quot;: &quot;tab&quot;,
    &quot;lineWidth&quot;: 100
  },</code></pre>
</div>

Show line numbers and highlight lines

linenumbers=true adds a gutter, and highlight emphasizes lines without cutting the rest. Both count in the file's own line numbers, so the gutter below starts at 36 and highlight="39-40" marks file lines 39 and 40.

{% snippet path="biome.jsonc" lines="36-53" linenumbers=true highlight="39-40" /%}
<div class="rf-codeblock">
  <pre data-language="jsonc" data-source="biome.jsonc" data-lines="36-53" style="--rf-start-line: 35" data-linenumbers="true" data-highlight-lines="39-40">
    <code data-language="jsonc" data-source="biome.jsonc" data-lines="36-53" data-linenumbers="true" data-highlight-lines="39-40">  &quot;formatter&quot;: {
    &quot;enabled&quot;: true,
    &quot;useEditorconfig&quot;: true,
    &quot;indentStyle&quot;: &quot;tab&quot;,
    &quot;lineWidth&quot;: 100
  },
  &quot;javascript&quot;: {
    &quot;formatter&quot;: {
      &quot;quoteStyle&quot;: &quot;single&quot;,
      &quot;jsxQuoteStyle&quot;: &quot;double&quot;
    }
  },
  &quot;json&quot;: {
    &quot;formatter&quot;: {
      &quot;indentStyle&quot;: &quot;space&quot;,
      &quot;indentWidth&quot;: 2
    }
  },</code>
  </pre>
</div>
  "formatter": {
    "enabled": true,
    "useEditorconfig": true,
    "indentStyle": "tab",
    "lineWidth": 100
  },
  "javascript": {
    "formatter": {
      "quoteStyle": "single",
      "jsxQuoteStyle": "double"
    }
  },
  "json": {
    "formatter": {
      "indentStyle": "space",
      "indentWidth": 2
    }
  },
<div class="rf-codeblock">
  <pre data-language="jsonc" data-source="biome.jsonc" data-lines="36-53" style="--rf-start-line: 35" data-linenumbers="true" data-highlight-lines="39-40"><code data-language="jsonc" data-source="biome.jsonc" data-lines="36-53" data-linenumbers="true" data-highlight-lines="39-40">  &quot;formatter&quot;: {
    &quot;enabled&quot;: true,
    &quot;useEditorconfig&quot;: true,
    &quot;indentStyle&quot;: &quot;tab&quot;,
    &quot;lineWidth&quot;: 100
  },
  &quot;javascript&quot;: {
    &quot;formatter&quot;: {
      &quot;quoteStyle&quot;: &quot;single&quot;,
      &quot;jsxQuoteStyle&quot;: &quot;double&quot;
    }
  },
  &quot;json&quot;: {
    &quot;formatter&quot;: {
      &quot;indentStyle&quot;: &quot;space&quot;,
      &quot;indentWidth&quot;: 2
    }
  },</code></pre>
</div>

highlight takes ranges, single lines, or a mix: "74-78,82,90-92". With symbol or match, use highlight-match instead, which takes regexes, so you are not guessing line numbers. An anchored slice also has its common indentation stripped (reindent), so a method does not render with a ragged left edge; a lines slice keeps its columns.

Both linenumbers and highlight work on a hand-written fence too: ```ts {% linenumbers=true highlight="3-5" %}.

Set the language

The language comes from the file extension:

ExtensionLanguage
.ts, .tsxtypescript
.js, .jsx, .mjs, .cjsjavascript
.sveltesvelte
.vuevue
.md, .markdocmarkdoc
.jsonjson
.jsoncjsonc
.htmlhtml
.csscss
.yml, .yamlyaml
.tomltoml
.sh, .bashbash
(others)text (no highlighting)

Set lang when the extension is misleading. A tsconfig.json holds comments, which would highlight as errors as json:

{% snippet path="site/tsconfig.json" lang="jsonc" /%}
<div class="rf-codeblock">
  <pre data-language="jsonc" data-source="site/tsconfig.json">
    <code data-language="jsonc" data-source="site/tsconfig.json">{
  &quot;extends&quot;: &quot;./.svelte-kit/tsconfig.json&quot;,
  &quot;compilerOptions&quot;: {
    &quot;rewriteRelativeImportExtensions&quot;: true,
    &quot;allowJs&quot;: true,
    &quot;checkJs&quot;: true,
    &quot;esModuleInterop&quot;: true,
    &quot;forceConsistentCasingInFileNames&quot;: true,
    &quot;resolveJsonModule&quot;: true,
    &quot;skipLibCheck&quot;: true,
    &quot;sourceMap&quot;: true,
    &quot;strict&quot;: true,
    &quot;moduleResolution&quot;: &quot;bundler&quot;
  }
  // Path aliases are handled by https://svelte.dev/docs/kit/configuration#alias
  // except $lib which is handled by https://svelte.dev/docs/kit/configuration#files
  //
  // To make changes to top-level options such as include and exclude, we recommend extending
  // the generated config; see https://svelte.dev/docs/kit/configuration#typescript
}
</code>
  </pre>
</div>
{
  "extends": "./.svelte-kit/tsconfig.json",
  "compilerOptions": {
    "rewriteRelativeImportExtensions": true,
    "allowJs": true,
    "checkJs": true,
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "resolveJsonModule": true,
    "skipLibCheck": true,
    "sourceMap": true,
    "strict": true,
    "moduleResolution": "bundler"
  }
  // Path aliases are handled by https://svelte.dev/docs/kit/configuration#alias
  // except $lib which is handled by https://svelte.dev/docs/kit/configuration#files
  //
  // To make changes to top-level options such as include and exclude, we recommend extending
  // the generated config; see https://svelte.dev/docs/kit/configuration#typescript
}
<div class="rf-codeblock">
  <pre data-language="jsonc" data-source="site/tsconfig.json"><code data-language="jsonc" data-source="site/tsconfig.json">{
  &quot;extends&quot;: &quot;./.svelte-kit/tsconfig.json&quot;,
  &quot;compilerOptions&quot;: {
    &quot;rewriteRelativeImportExtensions&quot;: true,
    &quot;allowJs&quot;: true,
    &quot;checkJs&quot;: true,
    &quot;esModuleInterop&quot;: true,
    &quot;forceConsistentCasingInFileNames&quot;: true,
    &quot;resolveJsonModule&quot;: true,
    &quot;skipLibCheck&quot;: true,
    &quot;sourceMap&quot;: true,
    &quot;strict&quot;: true,
    &quot;moduleResolution&quot;: &quot;bundler&quot;
  }
  // Path aliases are handled by https://svelte.dev/docs/kit/configuration#alias
  // except $lib which is handled by https://svelte.dev/docs/kit/configuration#files
  //
  // To make changes to top-level options such as include and exclude, we recommend extending
  // the generated config; see https://svelte.dev/docs/kit/configuration#typescript
}
</code></pre>
</div>

Add a caption or a title

A snippet has no title of its own. Wrap it in {% figure caption="…" %} for a caption below the code, or in {% codegroup title="…" %} for a title bar above it, like an editor tab naming the file.

{% figure caption="The counter's click handler: one function, called with +1 or −1" %}
	{% snippet path="site/examples/counter/script.js" symbol="update" /%}
{% /figure %}
<figure data-rune="figure" data-rune-fields="{&quot;body&quot;:&quot;mixed&quot;}">
  <div class="rf-codeblock">
    <pre data-language="javascript" data-source="site/examples/counter/script.js" data-lines="2-5" style="--rf-start-line: 1">
      <code data-language="javascript" data-source="site/examples/counter/script.js" data-lines="2-5">function update(delta) {
	count += delta;
	document.getElementById('count').textContent = count;
}</code>
    </pre>
  </div>
  <figcaption data-name="caption">The counter's click handler: one function, called with +1 or −1</figcaption>
</figure>
function update(delta) {
	count += delta;
	document.getElementById('count').textContent = count;
}
The counter's click handler: one function, called with +1 or −1
<figure class="rf-figure rf-figure--default rf-figure--center" data-size="default" data-align="center" data-elevation="flat" data-rune="figure" data-density="compact">
  <div class="rf-codeblock">
    <pre data-language="javascript" data-source="site/examples/counter/script.js" data-lines="2-5" style="--rf-start-line: 1"><code data-language="javascript" data-source="site/examples/counter/script.js" data-lines="2-5">function update(delta) {
	count += delta;
	document.getElementById('count').textContent = count;
}</code></pre>
  </div>
  <figcaption data-name="caption" class="rf-figure__caption" data-section="description">The counter's click handler: one function, called with +1 or −1</figcaption>
</figure>

Use snippets in codegroup and diff

Containers that take code blocks take snippets too, mixed freely with fences. In a codegroup each becomes a tab:

{% codegroup %}
	{% snippet path="site/examples/counter/script.js" /%}
	```html
	<!-- Load the script after the counter's markup -->
	<script src="script.js"></script>
	```
{% /codegroup %}
<section data-rune="code-group">
  <div role="tablist" data-name="tabs">
    <button data-name="tab" role="tab">
      <span>script.js</span>
    </button>
    <button data-name="tab" role="tab">
      <span>HTML</span>
    </button>
  </div>
  <div data-name="panels">
    <div role="tabpanel" data-name="panel">
      <div class="rf-codeblock">
        <pre data-language="javascript" data-source="site/examples/counter/script.js">
          <code data-language="javascript" data-source="site/examples/counter/script.js">let count = 0;
function update(delta) {
	count += delta;
	document.getElementById('count').textContent = count;
}
</code>
        </pre>
      </div>
    </div>
    <div role="tabpanel" data-name="panel">
      <div class="rf-codeblock">
        <pre data-language="html">
          <code data-language="html">&lt;!-- Load the script after the counter's markup --&gt;
&lt;script src=&quot;script.js&quot;&gt;&lt;/script&gt;
</code>
        </pre>
      </div>
    </div>
  </div>
</section>
let count = 0;
function update(delta) {
	count += delta;
	document.getElementById('count').textContent = count;
}
<!-- Load the script after the counter's markup -->
<script src="script.js"></script>
<section class="rf-codegroup rf-codegroup--scroll" data-overflow="scroll" data-elevation="flat" data-rune="code-group" data-density="compact" data-code-host="true">
  <div role="tablist" data-name="tabs" class="rf-codegroup__tabs">
    <button data-name="tab" role="tab" class="rf-codegroup__tab">
      <span>script.js</span>
    </button>
    <button data-name="tab" role="tab" class="rf-codegroup__tab">
      <span>HTML</span>
    </button>
  </div>
  <div data-name="panels" class="rf-codegroup__panels">
    <div role="tabpanel" data-name="panel" class="rf-codegroup__panel">
      <div class="rf-codeblock">
        <pre data-language="javascript" data-source="site/examples/counter/script.js"><code data-language="javascript" data-source="site/examples/counter/script.js">let count = 0;
function update(delta) {
	count += delta;
	document.getElementById('count').textContent = count;
}
</code></pre>
      </div>
    </div>
    <div role="tabpanel" data-name="panel" class="rf-codegroup__panel">
      <div class="rf-codeblock">
        <pre data-language="html"><code data-language="html">&lt;!-- Load the script after the counter's markup --&gt;
&lt;script src=&quot;script.js&quot;&gt;&lt;/script&gt;
</code></pre>
      </div>
    </div>
  </div>
</section>

In a diff, two snippets are the before and after; here the counter's button rule against its dark-theme override:

{% diff mode="split" %}
	{% snippet path="site/examples/counter/style.css" lines="8-15" /%}
	{% snippet path="site/examples/counter/style.css" lines="35-39" /%}
{% /diff %}
<div data-rune="diff" data-rune-fields="{&quot;mode&quot;:&quot;split&quot;,&quot;language&quot;:&quot;&quot;}" data-code-host>
  <div data-name="header">site/examples/counter/style.css</div>
  <div data-name="split-container">
    <div data-name="panel">
      <pre data-name="code" data-copy-selector="[data-name=&quot;line-content&quot;]">
        <div data-name="rows">
          <span data-name="line" data-line-status="remove">
            <span data-name="gutter-num" data-side="before">8</span>
            <span data-name="line-content" data-language="css">.counter button {</span>
          </span>
          <span data-name="line" data-line-status="remove">
            <span data-name="gutter-num" data-side="before">9</span>
            <span data-name="line-content" data-language="css">	padding: 6px 16px;</span>
          </span>
          <span data-name="line" data-line-status="remove">
            <span data-name="gutter-num" data-side="before">10</span>
            <span data-name="line-content" data-language="css">	border: 1px solid #d1d5db;</span>
          </span>
          <span data-name="line" data-line-status="remove">
            <span data-name="gutter-num" data-side="before">11</span>
            <span data-name="line-content" data-language="css">	border-radius: 6px;</span>
          </span>
          <span data-name="line" data-line-status="remove">
            <span data-name="gutter-num" data-side="before">12</span>
            <span data-name="line-content" data-language="css">	background: white;</span>
          </span>
          <span data-name="line" data-line-status="remove">
            <span data-name="gutter-num" data-side="before">13</span>
            <span data-name="line-content" data-language="css">	cursor: pointer;</span>
          </span>
          <span data-name="line" data-line-status="remove">
            <span data-name="gutter-num" data-side="before">14</span>
            <span data-name="line-content" data-language="css">	font-size: 16px;</span>
          </span>
          <span data-name="line" data-line-status="equal">
            <span data-name="gutter-num" data-side="before">15</span>
            <span data-name="line-content" data-language="css">}</span>
          </span>
        </div>
      </pre>
    </div>
    <div data-name="panel">
      <pre data-name="code" data-copy-selector="[data-name=&quot;line-content&quot;]">
        <div data-name="rows">
          <span data-name="line" data-line-status="add">
            <span data-name="gutter-num" data-side="after">35</span>
            <span data-name="line-content" data-language="css">[data-theme=&quot;dark&quot;] .counter button {</span>
          </span>
          <span data-name="line" data-line-status="add">
            <span data-name="gutter-num" data-side="after">36</span>
            <span data-name="line-content" data-language="css">	background: #374151;</span>
          </span>
          <span data-name="line" data-line-status="add">
            <span data-name="gutter-num" data-side="after">37</span>
            <span data-name="line-content" data-language="css">	border-color: #4b5563;</span>
          </span>
          <span data-name="line" data-line-status="add">
            <span data-name="gutter-num" data-side="after">38</span>
            <span data-name="line-content" data-language="css">	color: #f3f4f6;</span>
          </span>
          <span data-name="line" data-line-status="empty">
            <span data-name="gutter-num" data-side="after"></span>
            <span data-name="line-content"></span>
          </span>
          <span data-name="line" data-line-status="empty">
            <span data-name="gutter-num" data-side="after"></span>
            <span data-name="line-content"></span>
          </span>
          <span data-name="line" data-line-status="empty">
            <span data-name="gutter-num" data-side="after"></span>
            <span data-name="line-content"></span>
          </span>
          <span data-name="line" data-line-status="equal">
            <span data-name="gutter-num" data-side="after">39</span>
            <span data-name="line-content" data-language="css">}</span>
          </span>
        </div>
      </pre>
    </div>
  </div>
</div>
site/examples/counter/style.css
8.counter button {9 padding: 6px 16px;10 border: 1px solid #d1d5db;11 border-radius: 6px;12 background: white;13 cursor: pointer;14 font-size: 16px;15}
35[data-theme="dark"] .counter button {36 background: #374151;37 border-color: #4b5563;38 color: #f3f4f6;39}
<div class="rf-diff rf-diff--split" data-code-host data-mode="split" data-rune="diff" data-density="full">
  <div data-name="header" class="rf-diff__header">site/examples/counter/style.css</div>
  <div data-name="split-container" class="rf-diff__split-container">
    <div data-name="panel" class="rf-diff__panel">
      <pre data-name="code" data-copy-selector="[data-name=&quot;line-content&quot;]" class="rf-diff__code"><div data-name="rows" class="rf-diff__rows"><span data-name="line" data-line-status="remove" class="rf-diff__line"><span data-name="gutter-num" data-side="before" class="rf-diff__gutter-num">8</span><span data-name="line-content" data-language="css" class="rf-diff__line-content">.counter button {</span></span><span data-name="line" data-line-status="remove" class="rf-diff__line"><span data-name="gutter-num" data-side="before" class="rf-diff__gutter-num">9</span><span data-name="line-content" data-language="css" class="rf-diff__line-content">	padding: 6px 16px;</span></span><span data-name="line" data-line-status="remove" class="rf-diff__line"><span data-name="gutter-num" data-side="before" class="rf-diff__gutter-num">10</span><span data-name="line-content" data-language="css" class="rf-diff__line-content">	border: 1px solid #d1d5db;</span></span><span data-name="line" data-line-status="remove" class="rf-diff__line"><span data-name="gutter-num" data-side="before" class="rf-diff__gutter-num">11</span><span data-name="line-content" data-language="css" class="rf-diff__line-content">	border-radius: 6px;</span></span><span data-name="line" data-line-status="remove" class="rf-diff__line"><span data-name="gutter-num" data-side="before" class="rf-diff__gutter-num">12</span><span data-name="line-content" data-language="css" class="rf-diff__line-content">	background: white;</span></span><span data-name="line" data-line-status="remove" class="rf-diff__line"><span data-name="gutter-num" data-side="before" class="rf-diff__gutter-num">13</span><span data-name="line-content" data-language="css" class="rf-diff__line-content">	cursor: pointer;</span></span><span data-name="line" data-line-status="remove" class="rf-diff__line"><span data-name="gutter-num" data-side="before" class="rf-diff__gutter-num">14</span><span data-name="line-content" data-language="css" class="rf-diff__line-content">	font-size: 16px;</span></span><span data-name="line" data-line-status="equal" class="rf-diff__line"><span data-name="gutter-num" data-side="before" class="rf-diff__gutter-num">15</span><span data-name="line-content" data-language="css" class="rf-diff__line-content">}</span></span></div></pre>
    </div>
    <div data-name="panel" class="rf-diff__panel">
      <pre data-name="code" data-copy-selector="[data-name=&quot;line-content&quot;]" class="rf-diff__code"><div data-name="rows" class="rf-diff__rows"><span data-name="line" data-line-status="add" class="rf-diff__line"><span data-name="gutter-num" data-side="after" class="rf-diff__gutter-num">35</span><span data-name="line-content" data-language="css" class="rf-diff__line-content">[data-theme=&quot;dark&quot;] .counter button {</span></span><span data-name="line" data-line-status="add" class="rf-diff__line"><span data-name="gutter-num" data-side="after" class="rf-diff__gutter-num">36</span><span data-name="line-content" data-language="css" class="rf-diff__line-content">	background: #374151;</span></span><span data-name="line" data-line-status="add" class="rf-diff__line"><span data-name="gutter-num" data-side="after" class="rf-diff__gutter-num">37</span><span data-name="line-content" data-language="css" class="rf-diff__line-content">	border-color: #4b5563;</span></span><span data-name="line" data-line-status="add" class="rf-diff__line"><span data-name="gutter-num" data-side="after" class="rf-diff__gutter-num">38</span><span data-name="line-content" data-language="css" class="rf-diff__line-content">	color: #f3f4f6;</span></span><span data-name="line" data-line-status="empty" class="rf-diff__line"><span data-name="gutter-num" data-side="after" class="rf-diff__gutter-num"></span><span data-name="line-content" class="rf-diff__line-content"></span></span><span data-name="line" data-line-status="empty" class="rf-diff__line"><span data-name="gutter-num" data-side="after" class="rf-diff__gutter-num"></span><span data-name="line-content" class="rf-diff__line-content"></span></span><span data-name="line" data-line-status="empty" class="rf-diff__line"><span data-name="gutter-num" data-side="after" class="rf-diff__gutter-num"></span><span data-name="line-content" class="rf-diff__line-content"></span></span><span data-name="line" data-line-status="equal" class="rf-diff__line"><span data-name="gutter-num" data-side="after" class="rf-diff__gutter-num">39</span><span data-name="line-content" data-language="css" class="rf-diff__line-content">}</span></span></div></pre>
    </div>
  </div>
</div>

Know when the code has outgrown its prose

An anchor keeps the snippet on the right code, but the paragraph beside it can still go stale when that code changes. A reviewed marker records that someone read this version of the slice against the prose. It freezes nothing: the snippet still shows current code, and a change asks for a re-read.

{% snippet path="packages/types/src/config.ts" symbol="SiteConfig" reviewed="a3f91c4e:70b2d118" /%}

The CLI writes markers; don't write them by hand.

refrakt snippet review site/content/runes/file-ref.md   # stamp unmarked snippets
refrakt snippet review --check                          # report changed ones
refrakt snippet review --update                         # show each diff and re-stamp

A reformat that leaves the meaning unchanged is re-stamped without asking. Mark only snippets whose prose makes specific claims about the code; marking every one makes --check noise that people learn to ignore.

Show a page's own source

Pass $file.path (Content variables) to embed the source of the page the reader is on. This one:

{% snippet path=$file.path lang="markdoc" /%}
<div class="rf-codeblock">
  <pre data-language="markdoc" data-source="site/content/runes/snippet.md">
    <code data-language="markdoc" data-source="site/content/runes/snippet.md">---
title: Snippet
description: Embed a project file as a syntax-highlighted code block — composes inside codegroup, diff, and any future fence-consuming container
category: Code
plugin: core
status: stable
type: rune
---

{% include file=&quot;rune-intro.md&quot; variables={r: &quot;rune:snippet&quot;} /%}

Embed a project file, or part of one, as a syntax-highlighted code block. The file is read on every build, so the page never drifts from the code. A snippet is an ordinary code block once it is read, so it works anywhere a fenced block does, including inside `{% codegroup %}` and `{% diff %}`.

## Basic usage

`path` is relative to the project root. With nothing else, the whole file is embedded:

{% preview source=true %}

	{% snippet path=&quot;site/examples/counter/script.js&quot; /%}

{% /preview %}

Paths must stay inside the project: absolute paths, `..` that climbs out, symlinks that point out, and directories are build errors, as is a missing file.

## Embed part of a file by name

A line range breaks silently when someone edits the file above it. Name the region instead. `symbol` finds a declaration wherever it has moved to, and fails the build if it is renamed or deleted:

{% preview source=true %}

	{% snippet path=&quot;packages/runes/src/lang-map.ts&quot; symbol=&quot;inferLanguage&quot; /%}

{% /preview %}

`match` takes a regex applied to each line of the raw source, for anything `symbol` does not cover: `match=&quot;^.counter span&quot;` picks a CSS rule. Matches inside comments are skipped.

### Where the slice ends

`extent` sets how far the slice runs from the anchor. It is never guessed from the file.

| `extent` | Ends at | For |
|---|---|---|
| `auto` *(default)* | a `;` or the matching `}` | TypeScript, CSS, JSON |
| `dedent` | the first line back at the anchor's indent | Python, YAML |
| `section` | the next sibling at the anchor's own level | Markdown headings, TOML tables |
| `paired` | the matching close token | Markdoc, HTML, Svelte |

`auto` refuses a language without braces and semicolons, and names `extent=&quot;dedent&quot;` instead.

### When an anchor is not enough

| Write | To |
|---|---|
| `through=&quot;^}&quot;` | End at a regex, including the matching line |
| `until=&quot;^## &quot;` | End at a regex, excluding the matching line |
| `occurrence=2` | Take the second match when the anchor matches more than once |
| `lines=&quot;10-25&quot;` | Use a line range |

An ambiguous anchor warns and names every line that matched. Prefer a more specific `match` over `occurrence`: another match added above the one you meant shifts the count. An `occurrence` past the last match is an error.

## Embed a line range

`lines` slices by line number, 1-indexed and inclusive, as your editor counts them. Prefer an anchor where you can.

| Input | Meaning |
|-------|---------|
| `&quot;10-25&quot;` | Lines 10 through 25 |
| `&quot;10-&quot;` | Line 10 to the end of the file |
| `&quot;-20&quot;` | Lines 1 through 20 |
| `&quot;10&quot;` | Line 10 only |

An end past the end of the file is clamped, with a warning; a start past it is a build error.

{% preview source=true %}

	{% snippet path=&quot;biome.jsonc&quot; lines=&quot;36-41&quot; /%}

{% /preview %}

## Show line numbers and highlight lines

`linenumbers=true` adds a gutter, and `highlight` emphasizes lines without cutting the rest. Both count in the file's own line numbers, so the gutter below starts at 36 and `highlight=&quot;39-40&quot;` marks file lines 39 and 40.

{% preview source=true %}

	{% snippet path=&quot;biome.jsonc&quot; lines=&quot;36-53&quot; linenumbers=true highlight=&quot;39-40&quot; /%}

{% /preview %}

`highlight` takes ranges, single lines, or a mix: `&quot;74-78,82,90-92&quot;`. With `symbol` or `match`, use `highlight-match` instead, which takes regexes, so you are not guessing line numbers. An anchored slice also has its common indentation stripped (`reindent`), so a method does not render with a ragged left edge; a `lines` slice keeps its columns.

Both `linenumbers` and `highlight` work on a hand-written fence too: `` ```ts {% linenumbers=true highlight=&quot;3-5&quot; %} ``.

## Set the language

The language comes from the file extension:

| Extension | Language |
|-----------|----------|
| `.ts`, `.tsx` | `typescript` |
| `.js`, `.jsx`, `.mjs`, `.cjs` | `javascript` |
| `.svelte` | `svelte` |
| `.vue` | `vue` |
| `.md`, `.markdoc` | `markdoc` |
| `.json` | `json` |
| `.jsonc` | `jsonc` |
| `.html` | `html` |
| `.css` | `css` |
| `.yml`, `.yaml` | `yaml` |
| `.toml` | `toml` |
| `.sh`, `.bash` | `bash` |
| (others) | `text` (no highlighting) |

Set `lang` when the extension is misleading. A `tsconfig.json` holds comments, which would highlight as errors as `json`:

{% preview source=true %}

	{% snippet path=&quot;site/tsconfig.json&quot; lang=&quot;jsonc&quot; /%}

{% /preview %}

## Add a caption or a title

A snippet has no title of its own. Wrap it in `{% figure caption=&quot;…&quot; %}` for a caption below the code, or in `{% codegroup title=&quot;…&quot; %}` for a title bar above it, like an editor tab naming the file.

{% preview source=true %}

	{% figure caption=&quot;The counter's click handler: one function, called with +1 or −1&quot; %}
		{% snippet path=&quot;site/examples/counter/script.js&quot; symbol=&quot;update&quot; /%}
	{% /figure %}

{% /preview %}

## Use snippets in codegroup and diff

Containers that take code blocks take snippets too, mixed freely with fences. In a codegroup each becomes a tab:

{% preview source=true %}

	{% codegroup %}
		{% snippet path=&quot;site/examples/counter/script.js&quot; /%}
		```html
		&lt;!-- Load the script after the counter's markup --&gt;
		&lt;script src=&quot;script.js&quot;&gt;&lt;/script&gt;
		```
	{% /codegroup %}

{% /preview %}

In a diff, two snippets are the before and after; here the counter's button rule against its dark-theme override:

{% preview source=true %}

	{% diff mode=&quot;split&quot; %}
		{% snippet path=&quot;site/examples/counter/style.css&quot; lines=&quot;8-15&quot; /%}
		{% snippet path=&quot;site/examples/counter/style.css&quot; lines=&quot;35-39&quot; /%}
	{% /diff %}

{% /preview %}

## Know when the code has outgrown its prose

An anchor keeps the snippet on the right code, but the paragraph beside it can still go stale when that code changes. A `reviewed` marker records that someone read this version of the slice against the prose. It freezes nothing: the snippet still shows current code, and a change asks for a re-read.

```markdoc
{% snippet path=&quot;packages/types/src/config.ts&quot; symbol=&quot;SiteConfig&quot; reviewed=&quot;a3f91c4e:70b2d118&quot; /%}
```

The CLI writes markers; don't write them by hand.

```bash
refrakt snippet review site/content/runes/file-ref.md   # stamp unmarked snippets
refrakt snippet review --check                          # report changed ones
refrakt snippet review --update                         # show each diff and re-stamp
```

A reformat that leaves the meaning unchanged is re-stamped without asking. Mark only snippets whose prose makes specific claims about the code; marking every one makes `--check` noise that people learn to ignore.

## Show a page's own source

Pass `$file.path` ({% xref &quot;/docs/authoring/variables&quot; /%}) to embed the source of the page the reader is on. This one:

{% preview source=true %}

	{% snippet path=$file.path lang=&quot;markdoc&quot; /%}

{% /preview %}

## Attributes

{% include file=&quot;rune-attributes.md&quot; variables={r: &quot;rune:snippet&quot;} /%}

## See also

- [Codegroup](/runes/codegroup) — tabbed code blocks; consumes snippet children transparently.
- [Figure](/runes/figure) — a captioned container; captions a snippet below the code.
- [Diff](/runes/diff) — before/after code comparison; consumes snippet children transparently.
- [Content variables](/docs/authoring/variables) — `$file.path` for the view-source-of-current-page pattern.
</code>
  </pre>
</div>
---
title: Snippet
description: Embed a project file as a syntax-highlighted code block — composes inside codegroup, diff, and any future fence-consuming container
category: Code
plugin: core
status: stable
type: rune
---

{% include file="rune-intro.md" variables={r: "rune:snippet"} /%}

Embed a project file, or part of one, as a syntax-highlighted code block. The file is read on every build, so the page never drifts from the code. A snippet is an ordinary code block once it is read, so it works anywhere a fenced block does, including inside `{% codegroup %}` and `{% diff %}`.

## Basic usage

`path` is relative to the project root. With nothing else, the whole file is embedded:

{% preview source=true %}

	{% snippet path="site/examples/counter/script.js" /%}

{% /preview %}

Paths must stay inside the project: absolute paths, `..` that climbs out, symlinks that point out, and directories are build errors, as is a missing file.

## Embed part of a file by name

A line range breaks silently when someone edits the file above it. Name the region instead. `symbol` finds a declaration wherever it has moved to, and fails the build if it is renamed or deleted:

{% preview source=true %}

	{% snippet path="packages/runes/src/lang-map.ts" symbol="inferLanguage" /%}

{% /preview %}

`match` takes a regex applied to each line of the raw source, for anything `symbol` does not cover: `match="^.counter span"` picks a CSS rule. Matches inside comments are skipped.

### Where the slice ends

`extent` sets how far the slice runs from the anchor. It is never guessed from the file.

| `extent` | Ends at | For |
|---|---|---|
| `auto` *(default)* | a `;` or the matching `}` | TypeScript, CSS, JSON |
| `dedent` | the first line back at the anchor's indent | Python, YAML |
| `section` | the next sibling at the anchor's own level | Markdown headings, TOML tables |
| `paired` | the matching close token | Markdoc, HTML, Svelte |

`auto` refuses a language without braces and semicolons, and names `extent="dedent"` instead.

### When an anchor is not enough

| Write | To |
|---|---|
| `through="^}"` | End at a regex, including the matching line |
| `until="^## "` | End at a regex, excluding the matching line |
| `occurrence=2` | Take the second match when the anchor matches more than once |
| `lines="10-25"` | Use a line range |

An ambiguous anchor warns and names every line that matched. Prefer a more specific `match` over `occurrence`: another match added above the one you meant shifts the count. An `occurrence` past the last match is an error.

## Embed a line range

`lines` slices by line number, 1-indexed and inclusive, as your editor counts them. Prefer an anchor where you can.

| Input | Meaning |
|-------|---------|
| `"10-25"` | Lines 10 through 25 |
| `"10-"` | Line 10 to the end of the file |
| `"-20"` | Lines 1 through 20 |
| `"10"` | Line 10 only |

An end past the end of the file is clamped, with a warning; a start past it is a build error.

{% preview source=true %}

	{% snippet path="biome.jsonc" lines="36-41" /%}

{% /preview %}

## Show line numbers and highlight lines

`linenumbers=true` adds a gutter, and `highlight` emphasizes lines without cutting the rest. Both count in the file's own line numbers, so the gutter below starts at 36 and `highlight="39-40"` marks file lines 39 and 40.

{% preview source=true %}

	{% snippet path="biome.jsonc" lines="36-53" linenumbers=true highlight="39-40" /%}

{% /preview %}

`highlight` takes ranges, single lines, or a mix: `"74-78,82,90-92"`. With `symbol` or `match`, use `highlight-match` instead, which takes regexes, so you are not guessing line numbers. An anchored slice also has its common indentation stripped (`reindent`), so a method does not render with a ragged left edge; a `lines` slice keeps its columns.

Both `linenumbers` and `highlight` work on a hand-written fence too: `` ```ts {% linenumbers=true highlight="3-5" %} ``.

## Set the language

The language comes from the file extension:

| Extension | Language |
|-----------|----------|
| `.ts`, `.tsx` | `typescript` |
| `.js`, `.jsx`, `.mjs`, `.cjs` | `javascript` |
| `.svelte` | `svelte` |
| `.vue` | `vue` |
| `.md`, `.markdoc` | `markdoc` |
| `.json` | `json` |
| `.jsonc` | `jsonc` |
| `.html` | `html` |
| `.css` | `css` |
| `.yml`, `.yaml` | `yaml` |
| `.toml` | `toml` |
| `.sh`, `.bash` | `bash` |
| (others) | `text` (no highlighting) |

Set `lang` when the extension is misleading. A `tsconfig.json` holds comments, which would highlight as errors as `json`:

{% preview source=true %}

	{% snippet path="site/tsconfig.json" lang="jsonc" /%}

{% /preview %}

## Add a caption or a title

A snippet has no title of its own. Wrap it in `{% figure caption="…" %}` for a caption below the code, or in `{% codegroup title="…" %}` for a title bar above it, like an editor tab naming the file.

{% preview source=true %}

	{% figure caption="The counter's click handler: one function, called with +1 or −1" %}
		{% snippet path="site/examples/counter/script.js" symbol="update" /%}
	{% /figure %}

{% /preview %}

## Use snippets in codegroup and diff

Containers that take code blocks take snippets too, mixed freely with fences. In a codegroup each becomes a tab:

{% preview source=true %}

	{% codegroup %}
		{% snippet path="site/examples/counter/script.js" /%}
		```html
		<!-- Load the script after the counter's markup -->
		<script src="script.js"></script>
		```
	{% /codegroup %}

{% /preview %}

In a diff, two snippets are the before and after; here the counter's button rule against its dark-theme override:

{% preview source=true %}

	{% diff mode="split" %}
		{% snippet path="site/examples/counter/style.css" lines="8-15" /%}
		{% snippet path="site/examples/counter/style.css" lines="35-39" /%}
	{% /diff %}

{% /preview %}

## Know when the code has outgrown its prose

An anchor keeps the snippet on the right code, but the paragraph beside it can still go stale when that code changes. A `reviewed` marker records that someone read this version of the slice against the prose. It freezes nothing: the snippet still shows current code, and a change asks for a re-read.

```markdoc
{% snippet path="packages/types/src/config.ts" symbol="SiteConfig" reviewed="a3f91c4e:70b2d118" /%}
```

The CLI writes markers; don't write them by hand.

```bash
refrakt snippet review site/content/runes/file-ref.md   # stamp unmarked snippets
refrakt snippet review --check                          # report changed ones
refrakt snippet review --update                         # show each diff and re-stamp
```

A reformat that leaves the meaning unchanged is re-stamped without asking. Mark only snippets whose prose makes specific claims about the code; marking every one makes `--check` noise that people learn to ignore.

## Show a page's own source

Pass `$file.path` ({% xref "/docs/authoring/variables" /%}) to embed the source of the page the reader is on. This one:

{% preview source=true %}

	{% snippet path=$file.path lang="markdoc" /%}

{% /preview %}

## Attributes

{% include file="rune-attributes.md" variables={r: "rune:snippet"} /%}

## See also

- [Codegroup](/runes/codegroup) — tabbed code blocks; consumes snippet children transparently.
- [Figure](/runes/figure) — a captioned container; captions a snippet below the code.
- [Diff](/runes/diff) — before/after code comparison; consumes snippet children transparently.
- [Content variables](/docs/authoring/variables) — `$file.path` for the view-source-of-current-page pattern.
<div class="rf-codeblock">
  <pre data-language="markdoc" data-source="site/content/runes/snippet.md"><code data-language="markdoc" data-source="site/content/runes/snippet.md">---
title: Snippet
description: Embed a project file as a syntax-highlighted code block — composes inside codegroup, diff, and any future fence-consuming container
category: Code
plugin: core
status: stable
type: rune
---

{% include file=&quot;rune-intro.md&quot; variables={r: &quot;rune:snippet&quot;} /%}

Embed a project file, or part of one, as a syntax-highlighted code block. The file is read on every build, so the page never drifts from the code. A snippet is an ordinary code block once it is read, so it works anywhere a fenced block does, including inside `{% codegroup %}` and `{% diff %}`.

## Basic usage

`path` is relative to the project root. With nothing else, the whole file is embedded:

{% preview source=true %}

	{% snippet path=&quot;site/examples/counter/script.js&quot; /%}

{% /preview %}

Paths must stay inside the project: absolute paths, `..` that climbs out, symlinks that point out, and directories are build errors, as is a missing file.

## Embed part of a file by name

A line range breaks silently when someone edits the file above it. Name the region instead. `symbol` finds a declaration wherever it has moved to, and fails the build if it is renamed or deleted:

{% preview source=true %}

	{% snippet path=&quot;packages/runes/src/lang-map.ts&quot; symbol=&quot;inferLanguage&quot; /%}

{% /preview %}

`match` takes a regex applied to each line of the raw source, for anything `symbol` does not cover: `match=&quot;^.counter span&quot;` picks a CSS rule. Matches inside comments are skipped.

### Where the slice ends

`extent` sets how far the slice runs from the anchor. It is never guessed from the file.

| `extent` | Ends at | For |
|---|---|---|
| `auto` *(default)* | a `;` or the matching `}` | TypeScript, CSS, JSON |
| `dedent` | the first line back at the anchor's indent | Python, YAML |
| `section` | the next sibling at the anchor's own level | Markdown headings, TOML tables |
| `paired` | the matching close token | Markdoc, HTML, Svelte |

`auto` refuses a language without braces and semicolons, and names `extent=&quot;dedent&quot;` instead.

### When an anchor is not enough

| Write | To |
|---|---|
| `through=&quot;^}&quot;` | End at a regex, including the matching line |
| `until=&quot;^## &quot;` | End at a regex, excluding the matching line |
| `occurrence=2` | Take the second match when the anchor matches more than once |
| `lines=&quot;10-25&quot;` | Use a line range |

An ambiguous anchor warns and names every line that matched. Prefer a more specific `match` over `occurrence`: another match added above the one you meant shifts the count. An `occurrence` past the last match is an error.

## Embed a line range

`lines` slices by line number, 1-indexed and inclusive, as your editor counts them. Prefer an anchor where you can.

| Input | Meaning |
|-------|---------|
| `&quot;10-25&quot;` | Lines 10 through 25 |
| `&quot;10-&quot;` | Line 10 to the end of the file |
| `&quot;-20&quot;` | Lines 1 through 20 |
| `&quot;10&quot;` | Line 10 only |

An end past the end of the file is clamped, with a warning; a start past it is a build error.

{% preview source=true %}

	{% snippet path=&quot;biome.jsonc&quot; lines=&quot;36-41&quot; /%}

{% /preview %}

## Show line numbers and highlight lines

`linenumbers=true` adds a gutter, and `highlight` emphasizes lines without cutting the rest. Both count in the file's own line numbers, so the gutter below starts at 36 and `highlight=&quot;39-40&quot;` marks file lines 39 and 40.

{% preview source=true %}

	{% snippet path=&quot;biome.jsonc&quot; lines=&quot;36-53&quot; linenumbers=true highlight=&quot;39-40&quot; /%}

{% /preview %}

`highlight` takes ranges, single lines, or a mix: `&quot;74-78,82,90-92&quot;`. With `symbol` or `match`, use `highlight-match` instead, which takes regexes, so you are not guessing line numbers. An anchored slice also has its common indentation stripped (`reindent`), so a method does not render with a ragged left edge; a `lines` slice keeps its columns.

Both `linenumbers` and `highlight` work on a hand-written fence too: `` ```ts {% linenumbers=true highlight=&quot;3-5&quot; %} ``.

## Set the language

The language comes from the file extension:

| Extension | Language |
|-----------|----------|
| `.ts`, `.tsx` | `typescript` |
| `.js`, `.jsx`, `.mjs`, `.cjs` | `javascript` |
| `.svelte` | `svelte` |
| `.vue` | `vue` |
| `.md`, `.markdoc` | `markdoc` |
| `.json` | `json` |
| `.jsonc` | `jsonc` |
| `.html` | `html` |
| `.css` | `css` |
| `.yml`, `.yaml` | `yaml` |
| `.toml` | `toml` |
| `.sh`, `.bash` | `bash` |
| (others) | `text` (no highlighting) |

Set `lang` when the extension is misleading. A `tsconfig.json` holds comments, which would highlight as errors as `json`:

{% preview source=true %}

	{% snippet path=&quot;site/tsconfig.json&quot; lang=&quot;jsonc&quot; /%}

{% /preview %}

## Add a caption or a title

A snippet has no title of its own. Wrap it in `{% figure caption=&quot;…&quot; %}` for a caption below the code, or in `{% codegroup title=&quot;…&quot; %}` for a title bar above it, like an editor tab naming the file.

{% preview source=true %}

	{% figure caption=&quot;The counter's click handler: one function, called with +1 or −1&quot; %}
		{% snippet path=&quot;site/examples/counter/script.js&quot; symbol=&quot;update&quot; /%}
	{% /figure %}

{% /preview %}

## Use snippets in codegroup and diff

Containers that take code blocks take snippets too, mixed freely with fences. In a codegroup each becomes a tab:

{% preview source=true %}

	{% codegroup %}
		{% snippet path=&quot;site/examples/counter/script.js&quot; /%}
		```html
		&lt;!-- Load the script after the counter's markup --&gt;
		&lt;script src=&quot;script.js&quot;&gt;&lt;/script&gt;
		```
	{% /codegroup %}

{% /preview %}

In a diff, two snippets are the before and after; here the counter's button rule against its dark-theme override:

{% preview source=true %}

	{% diff mode=&quot;split&quot; %}
		{% snippet path=&quot;site/examples/counter/style.css&quot; lines=&quot;8-15&quot; /%}
		{% snippet path=&quot;site/examples/counter/style.css&quot; lines=&quot;35-39&quot; /%}
	{% /diff %}

{% /preview %}

## Know when the code has outgrown its prose

An anchor keeps the snippet on the right code, but the paragraph beside it can still go stale when that code changes. A `reviewed` marker records that someone read this version of the slice against the prose. It freezes nothing: the snippet still shows current code, and a change asks for a re-read.

```markdoc
{% snippet path=&quot;packages/types/src/config.ts&quot; symbol=&quot;SiteConfig&quot; reviewed=&quot;a3f91c4e:70b2d118&quot; /%}
```

The CLI writes markers; don't write them by hand.

```bash
refrakt snippet review site/content/runes/file-ref.md   # stamp unmarked snippets
refrakt snippet review --check                          # report changed ones
refrakt snippet review --update                         # show each diff and re-stamp
```

A reformat that leaves the meaning unchanged is re-stamped without asking. Mark only snippets whose prose makes specific claims about the code; marking every one makes `--check` noise that people learn to ignore.

## Show a page's own source

Pass `$file.path` ({% xref &quot;/docs/authoring/variables&quot; /%}) to embed the source of the page the reader is on. This one:

{% preview source=true %}

	{% snippet path=$file.path lang=&quot;markdoc&quot; /%}

{% /preview %}

## Attributes

{% include file=&quot;rune-attributes.md&quot; variables={r: &quot;rune:snippet&quot;} /%}

## See also

- [Codegroup](/runes/codegroup) — tabbed code blocks; consumes snippet children transparently.
- [Figure](/runes/figure) — a captioned container; captions a snippet below the code.
- [Diff](/runes/diff) — before/after code comparison; consumes snippet children transparently.
- [Content variables](/docs/authoring/variables) — `$file.path` for the view-source-of-current-page pattern.
</code></pre>
</div>

Attributes

AttributeTypeRequiredDescription
pathstring✓Path to the source file, relative to the project root. Rejected if it escapes the root.
linesstring—Line range. Formats: "10-25", "10-" (to EOF), "-20" (from start), "10" (single line). 1-indexed, inclusive. A coordinate into a file nobody promised to hold still — prefer `symbol` or `match`, which survive edits above the region. Mutually exclusive with both.
symbolstring—Name a declaration instead of a line range: `symbol="SiteConfig"`. The anchor is built from the language's keyword table, so a symbol that moves is still found and a symbol that is renamed fails loudly instead of rendering the wrong region. Includes the doc comment by default (see `doc`).
matchstring—Raw regex anchor, applied per line: `match="^\\.rf-hint\\s*\\{"`. The general form — `symbol` is sugar over it — and the way to address a language whose keywords the table does not carry.
occurrencenumber—Which match to take when the anchor is ambiguous, 1-based. An escape hatch, not a naming form: it is a better coordinate than a line number, but it still drifts when another match is inserted above the one addressed. Prefer a more specific `match=`. Out of range refuses rather than clamping.
extent"auto" | "dedent" | "section" | "paired"—How far the slice runs. `auto` (default) balances delimiters — TS, CSS, JSON. `dedent` consumes lines indented deeper than the anchor — Python, YAML. `section` runs to the next sibling at the anchor's own level — Markdown headings, TOML tables. `paired` balances a token pair — Markdoc, HTML, Svelte. Never inferred from the file.
untilstring—Regex ending the extent, excluding the matching line. Overrides `extent`. Refuses if it never matches rather than returning the rest of the file.
throughstring—As `until`, but including the matching line. Two attributes rather than one flag because `until="^}"` in code wants the brace in and `until="^## "` in Markdown wants the heading out — either default is silently wrong half the time.
docboolean—Include the preceding doc comment. Defaults on for `symbol` (which names an entity and delegates the boundary) and off for `match` (which names a line the author already chose). Annotations and decorators attach regardless.
reindentboolean—Strip the slice's common leading whitespace, so a nested target does not render with a ragged left edge. Defaults on for `symbol`/`match` and off for `lines`, so no existing line-addressed invocation changes how it renders. Relative structure is preserved, so a dedented Python method stays valid.
reviewedstring—Records that a human read this version of the slice and confirmed the prose around it matched. Freezes nothing — the snippet still tracks HEAD and re-resolves every build. When the slice changes, a diagnostic asks for a re-read; the page still renders the current code. Written by `refrakt snippet review`, never by hand.
highlight-matchstring—Comma-separated regexes; lines matching any of them are emphasized. The anchor-native form of `highlight` — under an anchor the author never saw a line number, so content is the only thing they can point at.
langstring—Syntax-highlighting language hint. Overrides the extension-based inference.
linenumbersboolean—Show line numbers in the gutter. Starting number derives from the `lines` range start (e.g. lines="74-125" → first line is 74), so numbers reflect the file's real offsets.
highlightstring—Range(s) to emphasize without cropping — Shiki-style format: "74-78", "74-78,82,90-92". Indices are file coordinates (same frame as `lines=`), and stay so under an anchor. Note that a *numeric* highlight under `symbol`/`match` carries the same coordinate exposure anchoring otherwise removes — the resolver chose the region, so the author is guessing at its line numbers. Use `highlight-match` there.

Universal attributes

bg

The background layer: image, video, gradient, flat overlay wash and legibility scrim, in a single injected layer behind the rune's content.

AttributeTypeRequiredDescription
bgstring—Background preset applied to this block
bg-fromstring—Gradient start colour — a semantic token name (→ var(--rf-color-*))
bg-gradient"to-t" | "to-b" | "to-l" | "to-r" | "to-tr" | "to-br" | "to-bl" | "to-tl"—Gradient direction (bounded named set)
bg-gradient-type"linear" | "radial" | "conic"—Gradient type
bg-tostring—Gradient end colour — a semantic token name
bg-viastring—Optional middle gradient stop — a semantic token name
scrim"top" | "bottom" | "left" | "right" | "none"—Scrim direction (heaviest edge); presence turns the scrim on, "none" opts out of the default cover scrim
scrim-blur"none" | "sm" | "md" | "lg"—Frost scrim blur amount
scrim-strength"sm" | "md" | "lg"—Gradient scrim strength
scrim-tone"dark" | "light"—Whether the scrim darkens (for light text) or lightens (for dark text)
scrim-type"gradient" | "frost"—Scrim treatment: gradient (default) or frost (backdrop blur)
elevation

How far the rune sits off the page, from sunken to overlay. The theme decides what each step looks like.

AttributeTypeRequiredDescription
elevation"sunken" | "flush" | "flat" | "raised" | "floating" | "overlay" | "none" | "sm" | "md" | "lg"—Surface depth, from sunken to overlay. Deprecated: none, sm, md and lg (read as flat, raised, raised and floating)
inset

Internal padding override.

AttributeTypeRequiredDescription
inset"flush" | "tight" | "default" | "loose" | "breathe"—Inner padding of this block
motion

Scroll-reveal entrance. You choose its character; the theme decides how it moves.

AttributeTypeRequiredDescription
reveal"none" | "fade" | "slide" | "scale" | "blur"—Scroll-reveal entrance character (none|fade|slide|scale|blur); the theme owns the choreography
staggerboolean—Cascade this block's items in as it reveals (no-op on single-child runes)
spacing

Block-level rhythm override.

AttributeTypeRequiredDescription
spacing"flush" | "tight" | "default" | "loose" | "breathe"—Vertical spacing above and below this block
substrate

Generated pattern fills behind the content, drawn by the theme.

AttributeTypeRequiredDescription
substrate"dots" | "grid" | "lines" | "cross" | "checker" | "none"—Generated surface pattern
substrate-fill"inherit" | "inset"—Surface fill the pattern sits on (full colour stays with tint)
substrate-opacity"sm" | "md" | "lg"—Pattern ink strength
substrate-size"sm" | "md" | "lg"—Pattern cell size
substrate-target"self" | "media"—Which surface the pattern fills (overrides the rune/theme default)
tint

Per-rune colour override: a named tint from the theme registry, with inline per-token overrides layered on top.

AttributeTypeRequiredDescription
tintstring—Color tint preset applied to this block
tint-mode"auto" | "dark" | "light"—Whether the tint adapts to auto, dark, or light mode
width

The track a block rune occupies.

AttributeTypeRequiredDescription
width"compact" | "narrow" | "content" | "wide" | "full"—Maximum width constraint for this block
Not availableWhy
dropcap, readingthis rune declares no prose body
framethis rune declares neither a `frameTarget` nor a media section
prominencethis rune has no page-section header or featured quotation

See also

  • Codegroup — tabbed code blocks; consumes snippet children transparently.
  • Figure — a captioned container; captions a snippet below the code.
  • Diff — before/after code comparison; consumes snippet children transparently.
  • Content variables — $file.path for the view-source-of-current-page pattern.