Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork23
mdast utility to serialize markdown
License
syntax-tree/mdast-util-to-markdown
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
mdast utility that turns a syntax tree into markdown.
- What is this?
- When should I use this?
- Install
- Use
- API
- List of extensions
- Syntax
- Syntax tree
- Types
- Compatibility
- Security
- Related
- Contribute
- License
This package is a utility that takes anmdastsyntax tree as input and turns it into serialized markdown.
This utility is a low level project.It’s used inremark-stringify,which focusses on making it easier to transform content by abstractingthese internals away.
If you want to handle syntax trees manually, use this.For an easier time processing content, use theremarkecosystem instead.
You can combine this utility with other utilities to add syntax extensions.Notable examples that deeply integrate with it aremdast-util-gfm,mdast-util-mdx,mdast-util-frontmatter,mdast-util-math, andmdast-util-directive.
This package isESM only.In Node.js (version 16+), install withnpm:
npm install mdast-util-to-markdown
In Deno withesm.sh:
import{toMarkdown}from'https://esm.sh/mdast-util-to-markdown@2'
In browsers withesm.sh:
<scripttype="module">import{toMarkdown}from'https://esm.sh/mdast-util-to-markdown@2?bundle'</script>
Say our moduleexample.js looks as follows:
/** *@import {Root} from 'mdast' */import{toMarkdown}from'mdast-util-to-markdown'/**@type {Root} */consttree={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 runningnode example.js yields:
>***>>\- a>b\
👉Note: observe the properly escaped characters which would otherwiseturn into a list and image respectively.
This package exports the identifiersdefaultHandlersandtoMarkdown.There is no default export.
Turn anmdast syntax tree into markdown.
Serialized markdown representingtree (string).
Default (CommonMark) handlers (Handlers).
Construct names for things generated bymdast-util-to-markdown (TypeScripttype).
This is an enum of strings, each being a semantic label, useful to know whenserializing whether we’re for example in a double (") or single (') quotedtitle.
typeConstructName=ConstructNameMap[keyofConstructNameMap]
Interface of registered constructs (TypeScript type).
interfaceConstructNameMap{/* see code */}
When working on extensions that use new constructs, extend the correspondinginterface to register its name:
declare module'mdast-util-to-markdown'{interfaceConstructNameMap{// Register a new construct name (value is used, key should match it).gfmStrikethrough:'gfmStrikethrough'}}
Handle a particular node (TypeScript type).
node(any)— expected mdast nodeparent(Node, optional)— parent ofnodestate(State)— info passed around about the current stateinfo(Info)— info on the surrounding of the node that is serialized
Serialized markdown representingnode (string).
Handle particular nodes (TypeScript type).
Each key is a node type (Node['type']), each value its corresponding handler(Handle).
typeHandlers=Record<Node['type'],Handle>
Info on the surrounding of the node that is serialized (TypeScript type).
now(Point)— current pointlineShift(number)— number of columns each line will be shifted by wrapping nodesbefore(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 timesthey cannot occur together at all.
Join functions receive two adjacent siblings and their parent and what theyreturn defines how many blank lines to use between them.
left(Node)— first of two adjacent siblingsright(Node)— second of two adjacent siblingsparent(Node)— parent of the two siblingsstate(State)— info passed around about the current state
How many blank lines to use between the siblings (boolean,number,optional).
Wheretrue is as passing1 andfalse means the nodes cannot bejoined by a blank line, such as two adjacent block quotes or indented codeafter 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
0for two paragraphs, which will resultin 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 markdownline(number)— line number relative to the fragmentblank(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
bulletis also a validrule:* - +; this would turn into a thematicbreak if serialized with three primary bullets;bulletOtheris used forthe last item - when a thematic break is the first child of a list item and
bulletis thesame character asrule:- ***; this would turn into a single thematicbreak if serialized with primary bullets;bulletOtheris used for theitem - when two unordered lists appear next to each other:
* a\n- b;bulletOtheris used for such lists
Marker to use in certain cases where the primary bullet doesn’t work ('*','+', or'-', default:'-' whenbullet is'*','*' otherwise).
Cannot be equal tobullet.
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 solvethat,'.'will be used whenbulletOrderedis')', and'.'otherwise
Whether to add the same number of number signs (#) at the end of an ATXheading 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 isempty, 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 (<https://example.com>) when possibleand 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 setextheadings (heading\n=======).Setext headings cannot be used for empty headings or headings with a rank ofthree 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 aJoin function like so:
functionjoinTightDefinitions(left,right){if(left.type==='definition'&&right.type==='definition'){return0}}
Handle particular nodes (Handlers, optional).
How to join blocks (Array<Join>, optional).
Schemas that define when characters cannot occur(Array<Unsafe>, optional).
List of extensions (Array<Options>, default:[]).Each extension is an object with the same interface asOptions itself.
Configuration passed tostate.safe (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 thatmust be encoded (as character references) insteadof escaped (character escapes).Only ASCII punctuation will use character escapes, so you never need topass non-ASCII-punctuation here
Info passed around about the current state (TypeScript type).
stack(Array<ConstructName>)— stack of constructs we’re inindexStack(Array<number>)— positions of child nodes in their parentsassociationId((node: Association) => string)— get an identifier from an association to match it to others (seeAssociation)enter((construct: ConstructName) => () => undefined)— enter a construct (returns a corresponding exit function)(seeConstructName)indentLines((value: string, map: Map) => string)— pad serialized markdown (seeMap)compilePattern((pattern: Unsafe) => RegExp)— compile an unsafe pattern to a regex (seeUnsafe)containerFlow((parent: Node, info: Info) => string)— serialize flow children (seeInfo)containerPhrasing((parent: Node, info: Info) => string)— serialize phrasing children (seeInfo)createTracker((info: Info) => Tracker)— track positional info in the output (seeInfo,Tracker)safe((value: string, config: SafeConfig) => string)— make a string safe for embedding (seeSafeConfig)options(Options)— applied user configurationunsafe(Array<Unsafe>)— applied unsafe patternsjoin(Array<Join>)— applied join handlershandle(Handle)— call the configured handler for the given nodehandlers(Handlers)— applied handlersbulletCurrent(stringorundefined)— list marker currently in usebulletLastUsed(stringorundefined)— 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 infoshift((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 characterinConstruct(Array<ConstructName>,ConstructName, optional)— constructs where this is badnotInConstruct(Array<ConstructName>,ConstructName, optional)— constructs where this is fine againbefore(string, optional)—characteris bad when this is before it (cannot be used together withatBreak)after(string, optional)—characteris bad when this is after itatBreak(boolean, optional)—characteris bad at a break (cannot be used together withbefore)
syntax-tree/mdast-util-directive— directivessyntax-tree/mdast-util-frontmatter— frontmatter (YAML, TOML, more)syntax-tree/mdast-util-gfm— GFMsyntax-tree/mdast-util-gfm-autolink-literal— GFM autolink literalssyntax-tree/mdast-util-gfm-footnote— GFM footnotessyntax-tree/mdast-util-gfm-strikethrough— GFM strikethroughsyntax-tree/mdast-util-gfm-table— GFM tablessyntax-tree/mdast-util-gfm-task-list-item— GFM task list itemssyntax-tree/mdast-util-math— mathsyntax-tree/mdast-util-mdx— MDXsyntax-tree/mdast-util-mdx-expression— MDX expressionssyntax-tree/mdast-util-mdx-jsx— MDX JSXsyntax-tree/mdast-util-mdxjs-esm— MDX ESM
Markdown is serialized according to CommonMark but care is taken to format insuch a way that the resulting markdown should work with most markdown parsers.Extensions can add support for custom syntax.
The syntax tree ismdast.
This package is fully typed withTypeScript.It exports the additional typesConstructName,ConstructNameMap,Handle,Handlers,Info,Join,Map,Options,SafeConfig,State, andUnsafe.
Projects maintained by the unified collective are compatible with maintainedversions of Node.js.
When we cut a new major release, we drop support for unmaintained versions ofNode.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 thesyntax tree, but there are several cases where that is impossible.It’ll do its best, but complete roundtripping is impossible given that any valuecould be injected into the tree.
As markdown is sometimes used for HTML, and improper use of HTML can open you upto across-site scripting (XSS) attack,use ofmdast-util-to-markdownand parsing it again later could potentially be unsafe.When parsing markdown afterwards and then going to HTML, use something likehast-util-sanitize to make the tree safe.
syntax-tree/mdast-util-from-markdown— parse markdown to mdastmicromark/micromark— parse markdownremarkjs/remark— process markdown
Seecontributing.md insyntax-tree/.github forways to get started.Seesupport.md for ways to get help.
This project has acode of conduct.By interacting with this repository, organization, or community you agree toabide by its terms.
About
mdast utility to serialize markdown
Topics
Resources
License
Code of conduct
Contributing
Security policy
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Sponsor this project
Uh oh!
There was an error while loading.Please reload this page.
Contributors4
Uh oh!
There was an error while loading.Please reload this page.