Skip to content
mispy Notes from a night desk

Teaching a Markdown renderer a new trick

A renderer is a pipeline with strong opinions about order. Adding a feature means finding the stage where your idea is still allowed to exist.

Markdown is pleasant because it stays out of the way. That pleasantness disappears the moment you need a feature the parser does not know about. Footnotes are a good example. The syntax is simple, the output is useful, and the implementation is an exercise in protecting things from other things.

Ghost uses a Markdown renderer with an extension layer. The layer can inspect the text before or after the usual transformations, which means a new syntax can be added without forking the parser. The trick is choosing the right moment.

Protect the code first

Footnotes use square brackets. So do links, images, and code samples. If you run a footnote substitution over the whole document, you will eventually rewrite something inside a fenced code block and turn a tutorial into a mess. The first pass, then, is not about footnotes at all. It is about hiding the regions where the syntax must remain literal.

A simple approach is to lift fenced blocks out of the text, replace them with unique placeholders, and put them back at the very end. The placeholders must be unlikely to collide with real content. A short random token is enough. This is the same idea as using a quarantine: move the fragile material somewhere the rest of the pipeline cannot touch it.

Then order the references

Inline markers can be numbered automatically or written by hand. Automatic numbering is friendlier, but it introduces state. The renderer has to walk the document in reading order, assign a number the first time it sees a marker, and reuse that number if the marker appears again. Definitions at the bottom of the document are matched by their label, not by their position.

protect fenced blocks
collect definitions by label
walk the document in reading order
assign numbers on first use
replace markers with linked superscripts
emit the definition list at the end
restore fenced blocks

Two details make the result usable. Each reference needs a unique identifier so the return link can find its way back. Each definition needs to be reachable by keyboard, which means the list belongs near the end of the article rather than floating in a sidebar.

Small warning

Regular expressions are tempting here because the syntax looks regular. The document is not. Code blocks, nested brackets, and escaped characters will find the edges of a clever pattern.

What the feature is worth

Footnotes are not decoration. They let a writer keep the main argument clean while preserving the evidence, the aside, or the caveat. A blog that supports them can say more without saying it all at once. The implementation is fiddly, but the reading experience is calmer, and that is the point.