Reference Options

Annotated source

mdsvex() takes one object of options. They apply to every document.

Full TypeScript definition
interface MdsvexOptions {
	extensions?: string[];
	frontmatter?: {
		parse?: (raw: string) => Record<string, unknown> | null | undefined;
	};
	templates?: Record<
		string,
		string | URL | { component: string | URL; components?: string | URL }
	>;
	select_template?: (
		id: string,
		metadata: Record<string, unknown>
	) => string | false | undefined;
	components?: string | URL | (string | URL)[];
	component_mode?: 'markdown' | 'all';
	plugins?: Bundle[];
	parse_plugins?: ParsePlugin[];
	highlight?: PluginHighlightOptions | Highlighter | false;
	math?: MathOptions | MathRenderer | false;
	footnotes?: { label?: string; back_label?: string; strict?: boolean };
	unwrap_images?: boolean;
	import_images?: boolean | { enhanced?: boolean };
	wrap_static?: boolean;
	links?: {
		routes?: string;
		base?: true | string | { import: string; from: string };
	};
	rewrite?: (
		url: string,
		ctx: { filename: string | undefined; type: 'link' | 'image'; written: string }
	) => string | null | undefined | void;
	heading_ids?:
		| boolean
		| { slug?: (text: string, heading: { depth: number }) => string };
	smart_punctuation?:
		| boolean
		| {
				quotes?: boolean | [string, string, string, string];
				dashes?: boolean;
				ellipses?: boolean;
		  };
	text?: { code_blocks?: boolean };
}

The file extensions mdsvex compiles. To use .md files as components too:

extensions: string[] = ['.svx'];
mdsvex({ extensions: ['.svx', '.md'] });

SvelteKit picks them up from here, see SvelteKit.

Replaces the built-in YAML parser. It gets the text between the fences and the path of the document.

frontmatter: {
	parse?: (
		raw: string,
		file: { filename: string | undefined }
	) => Record<string, unknown> | null | undefined;
};

See custom frontmatter parsers. On the atlas: frontmatter.

Components that wrap documents, by name. The default entry wraps every document that doesn't pick another.

templates: Record<string, string | URL | { component: string | URL; components?: string | URL }>;

See Templates. On the atlas: template.

Picks the template of a document whose frontmatter doesn't.

select_template: (id: string, metadata: Record<string, unknown>) => string | false | undefined;

See choosing a template. id is the path of the file. compile takes the same callback, with its filename as the path.

How a math fence and inline math render. renderer picks 'temml', the default, or 'katex', and options goes to that library. A function is a renderer of your own, and false leaves the fence a code block and inline math inline code.

math: MathOptions | MathRenderer | false = {};

See Math. On the atlas: math.

The accessible names of the footnotes section and of its back links, for a site that is not in English.

footnotes: { label?: string; back_label?: string; strict?: boolean } = {};

strict: false builds a document whose footnotes a compile rejects, with warnings in place of the error. On the atlas: footnote.

An image on a line of its own is a paragraph, so it renders as <p><img /></p>. That is a problem once an img replacement renders a block element, because a <figure> is not allowed inside a <p>:

unwrap_images: boolean = false;
src/lib/Figure.svelte
<script>
	let { src, alt, title } = $props();
</script>

<figure>
	<img {src} {alt} />
	{#if title}<figcaption>{title}</figcaption>{/if}
</figure>
src/lib/markdown.js
export { default as img } from './Figure.svelte';
mdsvex({ components: '#lib/markdown.js', unwrap_images: true });

On the atlas: image.

With unwrap_images, a paragraph that holds only images gets no <p>, so the figure stands on its own:

You write
Sales grew all year.

![A chart](/chart.png "Sales by month")

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

<p>Sales grew all year.</p>
<Img_MDSVEX_G
  src="/chart.png"
  alt="A chart"
  title="Sales by month"
/>

Several images in one paragraph are all unwrapped, on one line or on lines of their own. So is an image inside a link, such as [![A chart](/chart.png)](/full.png), where the link stays around the image. It works the same inside block quotes, list items, directives and HTML elements.

  • A paragraph with any text beside the image keeps its <p>, and so does one with a hard line break between two images.

compile() takes the option too, and the editor reads it from the manifest the plugin writes, or from unwrap_images in an mdsvex.config.json.

Wraps each run of two or more top level blocks with no Svelte in them in a <div style="display: contents">, so hydration steps over the run as one node instead of one node for each block:

wrap_static: boolean = false;
mdsvex({ wrap_static: true });
You write
# Title

Some text.

<Counter />

More {count}.

You get
Compiles to
<div style="display: contents">
  <h1>Title</h1>
  <p>Some text.</p>
</div>
<Counter />
<p>More {count}.</p>

compile() takes the option too.

  • The page looks the same, but a child selector such as article > p no longer matches a block inside a wrapper, and a sibling selector such as h1 + p doesn't match across the edge of one.

Gives every markdown heading an id made from its text, so a link can point at it:

heading_ids: boolean | { slug?: (text: string, heading: { depth: number }) => string } = false;
mdsvex({ heading_ids: true });
You write
## Getting _started_

## Getting started

## The `highlight` option

You get
Compiles to
<h2 id="getting-started">
  Getting <em>started</em>
</h2>
<h2 id="getting-started-1">
  Getting started
</h2>
<h2 id="the-highlight-option">
  The <code>highlight</code> option
</h2>

The id is the one GitHub makes: the text in lowercase, punctuation dropped, each space a hyphen, and letters of any script kept. A second heading with the same text gets -1, a third -2.

The text is what a reader sees. Emphasis, links and code contribute their text without the markup, and an image contributes its alt text. What Svelte renders contributes nothing, because it isn't known until the page runs: an expression such as {version}, a component and a directive.

On the atlas: heading.

  • A heading that is left with no text, such as ## {title}, gets no id.

A heading that already has an id keeps it, whether a parse plugin set it or you typed the heading as HTML, and no id made after it repeats it. Headings typed as HTML are otherwise left alone.

Each heading gets its id as it closes, from the ids before it, and an id never changes once given. Footnotes are numbered at the end, so a footnote whose id a heading took moves aside instead: ## Fn 1 keeps fn-1 and the footnote [^1] becomes fn-1-1.

  • An id you write yourself, on a heading typed as HTML or through a plugin that reads one from your text, is kept, and one that an element before it already has fails the compile with a HeadingIdError that names both:
You write
## Intro

<h2 id="intro">Again</h2>

Its compile throws

Error [mdsvex] the id "intro" of the element <h2> at 3:1 was given to the heading at 1:1 before it, give one of them another id

For another scheme, pass a slug function. It gets the text and the depth of the heading, and mdsvex numbers duplicates in what it returns. An empty string leaves the heading without an id. heading_slug is the default:

import { mdsvex, heading_slug } from 'mdsvex';

mdsvex({
	heading_ids: {
		slug: (text, { depth }) => (depth === 1 ? 'top' : heading_slug(text))
	}
});

The id is there for the function a parse plugin returns from its handler, which runs when the heading closes, and for every sequential plugin, so one can add an anchor that points at its heading:

const anchors = {
	heading: {
		parse(node) {
			return () => {
				node.prepend('link', { href: `#${node.attrs.id}`, 'aria-hidden': 'true' });
			};
		}
	}
};

mdsvex({ heading_ids: true, parse_plugins: [anchors] });
You write
## Getting started

You get
Compiles to
<h2 id="getting-started">
  <a
    href="#getting-started"
    aria-hidden="true"
  ></a>Getting started
</h2>

@mdsvex/plugin-anchors is that plugin, with a choice of where the link goes.

A replacement for a heading gets the id as a prop. compile() takes the option too. A streaming render makes the same ids as the heading arrives: make_heading_ids() from mdsvex/compile, given a slug or not, goes to the builder with set_headings. The editor reads the option from the manifest the plugin writes, or from heading_ids: true in an mdsvex.config.json, which can't hold a slug function.

Turns the punctuation you can type into the punctuation a typesetter would use:

smart_punctuation:
	| boolean
	| { quotes?: boolean | [string, string, string, string]; dashes?: boolean; ellipses?: boolean }
	= false;
mdsvex({ smart_punctuation: true });
You write
"quoted", 'quoted', it's, 1990--2020, wait --- what, and so on...

You get
Compiles to
<p>
  “quoted”, ‘quoted’, it’s, 1990–2020,
  wait — what, and so on…
</p>

It is off by default, so a document renders the characters it has unless you ask. mdsvex 0.x had it on, see smart punctuation in 0.x.

"quoted"

curly double quotes

'quoted', it's

curly single quotes, and the apostrophe

1990--2020

two hyphens are an en dash

wait --- what

three hyphens are an em dash

and so on...

three dots are an ellipsis

Only those five are replaced. A run of any other length stays as written, so four hyphens or four dots are still four:

You write
Four ---- hyphens and four .... dots. Run it with --watch, but a -- b, a--b and 1--2.

You get
Compiles to
<p>
  Four ---- hyphens and four .... dots.
  Run it with --watch, but a – b, a–b
  and 1–2.
</p>
  • Two hyphens after a space and before a letter are a command line flag and stay too, so run it with --watch is safe, while a -- b, a--b and 1--2 get a dash.

A quote opens after a space, at the start of a paragraph, heading, list item or table cell, and after an opening bracket, a dash or another quote that just opened. Anywhere else it closes, which also makes an apostrophe:

You write
"_word_" and _"word"_, the `code`'s, the '90s and 6'2".

You get
Compiles to
<p>
  “<em>word</em>” and <em>“word”</em>,
  the <code>code</code>’s, the ‘90s and
  6’2”.
</p>

A quote with a space on both sides is left straight. Markup is looked through: the quotes in _"word"_ and "_word_" face the same way, and the 's after a code span, a link or {name} is an apostrophe.

  • Quotes are not paired, so two cases come out wrong: an apostrophe at the start of a word opens ('90s, rock 'n' roll), and feet and inches close (6'2"). Type the character you want there, ’90s or 6′2″. A character you type yourself is never changed.

Each kind can be turned off, and quotes takes the four strings of another language, the opening and closing double quote and then the opening and closing single quote:

mdsvex({
	smart_punctuation: {
		dashes: false,
		// French, with a no-break space inside the guillemets
		quotes: ['«\u00a0', '\u00a0»', '“', '”']
	}
});
You write
"Bonjour", 'salut', l'ami -- 1990--2020.

You get
Compiles to
<p>
  « Bonjour », “salut”, l’ami --
  1990--2020.
</p>

German is ['„', '“', '‚', '‘']. An apostrophe between two letters or digits is always ’, whatever the closing single quote is. There is one style for the whole site, mdsvex does not read a document's language.

Only prose is touched. These stay exactly as written:

  • code spans, fenced code, highlighted code and math
  • Svelte expressions and blocks, such as {"a--b"} and {#if x === "y"}
  • attributes of elements and components, such as <Box --gap="1--2">
  • urls, and the text of an autolink such as <https://example.com/a--b>
  • the alt text of an image and the title of a link or an image
  • text inside <code>, <kbd>, <pre>, <samp>, <var>, <tt> and <textarea>, and the contents of <script> and <style>
  • character references, so &quot; and &#39; are a way to keep a straight quote
  • a character behind a backslash, so \", \', \-- and \... stay literal
  • frontmatter, HTML comments and thematic breaks

Text inside a component or any other element is prose and is changed.

heading_ids makes its ids from the text as written, so turning this on does not change any anchor. compile() takes the option too. It belongs to the compile and to the incremental HTML renderer, so the streaming Svelte renderer shows text as written. The editor reads the option from the manifest the plugin writes, or from smart_punctuation in an mdsvex.config.json.

What a ?text import reads. code_blocks: false leaves out code fences, math fences and <pre> elements, so a search index holds only prose:

text: { code_blocks?: boolean } = {};
mdsvex({ text: { code_blocks: false } });

compile_text takes code_blocks beside the options of compile.

Back to page index

mdsvex, markdown with Svelte in it. MIT licence.