mdast utility to serialize markdown
npm install mdast-util-to-markdown[![Build][build-badge]][build]
[![Coverage][coverage-badge]][coverage]
[![Downloads][downloads-badge]][downloads]
[![Size][size-badge]][size]
[![Sponsors][sponsors-badge]][collective]
[![Backers][backers-badge]][collective]
[![Chat][chat-badge]][chat]
[mdast][] utility that turns a syntax tree into markdown.
* What is this?
* When should I use this?
* Install
* Use
* API
* [toMarkdown(tree[, options])](#tomarkdowntree-options)
* defaultHandlers
* ConstructName
* ConstructNameMap
* Handle
* Handlers
* Info
* Join
* Map
* Options
* SafeConfig
* State
* Tracker
* Unsafe
* List of extensions
* Syntax
* Syntax tree
* Types
* Compatibility
* Security
* Related
* Contribute
* License
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-stringify][remark-stringify], which focusses on making it
easier to transform content by abstracting these internals away.
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-mdx][mdast-util-mdx],
[mdast-util-frontmatter][mdast-util-frontmatter],
[mdast-util-math][mdast-util-math], and
[mdast-util-directive][mdast-util-directive].
This package is [ESM only][esm].
In Node.js (version 16+), install with [npm][]:
``sh`
npm install mdast-util-to-markdown
In Deno with [esm.sh][esmsh]:
`js`
import {toMarkdown} from 'https://esm.sh/mdast-util-to-markdown@2'
In browsers with [esm.sh][esmsh]:
`html`
Say our module example.js looks as follows:
`js
/**
* @import {Root} from 'mdast'
*/
import {toMarkdown} from 'mdast-util-to-markdown'
/* @type {Root} /
const tree = {
type: 'root',
children: [
{
type: 'blockquote',
children: [
{type: 'thematicBreak'},
{
type: 'paragraph',
children: [
{type: 'text', value: '- a\nb !'},
{
type: 'link',
url: 'example.com',
children: [{type: 'text', value: 'd'}]
}
]
}
]
}
]
}
console.log(toMarkdown(tree))
`
β¦now running node example.js yields:
`markdown`
> *
>
> \- a
> b \!d
> π Note: observe the properly escaped characters which would otherwise
> turn into a list and image respectively.
This package exports the identifiers [defaultHandlers][api-default-handlers]toMarkdown
and [][api-to-markdown].
There is no default export.
Turn an [mdast][] syntax tree into markdown.
###### Parameters
* tree ([Node][node])options
β tree to serialize
* ([Options][api-options], optional)
β configuration
###### Returns
Serialized markdown representing tree (string).
Default (CommonMark) handlers ([Handlers][api-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
`ts`
type ConstructName = ConstructNameMap[keyof ConstructNameMap]
Interface of registered constructs (TypeScript type).
###### Type
`ts`
interface ConstructNameMap { / see code / }
When working on extensions that use new constructs, extend the corresponding
interface to register its name:
`ts`
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).
###### Parameters
* node (any)parent
β expected mdast node
* ([Node][node], optional)node
β parent of state
* ([State][api-state])info
β info passed around about the current state
* ([Info][api-info])
β info on the surrounding of the node that is serialized
###### Returns
Serialized markdown representing node (string).
Handle particular nodes (TypeScript type).
Each key is a node type (Node['type']), each value its corresponding handlerHandle
([][api-handle]).
###### Type
`ts`
type Handlers = Record
Info on the surrounding of the node that is serialized (TypeScript type).
###### Fields
* now ([Point][point])lineShift
β current point
* (number)before
β number of columns each line will be shifted by wrapping nodes
* (string)after
β characters before this (guaranteed to be one, can be more)
* (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.
###### Parameters
* left ([Node][node])right
β first of two adjacent siblings
* ([Node][node])parent
β second of two adjacent siblings
* ([Node][node])state
β parent of the two siblings
* ([State][api-state])
β info passed around about the current state
###### Returns
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:
`markdown
> 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).
###### Parameters
* value (string)line
β a single line of serialized markdown
* (number)blank
β line number relative to the fragment
* (boolean)
β whether the line is considered blank in markdown
###### Returns
Padded line (string).
Configuration (TypeScript type).
##### Fields
The following fields influence how markdown is serialized.
###### options.bullet
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 thematicbulletOther
break if serialized with three primary bullets; is used forbullet
the last item
* when a thematic break is the first child of a list item and is therule
same character as : - *; this would turn into a single thematicbulletOther
break if serialized with primary bullets; is used for the a\n- b
item
when two unordered lists appear next to each other: ;bulletOther
is used for such lists
###### options.bulletOther
Marker to use in certain cases where the primary bullet doesnβt work ('*','+', or '-', default: '-' when bullet is '', '' otherwise).
Cannot be equal to bullet.
###### options.bulletOrdered
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
###### options.closeAtx
Whether to add the same number of number signs (#) at the end of an ATXboolean
heading as the opening sequence (, default: false).
###### options.emphasis
Marker to use for emphasis ('' or '_', default: '').
###### options.fence
Marker to use for fenced code (''` or '~', default: ''`).
###### options.fences
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.
###### options.incrementListMarker
Whether to increment the counter of ordered lists items (boolean, default:true).
###### options.listItemIndent
How to indent the content of list items ('mixed', 'one', or 'tab','one'
default: ).'one'
Either with the size of the bullet plus one space (when ), a tab stop'tab'
(), or depending on the item and its parent list ('mixed', uses 'one''tab'
if the item and list are tight and otherwise).
###### options.quote
Marker to use for titles ('"' or "'", default: '"').
###### options.resourceLink
Whether to always use resource links (boolean, default: false).
The default is to use autolinks () when possibletext
and resource links () otherwise.
###### options.rule
Marker to use for thematic breaks ('', '-', or '_', default: '').
###### options.ruleRepetition
Number of markers to use for thematic breaks (number, default: 3, min: 3).
###### options.ruleSpaces
Whether to add spaces between markers in thematic breaks (boolean, default:false).
###### options.setext
Whether to use setext headings when possible (boolean, default: false).# heading
The default is to always use ATX headings () instead of setextheading\n=======
headings ().
Setext headings cannot be used for empty headings or headings with a rank of
three or more.
###### options.strong
Marker to use for strong ('' or '_', default: '').
###### options.tightDefinitions
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 [Join][api-join] function like so:
`js`
function joinTightDefinitions(left, right) {
if (left.type === 'definition' && right.type === 'definition') {
return 0
}
}
###### options.handlers
Handle particular nodes ([Handlers][api-handlers], optional).
###### options.join
How to join blocks ([Array][api-join], optional).
###### options.unsafe
Schemas that define when characters cannot occur
([Array][api-unsafe], optional).
###### options.extensions
List of extensions (Array, default: []).Options
Each extension is an object with the same interface as itself.
Configuration passed to state.safe (TypeScript type).
###### Fields
* before (string)after
β characters before this (guaranteed to be one, can be more)
* (string)encode
β characters after this (guaranteed to be one, can be more)
* (Array, 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).
###### Fields
* stack ([Array][api-construct-name])indexStack
β stack of constructs weβre in
* (Array)associationId
β positions of child nodes in their parents
* ((node: Association) => string)Association
β get an identifier from an association to match it to others (see
[][association])enter
* ((construct: ConstructName) => () => undefined)ConstructName
β enter a construct (returns a corresponding exit function)
(see [][api-construct-name])indentLines
* ((value: string, map: Map) => string)Map
β pad serialized markdown (see [][api-map])compilePattern
* ((pattern: Unsafe) => RegExp)Unsafe
β compile an unsafe pattern to a regex (see [][api-unsafe])containerFlow
* ((parent: Node, info: Info) => string)Info
β serialize flow children (see [][api-info])containerPhrasing
* ((parent: Node, info: Info) => string)Info
β serialize phrasing children (see [][api-info])createTracker
* ((info: Info) => Tracker)Info
β track positional info in the output (see [][api-info],Tracker
[][api-tracker])safe
* ((value: string, config: SafeConfig) => string)SafeConfig
β make a string safe for embedding (see [][api-safe-config])options
* ([Options][api-options])unsafe
β applied user configuration
* ([Array][api-unsafe])join
β applied unsafe patterns
* ([Array][api-join])handle
β applied join handlers
* ([Handle][api-handle])handlers
β call the configured handler for the given node
* ([Handlers][api-handlers])bulletCurrent
β applied handlers
* (string or undefined)bulletLastUsed
β list marker currently in use
* (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.
###### Fields
* current (() => Info)shift
β get current tracked info
* ((value: number) => undefined)move
β define a relative increased line shift (the typical indent for lines)
* ((value: string) => string)
β move past some generated markdown
Schema that defines when a character cannot occur (TypeScript type).
###### Fields
* character (string)inConstruct
β single unsafe character
* ([Array][api-construct-name],ConstructName
, optional)notInConstruct
β constructs where this is bad
* ([Array][api-construct-name],ConstructName
, optional)before
β constructs where this is fine again
* (string, optional)character
β is bad when this is before it (cannot be used together withatBreak
)after
* (string, optional)character
β is bad when this is after itatBreak
* (boolean, optional)character
β is bad at a break (cannot be used together with before)
* syntax-tree/mdast-util-directive
β directives
* syntax-tree/mdast-util-frontmatter
β frontmatter (YAML, TOML, more)
* syntax-tree/mdast-util-gfm
β GFM
* syntax-tree/mdast-util-gfm-autolink-literal
β GFM autolink literals
* syntax-tree/mdast-util-gfm-footnote
β GFM footnotes
* syntax-tree/mdast-util-gfm-strikethrough
β GFM strikethrough
* syntax-tree/mdast-util-gfm-table
β GFM tables
* syntax-tree/mdast-util-gfm-task-list-item
β GFM task list items
* syntax-tree/mdast-util-math
β math
* syntax-tree/mdast-util-mdx
β MDX
* syntax-tree/mdast-util-mdx-expression
β MDX expressions
* syntax-tree/mdast-util-mdx-jsx
β MDX JSX
* syntax-tree/mdast-util-mdxjs-esm
β MDX ESM
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.
The syntax tree is [mdast][].
This package is fully typed with [TypeScript][].
It exports the additional types
[ConstructName][api-construct-name],ConstructNameMap
[][api-construct-name-map],Handle
[][api-handle],Handlers
[][api-handlers],Info
[][api-info],Join
[][api-join],Map
[][api-map],Options
[][api-options],SafeConfig
[][api-safe-config],State
[][api-State], andUnsafe
[][api-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-markdownhast-util-sanitize
and parsing it again later could potentially be unsafe.
When parsing markdown afterwards and then going to HTML, use something like
[][hast-util-sanitize] to make the tree safe.
* syntax-tree/mdast-util-from-markdown
β parse markdown to mdast
* micromark/micromark
β parse markdown
* remarkjs/remark
β process markdown
See [contributing.md][contributing] in [syntax-tree/.github][health] forsupport.md`][support] for ways to get help.
ways to get started.
See [
This project has a [code of conduct][coc].
By interacting with this repository, organization, or community you agree to
abide by its terms.
[MIT][license] Β© [Titus Wormer][author]
[build-badge]: https://github.com/syntax-tree/mdast-util-to-markdown/workflows/main/badge.svg
[build]: https://github.com/syntax-tree/mdast-util-to-markdown/actions
[coverage-badge]: https://img.shields.io/codecov/c/github/syntax-tree/mdast-util-to-markdown.svg
[coverage]: https://codecov.io/github/syntax-tree/mdast-util-to-markdown
[downloads-badge]: https://img.shields.io/npm/dm/mdast-util-to-markdown.svg
[downloads]: https://www.npmjs.com/package/mdast-util-to-markdown
[size-badge]: https://img.shields.io/badge/dynamic/json?label=minzipped%20size&query=$.size.compressedSize&url=https://deno.bundlejs.com/?q=mdast-util-to-markdown
[size]: https://bundlejs.com/?q=mdast-util-to-markdown
[sponsors-badge]: https://opencollective.com/unified/sponsors/badge.svg
[backers-badge]: https://opencollective.com/unified/backers/badge.svg
[collective]: https://opencollective.com/unified
[chat-badge]: https://img.shields.io/badge/chat-discussions-success.svg
[chat]: https://github.com/syntax-tree/unist/discussions
[npm]: https://docs.npmjs.com/cli/install
[esmsh]: https://esm.sh
[license]: license
[author]: https://wooorm.com
[health]: https://github.com/syntax-tree/.github
[contributing]: https://github.com/syntax-tree/.github/blob/main/contributing.md
[support]: https://github.com/syntax-tree/.github/blob/main/support.md
[coc]: https://github.com/syntax-tree/.github/blob/main/code-of-conduct.md
[esm]: https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c
[typescript]: https://www.typescriptlang.org
[xss]: https://en.wikipedia.org/wiki/Cross-site_scripting
[hast-util-sanitize]: https://github.com/syntax-tree/hast-util-sanitize
[point]: https://github.com/syntax-tree/unist#point
[mdast]: https://github.com/syntax-tree/mdast
[node]: https://github.com/syntax-tree/mdast#nodes
[association]: https://github.com/syntax-tree/mdast#association
[mdast-util-gfm]: https://github.com/syntax-tree/mdast-util-gfm
[mdast-util-mdx]: https://github.com/syntax-tree/mdast-util-mdx
[mdast-util-frontmatter]: https://github.com/syntax-tree/mdast-util-frontmatter
[mdast-util-math]: https://github.com/syntax-tree/mdast-util-math
[mdast-util-directive]: https://github.com/syntax-tree/mdast-util-directive
[remark]: https://github.com/remarkjs/remark
[remark-stringify]: https://github.com/remarkjs/remark/tree/main/packages/remark-stringify
[api-construct-name]: #constructname
[api-construct-name-map]: #constructnamemap
[api-default-handlers]: #defaulthandlers
[api-handle]: #handle
[api-handlers]: #handlers
[api-info]: #info
[api-join]: #join
[api-map]: #map
[api-options]: #options
[api-safe-config]: #safeconfig
[api-state]: #state
[api-to-markdown]: #tomarkdowntree-options
[api-tracker]: #tracker
[api-unsafe]: #unsafe