Cheat Sheet
comark (core)
parseMarkdown(source, options?)
Parse Comark content into a MarkdownDocument.
import { parseMarkdown } from 'comark'
import shiki from 'comark/plugins/shiki'
const result = await parseMarkdown(source, {
autoUnwrap: true, // Remove <p> wrappers from single-paragraph containers
autoClose: true, // Auto-close incomplete syntax
plugins: [shiki()] // HTML parsing is on by default via the html plugin
})
result.nodes // Node[]: parsed AST nodes
result.frontmatter // Record<string, any>: frontmatter data
result.meta.toc // TOC object (from toc plugin)
result.meta.summary // Node[] (from summary plugin)createMarkdownParser(options?)
Creates a reusable parser that initializes once across multiple documents.
import { createMarkdownParser } from 'comark'
const parse = createMarkdownParser({ plugins: [shiki()] })
const tree1 = await parse('# Document 1')
const tree2 = await parse('# Document 2')renderMarkdown(document, options?)
Converts a MarkdownDocument back to a Markdown string.
import { parseMarkdown } from 'comark'
import { renderMarkdown } from 'comark/render'
const document = await parseMarkdown(source)
const markdown = await renderMarkdown(document, {
maxInlineAttributes: 3, // Switch to YAML block syntax above this threshold
})autoCloseMarkdown(source)
Closes unclosed Markdown syntax and Comark components during streaming.
import { autoCloseMarkdown } from 'comark'
autoCloseMarkdown('**bold') // '**bold**'
autoCloseMarkdown('::alert\nText') // '::alert\nText\n::'String renderers
@comark/html
renderHtml(markdown, options?)
Parses and renders Markdown to an HTML string in one call.
import { renderHtml } from '@comark/html'
const html = await renderHtml('# Hello\n\nThis is **bold**.')createHtmlRenderer(options?)
Creates a reusable parse-and-render function initialized once.
import { createHtmlRenderer } from '@comark/html'
const renderHtml = createHtmlRenderer({
plugins: [shiki()],
components: {
alert: async ([, attrs, ...children], { render }) =>
`<div class="alert-${attrs.type}">${await render(children)}</div>`
}
})
const html = await renderHtml(source)renderHtmlFromDocument(document, options?)
Renders a pre-parsed MarkdownDocument to an HTML string.
import { renderHtmlFromDocument } from '@comark/html'
const html = await renderHtmlFromDocument(document, {
components: {
alert: async ([, attrs, ...children], { render }) =>
`<div class="alert-${attrs.type}">${await render(children)}</div>`
}
})@comark/ansi
renderAnsi(markdown, options?)
Parses and renders Markdown to an ANSI-styled terminal string in one call.
import { renderAnsi } from '@comark/ansi'
const output = await renderAnsi('# Hello\n\nThis is **bold**.')
process.stdout.write(output)createAnsiRenderer(options?)
Creates a reusable parse-and-render function with pre-configured parser and ANSI renderer options.
import { createAnsiRenderer } from '@comark/ansi'
const renderAnsi = createAnsiRenderer({ colors: false, width: 120 })
const output = await renderAnsi('# Hello')renderAnsiFromDocument(document, options?)
Renders a pre-parsed MarkdownDocument to an ANSI-styled string.
import { parseMarkdown } from 'comark'
import { renderAnsiFromDocument } from '@comark/ansi'
const document = await parseMarkdown('# Hello')
const output = await renderAnsiFromDocument(document)
process.stdout.write(output)printAnsi(markdown, options?)
Parses and renders Markdown directly to stdout. Replaces the deprecated writeAnsi alias.
import { printAnsi } from '@comark/ansi'
await printAnsi('# Hello\n\nThis is **bold**.')createAnsiPrinter(options?)
Creates a reusable Markdown printer. Pass writer to target something other than process.stdout. Replaces the deprecated createAnsiWriter alias.
import { createAnsiPrinter } from '@comark/ansi'
const printAnsi = createAnsiPrinter({
writer: (output) => process.stderr.write(output),
})
await printAnsi('# Hello')Framework renderers
@comark/vue, @comark/react, @comark/svelte, and @comark/angular share the same component API under their own import paths.
<Markdown>
Parses and renders Markdown in one async step.
<Markdown :plugins="[shiki()]" :components="{ alert: Alert }">
{{ content }}
</Markdown><Markdown plugins={[shiki()]} components={{ alert: Alert }}>
{content}
</Markdown><Markdown value={content} plugins={[shiki()]} components={{ alert: Alert }} /><comark-markdown [value]="content" [plugins]="[shiki()]" [components]="{ alert: Alert }" /><MarkdownDocument>
Renders a pre-parsed MarkdownDocument with no parser shipped to the client.
<MarkdownDocument :value="document" :components="{ alert: Alert }" /><MarkdownDocument value={document} components={{ alert: Alert }} /><MarkdownDocument value={document} components={{ alert: Alert }} /><comark-markdown-document [value]="document" [components]="{ alert: Alert }" />defineMarkdownComponent(options)
Creates a pre-configured <Markdown> component with default plugins and component mappings.
import { defineMarkdownComponent } from '@comark/vue' // or @comark/react, @comark/angular
export const AppMarkdown = defineMarkdownComponent({
plugins: [shiki(), toc()],
components: { alert: CustomAlert },
})In@comark/angular,provideMarkdownandprovideMarkdownDocumentare the AOT-safe alternatives. They return configProviderobjects forMARKDOWN_CONFIG/MARKDOWN_DOCUMENT_CONFIG: register them once at bootstrap (or in a route or ancestor injector) and every staticMarkdown/MarkdownDocumentcomponent inherits the config. ThedefineMarkdownComponent/defineMarkdownDocumentComponentfactories still return component classes for JIT builds. See the Angular renderer guide.
Transforming nodes before render
transformNode lets you change the tag or props of an element node right before it renders, based on its props and the render context. Use it when a value is only known at render time, such as runtime data, and components alone can't express the change.
The option takes a function or an array of functions. Every renderer accepts it: the <Markdown> and <MarkdownDocument> components in Vue, React, Svelte, and Angular, defineMarkdownComponent, defineMarkdownDocumentComponent, and the @comark/html and @comark/ansi render functions.
import type { NodeTransform } from 'comark'
const transformNode: NodeTransform = ({ tag, props, renderData }) => {
if (tag !== 'cta') return
return {
tag: 'a',
props: { ...props, href: `/users/${renderData.data.userId}/dashboard` },
}
}<MarkdownDocument :value="document" :data="{ userId: 42 }" :transform-node="transformNode" /><MarkdownDocument value={document} data={{ userId: 42 }} transformNode={transformNode} /><MarkdownDocument value={document} data={{ userId: 42 }} {transformNode} /><comark-markdown-document [value]="document" [data]="{ userId: 42 }" [transformNode]="transformNode" />const html = await renderHtmlFromDocument(document, { data: { userId: 42 }, transformNode })The function receives:
tag: the tag the renderer will use.props: the node's attributes with:bindings resolved. Every renderer strips the leading:, parses the value as JSON, and looks up non-JSON values as a data path.:count="5"resolves to{ count: 5 }, and a missing path resolves toundefined.node: the node as it is in the document.parent: the parent element node, when the renderer knows it. Svelte doesn't pass it.renderData:{ frontmatter, meta, data, props }, wherepropsholds the parent's props.
Return { tag?, props? } to replace either one, or nothing to keep the node as it is. Comark does not resolve : keys in the returned props again. The node's children see the returned props as their parent props, so :title="props.title" in a child reads the new value.
These rules apply:
- Lookup. A returned tag is looked up like any tag, in
components, thencomponentsManifest, then as a native element. Anasprop still takes precedence in Vue, React, and Angular, so remove it frompropsif the new tag must win. - Order. With an array, each function sees the result of the previous one.
defineMarkdownComponentanddefineMarkdownDocumentComponentrun their owntransformNodebefore the instance's. - Safety. The returned tag and props render as-is, like the output of a custom component. Comark doesn't sanitize them, and the security plugin runs at parse time, so its options don't apply either. Validate anything the function builds from untrusted data, such as URLs from
data, and return a valid tag name. - Purity. The function must be synchronous and must not mutate
props,node, orrenderData. It runs for every element node on every render, and Angular can call it twice for a node that renders as a custom component. - Stable reference. In Vue, React, and Angular, define the function or array once, outside the render. A new array on every render makes the document render again.
Stream effects
Stream effects decorate the document at render time while streaming is true. Every framework renderer accepts a single effects prop: an array of effects that run in order and never modify the parsed document. Import the built-in effects (caret(), fade(), pace(), typewriter()) from comark/effects.
caret and fade props were removed from every renderer. Import caret() and fade() from comark/effects and pass them through effects instead. For example, caret becomes effects={[caret()]} and :fade="{ delay: 30 }" becomes :effects="[fade({ delay: 30 })]".<script setup lang="ts">
import { caret, fade } from 'comark/effects'
const effects = [fade(), caret()]
</script>
<template>
<Markdown :value="text" :streaming="isStreaming" :effects="effects" />
</template>import { caret, fade } from 'comark/effects'
const effects = [fade(), caret()]
<Markdown value={text} streaming={isStreaming} effects={effects} /><script lang="ts">
import { caret, fade } from 'comark/effects'
const effects = [fade(), caret()]
</script>
<Markdown value={text} streaming={isStreaming} {effects} /><comark-markdown [value]="text" [streaming]="isStreaming" [effects]="effects" />Define the array once, outside the render, so effects keep their state between renders. Effects run in array order. Put pace() first, then fade(), then caret(), so later effects only see released text and the caret lands after any decorated text.
Fade-in
fade() wraps newly streamed text in <span class="comark-fade"> elements that fade from transparent. Comark compares each top-level block's text with what is already on screen and only wraps the characters past the common prefix, so text never fades twice, even when a paragraph turns into a heading or a closing ** arrives. After a block's last animation finishes, its spans merge back into plain text. Renderers keep scheduling frames until that happens, even after streaming turns false.
interface FadeOptions {
duration?: number // Animation length in ms (default: 300)
easing?: FadeEasing // CSS timing function (default: 'ease-out')
animation?: 'fade' | 'blur' | 'slide' // Built-in animation, ignored when `class` is set (default: 'fade')
delay?: number // Delay in ms between units; 0 fades each chunk as a whole (default: 30 for 'word', 20 for 'char')
unit?: 'word' | 'char' // Fade whole words or one character at a time (default: 'word')
class?: string // Class on fading spans, images, rules, and checkboxes (default: 'comark-fade')
styles?: boolean // Add the default keyframes to the page (default: true unless `class` is set)
exclude?: readonly string[] // Tags that never fade (default: DEFAULT_FADE_EXCLUDE)
}
type FadeEasing =
| 'linear' | 'ease' | 'ease-in' | 'ease-out' | 'ease-in-out' | 'step-start' | 'step-end'
| `cubic-bezier(${string})` | `steps(${string})` | `linear(${string})` | `var(${string})`fade({ delay: 30, easing: 'cubic-bezier(0.2, 0, 0, 1)' })- Content not faded. The first render shows text immediately, and so do updates while
streamingisfalseonce no paced backlog is draining. Code blocks (pre),math,mermaid,svg,script,style, andtextareanever fade, because their content is highlighted or rendered as a whole. - Word delay. Words queue
delayms behind each other across chunks and blocks, and the queue never falls more thandurationbehind the stream. Passdelay: 0to fade each chunk as a whole. Spaces, including no-break and ideographic spaces, separate words, and each Han or kana character is a word of its own, so CJK text cascades instead of fading as one block. - Images, rules, checkboxes, and list markers.
img,hr, and task listinputelements get the fade class and fade in their place in the word queue. A new list item getscomark-fade-marker(or<class>-marker) and the--comark-fade-delay,--comark-fade-duration, and--comark-fade-easingcustom properties, which the default styles use to fade its::markercolor with the item's first word. - Presets.
animation: 'blur'addscomark-fade-blur(sharpens from a 4px blur) and'slide'addscomark-fade-slide(rises0.25em). Slide animatestopon a relatively positioned span, becausetransformdoes not apply to inline text. - Styles. By default the keyframes are added to the page once, through a constructable stylesheet when the browser supports one. They respect
prefers-reduced-motion. Passclassto drive the animation with your own CSS, orstyles: falseto shipFADE_STYLESfromcomark/effectsyourself, for example inside a shadow root.
.my-fade {
animation: my-fade 400ms ease-out both;
}
@keyframes my-fade {
from { opacity: 0; filter: blur(4px); }
}Pacing
fade() and typewriter() show each chunk as soon as it arrives. To release text at a steady rate, independent of how fast chunks arrive, put pace() before them:
const effects = [pace({ speed: 80, catchUp: 1000 }), fade({ delay: 30 }), caret()]interface PaceOptions {
speed?: number // Base reveal speed in characters per second (default: 45)
catchUp?: number // Speed up when the reveal falls more than this many ms behind the received text (default: Infinity)
exclude?: readonly string[] // Tags shown whole once the reveal reaches them (default: DEFAULT_FADE_EXCLUDE)
}- Drain. The renderer keeps rendering until the backlog drains, even after
streamingturnsfalse, and later effects keep treating the released text as streaming so it still fades. - First render. The first render shows the full current input, so server rendering and hydration contain the text. Only text that arrives after that is paced.
- Whole words. While
pace()has a backlog,fade()in word mode holds back a partially released word and fades it once it is complete. - Excluded content. Code blocks, math, and diagrams count no text and appear whole once the reveal reaches them.
Custom effects
An effect receives the top-level nodes and returns new ones. It must not mutate its input: copy only the arrays you change, so unchanged blocks keep their identity and skip re-rendering. Give nodes you insert a $.key so renderers keep their DOM between renders.
import type { StreamEffect } from 'comark/effects'
const highlightNewBlock: StreamEffect<{ count: number }> = {
name: 'highlight-new-block',
init: () => ({ count: 0 }),
apply(nodes, { streaming, state }) {
state.count = nodes.length
if (!streaming || nodes.length === 0) return nodes
const last = nodes[nodes.length - 1]
if (!Array.isArray(last) || last[0] === null) return nodes
return [...nodes.slice(0, -1), [last[0], { ...last[1], class: 'is-streaming' }, ...last.slice(2)]]
},
}<Markdown value={text} streaming={isStreaming} effects={[highlightNewBlock, caret()]} />Each renderer instance keeps one state per effect name between renders, created by init. The context also carries streaming, now (a millisecond timestamp for the render), and backlog (whether an earlier effect such as pace() still holds text back).
Two optional hooks keep the renderer rendering without new input. pending(state) returns true while the effect holds text back, so later effects see streaming and backlog as true. settling(state) returns true while the effect only needs another render to clean up its own decoration, as fade() does to merge finished spans. Later effects still see the real streaming value, so caret() hides when the stream ends.
Effects run in array order. Put pace() first so later effects only see released text, and caret() last. typewriter() types text out one character at a time at speed (default 100 characters per second). Pair it with pace() at the same speed so the queue never grows: [pace({ speed: 100 }), typewriter({ speed: 100 })].
comark/effects also exports createStreamRenderer() for custom renderers, plus caret(), fade(), pace(), typewriter(), getChildKeys(), CARET_STYLES, FADE_STYLES, and TYPEWRITER_STYLES.
Types
MarkdownDocument
interface MarkdownDocument {
nodes: Node[]
frontmatter: Record<string, any>
meta: {
toc?: Toc
summary?: Node[]
[key: string]: any
}
}RenderMarkdownOptions
interface RenderMarkdownOptions {
maxInlineAttributes?: number // Max inline attributes before switching to YAML block (default: 3)
blockAttributesStyle?: 'frontmatter' | 'codeblock' // Block attribute syntax style (default: 'codeblock')
rawHtmlText?: 'escape' | 'verbatim' // Text inside raw HTML blocks: escape tag-like `<` (default) or keep as-is
frontmatterOptions?: DumpOptions // js-yaml options for frontmatter serialization
components?: Record<string, NodeHandler | ConditionalNodeHandler> // Custom render handlers for specific elements
data?: Record<string, any> // Additional data passed to render handlers
}Node
type Node =
| string // TextNode
| [tag: string, attrs: ElementNodeAttributes, ...children: Node[]] // ElementNode
| [tag: null, attrs: ElementNodeAttributes, comment: string] // CommentNodeParserOptions
interface ParserOptions {
autoUnwrap?: boolean // default: true
autoClose?: boolean | AutoCloseFunction // default: true
unwrap?: boolean | string | string[] // strip top-level wrapper tags, for example 'p' (default: false)
linkify?: boolean // deprecated: use registerDefaultPlugins: false + linkify()
headingIds?: boolean | 'nested' | 'flat' // default: true ('flat'); slug from visible text, duplicates get -1, -2, ... (keeps Unicode letters/numbers, omits symbol-only ids), explicit id wins
registerDefaultPlugins?: boolean // default: true
plugins?: ComarkPlugin[]
tracer?: ComarkTracer // OpenTelemetry-style tracer for parse spans
}Toc
// Exported from 'comark/plugins/toc'
interface Toc {
title: string
depth: number
searchDepth: number
links: TocLink[]
}
interface TocLink {
id: string
text: string
depth: number
children?: TocLink[]
}Imports
// Core
import { parseMarkdown, createMarkdownParser, autoCloseMarkdown } from 'comark'
import { renderMarkdown } from 'comark/render'
import type { RenderMarkdownOptions } from 'comark/render'
import { defineComarkPlugin } from 'comark'
// Stream effects
import { caret, fade, createStreamRenderer, FADE_STYLES } from 'comark/effects'
import type { StreamEffect, FadeOptions, CaretOptions } from 'comark/effects'
// Plugins
import shiki from 'comark/plugins/shiki'
import emoji from 'comark/plugins/emoji'
import toc from 'comark/plugins/toc'
import summary from 'comark/plugins/summary'
import security from 'comark/plugins/security'
// HTML rendering
import { createHtmlRenderer, renderHtml, renderHtmlFromDocument } from '@comark/html'
// ANSI rendering
import {
renderAnsi,
renderAnsiFromDocument,
createAnsiRenderer,
printAnsi,
createAnsiPrinter,
} from '@comark/ansi'
// Vue
import { Markdown, MarkdownDocument, defineMarkdownComponent } from '@comark/vue'
// React
import { Markdown, MarkdownDocument, defineMarkdownComponent } from '@comark/react'
// Svelte
import { Markdown, MarkdownDocument } from '@comark/svelte'
// Types
import type {
MarkdownDocument,
ElementNode,
TextNode,
CommentNode,
ElementNodeAttributes,
Node,
ParserOptions,
ComarkPlugin,
} from 'comark'Related
- Parse API - Full parse options, plugins, and examples
- Render API - Render a
MarkdownDocumentback to Markdown - Streaming API - Handle incomplete syntax for streaming
- HTML rendering - Server-side HTML generation
- Vue rendering - Render in Vue applications
- React rendering - Render in React applications
- Svelte rendering - Render in Svelte applications
- Nuxt - Nuxt module shipped in
@comark/vue - ANSI rendering - Terminal output
- Plugins - Syntax highlighting, math, TOC, and more
- Document model - Parsed document and node model
Streaming API
Render incomplete Markdown correctly during streaming. autoCloseMarkdown() closes unterminated syntax so AI output displays at every frame.
Why Comark?
Comark gives JavaScript applications one Markdown pipeline for standards-based parsing, serializable documents, multiple renderers, plugins, and streaming.