mdast utility to serialize markdown

Downloads in past


8832.1.0a year ago4 years agoMinified + gzip package size for mdast-util-to-markdown in KB


!Buildbuild-badgebuild !Coveragecoverage-badgecoverage !Downloadsdownloads-badgedownloads !Sizesize-badgesize !Sponsorssponsors-badgecollective !Backersbackers-badgecollective !Chatchat-badgechat
mdast utility that turns a syntax tree into markdown.


*   [`toMarkdown(tree[, options])`](#tomarkdowntree-options)
*   [`defaultHandlers`](#defaulthandlers)
*   [`ConstructName`](#constructname)
*   [`ConstructNameMap`](#constructnamemap)
*   [`Handle`](#handle)
*   [`Handlers`](#handlers)
*   [`Info`](#info)
*   [`Join`](#join)
*   [`Map`](#map)
*   [`Options`](#options)
*   [`SafeConfig`](#safeconfig)
*   [`State`](#state)
*   [`Tracker`](#tracker)
*   [`Unsafe`](#unsafe)

What is this?

This package is a utility that takes an mdast
syntax tree as input and turns it into serialized markdown.
This utility is a low level project. It’s used in remark-stringifyremark-stringify, which focusses on making it easier to transform content by abstracting these internals away.

When should I use this?

If you want to handle syntax trees manually, use this. For an easier time processing content, use the remark ecosystem instead.
You can combine this utility with other utilities to add syntax extensions. Notable examples that deeply integrate with it are mdast-util-gfm
mdast-util-gfm, mdast-util-mdxmdast-util-mdx, mdast-util-frontmattermdast-util-frontmatter, mdast-util-mathmdast-util-math, and mdast-util-directivemdast-util-directive.


This package is ESM onlyesm. In Node.js (version 16+), install with npm:
npm install mdast-util-to-markdown

In Deno with esm.shesmsh:
import {toMarkdown} from ''

In browsers with esm.shesmsh:
<script type="module">
  import {toMarkdown} from ''


Say our module example.js looks as follows:
import {toMarkdown} from 'mdast-util-to-markdown'

/** @type {import('mdast').Root} */
const tree = {
  type: 'root',
  children: [
      type: 'blockquote',
      children: [
        {type: 'thematicBreak'},
          type: 'paragraph',
          children: [
            {type: 'text', value: '- a\nb !'},
              type: 'link',
              url: '',
              children: [{type: 'text', value: 'd'}]


…now running node example.js yields:
> ***
> \- a
> b \![d](

πŸ‘‰ Note: observe the properly escaped characters which would otherwise turn into a list and image respectively.


This package exports the identifiers defaultHandlersapi-default-handlers and toMarkdownapi-to-markdown. There is no default export.

toMarkdown(tree[, options])

Turn an mdast syntax tree into markdown.
β€” tree to serialize
β€” configuration
Serialized markdown representing tree (string).


Default (CommonMark) handlers (Handlers


Construct names for things generated by mdast-util-to-markdown (TypeScript type).
This is an enum of strings, each being a semantic label, useful to know when serializing whether we’re for example in a double (") or single (') quoted title.
type ConstructName = ConstructNameMap[keyof ConstructNameMap]


Interface of registered constructs (TypeScript type).
interface ConstructNameMap { /* see code */ }

When working on extensions that use new constructs, extend the corresponding interface to register its name:
declare module 'mdast-util-to-markdown' {
  interface ConstructNameMap {
    // Register a new construct name (value is used, key should match it).
    gfmStrikethrough: 'gfmStrikethrough'


Handle a particular node (TypeScript type).
  • node (any)
β€” expected mdast node
β€” parent of `node`
β€” info passed around about the current state
β€” info on the surrounding of the node that is serialized
Serialized markdown representing node (string).


Handle particular nodes (TypeScript type).
Each key is a node type (Node['type']), each value its corresponding handler (Handleapi-handle).
type Handlers = Record<Node['type'], Handle>


Info on the surrounding of the node that is serialized (TypeScript type).
β€” current point
  • lineShift (number)
β€” number of columns each line will be shifted by wrapping nodes
  • before (string)
β€” characters before this (guaranteed to be one, can be more)
  • after (string)
β€” characters after this (guaranteed to be one, can be more)


How to join two blocks (TypeScript type).
β€œBlocks” are typically joined by one blank line. Sometimes it’s nicer to have them flush next to each other, yet other times they cannot occur together at all.
Join functions receive two adjacent siblings and their parent and what they return defines how many blank lines to use between them.
β€” first of two adjacent siblings
β€” second of two adjacent siblings
β€” parent of the two siblings
β€” info passed around about the current state
How many blank lines to use between the siblings (boolean, number, optional).
Where true is as passing 1 and false means the nodes cannot be joined by a blank line, such as two adjacent block quotes or indented code after a list, in which case a comment will be injected to break them up:
> Quote 1


> Quote 2

πŸ‘‰ Note: abusing this feature will break markdown. One such example is when returning 0 for two paragraphs, which will result in the text running together, and in the future to be seen as one paragraph.


Map function to pad a single line (TypeScript type).
  • value (string)
β€” a single line of serialized markdown
  • line (number)
β€” line number relative to the fragment
  • blank (boolean)
β€” whether the line is considered blank in markdown
Padded line (string).


Configuration (TypeScript type).
The following fields influence how markdown is serialized.
Marker to use for bullets of items in unordered lists ('*', '+', or '-', default: '*').
There are three cases where the primary bullet cannot be used:
  • when three or more list items are on their own, the last one is empty, and
`bullet` is also a valid `rule`: `* - +`; this would turn into a thematic
break if serialized with three primary bullets; `bulletOther` is used for
the last item
  • when a thematic break is the first child of a list item and bullet is the
same character as `rule`: `- ***`; this would turn into a single thematic
break if serialized with primary bullets; `bulletOther` is used for the
  • when two unordered lists appear next to each other: * a\n- b;
`bulletOther` is used for such lists
Marker to use in certain cases where the primary bullet doesn’t work ('*', '+', or '-', default: '-' when bullet is '*', '*' otherwise).
Cannot be equal to bullet.
Marker to use for bullets of items in ordered lists ('.' or ')', default: '.').
There is one case where the primary bullet for ordered items cannot be used:
  • when two ordered lists appear next to each other: 1. a\n2) b; to solve
that, `'.'` will be used when `bulletOrdered` is `')'`, and `'.'` otherwise
Whether to add the same number of number signs (#) at the end of an ATX heading as the opening sequence (boolean, default: false).
Marker to use for emphasis ('*' or '_', default: '*').
Marker to use for fenced code (`''` or '~', default: ''``).
Whether to use fenced code always (boolean, default: true). The default is to use fenced code if there is a language defined, if the code is empty, or if it starts or ends in blank lines.
Whether to increment the counter of ordered lists items (boolean, default: true).
How to indent the content of list items ('mixed', 'one', or 'tab', default: 'one'). Either with the size of the bullet plus one space (when 'one'), a tab stop ('tab'), or depending on the item and its parent list ('mixed', uses 'one' if the item and list are tight and 'tab' otherwise).
Marker to use for titles ('"' or "'", default: '"').
Whether to always use resource links (boolean, default: false). The default is to use autolinks (<>) when possible and resource links ([text](url)) otherwise.
Marker to use for thematic breaks ('*', '-', or '_', default: '*').
Number of markers to use for thematic breaks (number, default: 3, min: 3).
Whether to add spaces between markers in thematic breaks (boolean, default: false).
Whether to use setext headings when possible (boolean, default: false). The default is to always use ATX headings (# heading) instead of setext headings (heading\n=======). Setext headings cannot be used for empty headings or headings with a rank of three or more.
Marker to use for strong ('*' or '_', default: '*').
Whether to join definitions without a blank line (boolean, default: false).
The default is to add blank lines between any flow (β€œblock”) construct. Turning this option on is a shortcut for a Joinapi-join function like so:
function joinTightDefinitions(left, right) {
  if (left.type === 'definition' && right.type === 'definition') {
    return 0
Handle particular nodes (Handlersapi-handlers, optional).
How to join blocks (Array<Join>api-join, optional).
Schemas that define when characters cannot occur (Array<Unsafe>api-unsafe, optional).
List of extensions (Array<Options>, default: []). Each extension is an object with the same interface as Options itself.


Configuration passed to (TypeScript type).
  • before (string)
β€” characters before this (guaranteed to be one, can be more)
  • after (string)
β€” characters after this (guaranteed to be one, can be more)
  • encode (Array<string>, optional)
β€” extra characters that *must* be encoded (as character references) instead
of escaped (character escapes).
Only ASCII punctuation will use character escapes, so you never need to
pass non-ASCII-punctuation here


Info passed around about the current state (TypeScript type).
β€” stack of constructs we’re in
  • indexStack (Array<number>)
β€” positions of child nodes in their parents
  • associationId ((node: Association) => string)
β€” get an identifier from an association to match it to others (see
  • enter ((construct: ConstructName) => () => undefined)
β€” enter a construct (returns a corresponding exit function)
(see [`ConstructName`][api-construct-name])
  • indentLines ((value: string, map: Map) => string)
β€” pad serialized markdown (see [`Map`][api-map])
  • compilePattern ((pattern: Unsafe) => RegExp)
β€” compile an unsafe pattern to a regex (see [`Unsafe`][api-unsafe])
  • containerFlow ((parent: Node, info: Info) => string)
β€” serialize flow children (see [`Info`][api-info])
  • containerPhrasing ((parent: Node, info: Info) => string)
β€” serialize phrasing children (see [`Info`][api-info])
  • createTracker ((info: Info) => Tracker)
β€” track positional info in the output (see [`Info`][api-info],
  • safe ((value: string, config: SafeConfig) => string)
β€” make a string safe for embedding (see [`SafeConfig`][api-safe-config])
β€” applied user configuration
β€” applied unsafe patterns
β€” applied join handlers
β€” call the configured handler for the given node
β€” applied handlers
  • bulletCurrent (string or undefined)
β€” list marker currently in use
  • bulletLastUsed (string or undefined)
β€” list marker previously in use


Track positional info in the output (TypeScript type).
This info isn’t used yet but such functionality will allow line wrapping, source maps, etc.
  • current (() => Info)
β€” get current tracked info
  • shift ((value: number) => undefined)
β€” define a relative increased line shift (the typical indent for lines)
  • move ((value: string) => string)
β€” move past some generated markdown


Schema that defines when a character cannot occur (TypeScript type).
  • character (string)
β€” single unsafe character
`ConstructName`, optional)
β€” constructs where this is bad
`ConstructName`, optional)
β€” constructs where this is fine again
  • before (string, optional)
β€” `character` is bad when this is before it (cannot be used together with
  • after (string, optional)
β€” `character` is bad when this is after it
  • atBreak (boolean, optional)
β€” `character` is bad at a break (cannot be used together with `before`)

List of extensions

β€” directives
β€” frontmatter (YAML, TOML, more)
β€” GFM
β€” GFM autolink literals
β€” GFM footnotes
β€” GFM strikethrough
β€” GFM tables
β€” GFM task list items
β€” math
β€” MDX
β€” MDX expressions


Markdown is serialized according to CommonMark but care is taken to format in such a way that the resulting markdown should work with most markdown parsers. Extensions can add support for custom syntax.

Syntax tree

The syntax tree is mdast.


This package is fully typed with TypeScript. It exports the additional types ConstructNameapi-construct-name, ConstructNameMapapi-construct-name-map, Handleapi-handle, Handlersapi-handlers, Infoapi-info, Joinapi-join, Mapapi-map, Optionsapi-options, SafeConfigapi-safe-config, Stateapi-State, and Unsafeapi-Unsafe.


Projects maintained by the unified collective are compatible with maintained versions of Node.js.
When we cut a new major release, we drop support for unmaintained versions of Node. This means we try to keep the current release line, mdast-util-to-markdown@^2, compatible with Node.js 16.


mdast-util-to-markdown will do its best to serialize markdown to match the syntax tree, but there are several cases where that is impossible. It’ll do its best, but complete roundtripping is impossible given that any value could be injected into the tree.
As markdown is sometimes used for HTML, and improper use of HTML can open you up to a cross-site scripting (XSS)xss attack, use of mdast-util-to-markdown and parsing it again later could potentially be unsafe. When parsing markdown afterwards and then going to HTML, use something like hast-util-sanitizehast-util-sanitize to make the tree safe.


β€” parse markdown to mdast
β€” parse markdown
β€” process markdown


See contributing.mdcontributing in syntax-tree/.githubhealth for ways to get started. See support.mdsupport for ways to get help.
This project has a code of conductcoc. By interacting with this repository, organization, or community you agree to abide by its terms.


MITlicense Β© Titus Wormerauthor