Markdown conversion has two directions:
Use MarkdownPlugin for editor-bound conversion. Use the standalone functions
from platejs/markdown for detached browser, server, worker, and CLI work.
import { MarkdownPlugin } from 'platejs/markdown';
import { createEditor } from 'platejs';
const editor = createEditor({
plugins: [BaseParagraphPlugin, BaseHeadingPlugin, BaseBoldPlugin, MarkdownPlugin],
});
const result = editor.api.markdown.parse('# Hello\n\n**Plate** document');
if (result.ok) {
editor.update((tx) => tx.value.replace(result.document));
}
showDiagnostics(result.diagnostics);parse returns one complete EditorDocumentValue, including the roots that
mappings read and a leading front matter block in meta. Use
parseSlice for block insertion and
parseInline for inline insertion. Both return a closed, rootless
ContentSlice.
const blocks = editor.api.markdown.parseSlice('- One\n- Two');
const inline = editor.api.markdown.parseInline('Hello **world**');
if (blocks.ok) editor.update.slice.replace(blocks.slice);
if (inline.ok) editor.update.slice.replace(inline.slice);const blocks = editor.api.markdown.parseSlice('- One\n- Two');
const inline = editor.api.markdown.parseInline('Hello **world**');
if (blocks.ok) editor.update.slice.replace(blocks.slice);
if (inline.ok) editor.update.slice.replace(inline.slice);parseInline accepts one paragraph of content; block content fails with
markdown-inline-blocks. Direct syntax parsing does not preserve arbitrary open
edges or detached roots. Those are native transfer properties owned by
DataTransferFormat.
import { BaseBoldPlugin, BaseHeadingPlugin } from 'platejs';
import { parseMarkdown } from 'platejs/markdown';
const plugins = [BaseHeadingPlugin, BaseBoldPlugin] as const;
const result = parseMarkdown(source, { plugins });import { BaseBoldPlugin, BaseHeadingPlugin } from 'platejs';
import { parseMarkdown } from 'platejs/markdown';
const plugins = [BaseHeadingPlugin, BaseBoldPlugin] as const;
const result = parseMarkdown(source, { plugins });Standalone functions compile the supplied plugin declarations for one operation. They do not activate an editor runtime, handlers, effects, or React hooks. Parse slices and inline content through an installed editor.
const result = editor.api.markdown.serialize({
projection: 'proposed',
});
showDiagnostics(result.diagnostics);
if (result.ok) downloadMarkdown(result.data);const result = editor.api.markdown.serialize({
projection: 'proposed',
});
showDiagnostics(result.diagnostics);
if (result.ok) downloadMarkdown(result.data);Pass a captured document when the operation should not read the current value:
const result = editor.api.markdown.serialize({
document: editor.read.value(),
projection: 'accepted',
});const result = editor.api.markdown.serialize({
document: editor.read.value(),
projection: 'accepted',
});import { serializeMarkdown } from 'platejs/markdown';
const result = serializeMarkdown(document, {
plugins,
projection: 'accepted',
});import { serializeMarkdown } from 'platejs/markdown';
const result = serializeMarkdown(document, {
plugins,
projection: 'accepted',
});In plain Node, pass base plugins rather than a static kit such as
BaseEditorKit. Its math-static component imports the KaTeX stylesheet, and
Node throws on a CSS import.
Serialization asserts the document and the selected authored projection. Invalid model data and mapping bugs throw. Expected format loss returns a diagnosed result.
lossPolicy defaults to 'reject'. Unsupported visible content returns
{ ok: false, diagnostics } without data. lossPolicy: 'allow' can publish
only a drop, replacement, or unwrap that the format reports as a warning. A
loss that keeps the content, such as a paragraph boundary folded into <br/>
in a table cell, warns under every policy.
Plate reads and writes CommonMark plus the tags that installed feature plugins
register, after a leading front matter block. GFM, math,
emoji, and CJK emphasis come from the
remark plugins configured on MarkdownPlugin. Registered
tags look like HTML, but only registered names are tags and nothing is
evaluated. Other HTML stays text, which RawHtmlPlugin writes
back as HTML when its block passes a check.
| Tag | Feature |
|---|---|
<callout icon="💡">…</callout> | Callout |
<columnGroup>, <column width="50%"> | Column |
<details>, <summary> | Details |
<toc /> | Table of Contents |
<date value="2025-01-01" /> | Date |
<img>, <figure> with <figcaption> | Image |
<video src="…" />, <audio>, <file>, <mediaEmbed> | Media |
<u>, <kbd>, <mark>, <sub>, <sup>, <del> | Basic marks |
<span style="color: red;"> | Font colors, family, size, and weight |
A tag is registered only while its feature plugin is installed. Element tags use the schema type, so an application that renames a type also renames its tag.
RawHtmlPlugin keeps a file's raw HTML through a save. The Markdown kit
installs it. An editor with its own plugin list adds it beside
MarkdownPlugin:
import { BaseParagraphPlugin, createEditor } from 'platejs';
import { MarkdownPlugin, RawHtmlPlugin } from 'platejs/markdown';
const editor = createEditor({
plugins: [BaseParagraphPlugin, MarkdownPlugin, RawHtmlPlugin],
});import { BaseParagraphPlugin, createEditor } from 'platejs';
import { MarkdownPlugin, RawHtmlPlugin } from 'platejs/markdown';
const editor = createEditor({
plugins: [BaseParagraphPlugin, MarkdownPlugin, RawHtmlPlugin],
});An app whose own plugin already declares a rawHtml mark keeps that plugin and
leaves RawHtmlPlugin out, because two plugins cannot own one mark.
The plugin changes the editor's schema fingerprint, so an editor with it
refuses a document saved under the earlier schema identity. An app that saves
documents under a named schema increments its version and adds a migration
step, as Document migrations shows. An app
that saves { document, schema } under the derived identity opens each saved
document in an editor without the plugin and passes its read.value() to the
new editor.
Import gives the rawHtml mark to raw HTML that no registered tag claims, such
as a README's centered header, and to most HTML comments on lines of their own
in the document, a block quote or a list item. The editor shows that text as
plain text, and export writes it back as HTML:
<p align="center">
<img src="logo.png" width="200" />
</p>
<!-- markdownlint-disable --><p align="center">
<img src="logo.png" width="200" />
</p>
<!-- markdownlint-disable --><!-- a <!-- b -->, also stays
plain text, where an editor without the plugin drops it.p, div, img, kbd and details, and
attributes such as align, alt, href, src, title and width. It
refuses every other tag and attribute, such as script, class, style and
event handlers, and a doctype.href or src URL passes when it is empty or Plate's URL safety rules
accept it, and a cite or srcset URL passes only when those rules accept
it. The rules refuse script-capable schemes such as javascript:. The check
does not read the Link plugin's allowedSchemes, so
<a href="smb://server/share">x</a> writes back as HTML, while the Link
plugin with its default schemes refuses [x](smb://server/share).markdown-unsafe-content warning.
In rare cases, such as a mapping that copies marked text, export writes all
marked text in the document escaped. Plate writes a details summary line as
HTML, so a CommonMark reader still reads escaped text there as HTML, while
Plate reads it back as the same plain text.<callout>, raw HTML
writes back only in pieces that fit on one line. An HTML block there stays
plain text and saves escaped, and one directly inside <details> fails the
parse with markdown-schema-invalid, unless it is a comment. A <block>
wrapper around one HTML block drops on import, and its HTML writes back. A
footnote definition keeps all of its raw HTML as plain text.<!---->, the separator
Plate writes between two blocks. <!-- c --> after -, one indented
after a list, such as one space after - a, and one whose indent keeps a tab
after the indent of its quote or list item. Such a comment drops, and such
HTML saves escaped.rawHtml in MarkdownPlugin's plainMarks stops import from
marking, so tags stay plain text and comment blocks drop. Naming it in a
serialize call's plainMarks writes marked text escaped, with no warning.<callout icon="💡">Remember to save.</callout>
<details>
<summary>Title</summary>
Body text.
</details>
Due <date value="2025-01-01" />, ask [Jane](mention:user_123).<callout icon="💡">Remember to save.</callout>
<details>
<summary>Title</summary>
Body text.
</details>
Due <date value="2025-01-01" />, ask [Jane](mention:user_123).& is written as &, " as
", a newline as , and | as |.A and a, are written
as distinct labels.--- rules written with rule: '-', opens with a line ending so
it reads back as written.markdown-unsupported-node warning under every policy.RawHtmlPlugin, an HTML block that holds only closed
comments drops with a lossless warning.<br>, <br/>, and <br /> become line breaks.markdown-tag-repair warning
with reason: 'unclosed' | 'unmatched' | 'misplaced'.name={…} are read as their raw text.[text][ref] with a [ref]: url
definition, resolve to ordinary links and images.markdown-unsafe-content
warning under every policy: lossless when the destination could run script,
such as javascript: or data:, and lossy otherwise, such as a
protocol-relative or malformed URL. An image whose source cannot load keeps
its alt text and reports a lossy one; a script source never rendered, so its
removal is lossless. Link's allowedSchemes narrows or widens link schemes
above that floor; a link it rejects keeps its label and reports a lossy
markdown-unsupported-node warning.A GFM row is one line, so Plate writes a table cell's blocks inline on that line:
| Plan |
| ---- |
| Intro<ul><li><input type="checkbox" checked disabled /> ship</li></ul><ol start="3"><li>step</li></ol> || Plan |
| ---- |
| Intro<ul><li><input type="checkbox" checked disabled /> ship</li></ul><ol start="3"><li>step</li></ol> |<ul>, <ol start="n">, and <li> HTML,
with a disabled checkbox leading each task item. With List
installed, parsing reads that HTML back as list paragraphs; without it, the
HTML stays literal text.<br/>. Parsing reads them back as one
paragraph with line breaks, so serializing reports the folded boundary as a
lossy warning.<img src="…" width="200" />, keep their attributes and read back as blocks.
Serializing drops other unsupported blocks, such as a horizontal rule or a
captioned image, and reports it under lossPolicy.markdown-property-omitted.| ends a cell early. In inline math, serializing writes
| as \vert and \| as \Vert, writes | in a text-mode group such as
\text{…} as \textbar{}, and gives \verb a delimiter other than |.
Inline math with a | or \| it cannot place, such as one in another
command's argument, an array column spec or \verb text, becomes text.
Serializing writes | as %7C in an autolink destination and | in
raw HTML, turns a line ending in inline math or raw HTML into a space, and
writes inline code holding \| as text. Each kind of rewrite reports one
lossy warning per cell.Mentions are links with a mention: URL. Bare @jane text stays text.
Hello [Jane Smith](mention:user_123).Hello [Jane Smith](mention:user_123).See Mention.
Markdown does not carry element IDs, and serialization writes none. Parsing
reads a <block id="…"> wrapper around one block: with ElementIdPlugin
installed, the block keeps that id; otherwise the wrapper is removed with a
markdown-unsupported-node warning. Mappings cannot claim the block tag.
parse reads one leading YAML or TOML block, as Obsidian, Jekyll, and Hugo
notes open with, into the document's metadata instead of a rule and a heading:
---
title: Hello
tags: [a, b]
---
# Body---
title: Hello
tags: [a, b]
---
# Bodyimport { getMarkdownFrontmatter } from 'platejs/markdown';
const result = editor.api.markdown.parse(source);
if (result.ok) {
getMarkdownFrontmatter(result.document);
// { format: 'yaml', value: 'title: Hello\ntags: [a, b]' }
}import { getMarkdownFrontmatter } from 'platejs/markdown';
const result = editor.api.markdown.parse(source);
if (result.ok) {
getMarkdownFrontmatter(result.document);
// { format: 'yaml', value: 'title: Hello\ntags: [a, b]' }
}The block is stored at meta['markdown.frontmatter'] as
{ format: 'yaml' | 'toml', value: string }, where value is the text between
the fences with LF line endings. serialize writes it first, then the body
right after the closing line. A note with no other content exports as the
block alone.
--- for
YAML or +++ for TOML, with optional trailing spaces or tabs. A YAML block
closes on a --- or ... line, a TOML block on a +++ line.# comment must be a setting,
such as title: Hello in YAML, or title = 'Hello' or [params] in TOML.
A note that opens with a rule and plain text keeps them.parse reads front matter. parseSlice, parseInline, paste, and AI
streaming read the same lines as CommonMark.Parse value with a parser for its format. Add a line ending to a non-empty
value first, because the last line of a YAML block scalar keeps its line break
only when one follows:
import { parse as parseToml } from 'smol-toml';
import { parse as parseYaml } from 'yaml';
const frontmatter = getMarkdownFrontmatter(result.document);
const text = frontmatter?.value ? `${frontmatter.value}\n` : '';
const data = frontmatter?.format === 'toml' ? parseToml(text) : parseYaml(text);import { parse as parseToml } from 'smol-toml';
import { parse as parseYaml } from 'yaml';
const frontmatter = getMarkdownFrontmatter(result.document);
const text = frontmatter?.value ? `${frontmatter.value}\n` : '';
const data = frontmatter?.format === 'toml' ? parseToml(text) : parseYaml(text);To change the block, change it on the copy of the document you pass to
serialize. Replacing a live editor's value with new meta resets its caret,
undo history, and local fields. Edit YAML with yaml's parseDocument and
set, which keep the quoting the reader needs, and store the result minus
exactly one final line ending. Never trim it, because a |+ block scalar keeps
its trailing line breaks:
import { getMarkdownFrontmatter } from 'platejs/markdown';
import { parseDocument } from 'yaml';
const document = editor.read.value();
const frontmatter = getMarkdownFrontmatter(document);
if (frontmatter?.format === 'yaml') {
const yaml = parseDocument(frontmatter.value ? `${frontmatter.value}\n` : '');
yaml.set('draft', false);
const text = yaml.toString();
const value = text.endsWith('\n') ? text.slice(0, -1) : text;
const result = editor.api.markdown.serialize({
document: {
...document,
meta: {
...document.meta,
'markdown.frontmatter': { format: 'yaml', value },
},
},
});
}import { getMarkdownFrontmatter } from 'platejs/markdown';
import { parseDocument } from 'yaml';
const document = editor.read.value();
const frontmatter = getMarkdownFrontmatter(document);
if (frontmatter?.format === 'yaml') {
const yaml = parseDocument(frontmatter.value ? `${frontmatter.value}\n` : '');
yaml.set('draft', false);
const text = yaml.toString();
const value
A document replaced with only its children has no meta, so it loses the
block. In a collaborative editor, Yjs does not sync meta, so a peer that did
not import the file exports the note without its front matter.
Two rules around text read as front matter when the first line between them
that is not blank or a comment reads as a YAML setting. That includes a line of
text holding : , such as _Note_: read this, and a line that opens with {.
Export writes those lines back unchanged. A block of only blank lines or
comments reads as CommonMark.
Parse each unfinished stream prefix with partial: true and the previous
result, then parse the complete source strictly with the same hint:
const preview = editor.api.markdown.parseSlice(accumulated, {
lossPolicy: 'allow',
partial: true,
previous,
});
previous = preview.ok ? preview : undefined;
// When the stream finishes or the user stops it:
const result = editor.api.markdown.parseSlice(accumulated, { previous });
previous = undefined;const preview = editor.api.markdown.parseSlice(accumulated, {
lossPolicy: 'allow',
partial: true,
previous,
});
previous = preview.ok ? preview : undefined;
// When the stream finishes or the user stops it:
const result = editor.api.markdown.parseSlice(accumulated, { previous });
previous = undefined;partial: true hides a trailing tag that has not finished arriving, such as
Before <callo, and does not report tags left open at the end of the source.
lossPolicy: 'allow' keeps unsupported content visible as text while the
stream is incomplete. previous must come from the same method of the same
editor. When the source extends the previous result's source and the plugins
and limits are unchanged, blocks it already completed keep their node objects;
any other hint parses the whole source. A parse under another lossPolicy,
such as the strict final parse, keeps only the completed blocks that reported
nothing. A source with a link reference or footnote definition ([id]: url,
[^1]: note) always parses whole, because a definition can change blocks
before it.
A partial parse also shows bold, italic and strikethrough that have not
closed yet, so the preview of Use **bold shows bold in bold. It parses a
closed copy of the unfinished block, with the closers that block needs. The
copy goes through the same plugins and schema, and the preview shows it only
when it keeps every received character. Up to three trailing *, _ or ~
that could still open styling, or one trailing backslash, stay hidden until the
next character arrives. Markers that cannot open styling show as received, such
as the star in 2*3 and the underscore in foo_bar. The parse makes no closed
copy when the unfinished block holds more than 2,000 characters, or when the
source has a link reference or footnote definition or starts with a byte order
mark. Styling that opened more than 1,000 characters back gets no closer
either. Such a block shows its markers until they close. Code spans, links,
images, math and block syntax such as table rows show as received until they
finish, and so does styling inside link text or after an unclosed backtick.
A partial parse converts only the text after the kept blocks. Each kept block
came from a parse of its own part of the source, so a remark plugin that reads
the whole tree, such as one that numbers or joins blocks, can make a preview
differ from a fresh parse. A parse without partial converts the whole source
once. When the kept blocks match the start of that conversion apart from list
ids, the result holds the kept blocks and the rest of the conversion; otherwise
the result is the conversion. Whatever remark plugins run, the final result
matches a fresh parse apart from list ids.
Render a read-only preview as a document of the parsed blocks; the editor supplies the plugins and is not edited:
<EditorStatic editor={editor} document={{ children: nodes }} /><EditorStatic editor={editor} document={{ children: nodes }} />To show the stream in an editable editor instead, publish each result outside the undo history. Replace only the blocks after the first one that changed, or the whole value when no leading block is unchanged:
let start = 0;
while (start < nodes.length && published[start] === nodes[start]) start += 1;
if (start === 0) {
editor.update({ history: 'skip' }).value.replace({ children: nodes });
} else {
editor.update({ history: 'skip' }, (tx) => {
tx.nodes.replaceChildren(nodes.slice(start), { at: [], index: start });
});
}
published = nodes;let start = 0;
while (start < nodes.length && published[start] === nodes[start]) start += 1;
if (start === 0) {
editor.update({ history: 'skip' }).value.replace({ children: nodes });
} else {
editor.update({ history: 'skip' }, (tx) => {
tx.nodes.replaceChildren(nodes.slice(start), { at: [], index: start });
});
}
published = nodes;An editor with authored changes records every node write as an authored change, so an editable preview with authored changes always replaces the value.
The consumer owns the source, the abort signal, the hint and the preview cadence:
previous. Drop it when the stream
finishes, is cancelled or replaced, or unmounts.partial, continuing the latest preview. A failed final parse clears
the preview.AI chat previews follow the same rules; see AI streaming.
Markdown has no list identity, so each parse gives every Markdown list a new
listId. Two parses of one source are equal up to their list ids. A parse that
continues a previous result keeps the ids of the blocks it reuses, and a list
it converts again gets new ids. To compare parses, rename each listId in
order of first appearance. See List for how
Plate reads and writes lists.
Markdown represents visible accepted or proposed content. It does not append
a hidden Plate document and cannot restore exact review state.
const proposed = editor.api.markdown.serialize({ projection: 'proposed' });
const accepted = editor.api.markdown.serialize({ projection: 'accepted' });const proposed = editor.api.markdown.serialize({ projection: 'proposed' });
const accepted = editor.api.markdown.serialize({ projection: 'accepted' });Use authored JSON for exact proposals, decisions, roots, and metadata. Use DOCX review export for Word revisions. See Authored Changes.
Declare mappings on the plugin that owns the node or mark. Most mappings are declarations: Plate builds the node, converts its properties, and reads and writes its children from the plugin's schema.
import { definePlugin, property, schema } from 'platejs';
const CalloutPlugin = definePlugin('callout', {
schema: {
element: schema.element.textBlock({
properties: { tone: property.string() },
}),
},
formats: ({ defineFormats, schema: { type } }) =>
defineFormats({ markdown: { tag: type } }),
});import { definePlugin, property, schema } from 'platejs';
const CalloutPlugin = definePlugin('callout', {
schema: {
element: schema.element.textBlock({
properties: { tone: property.string() },
}),
},
formats: ({ defineFormats, schema: { type } }) =>
defineFormats({ markdown: { tag: type } }),
});This mapping reads and writes <callout tone="info">Text</callout>.
tag registers a Plate tag. For an element, use its schema type, so an
application that renames the type also renames the tag.textAlign, by key. List properties never become attributes, because the
Markdown list around the element carries them. A property with a default
that is not omitted is filled in when its attribute is absent.attributes renames the plugin's own properties on the wire:markdown: { tag: type, attributes: { url: 'src' } }markdown: { tag: type, attributes: { url: 'src' } }markdown-property-omitted warning. When a required value is invalid, such
as an unsafe src, the element is removed and its content kept. A script
URL reports a lossless markdown-unsafe-content warning instead.A plugin whose schema declares a mark maps a mark. Its declarations name
where the mark comes from and how it is written:
// A standard Markdown container.
markdown: { node: 'strong' }
// A tag: `<kbd>` reads as `true` and a `true` mark writes `<kbd>`.
markdown: { tag: 'kbd' }
// One tag per value of an enum mark.
markdown: [
{ tag: 'sub', value: 'sub' },
{ tag: 'sup', value: 'sup' },
]
// A CSS-valued mark: `<span style="color: red;">` reads as `'red'`.
markdown: { tag: 'span', style: 'color' }// A standard Markdown container.
markdown: { node: 'strong' }
// A tag: `<kbd>` reads as `true` and a `true` mark writes `<kbd>`.
markdown: { tag: 'kbd' }
// One tag per value of an enum mark.
markdown: [
{ tag: 'sub', value: 'sub' },
{ tag: 'sup', value: 'sup' },
]
// A CSS-valued mark: `<span style="color: red;">` reads as `'red'`.
markdown: { tag: 'span', style: 'color' }node accepts 'strong', 'emphasis', 'delete', and 'inlineCode'.value matches, so a
later declaration for the same value only reads, as <del> does next to
{ node: 'delete' }.<span style="color: red; background-color: yellow;"> sets both marks. A
tag no mark mapping reads keeps its source text.markdown-property-omitted warning.Use decode and encode for a real format difference. Image chooses between
, <img>, and <figure>; Date writes a value it cannot normalize
as text.
markdown: {
node: 'heading',
decode: ({ decode, marks, node }) => ({
children: decode(node.children, marks),
level: node.depth,
type,
}),
encode: ({ encodePhrasing, node, preserve }) => {
preserve('level');
return {
children: encodePhrasing(node.children),
depth: node.level,
type: 'heading',
};
},
}markdown: {
node: 'heading',
decode: ({ decode, marks, node }) => ({
children: decode(node.children, marks),
level: node.depth,
type,
}),
encode: ({ encodePhrasing, node, preserve }) => {
preserve('level');
return {
children: encodePhrasing(node.children),
depth: node.level,
type: 'heading',
};
},
}node selects a standard Markdown node kind, such as 'blockquote',
'link', or 'image'. Select one of node or tag. nestedTags names
tags read only inside this tag, such as Image's figcaption.undefined from decode declines the node; the next mapping for
the same source runs, in descending priority order. Mention decodes
mention: links this way before Link.marks contains the inherited persisted text marks. Pass it to decode or
decodeNodes when nested content must keep those marks.previousSibling is the Markdown node before this one. Lists use it to read
a list right after another as restarted numbering.readTagAttributes(tag?) returns { attributes, properties }: every
attribute as written, and the node's properties decoded as a declared tag
decodes them.refuse(message) reports content the feature cannot represent as
markdown-unsupported-node. A refused tag keeps its source text.report({ action, kind, message, nodeType }) reports a loss the mapping
handled itself. kind: 'property' marks a loss that keeps the content, such
as a link destination the editor does not allow; it warns under every
policy. The default kind: 'element' follows the loss policy.decode, report({ key, message }) reports a property that the mapping
left off the node it built, such as indent on a block the schema cannot
indent. The report is markdown-property-omitted with that key, and it
warns under every policy. An encoder does not report a property it leaves
out, because serialization reports every property the encoder does not
claim.caption(children) returns inline content when children is one paragraph,
and null otherwise.preserve(...keys) claims that the returned output carries these properties
of the plugin. Every other content property on the node is reported as
markdown-property-omitted. Claims count only when encode returns output.encodeNodeAttributes() writes the node's attributes as a declared tag does
and claims them. encodeAttributes(properties) writes the given property
values and claims each property whose attribute the returned output keeps.encodeLine(children) writes block children on one line, as Plate writes a
table cell. encodePhrasing(children) writes inline
children. decodeLine(children, marks?) reads that line back into blocks.Pass an array to declare several mappings for one plugin. Use
defineFormats(map) for self mappings and defineFormats(TargetPlugin, map)
for a foreign target. A plugin's formats accept only the html, markdown,
and plainText keys; MIME payloads belong in dataTransferFormats.
An element that owns a content root writes that
root's blocks through contentRoot(slot). It returns the blocks of the root
that slot names on the node, in stored order. encode may return an array of
Markdown nodes, which are written as siblings in the element's place.
import { definePlugin, schema } from 'platejs';
const AsidePlugin = definePlugin('aside', {
schema: {
element: {
contentRoots: {
body: {
content: schema.content.type('paragraph', {
default: { type: 'paragraph' },
min: 1,
}),
ownership: 'exclusive',
},
},
void: 'block',
},
},
formats: ({ defineFormats }) =>
defineFormats({
markdown: {
encode: ({ contentRoot, encode }) => encode(contentRoot('body')),
},
}),
});import { definePlugin, schema } from 'platejs';
const AsidePlugin = definePlugin('aside', {
schema: {
element: {
contentRoots: {
body: {
content: schema.content.type('paragraph', {
default: { type: 'paragraph' },
min: 1,
}),
ownership: 'exclusive',
},
},
void: 'block',
},
},
formats: ({ defineFormats }) =>
defineFormats({
markdown: {
Markdown has no syntax for a separate root, so parsing this output reads the
blocks as ordinary blocks of the document. Serialization reports each named
root that no mapping reads through contentRoot as
markdown-unsupported-root. Reading a slot the node does not own throws.
Configure remark plugins once on MarkdownPlugin. Every parse and serialize
operation of that editor uses them. MarkdownKit enables GFM, math, emoji,
and CJK emphasis:
import { MarkdownPlugin, RawHtmlPlugin } from 'platejs/markdown';
import remarkCjkFriendlyGfmStrikethrough from 'remark-cjk-friendly-gfm-strikethrough/bidi';
import remarkCjkFriendly from 'remark-cjk-friendly/bidi';
import remarkEmoji from 'remark-emoji';
import remarkGfm from 'remark-gfm';
import remarkMath from 'remark-math';
export const MarkdownKit = [
MarkdownPlugin.configure({
initialState: {
remarkPlugins: [
remarkMath,
remarkGfm,
remarkCjkFriendly,
remarkCjkFriendlyGfmStrikethrough,
remarkEmoji,
],
},
}),
RawHtmlPlugin,
];import { MarkdownPlugin, RawHtmlPlugin } from 'platejs/markdown';
import remarkCjkFriendlyGfmStrikethrough from 'remark-cjk-friendly-gfm-strikethrough/bidi';
import remarkCjkFriendly from 'remark-cjk-friendly/bidi';
import remarkEmoji from 'remark-emoji';
import remarkGfm from 'remark-gfm';
import remarkMath from 'remark-math';
export const MarkdownKit = [
MarkdownPlugin.configure({
initialState: {
remarkPlugins: [
remarkMath,
remarkGfm,
remarkCjkFriendly,
remarkCjkFriendlyGfmStrikethrough,
remarkEmoji,
],
import { MarkdownPlugin } from 'platejs/markdown';
import remarkGfm from 'remark-gfm';
const plugins = [
...BasicBlocksKit,
MarkdownPlugin.configure({
initialState: { remarkPlugins: [remarkGfm] },
}),
];import { MarkdownPlugin } from 'platejs/markdown';
import remarkGfm from 'remark-gfm';
const plugins = [
...BasicBlocksKit,
MarkdownPlugin.configure({
initialState: { remarkPlugins: [remarkGfm] },
}),
];Standalone functions read the configured MarkdownPlugin from plugins.
Remark plugins must be synchronous. An attacher or transformer that returns a
Promise is a configuration error and throws. The synchronous functions never
return Result | Promise<Result>. Remark plugins must also keep no state
between parses, because a partial parse runs them on the closed copy of an
unfinished block as well as on the received text. See
Streaming previews.
Files need no remark-frontmatter for their front matter.
When the list still holds it, it reads every slice and every block Plate's
reader refuses. Unless a mapping decodes the yaml or toml node it makes,
that node is a lossy markdown-unsupported-node, which fails the parse under
the default policy. A streaming preview that continues
its previous result reads the whole source again while the plugin adds front
matter syntax, as it does with its default options, so it matches a fresh parse
of the same text.
CommonMark leaves ** literal when punctuation ends the bold text and a letter
follows, so 这是**重点。**然后继续 stays plain text. remark-cjk-friendly
and remark-cjk-friendly-gfm-strikethrough read bold, strikethrough, and *
italic that end in Chinese, Japanese, or Korean punctuation as marks. They read
a source without CJK characters as CommonMark does. MarkdownKit installs
both. A custom plugin list adds them after remarkGfm:
import { MarkdownPlugin } from 'platejs/markdown';
import remarkCjkFriendlyGfmStrikethrough from 'remark-cjk-friendly-gfm-strikethrough/bidi';
import remarkCjkFriendly from 'remark-cjk-friendly/bidi';
import remarkGfm from 'remark-gfm';
MarkdownPlugin.configure({
initialState: {
remarkPlugins: [
remarkGfm,
remarkCjkFriendly,
remarkCjkFriendlyGfmStrikethrough,
],
},
});import { MarkdownPlugin } from 'platejs/markdown';
import remarkCjkFriendlyGfmStrikethrough from 'remark-cjk-friendly-gfm-strikethrough/bidi';
import remarkCjkFriendly from 'remark-cjk-friendly/bidi';
import remarkGfm from 'remark-gfm';
MarkdownPlugin.configure({
initialState: {
remarkPlugins: [
remarkGfm,
remarkCjkFriendly,
remarkCjkFriendlyGfmStrikethrough,
],
},
});Serialize runs the same plugins, so it writes bold and strikethrough next to CJK
text with plain ** and ~~. That needs mdast-util-to-markdown 2.1.3 or
later. _ keeps CommonMark's rule, and Plate writes italic with _, so it
writes italic next to CJK letters with character references, such as
这是_斜体。_文字.
Parse success contains warnings and exactly one carrier. Failure contains a
nonempty error-first diagnostic tuple and no carrier. Serialization follows the
same rule for data.
if (!result.ok) {
reportImportFailure(result.diagnostics);
return;
}
useDocument(result.document);
reportWarnings(result.diagnostics);if (!result.ok) {
reportImportFailure(result.diagnostics);
return;
}
useDocument(result.document);
reportWarnings(result.diagnostics);| Code | Severity | Reports |
|---|---|---|
markdown-unsupported-node | Warning when lossless or when the content stays; other lossy follows lossPolicy | Content no mapping accepts, refused content, or nodes dropped on export (lossy), such as a table when no remark plugin, like remark-gfm, writes tables. Raw HTML kept as text, HTML comments and removed <block> wrappers are lossless. A table cell's folded paragraph boundary or collapsed block keeps its content and warns. |
markdown-unsafe-content | Warning when lossless; lossy follows lossPolicy | A removed link or image destination, or marked raw HTML whose block fails the raw HTML check on export. |
markdown-tag-repair | Warning | An unclosed, unmatched, or misplaced registered tag. |
markdown-property-omitted | Warning | A property or mark Markdown cannot carry on export, such as a paragraph's textAlign, or an invalid tag attribute value on import. |
markdown-limit-exceeded | Error | Source bytes, node count, or depth above limits. |
markdown-inline-blocks | Error | parseInline input that produced blocks. |
markdown-schema-repair | Warning; error when lossy under 'reject' | A schema repair applied to the parsed document. |
markdown-schema-invalid | Error | Parsed content the schema rejects. |
markdown-unsupported-root, markdown-unsupported-metadata | Warning | A named root that no mapping read through contentRoot, or document metadata other than front matter, omitted on export. |
markdown-frontmatter-omitted | Lossy: error under 'reject', warning under 'allow' | Stored front matter that export cannot write back. Its reason is shape for a value that is not { format, value } strings, format for a format other than yaml or toml, or unreadable for a value that holds a CR, is not well-formed Unicode, or would not read back the same. Under the default policy the export fails; lossPolicy: 'allow' exports the file without the block. |
Authored projection diagnostics use the same result. Configuration failures and mapping contract violations throw.
The defaults are 5 MiB of UTF-8 source, 100,000 mdast nodes, and depth 256. Markdown checks bytes before parsing and applies node/depth admission after the parser returns because mdast does not expose a bounded construction hook.
| API | Result |
|---|---|
parseMarkdown(source, options) | Complete EditorDocumentValue. |
serializeMarkdown(document, options) | Markdown string in data. |
editor.api.markdown.parse(source, options?) | Complete document using the installed target. |
editor.api.markdown.parseSlice(source, options?) | Closed, rootless block ContentSlice. |
editor.api.markdown.parseInline(source, options?) | Closed, rootless inline ContentSlice. |
editor.api.markdown.serialize(options?) | Current or supplied document using the installed target. |
Import MarkdownPlugin, RawHtmlPlugin, the standalone functions, and their
result, diagnostic, and option types from platejs/markdown.
| Parse option | Use |
|---|---|
limits | Override maxBytes, maxNodes, or maxDepth. |
lossPolicy | 'reject' (default) or 'allow'. |
partial | Parse an unfinished stream prefix for a preview. |
previous | editor.api.markdown.parseSlice only: the previous result of a growing source to continue. |
| Serialize option | Use |
|---|---|
document | Editor method only: the document to serialize, typed as the editor's value. Defaults to the current value. |
lossPolicy | 'reject' (default) or 'allow'. |
plainMarks | Mark keys written as plain text without Markdown formatting. Defaults to MarkdownPlugin's plainMarks. |
preserveEmptyParagraphs | Keep empty paragraphs. Defaults to true. |
projection | 'accepted' or 'proposed'. Required when the document has pending suggestions. |
remarkStringifyOptions | Options passed to remark-stringify. |
spread | Write loose lists. Defaults to false. |
Standalone functions also require plugins and accept schema. Installed
editor methods omit both because the plugin captures them from the editor.
MarkdownPlugin state holds remarkPlugins, remarkStringifyOptions, and
plainMarks. When its plainMarks names rawHtml, import gives raw HTML no
mark.