markdown-to-djot-ast
v0.0.8
Published
A lightweight Javascript/Typescript library to convert Markdown content into a djot.js AST
Downloads
42
Maintainers
Readme
markdown-to-djot-ast
markdown-to-djot-ast is a lightweight Javascript/Typescript library to convert Markdown content into a djot.js AST.
This is useful for supporting Djot and Markdown files, offering consistent filtering and rendering processes across formats.
The library leverages the famous markdown-it package to parse Markdown content to tokens. The tokens are subsequently transformed into a Djot.js AST.
Install
npm install markdown-to-djot-ast
Use
import { readFileSync } from "fs";
import * as path from "path";
import markdownit from "markdown-it";
import { parseMarkdown } from "markdown-to-djot-ast";
import { parse as parseDjot, renderAST } from "@djot/djot";
const md = markdownit();
const input = readFileSync(filename, "utf8");
// Parse `*.md` files with markdown-it and `*.dj` files with djot.js:
const doc =
path.extname(filename) === ".md"
? parseMarkdown(md, input, { sourcePositions: true })
: parseDjot(input, { sourcePositions: true });
// Process Markdown and Djot in the same way, f.ex:
console.log(renderAST(doc));
Supported markdown-it plugins
- markdown-it-sub
- markdown-it-sup
- markdown-it-mark
- markdown-it-ins
- @mdit/plugin-alert
- Math Plugins (
math_inline
,math_block
)
Custom token handler
You can provide a token handler to parseMarkdown
to support custom markdown-it plugins.
parseMarkdown(md, input, {
tokenHandlers: { mytoken_open: (token) => ({ tag: "div", children: [] }) },
});
Handling of unsupported tokens
Unknown tokens will be converted into a Div
Djot node with a warning:
// Print all warnings to the console
parseMarkdown(md, input, {
warn: console.warn,
});