----
title: MARKDOWN module – parsing markdown
SPDX-FileCopyrightText: 2024 Norman Gray <https://nxg.me.uk>
SPDX-License-Identifier: BSD-2-Clause


This is a basic [Markdown][] parser.

The parser's ambitions are modest – it is intended to
implement the core of the format, but not to be a comprehensive
implementation.
The implementation covers a decent fraction of the
[Gruber spec][gruber]; the only major omission is that it currently
knows nothing about inline HTML.

The implementation is intended to be Unicode-friendly,
though the only places where this is relevant are in
link reference keys (ie, `[key]: URL`) and in the YAML-style
hash mentioned below.

The default output is in the form of ‘x-expressions’ – XML represented as
scheme s-expressions, which is easy to wrangle (see the `xexpr` module).

You can parse a Markdown file with either
[`parse-markdown-file`](#fn-parse-markdown-file) or
[`parse-markdown-file/metadata`](#fn-parse-markdown-file/metadata).
The former returns the parsed contents of the file as an xexpr.
The latter additionally returns, as multiple values, a structure which
can be queried with
[`metadata/type`](#fn-metadata/type), obtaining either annotations or
citation information as described below.

There is experimental built-in support for references, in the
style of [RMarkdown][].  Specifically, if a Markdown
document contains references marked up like `[@foo]`, then the
multiple values returned from `parse-markdown-file/metadata` will be a
parse-tree _and_ a collection of ‘metadata’.  From that metadata, you
can extract (with `(metadata/type metadata 'citation)`) a list of citations and
the place in the parse-tree where they appear.  The latter are the
`(cite "foo")` elements in the parse-tree, which can therefore be
edited retrospectively.  A way of using this is illustrated in
`examples/bibliography-in-markdown.scm`.

Similarly, `(metadata/type metadata 'annotation)` will produce a list of
`("key" "value")` lists containing annotations from the input Markdown
file.  The annotations are of the form

    ---
    key: value

(ie, a YAML-style hash; this is the only YAML-ish content which is recognised).  Note that

    Text
    ---
    key: value

will also be recognised as metadata, rather than a section heading.  So don't write that.

[Markdown]: https://en.wikipedia.org/wiki/Markdown
[RMarkdown]: https://bookdown.org/yihui/rmarkdown-cookbook/bibliography.html
[gruber]: https://daringfireball.net/projects/markdown/
