Reference Syntax highlighting

Annotated source

The Vite plugin highlights fenced code and inline code with a language with twinkleplop, with no setup. Every bundled language loads the first time a document has code.

Highlighted code is ordinary markup in your component, not {@html}. mdsvex escapes every { and } in it, so code is never read as a Svelte expression, whichever highlighter produced it.

mdsvex adds no CSS. A twinkleplop theme is a stylesheet you import once, usually in your root layout:

import '@twinkleplop/theme-github';

The themes are @twinkleplop/theme-github, theme-atom-one, theme-ayu, theme-catppuccin, theme-material, theme-night-owl, theme-rose-pine and theme-solarized. Each has three stylesheets:

  • the package itself, light colours by default and dark ones under a .dark ancestor, for sites that toggle a dark class;
  • /light and /dark, one variant each, for a fixed mode.

To follow the reader's system setting, import the light variant and add the dark one under a media query:

src/routes/+layout.svelte
<script>
	import '@twinkleplop/theme-github/light';
	import '../app.css';

	let { children } = $props();
</script>

{@render children()}
src/app.css
@import '@twinkleplop/theme-github/dark' (prefers-color-scheme: dark);

A theme only colours tokens. It sets --twp-background without applying it, and leaves the block's layout and the classes that fence meta and code directives add to you:

pre.twinkleplop {
	padding: 1em;
	overflow-x: auto;
	background: var(--twp-background);
}

.twinkleplop .highlight,
.twinkleplop .highlighted-word {
	background: rgb(127 127 127 / 0.2);
}

.twinkleplop .diff-add {
	background: rgb(0 200 0 / 0.15);
}

.twinkleplop .diff-del {
	background: rgb(200 0 0 / 0.15);
}

.twinkleplop .ln {
	display: inline-block;
	width: 2em;
	margin-right: 1em;
	text-align: right;
	opacity: 0.5;
}

.has-focus .l:not(.focus) {
	opacity: 0.5;
}

A highlighted block renders as below. Each line is a span.l, each token a span.tok with its type as a class, and a line number a span.ln:

mdsvex({ highlight: {} });
You write
```ts {1}
const a = 1;
```

You get
Compiles to
<pre
  class="twinkleplop language-ts has-highlight"
  data-language="ts"><code
    ><span class="l highlight"
      ><span class="tok keyword"
        >const</span
      > <span class="tok constant"
        >a</span
      > <span class="tok operator"
        >=</span
      > <span class="tok number">1</span
      ><span class="tok punctuation"
        >;</span
      ></span
    ></code
  ></pre>

On the atlas: code fence.

highlight takes these options in mdsvex(), the PluginHighlightOptions type of mdsvex:

interface PluginHighlightOptions {
	languages?: Record<string, LanguageModule | HtmlHighlighter | string>;
	default_language?: string;
	on_unknown_language?: 'plain' | 'throw';
	line_numbers?: boolean | { start?: number };
	annotations?: AnnotationPlugin[] | false;
	render?: RenderOptions;
	parse_meta?: (raw: string, parsed: RenderOptions) => RenderOptions | void;
	twoslash?: boolean | { svelte?: boolean };
}
  • languages adds languages and aliases, merged over the bundled ones. See languages.
  • default_language highlights fences that name no language.
  • on_unknown_language decides what happens to a language mdsvex doesn't have. 'plain', the default, renders it as plain code and warns once per file and language. 'throw' fails the build. A language a plugin claims, such as mermaid with @mdsvex/plugin-diagram, is never looked up, so it neither warns nor throws.
  • line_numbers numbers every fence's lines, { start: 10 } from 10. A fence's own meta overrides it.
  • annotations lists the code directives. Leave it out for the defaults, or pass false for none.
  • render is twinkleplop's render options under every fence's own, such as indent_guides, whitespace or the line and token hooks. See twinkleplop's render options.
  • parse_meta gets a fence's raw meta and the render options the meta conventions set, and returns the render options to use, for house conventions of your own.
  • twoslash turns on twoslash.

highlight also takes a function, or false to render every block as a plain <pre><code class="language-js">.

These languages are bundled: bash, c, cpp, css, diff, dockerfile, dotenv, go, graphql, html, http, ini, javascript, json, jsonc, markdown, powershell, python, rust, shellsession, sql, svelte, toml, tsx, typescript and yaml. Fences inside a markdown block are highlighted too.

These aliases are built in:

aliaslanguage
js, mjs, cjsjavascript
ts, mts, ctstypescript
jsxtsx
sh, shell, zshbash
console, shell-sessionshellsession
ymlyaml
mdmarkdown
envdotenv
patchdiff
pypython
rsrust

A fence's language is looked up as written, then lowercased, so Dockerfile and JSON work.

  • A language mdsvex doesn't have renders as plain code, in the same markup, so themes and line numbers still apply, with one warning per file. A fence with no language renders the same way, unless you set default_language.

languages adds to these. A string is an alias. A twinkleplop language package is passed as its module namespace:

import * as zig from '@acme/twinkleplop-zig';

mdsvex({
	highlight: {
		languages: { zig, zg: 'zig', svx: 'markdown', vue: 'html' }
	}
});

A language can also be a function, (code, render) => html, that renders HTML itself.

  • Code directives don't apply to it.

The info string after the language takes the conventions of Shiki, VitePress and rehype-pretty-code:

{1,3-4}

highlights lines 1, 3 and 4 with the highlight class

{1,3-4}#id

adds data-highlighted-line-id="id" to those lines

/word/

highlights every word with the highlighted-word class

/word/2-3, /word/#id

the second and third word only, or adds data-chars-id="id"

:line-numbers, :line-numbers=10, :no-line-numbers

turns line numbers on, from 10, or off

showLineNumbers, showLineNumbers{10}

turns line numbers on, from 10

[math.ts], title="math.ts"

a title

caption="…"

a caption

twoslash
src=./math.ts, src=./math.ts#L5-L20

shows a file, or some of its lines

run, run=client

runs the block as a module, with the page or when asked

A fence with a title or caption renders inside a <figure class="twinkleplop-block">, with a <figcaption class="twinkleplop-title"> above the code and a <figcaption class="twinkleplop-caption"> below it:

You write
```ts title="math.ts" {2} :line-numbers
export function add(a: number, b: number) {
	return a + b;
}
```

You get
Compiles to
<figure
  class="twinkleplop-block"
  data-language="ts"
>
  <figcaption class="twinkleplop-title">
    math.ts
  </figcaption>
  <pre
    class="twinkleplop language-ts has-highlight"
    data-language="ts"><code
      ><span class="l"
        ><span class="ln">1</span><span
          class="tok keyword"
          >export</span
        > <span class="tok keyword"
          >function</span
        > <span class="tok function"
          >add</span
        ><span class="tok punctuation"
          >(</span
        ><span class="tok parameter"
          >a</span
        ><span class="tok punctuation"
          >:</span
        > <span class="tok type"
          >number</span
        ><span class="tok punctuation"
          >,</span
        > <span class="tok parameter"
          >b</span
        ><span class="tok punctuation"
          >:</span
        > <span class="tok type"
          >number</span
        ><span class="tok punctuation"
          >)</span
        > <span class="tok punctuation"
          >&#123;</span
        ></span
      >
<span class="l highlight"
        ><span class="ln">2</span>	<span
          class="tok keyword"
          >return</span
        > <span class="tok identifier"
          >a</span
        > <span class="tok operator"
          >+</span
        > <span class="tok identifier"
          >b</span
        ><span class="tok punctuation"
          >;</span
        ></span
      >
<span class="l"
        ><span class="ln">3</span><span
          class="tok punctuation"
          >&#125;</span
        ></span
      ></code
    ></pre>
</figure>

A replaced pre gets them as props instead. With highlight: false there's no figure, and the fence renders as a plain <pre><code>.

The language- class carries only the language, never the rest of the meta.

  • A line range past the end of the fence fails the build, so a stale range doesn't silently highlight nothing:
You write
```ts {9}
let a;
```

Its compile throws

Error line 9 is beyond the fence's 1 line (`ts` fence at /example.svx:1)

A parse plugin reads the same conventions with fence_meta, from the info string a code_fence node has in its handler:

import { fence_meta } from 'mdsvex/compile';

const titled = {
	code_fence: {
		parse(node) {
			const { lang, title, src, props } = fence_meta(node.info);
			// 'ts', 'math.ts', undefined, [['wrap', true]] for ```ts [math.ts] wrap
		}
	}
};

It gives the language, the rest as meta, the title and caption, what src= names, run for a fence that runs, the key=value pairs and bare flags no convention claims as props, and every part as it was written as parts.

src= in the meta of a fence shows a file in place of code written in the document, so the docs never drift from the code they describe. The fence itself stays empty.

```ts src=./math.ts
```

```src=#lib/math.ts#L5-L20 title="math.ts"
```

The path resolves as an import from the document would: a relative path, a Vite alias, or a #lib/… subpath import. Write ./math.ts, since a bare math.ts is a package name to an import. Quote a path with spaces, src="./my file.ts".

These fail the build, each at the fence:

  • the file does not resolve or cannot be read;
  • the slice asks for lines the file does not have, so a stale range never silently shows the wrong code;
  • the fence has code of its own, which would otherwise go missing.

A slice after the path shows some of the lines, counted from 1:

#L5

line 5

#L5-L20

lines 5 to 20

#L5-

line 5 to the end

#-L20

the start to line 20

A fence with no language takes it from the file name, so src=./math.ts is highlighted as ts and src=./Dockerfile as dockerfile. A language you write wins.

Everything else in the meta works as it does on any fence: line highlights count the lines shown, a title is still [math.ts] or title=, and src= sets none.

The file is highlighted like code written in the fence, and a replaced pre gets src as a prop, as written. In dev, saving the file updates every page that shows it, and a watch build compiles those documents again.

compile() reads no files. Give it the text of each file in sources, keyed by the path as the fence has it, without the slice:

compile(source, {
	sources: { './math.ts': 'export const a = 1;\n' }
});

sources: false leaves src= unread, and the fence renders as written. The editor reads no files either, so it shows such a fence empty and reports only a fence that has code of its own.

  • A fence whose file is not in sources throws a SourceError, which has a code (src_missing, src_slice, src_body or src_spec), the spec, and a line and column:
You write
```ts src=./math.ts
```

Its compile throws

Error No text was given for ./math.ts, pass it in the sources option (fence at /example.svx:1)

A code directive is a marker in a comment, [!verb], that styles part of the code and disappears from the output. A line that holds only markers is dropped.

You write
```js
const config = {
	theme: 'light', // [!del]
	theme: 'dark', // [!add]
	lines: true // [!hl]
};
```

You get
Compiles to
<pre
  class="twinkleplop language-js has-diff-del has-diff-add has-highlight"
  data-language="js"><code
    ><span class="l"
      ><span class="tok keyword"
        >const</span
      > <span class="tok constant"
        >config</span
      > <span class="tok operator"
        >=</span
      > <span class="tok punctuation"
        >&#123;</span
      ></span
    >
<span class="l diff-del">	<span
        class="tok property">theme</span
      ><span class="tok punctuation"
        >:</span
      > <span class="tok string"
        >&#39;light&#39;</span
      ><span class="tok punctuation"
        >,</span
      ></span
    >
<span class="l diff-add">	<span
        class="tok property">theme</span
      ><span class="tok punctuation"
        >:</span
      > <span class="tok string"
        >&#39;dark&#39;</span
      ><span class="tok punctuation"
        >,</span
      ></span
    >
<span class="l highlight">	<span
        class="tok property">lines</span
      ><span class="tok punctuation"
        >:</span
      > <span class="tok boolean"
        >true</span
      ></span
    >
<span class="l"
      ><span class="tok punctuation"
        >&#125;;</span
      ></span
    ></code
  ></pre>

These are on by default:

[!hl]

highlight, a highlighted line

[!em]

emphasis, drawing attention

[!focus]

focus, and has-focus on the <pre>, the lines to look at

[!dim]

subdued, fading lines out

[!add], [!del], [!mod]

diff-add, diff-del, diff-mod, diffs

[!err], [!warn], [!info]

error, warning, info, diagnostics

[!eval]

no class, live values

With no arguments, a directive applies to its own line. [!hl +2] applies to the two lines below the marker, [!hl :3...5] to lines 3 to 5, and [!hl =total] to every total on the marker's line.

Twinkleplop's directive docs have every form. The <pre> also gets a has- class for each class inside it, such as has-diff-add.

annotations picks the directives. Content written for Shiki's transformers, // [!code ++], works with shiki_notation added:

import { default_annotations, shiki_notation } from 'mdsvex/highlight';

mdsvex({
	highlight: { annotations: [...default_annotations, shiki_notation()] }
});
You write
```js
const theme = 'dark'; // [!code ++]
```

You get
Compiles to
<pre
  class="twinkleplop language-js has-diff-add"
  data-language="js"><code
    ><span class="l diff-add"
      ><span class="tok keyword"
        >const</span
      > <span class="tok constant"
        >theme</span
      > <span class="tok operator"
        >=</span
      > <span class="tok string"
        >&#39;dark&#39;</span
      ><span class="tok punctuation"
        >;</span
      ></span
    ></code
  ></pre>

annotations: false turns directives off, and markers stay in the code as written.

A code span that starts with #! and a language is highlighted:

You write
Call `#!ts add(1, 2)` to add numbers.

You get
Compiles to
<p>
  Call <code
    class="twinkleplop twinkleplop-inline language-ts"
    ><span class="tok function"
      >add</span
    ><span class="tok punctuation"
      >(</span
    ><span class="tok number">1</span
    ><span class="tok punctuation"
      >,</span
    >
    <span class="tok number">2</span
    ><span class="tok punctuation"
      >)</span
    ></code
  > to add numbers.
</p>

It renders as <code class="twinkleplop twinkleplop-inline language-ts">, with token spans inside and no #!ts. A code span without #! stays a plain <code>. A code replacement gets highlighted spans as children, and the language as a lang prop.

On the atlas: code span.

A pre replacement wraps the highlighted block. It gets these props:

propvalue
childrenthe whole highlighted <pre> element
langthe fence's language
metathe rest of the info string, raw
codethe text a reader sees, without directive markers, with live values in place
title, captionfrom the fence meta, when it has them
srcthe path a fence takes its code from, as written, slice included
modulethe module of a fence marked run
loada function that imports the module of a fence marked run=client
meta propseach part of the meta that no convention claims

children is the <pre> itself, not its <code>, because Svelte only keeps whitespace inside a <pre> it can see. A replaced pre gets no <figure>, so the title, caption and anything else around the code are up to the component.

  • Render children with {@render children()} inside your own markup, never inside another <pre>.

A copy button with a filename:

src/lib/markdown/Pre.svelte
<script>
	let { code, title, children } = $props();

	let copied = $state(false);

	async function copy() {
		await navigator.clipboard.writeText(code);
		copied = true;
		setTimeout(() => (copied = false), 1500);
	}
</script>

<div class="code">
	<div class="bar">
		{#if title}<span>{title}</span>{/if}
		<button onclick={copy}>{copied ? 'copied' : 'copy'}</button>
	</div>
	{@render children()}
</div>
src/lib/markdown.js
export { default as pre } from './markdown/Pre.svelte';

@mdsvex/plugin-code-blocks is a finished one, with an announced result and the caption, to use or to copy.

Meta that no convention claims becomes props. key="value", key='value' and key=value give a string, and a bare key gives true:

mdsvex({ components: '#lib/markdown.js', highlight: {} });
You write
```svelte title="App.svelte" playground height=300
<h1>Hello</h1>
```

You get
Compiles to
<script>
  import { pre as Pre_MDSVEX_G } from '#lib/markdown.js';
</script>

<Pre_MDSVEX_G
  lang={'svelte'}
  meta={'title="App.svelte" playground height=300'}
  title={'App.svelte'}
  playground={true}
  height={'300'}
  code={'<h1>Hello</h1>'}
  ><pre
    class="twinkleplop language-svelte"
    data-language="svelte"><code
      ><span class="l"
        ><span class="tok punctuation"
          >&lt;</span
        ><span class="tok tag_name"
          >h1</span
        ><span class="tok punctuation"
          >&gt;</span
        >Hello<span
          class="tok punctuation"
          >&lt;/</span
        ><span class="tok tag_name"
          >h1</span
        ><span class="tok punctuation"
          >&gt;</span
        ></span
      ></code
    ></pre></Pre_MDSVEX_G
>

That fence gives playground={true} and height="300", as well as title. Meta props, title and caption don't depend on the highlighter, so a pre gets them with highlight: false too.

  • Expression values, key={…}, aren't read.
  • A meta prop named lang, meta, code, title, caption, class, children, src, module or load is dropped with a warning.

See the code blocks playground example.

highlight can be a function instead of options. It gets the code and what mdsvex knows about it, and returns HTML:

type Highlighter = (
	code: string,
	info: { lang: string; meta: string; inline: boolean; filename?: string }
) => string | null | undefined;
  • lang is the fence's language, "" when it names none, and meta the rest of the info string.
  • inline is true for a code span with #!. Plain code spans never reach the highlighter.
  • A fence in a language a plugin claims never reaches it either, the plugin renders that fence.
  • It returns a whole <pre> for a fence, or a <code> for inline code. null or undefined renders that code plain.
  • It must be synchronous. Do any async setup before mdsvex() is called, with top-level await in your Vite config.
  • It returns ordinary HTML. Don't escape it for Svelte, with escapeSvelte or anything else, and don't wrap it in {@html}. mdsvex escapes every brace in what you return, so a {@html …} wrapper would show up as text.

With Shiki:

vite.config.js
import { sveltekit } from '@sveltejs/kit/vite';
import { mdsvex } from 'mdsvex';
import { createHighlighter } from 'shiki';
import { defineConfig } from 'vite';

const shiki = await createHighlighter({
	themes: ['github-dark'],
	langs: ['javascript', 'typescript', 'svelte']
});

export default defineConfig({
	plugins: [
		mdsvex({
			highlight: (code, { lang, inline }) =>
				inline || !shiki.getLoadedLanguages().includes(lang)
					? null
					: shiki.codeToHtml(code, { lang, theme: 'github-dark' })
		}),
		sveltekit()
	]
});

Shiki's transformers go in the codeToHtml call, as they would anywhere else. A pre replacement wraps a custom highlighter's output too, and gets the same props.

Twoslash shows type information from the TypeScript compiler in your code. It is opt-in, as it starts a TypeScript environment. Install it:

npm i --save-dev @twinkleplop/twoslash
  • Turning it on without the package installed is an error that names the package.

Turn it on, and import its styles next to your theme:

mdsvex({ highlight: { twoslash: true } });
import '@twinkleplop/twoslash/style.css';
```ts twoslash
const total = [1, 2, 3].reduce((a, b) => a + b, 0);
//    ^?
```

Fences with twoslash in their meta then go through twoslash. twoslash: true covers ts, js and tsx fences. For Svelte fences too, install @twinkleplop/twoslash-svelte as well and use twoslash: { svelte: true }.

compile is synchronous and loads nothing, so it doesn't highlight unless you pass highlight. mdsvex/highlight builds the same configuration the plugin uses:

import { compile } from 'mdsvex/compile';
import { create_highlight, load_default_languages } from 'mdsvex/highlight';

const highlight = create_highlight({
	languages: await load_default_languages()
});

const { code } = compile(source, { highlight, filename: 'post.svx' });

create_highlight takes HighlightOptions from mdsvex/highlight, the options above apart from twoslash, which there is false or highlighters by language, Record<string, HtmlHighlighter>. load_default_languages loads every bundled language once.

In a browser, language_loaders loads them one at a time, so you only fetch what you use:

import { create_highlight, language_loaders } from 'mdsvex/highlight';

const highlight = create_highlight({
	languages: {
		svelte: await language_loaders.svelte(),
		typescript: await language_loaders.typescript()
	}
});

compile also takes a highlighter function, or false.

Back to page index

mdsvex, markdown with Svelte in it. MIT licence.