Skip to article frontmatterSkip to article content

Generate MyST AST in plugins

A common usecase with plugins involves generating MyST AST and inserting it into the document. This page covers a few ways that you can do so.

Parse MyST markdown to AST in a directive or role

The easiest way to generate MyST AST in a plugin is by using the parseMyst function in the ctx variable. It may be easier to parse MyST Markdown into AST nodes rather than using the MyST sandbox to preview them.

Here’s an example of using the parseMyst function within a directive plugin to parse the argument of the directive into MyST AST:

src/myplugin.mjs
const myDirective = {
  name: "mydirective",
  doc: "My new directive!",
  arg: { type: String, doc: "To be parsed into MyST AST." },
  run(data, vfile, ctx) {
    const ast = ctx.parseMyst(data.arg);
    return ast.children[0];
  },
};

ctx.parseMyst returns a root node, which contains the parsed MyST. This function takes the first child of the root node, which is usually better for inserting into the document.

You can also use this to manually construct MyST outputs using the arguments of your directive as data. For example:

src/justacard.mjs
const myDirective = {
  name: "justacard",
  doc: "Basically does what a card directive does!",
  arg: { type: String, doc: "To be parsed into MyST AST." },
  body: { type: String, doc: "The body of the directive." },
  run(data, vfile, ctx) {
    const ast = ctx.parseMyst(`:::{card} ${data.arg}\n${data.body}\n:::`);
    return ast.children[0];
  },
};

Use the MyST Sandbox to identify card AST structure

The MyST interactive sandbox is a great way to explore what MyST looks like when it is rendered, and what its underlying AST structure looks like.

This is particularly useful if you’re generating MyST AST from scratch. For example, as part of a plugin role or directive.

For example, here’s a video that shows how to use the MyST sandbox to explore the structure of a {card} directive.

Using the MyST sandbox to preview and show the AST of the {card} directive.