Inside a document pipeline

Jennifer

doctree, MyST, reStructuredText and fonts: the model under Grimoire and Cantrip, and how to extend it.

November 2026, by @mplx.
Based on Jennifer 0.27.0

Powered by Jennifer's Cantrip - Markdown into slide decks, https://github.com/jennifer-language/cantrip
1 / 21

One tree in the middle

markdown.parse  \                     / render("html")   HTML, XHTML
myst.parse       >  doctree.Node  -->   render("ansi")   terminal
rst.parse       /        |            \ renderPdf        PDF over pdf
                     your transforms
2 / 21

The Node

export def struct Node {        # modules/doctree.j
    kind as string,             # "heading", "link", "text", ...
    level as int,               # a heading's level
    text as string,             # a leaf's text, an image's alt
    lang as string,             # code language, admonition kind
    ordered as bool,
    url as string,              # link and image target
    title as string,            # link title, admonition title
    align as string,            # table cell alignment
    attrs as map of string to string,   # id, class, ...
    children as list of Node
};
3 / 21

Looking at a tree

func dump(n as doctree.Node, pad as string) {
    io.printf("%s%s%s\n", $pad, $n.kind, ...);   # + a text's "text"
    for (def c in doctree.children($n)) { dump($c, $pad + "  "); }
}
document                     link
  heading                      text "that"
    text "Guide"             text "."
  paragraph                list
    text "Read "             item
    strong                     text "one"
      text "this"            item
    text " and "               text "two"
4 / 21

Selectors are paths, not searches

doctree.text(doctree.get($doc, "list/item[2]"));      # two
len(doctree.findAll($doc, "paragraph/link"));          # 1
len(doctree.findAll($doc, "link"));                    # 0
doctree.has($doc, "*/strong");                         # true
doctree.attr($link, "href");                           # https://x.org
5 / 21

Three readers, one tree

markdown.parse("> [!WARNING]\n> Back up *first*.\n")
myst.parse('```{warning}' + "\nBack up *first*.\n```\n")
rst.parse(".. warning:: Back up *first*.\n")
admonition warning: Back up first.
admonition warning: Back up first.
admonition warning: Back up first.
<div class="admonition admonition-warning"><p class="admonition-title">
Warning</p><p>Back up <em>first</em>.</p></div>
6 / 21

MyST: directives, roles, targets

(setup)=                       heading {"id": "setup"}
## Setup                       figure {"id": "fig-pipe"}
```{figure} pipeline.png         image pipeline.png
:name: fig-pipe                  caption > text "The pipeline."
The pipeline.                  admonition note
```                              link #fig-pipe > "The pipeline."
:::{note}                        link #setup > "Setup"
See {numref}`fig-pipe` and       codespan {"class": "kbd"} "Ctrl+C"
{ref}`setup`; {kbd}`Ctrl+C`.   paragraph
:::                              text "{foo}`bar`"
Read {pep}`8`, then {foo}`bar`.
warning line 14: Unknown role "foo"; kept as text.
7 / 21

reStructuredText: the same shapes

Setup                          heading {"id": "setup", "class": "title"}
=====                          figure {"id": "fig-pipe"}
.. _fig-pipe:                  admonition note
.. figure:: pipeline.png         link #fig-pipe > "fig-pipe"
   The pipeline.                 link #setup > "Setup"
.. note:: See fig-pipe_ and      text ":kbd:`Ctrl+C`."
   `Setup`_; :kbd:`Ctrl+C`.    title: Setup
Read :pep:`8`, then missing_.
error line 10: Unknown interpreted text role "kbd".
error line 12: Unknown target name: "missing".
8 / 21

A transform: value semantics shape it

# Pass 1: every figure's "#id", in document order.
func figures(n as doctree.Node) {
    def ids as list of string init [];
    if ($n.kind == "figure") {
        $ids[] = "#" + doctree.attr($n, "id");
    }
    for (def c in doctree.children($n)) {
        $ids = lists.concat($ids, figures($c));
    }
    return $ids;
}

No pointers into the tree: read it, then rebuild it.

9 / 21

Pass 2: rebuild with numbers

func number(n as doctree.Node, nums as map of string to int) {
    def kids as list of doctree.Node init [];
    for (def c in doctree.children($n)) {
        if ($c.kind == "caption") {
            $c.children = lists.concat([label($n, $nums)], $c.children);
        }
        $kids[] = number($c, $nums);
    }
    $n.children = $kids;
    ...   # a link to a figure's "#id": text "Figure {$nums[$n.url]}"
    return $n;
}
10 / 21

A table of contents in the tree

func withToc(doc as doctree.Node) {
    def toc as doctree.Node init doctree.Node{kind: "list"};
    def body as list of doctree.Node init [];
    for (def n in doctree.children($doc)) {
        if ($n.kind == "heading" and $n.level == 2) {
            $n.attrs["id"] = slug(doctree.text($n));
            $toc.children[] = entry($n);     # item > link "#id"
        }
        $body[] = $n;
    }
    ...   # [$body[0], $toc] + the rest
}
<h1>Guide</h1><ul><li><a href="#install-it">Install it</a></li>...
11 / 21

HTML: escaped and filtered by default

doctree.renderHtml($doc, doctree.HtmlOptions{allowRawHtml: true});
12 / 21

PDF: PdfOptions

def o as doctree.PdfOptions init doctree.pdfDefaults();   # Letter
$o.pageWidth = 595;  $o.pageHeight = 842;  $o.margin = 56;  # A4
$o.bodyFont = "Times-Roman";  $o.boldFont = "Times-Bold";
$o.headingStyles = [doctree.headingStyle(doctree.rgb(214, 228, 240)),
    doctree.headingStyle(doctree.gray(235))];
$o.tableHeaderFill = doctree.gray(225);
$o.codeFill = doctree.gray(245);  $o.codeBorder = doctree.gray(170);
$o.quoteRule = doctree.rgb(70, 110, 160);
$o.title = "Pipeline notes";  $o.bookmarkLevel = 2;
def d as pdf.Document init doctree.renderPdfDoc(myst.parse($src), $o);
fs.writeBytes("notes.pdf", pdf.render(pdf.setFooter($d, $foot)));
13 / 21

The page it produced

The first page of notes.pdf, rendered with pdftoppm

The city of Gdansk, written with its accented n (U+0144) in the source, prints as Gda?sk: the font slots take only the standard-14 PDF fonts.

14 / 21

Why Unicode text needs an embedded font

def path as string init "/usr/share/fonts/TTF/DejaVuSans.ttf";
def body as pdf.LoadedFont init pdf.loadFont("Body", fs.readBytes($path));
def s as string init "Gda\u0144sk, \u0394\u03b5\u03bb\u03c6\u03bf\u03af, " +
    "\u041a\u0438\u0435\u0432";
def p as pdf.Page init pdf.textUnicode(pdf.page(300, 60), 12, 24, $body, 16, $s);
def doc as pdf.Document init pdf.addFont(pdf.document(), $body);

The line drawn in DejaVu Sans

402743 bytes, 176.296875 pt wide
15 / 21

The font module: what a layout engine needs

DejaVu Sans: 6253 glyphs, 2048 units per em
ascender 1556, descender -492, line gap 410
advance A 1401, V 1401; kern A,V -131
glyph ids of U+006E, U+0144, U+4E2D: [81, 262, 0]
L: M 201 1493 L 403 1493 L 403 170 L 1130 170 L 1130 0 L 201 0 ...
16 / 21

Outlines and kerning, by hand

if ($kerned and $prev != 0) {
    $x = $x + font.kern($f, $prev, $cp);
}
def d as string init font.glyphPath($f, $cp);   # font units, y up
$out = $out + "<path transform=\"translate({$x},{$y}) scale(1,-1)\"" + ...;
$x = $x + font.advance($f, $cp);

AVATAR set without and with kerning

17 / 21

Hostile input: caps, and kind "limit"

markdown: limit: document nesting too deep (over 100 levels)
myst: limit: document nests too deep (over 50 directive levels)
rst: limit: document nests too deep (document nests too deep (over
  100 levels))
truncated: font: font.parse: malformed font: bytes index 614174 out of
  bounds (len 4000)
18 / 21

Sharp edges in 0.26.0

depth 4: 15 ms, 830 bytes            30 levels: 30 <em>
depth 8: 135 ms, 867 bytes           40 levels: 32 <em>
depth 10: 366 ms, 883 bytes
depth 12: 1424 ms, 903 bytes
depth 14: 5390 ms, 920 bytes
if (depth($doc) > PDF_MAX_DEPTH) {   # your own guard, 12 here
    throw Error{kind: "limit", message: "too deep for the PDF layout"};
}
19 / 21

Performance: measure a big document

parse 41 KiB: 1180 ms     html 91 KiB: 672 ms     pdf 84 KiB: 1192 ms

$ jennifer profile big.j
   HITS         SELF           CUM  POSITION
   1600   5.513181ms  1.508165519s  doctree.j:3025:5    renderBlock
    400   1.418027ms  640.145809ms  doctree.j:3047:13   renderTable
   4400  48.715815ms  983.947984ms  markdown_blocks.inc.j:852:9
   4801  32.832298ms  651.475266ms  markdown.j:717:5    inline

profile --allocs: one 32 MiB copy of the whole tree, markdown.j:897

20 / 21

Read more

Based on Jennifer 0.27.0, November 2026.

21 / 21