Skip to content

Markdown

Hamur reads Markdown in core, with no module to install. A .md file under app/pages/ is a page, a .md import gives you a parsed document, and hamur/markdown parses and renders Markdown in your own code. For collections of Markdown files with a schema, queries and search, add Content.

The parser is Bun.markdown, so parsing runs at build, in hamur dev and on the bun preset. It turns a document into the Markdown AST: a tree of plain arrays, ["h2", { id: "intro" }, "Intro"], that is JSON. That tree is what ships. Rendering it needs no Bun, so it works on every preset and in the browser, and server HTML and hydration agree in all six UI libraries.

Markdown pages

A .md file under app/pages/ is a route, in every adapter. The path rules are those of Routing: app/pages/pricing.md is /pricing, and about.md next to about.tsx fails with the usual Duplicate route /about.

md
---
title: Pricing
description: What each plan costs.
price: 9
---

# Pricing

Plans start at {{ $doc.price }} dollars a month. :badge[New]{color="green"}

::alert{type="info"}
Prices are per seat.

#title
Good to know
::

Pay [yearly]{.note #yearly} and save two months.

```ts [pricing.ts] {2}
const plans = ["free", "team"]
const price = 9
```

The frontmatter, a YAML block between two --- lines, sets the page:

KeyEffect
titlethe page's <title>; without it, the text of the first h1
descriptionthe description meta tag; there is no fallback
layoutthe layout, as layout in a page's meta; default when absent
metaa mapping of literal page meta keys, such as middleware
any other keyfree data; read it in the page with {{ $doc.key }}

title and description set the head from the page component, so a layout's own useHead title does not override them. Setting a title in both title and meta.head fails with set the title in frontmatter title or in meta.head, not both. A meta that is not a mapping fails with frontmatter meta must be a mapping (got string). A layout that does not exist warns at build and answers 500 at run time, as for any page.

A relative link such as [next](./setup.md) that names another Markdown page becomes that page's path. Other relative links stay as written. A relative image (![x](./x.png)) goes through the asset pipeline: the file is imported with ?meta, and the img gets its URL, width, height, loading="lazy" and decoding="async". With @hamur/image installed the URL comes from its builder. A file that does not exist fails the build: pricing.md:4: image ./x.png not found.

A page has no code of its own: its chunk holds the AST and the renderer, and an internal link navigates on the client. hamur dev parses the file again when you save it, and the page updates without a restart.

Import a Markdown file

A .md import gives the parsed document, in a page, a component or a server file:

ts
import post, { frontmatter, headings, html } from "./app/pages/pricing.md"

export const summary = { title: post.title, price: frontmatter.price, headings: headings.length, html }

post is the whole document with html added: title, description, excerpt, headings, toc, text, readingTime, components, assets, frontmatter and ast. html is renderMarkdownAst(ast). Typegen writes the types of these imports to .hamur/types/markdown.d.ts; see Directory structure. import raw from "./post.md?raw" gives the source text.

Render the document with MarkdownRenderer and value={post}, or write html with your library's raw HTML form. Only write html of Markdown you wrote or trust.

ts
import { MarkdownRenderer } from "@hamur/adapter-html"
import type { MarkdownDocument } from "hamur/markdown"
import Alert from "./app/components/content/Alert.ts"
import Badge from "./app/components/content/Badge.ts"

export function notes(post: MarkdownDocument): string {
  return MarkdownRenderer({ value: post, components: { alert: Alert, badge: Badge } })
}

Parse and render in your own code

parseMarkdown(source, options?) returns a promise of the document. renderMarkdownAst(ast) returns HTML and runs anywhere.

ts
import { parseMarkdown, renderMarkdownAst } from "hamur/markdown"

const source = [
  "---",
  "title: Install",
  "---",
  "",
  "# Install",
  "",
  "## Requirements",
  "",
  "Bun 1.4.4 or newer.",
  "",
].join("\n")

export const document = await parseMarkdown(source, { file: "install.md" })

export const html = renderMarkdownAst(document.ast)
export const { title, readingTime, toc } = document
FieldWhat
astthe Markdown AST
frontmatterthe YAML mapping, {} when there is none
title, descriptionfrontmatter first, then the first h1 and the first paragraph
excerptthe AST before <!--more-->, else the first paragraph
headings{ depth, id, text } for every heading, in order
tocthe headings nested by depth
textthe text outside code blocks and raw HTML
readingTimeminutes, at least 1
componentsthe Markdown components the document names
assetsthe relative image URLs, as written

parseMarkdown needs Bun.markdown. Called anywhere else it throws parseMarkdown runs at build or on the bun preset; importing hamur/markdown there is safe, and renderMarkdownAst and toc work. Its errors start with the file you pass as file.

The markdown key

Config options for every parse in the app: pages, imports and content collections.

ts
import { defineConfig } from "hamur"
import remarkTodos from "./remark-todos.ts"

export default defineConfig({
  framework: "html",
  site: { url: "https://example.com" },
  markdown: {
    toc: { depth: [2, 3] },
    headingLinks: "prepend",
    externalLinks: {},
    wordsPerMinute: 220,
    remarkPlugins: [remarkTodos],
    highlight: { theme: { light: "github-light", dark: "github-dark" } },
  },
})
KeyDefaultMeaning
htmlfalsekeep raw HTML blocks as html nodes; off, they are text and every renderer escapes them
autolinkstrueGFM autolinks: https://…, www.… and addresses
hardSoftBreaks, underline, latexMath, wikiLinksfalsepassed to Bun.markdown
contentHeadingtruetitle falls back to the first h1
toc{ depth: [2, 3], searchDepth: 2 }which heading depths enter toc, and how many component levels deep headings are collected; false leaves toc empty
headingLinksfalse"prepend" or "wrap": a link on each heading, see Headings
headingLinkDepth[2, 3, 4]the depths that get a link
externalLinksfalse{ target?, rel? }; {} gives target="_blank" and rel="noopener noreferrer"
wordsPerMinute200the speed behind readingTime
remarkPlugins, rehypePlugins[]imported plugins, see Plugins
highlighton, no theme CSSsee Highlighting

A wrong value fails when the config loads and names the key: markdown.toc.depth must be [from, to] with 1 <= from <= to <= 6 (got [3, 2]), markdown.headingLinks must be false, "prepend" or "wrap" (got true), markdown.wordsPerMinute must be a positive number (got 0). Bun 1.4.4 accepts underline and latexMath but does not act on them yet, so $x$ stays text; Hamur passes the flags, so they work when a Bun release does.

Frontmatter, excerpt and reading time

A document whose first line is --- has frontmatter up to the next --- line. It is parsed as YAML and must be a mapping. The errors name the file and the line: post.md:3: frontmatter: <reason>, post.md:1: frontmatter must be a mapping (got array), post.md:1: frontmatter is not closed by a --- line.

Put <!--more--> after the part that should be the excerpt. Without it the excerpt is the first paragraph. The marker never reaches the AST.

readingTime is ceil(words / wordsPerMinute), at least 1. A word is a run of letters or digits, so don't is two, and code blocks and raw HTML are not counted. A Chinese or Japanese run counts as one word.

Headings, anchors and the table of contents

Hamur sets every heading's id itself, by GitHub's rules: the text in lower case, every character that is not a letter, digit, -, _ or space removed, spaces turned into -. A repeat gets -1, -2, and a heading with no usable text is section. The id is the anchor everywhere: in the AST, headings, toc and renderEntry.

toc nests the headings of the depth range under the nearest shallower one: an h4 after an h2 is the h2's child. A level that is skipped adds no empty entry.

headingLinks: "prepend" puts <a class="heading-anchor" href="#id" aria-hidden="true">#</a> first in each heading of headingLinkDepth; "wrap" wraps the heading's text in <a href="#id">. The link is in the AST, so every renderer and every prose override receives it, and title, headings, toc and text keep the heading's own text.

There is no ## Title {#id} form; change the heading's text to change its anchor.

Plugins

markdown.remarkPlugins and markdown.rehypePlugins take plugins you installed or wrote, each imported in hamur.config.ts and listed as the attacher or [attacher, options]; a string fails with the import line to write. An attacher is a unified-style plugin: Hamur calls it with the options and then calls the transformer it returns with (tree, file). A returned tree replaces the one given, and a promise is awaited.

ts
interface MdastNode {
  type: string
  value?: string
  children?: MdastNode[]
}

const startsWithTodo = (node: MdastNode): boolean =>
  node.type === "paragraph" && node.children?.[0]?.value?.startsWith("TODO") === true

export default function remarkTodos() {
  return (tree: MdastNode): MdastNode => ({ ...tree, children: tree.children?.filter((node) => !startsWithTodo(node)) })
}

Hamur has no unified, remark or rehype dependency. Remark plugins see an mdast view of the AST and rehype plugins a hast view, and the result is converted back, so only the node types the AST has a form for survive. The mdast view carries MDC components as containerDirective and textDirective nodes. A plugin that needs this.data() or this.parser fails with remark plugin "x" needs a unified processor, which Hamur does not provide, and one that leaves a node type the AST cannot hold, such as footnoteReference, fails with the node's name.

What a plugin adds is rendered by the same rules as the parser's output: an onclick, a style, a <script> or a javascript: link never reaches the page.

Plugins run in hamur build and hamur dev, on Markdown pages and .md imports. Collection entries of Content are parsed with the markdown key but without plugins, and so is a document that the bun preset parses at run time. Plugins has the node tables and the error messages.

Markdown components

A Markdown component is a component you name inside Markdown, with MDC syntax. Props are data: strings, JSON and YAML. The AST holds the component as a node with its name and props, and each adapter renders it as a component of its own library.

FormWritten asGives
block::alert{type="info"} … ::a component with a default slot
nested block:::card … ::: inside a :: blocka child component; one more colon per level
block, no body::dividera component with no children
YAML props--- lines at the top of a blockprops from YAML
named slot#title on its own line inside a blockthe slot title; text before the first #name is the default slot
inline:badge[New]{color="green"}an inline component; […] is Markdown
span[text]{.note #id data-x="1"}a span with a class, an id and attributes
binding{{ $doc.price }}the frontmatter value as text
Markdoc style{% alert type="info" %} … {% /alert %}the same node as ::alert

In {…}, key="value" is a string, :key="<JSON>" the parsed JSON, key alone is true, .name adds a class and #name sets the id. Component names are lower-case kebab case; ::Alert is read as alert, and a name that is a Markdown element (table) or template fails. Nothing inside a code block, a code span or an HTML block is read, and a colon that starts no valid form (10:30) stays text.

A component is found by name, first match wins:

  1. the components prop of MarkdownRenderer or ContentRenderer;
  2. a file app/components/content/<PascalName>.<ext> in the app or a layer: alert is Alert, my-card is MyCard.
ts
const KINDS = new Set(["info", "warning"])

export default function Alert({
  type = "info",
  title = "",
  children = "",
}: {
  type?: string
  title?: string
  children?: string
}): string {
  return `<aside class="alert alert-${KINDS.has(type) ? type : "info"}"><strong>${title}</strong>${children}</aside>`
}

A Markdown page imports the files its document names. A name with no component logs [markdown] no component for "alert" once and renders its children. A document rendered at run time, such as an import or a content entry, resolves the components prop and the prose files only; a component file reaches it through the prop. The slot forms differ by library:

LibraryDefault slotNamed slot title
React, Preactchildrenthe prop title, rendered nodes
Solidchildrenthe prop title, a JSX element
Vuethe default slotthe slot title
Sveltethe children snippetthe snippet prop title
htmlthe children stringthe string argument title

Every adapter exports MarkdownRenderer, with value (a node, a list of nodes or a document) and components; see Adapters. It writes html nodes only when you pass raw, which a Markdown page does under markdown.html: true.

Syntax errors name the line: post.md:12: ::alert is not closed; add a line :: after its body, post.md:20: :: closes no component, post.md:7: :count="3,": not JSON, post.md:9: #title is a slot and needs an enclosing component. A binding the frontmatter lacks renders as nothing and warns once.

Not built: components inside list items and blockquotes, attributes after links or emphasis ([a](/x){target=_blank}; externalLinks covers the common case), inline Markdoc tags, and ## Title {#id}.

Why there is no MDX

MDX puts JavaScript expressions in Markdown, and they mean different things in each library: JSX in React, Preact and Solid, and nothing in Vue and Svelte templates. Supporting it takes an ECMAScript parser and a compile step for each library, and a document would render in one adapter only. MDC tags carry data, so a document renders the same in all six libraries, stays JSON, and the build knows every component a document uses from its components list. If you need logic, put it in the component and pass it data.

Highlighting

Code blocks are coloured where the document is parsed, so a page ships coloured markup and no client JavaScript. A fence can carry a file name and highlighted lines, as the last block of the pricing page above does: ```ts [pricing.ts] {2}.

[pricing.ts] is the filename and {1,3-4} a list of lines and ranges; both reach ProsePre, which writes the file name as data-filename. A bad list fails with post.md:8: fence {1,a}: a line list holds numbers and ranges (got "a"), and a line beyond the block warns and is ignored.

For each block that still holds plain text, three steps run in order, and the first to answer wins:

  1. the markdown:highlight build hook, which gets a HighlightBlock and returns an AST node, an HTML string or undefined;
  2. Hamur's tokenizer, for a language it knows and markdown.highlight allows;
  3. otherwise the block stays text with class="language-<lang>".

The tokenizer is a hand-written scanner for each language, with no grammar files and no dependency:

LanguageAliases
ts, tsx, js, jsxtypescript, mts, cts; javascript, mjs, cjs
jsonjsonc
css, htmlhtm
bashsh, shell, zsh
vue, sveltethe <script> and <style> parts are read as script and CSS
yaml, toml, markdown, diff, sql, graphql, python, go, rust, shell-sessionyml; md; gql; py; rs; console

A language matches in any case. A module adds languages with addHighlightLanguage of hamur/kit, used by the build but not by the bun preset's run-time parse. highlight: false colours nothing, langs only the names listed, excludeLangs all but those.

Each line is a span with the class line, and a token a span with tok-keyword, tok-string or another of the kinds keyword, string, number, comment, function, type, variable, property, operator, punctuation, tag, attribute, regexp, constant, builtin and meta. A highlighted line adds line-highlight, and in diff an added or removed line adds line-added or line-removed.

Themes

Without a theme the app ships no colours: style the tok-* classes yourself. markdown.highlight.theme: { light, dark? } names shipped themes, hamur-light, hamur-dark, github-light and github-dark, and the build adds a CSS file to the global CSS. It sets --tok-<kind> variables on :root, light as they are and dark under prefers-color-scheme: dark and :root[data-theme="dark"], and rules such as .tok-keyword { color: var(--tok-keyword) } use them, so you change a colour by setting its variable. An unknown name fails at load: markdown.highlight.theme.light "nord" is not a theme (have: hamur-light, hamur-dark, github-light, github-dark).

Not built: TextMate grammars, Shiki and a WASM regular-expression engine, semantic highlighting and twoslash.

Where next

  • Content: collections, schemas, queries, navigation and search.
  • hamur/markdown: every export, with the AST tables and error messages.
  • Directory structure: app/components/content/ and the .md import types.