Skip to Content
Vuesho

Markdown Extensions

Add Markdown syntax from a plugin.

A plugin adds syntax to every page with markdown-it plugins, and changes code blocks with Shiki transformers. A single site can do the same with the config's markdown option, as markdown-it Plugins shows.

Adding Syntax

markdown is a function that returns the extensions. It runs once, without the site context, so an import inside it loads only for a site that adds the plugin:

emoji-plugin.ts
import type { AppShape, Plugin } from "vuesho/config";

export function emojiPlugin<C extends AppShape>(): Plugin<C> {
  return {
    name: "acme:emoji",
    async markdown() {
      const { full } = await import("markdown-it-emoji");
      return {
        markdownItPlugins: [full], 
        highlight: { transformers: [] }, // Shiki transformers for every code block.
      };
    },
  };
}

Plugins' extensions run in plugin order, before the markdown options of the page's collection, or the config's when the collection has none.

markdown-it 15 ships its own types, so install it instead of @types/markdown-it, which describes version 14:

npm i -D markdown-it@15

Writing Rules

A core rule of markdown-it changes state.tokens, the tokens of a page, with the helpers of vuesho/markdown.

Inserting Components

createVueElement() creates a token for a Vue element or for a component that pages use without an import. Pass 1 to open the element and -1 to close it. The last argument is the token the element comes from, which gives errors their line:

quote-cards.ts
import type { MarkdownIt } from "markdown-it";
import { createVueElement } from "vuesho/markdown";

// Renders each blockquote in a <Card>.
export function quoteCards(md: MarkdownIt) {
  md.core.ruler.push("quote_cards", (state) => {
    const tokens = state.tokens;
    for (let i = tokens.length - 1; i >= 0; i--) {
      if (tokens[i].type !== "blockquote_open") continue;
      let end = i;
      while (tokens[end].type !== "blockquote_close" || tokens[end].level !== tokens[i].level)
        end++;
      tokens.splice(end + 1, 0, createVueElement(state, "Card", {}, -1, tokens[i]));
      tokens.splice(i, 0, createVueElement(state, "Card", { title: "Quote" }, 1, tokens[i]));
    }
  });
}
quotes-plugin.ts
import type { AppShape, Plugin } from "vuesho/config";
import { quoteCards } from "./quote-cards";

export function quotesPlugin<C extends AppShape>(): Plugin<C> {
  return {
    name: "acme:quotes",
    markdown: () => ({ markdownItPlugins: [quoteCards] }),
  };
}

A page's Markdown, which LLMs read, is written from what the page renders, without the elements that rules add. state.env.file is the path of the file being parsed: the page, or a file it includes.

Replacing Tags

Each tag in a page is a token, with the tag name in token.info and its source in token.content. readTagAttributes() reads the attributes:

import { readTagAttributes } from "vuesho/markdown";

// `<Card>` and `</Card>`, each on its own line: `vue_open` and `vue_close`.
// `<Badge />` or a comment on its own line: `vue_tag`.
// A tag inside a paragraph: `html_inline`, a child of the `inline` token.

// For `<Video title="Tom &amp; Jerry" :autoplay="false" muted />`:
readTagAttributes(token);
// [{ name: "title", value: "Tom & Jerry" },
//  { name: ":autoplay", value: "false" },
//  { name: "muted", value: null }]

replaceElements() replaces every element that has a given name, or any name in a set, with the tokens its callback returns. When the callback returns undefined, the element stays. importBinding() imports a relative file or a package into the page, and returns the variable the template uses for it:

demos.ts
import type { MarkdownIt } from "markdown-it";
import {
  importBinding,
  replaceElements,
  readTagAttributes,
  createVueElement,
} from "vuesho/markdown";

// `<demo src="./counter.vue" />` renders the file's component.
export function demos(md: MarkdownIt) {
  md.core.ruler.push("demos", (state) => {
    state.tokens = replaceElements(state.tokens, "demo", (token) => {
      const src = readTagAttributes(token)?.find((attribute) => attribute.name === "src")?.value;
      if (!src) return;
      const component = importBinding(state, token, src); 
      return [
        createVueElement(state, "component", { ":is": component }, 1, token),
        createVueElement(state, "component", {}, -1, token),
      ];
    });
  });
}

Creating Code Tabs

generateCodeBlockTabs() returns the tokens for a set of code tabs, which a rule puts in place of a token:

shells.ts
import type { MarkdownIt } from "markdown-it";
import { generateCodeBlockTabs } from "vuesho/markdown";

// A `sh` block becomes tabs for macOS and Windows.
export function shells(md: MarkdownIt) {
  md.core.ruler.push("shells", (state) => {
    state.tokens = state.tokens.flatMap((token) => {
      if (token.type !== "fence" || token.info !== "sh") return [token];
      const block = (content: string) =>
        Object.assign(new state.Token("fence", "code", 0), { info: "sh", content, map: token.map });
      return generateCodeBlockTabs(state, token, {
        tabs: [
          { value: "macOS", tokens: [block(token.content)] },
          { value: "Windows", tokens: [block(token.content.replaceAll("/", "\\"))] },
        ],
        persist: { id: "os" },
      });
    });
  });
}

markdown keeps the source block in the page's Markdown instead of the tabs.

Prop

Type

Rule Order

<include> runs right after the inline rule, and heading IDs are set right after that. The tokens a rule receives depend on where it registers:

// Runs on the page and on each included file separately, where `env.file` is that file.
// It runs before heading IDs are set, so it can remove a tag from a heading's text.
md.core.ruler.after("inline", "my_rule", rule);

// Runs once, on the whole page with its included files.
md.core.ruler.push("my_rule", rule);

Watching Files

A rule that reads another file adds it to env.dependencies, so the dev server recompiles the page when that file changes:

import { readFileSync } from "node:fs";
import path from "node:path";
import type { MarkdownEnv } from "vuesho/markdown";

const env = state.env as MarkdownEnv;
const file = path.resolve(path.dirname(env.file), "data.json");
env.dependencies.push(file); 
const data = JSON.parse(readFileSync(file, "utf8"));

Reporting Problems

diagnose() reports a problem, with a code and a message, at a token's line. It works in included files too. The build then lists every problem on the site together:

import { diagnose } from "vuesho/markdown";

if (!src) {
  diagnose(state, token, "E-DEMO-SRC", "`<demo>` needs a `src`.");
  return;
}

Setting Markdown and Search Text

By default, the content inside an element from a rule stays in the page's Markdown and in search as the page renders it. createVueElement()'s last argument replaces the element in the Markdown and leaves its content out of search. getStructuredData() returns a token's search records, which replace those of the token and its content:

import { getStructuredData, createVueElement } from "vuesho/markdown";

const open = createVueElement(state, "TypeTable", attributes, 1, token, {
  markdown: "| Prop | Type |\n| --- | --- |\n| size | `number` |",
});

getStructuredData(open).push({
  heading: "type-table-size",
  content: "| size | `number` |",
  table: "type-table",
});

getStructuredData() works on any token, like a code block. On a page with path params, the Markdown can mix text and expressions:

createVueElement(state, "Install", {}, 1, token, {
  markdown: ["Run `npm create ", { expression: "framework" }, "-app`."],
});

Computing Page Data

A rule writes JSON values to env.pageData while the page compiles. The plugin lists their keys in pageData and declares their types:

reading-time-plugin.ts
import type { MarkdownIt } from "markdown-it";
import type { AppShape, Plugin } from "vuesho/config";
import type { MarkdownEnv } from "vuesho/markdown";

function readingTime(md: MarkdownIt) {
  md.core.ruler.push("reading_time", (state) => {
    const words = state.tokens
      .filter((token) => token.type === "inline")
      .reduce((count, token) => count + token.content.split(/\s+/).length, 0);
    (state.env as MarkdownEnv).pageData.readingTime = Math.ceil(words / 200); 
  });
}

export function readingTimePlugin<C extends AppShape>(): Plugin<
  C,
  { pageData: { /** Reading time in minutes. */ readingTime?: number } }
> {
  return {
    name: "acme:reading-time",
    markdown: () => ({ markdownItPlugins: [readingTime] }),
    pageData: ["readingTime"], 
  };
}

The fields reach usePage().value.pageData, this.getPageData() and transformPage, and override defaults like description.

Every Page Compiles

With pageData, a hook that reads every page's page data, like the sitemap's, compiles every Markdown page. A value that doesn't need the tokens is cheaper to compute in transformPage.

Built-in Rules

Numbering Headings

numberInToc() numbers entries in the table of contents. A heading left out of the table of contents still counts:

figures.ts
import type { MarkdownIt } from "markdown-it";
import { numberInToc } from "vuesho/markdown";

// `## Setup [figure]` has the id `setup`, and the entry { title: "Setup", url: "#setup", depth: 2, figure: 1 }.
export function figures(md: MarkdownIt) {
  md.core.ruler.after("inline", "figures", (state) => {
    for (const [i, token] of state.tokens.entries()) {
      const text = token.type === "heading_open" && state.tokens[i + 1].children?.at(-1);
      if (!text || !text.content.endsWith(" [figure]")) continue;
      text.content = text.content.slice(0, -" [figure]".length);
      numberInToc(token, "figure", "figures"); 
    }
  });
}

To show the numbers, replace the layout's toc part with a component that renders them, as Replacing a Part shows.

Block IDs

blockId adds an id and a data-block attribute to each paragraph and list item, for a feature that targets one block, like feedback. The id is a hash of the block's text. blockId skips content inside components:

block-plugin.ts
import type { AppShape, Plugin } from "vuesho/config";
import { blockId } from "vuesho/markdown";

export function blockPlugin<C extends AppShape>(): Plugin<C> {
  return {
    name: "acme:blocks",
    markdown: () => ({ markdownItPlugins: [[blockId, { addDataAttribute: "acme" }]] }),
  };
}
<p id="xswgmdo9oeujrejlt0siwu4dq4k5joxgoaehyanigwa" data-block="acme">A paragraph of the page.</p>

Prop

Type