# Markdown Extensions

Add Markdown syntax from a plugin.

A plugin adds syntax to every page with [markdown-it](https://github.com/markdown-it/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](/markdown#markdown-it-plugins) shows.

## Adding Syntax [#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:

```ts title="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], // [!code highlight]
        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
npm i -D markdown-it@15
```

## Writing Rules [#writing-rules]

A [core rule](https://github.com/markdown-it/markdown-it/blob/master/docs/architecture.md) of markdown-it changes `state.tokens`, the tokens of a page, with the helpers of `vuesho/markdown`.

### Inserting Components [#inserting-components]

`createVueElement()` creates a token for a Vue element or for a [component](/markdown/components) 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:

```ts title="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]));
    }
  });
}
```

```ts title="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](/ai#markdown-version) 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 [#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:

```ts
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:

```ts title="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); // [!code highlight]
      return [
        createVueElement(state, "component", { ":is": component }, 1, token),
        createVueElement(state, "component", {}, -1, token),
      ];
    });
  });
}
```

### Creating Code Tabs [#creating-code-tabs]

`generateCodeBlockTabs()` returns the tokens for a set of [code tabs](/markdown#code-tabs), which a rule puts in place of a token:

```ts title="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.

### CodeBlockTabsOptions

| Prop            | Type                                | Description                                                                                                          |
| --------------- | ----------------------------------- | -------------------------------------------------------------------------------------------------------------------- |
| `tabs`          | `CodeBlockTab[]`                    | The tabs to render, each with its value, an optional label, and markdown-it tokens.                                  |
| `defaultValue?` | `string \| undefined`               | The tab open first. Default: `the first tab`                                                                         |
| `persist?`      | `false \| TabsPersist \| undefined` | Keeps the selected tab in sync across blocks with the same group ID, or `false` to turn it off.                      |
| `markdown?`     | `string \| undefined`               | The tabs in the Markdown of the page, like the code block they are made from. Default: `the code blocks of the tabs` |

### Rule Order [#rule-order]

[`<include>`](/markdown#includes) runs right after the `inline` rule, and heading IDs are set right after that. The tokens a rule receives depend on where it registers:

```ts
// 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 [#watching-files]

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

```ts
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); // [!code highlight]
const data = JSON.parse(readFileSync(file, "utf8"));
```

### Reporting Problems [#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:

```ts
import { diagnose } from "vuesho/markdown";

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

## Setting Markdown and Search Text [#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:

```ts
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](/routing#path-params), the Markdown can mix text and expressions:

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

## Computing Page Data [#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:

```ts title="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); // [!code highlight]
  });
}

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"], // [!code highlight]
  };
}
```

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

<Callout type="warn" title="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`](/content-hooks#page-data).
</Callout>

## Built-in Rules [#built-in-rules]

### Numbering Headings [#numbering-headings]

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

```ts title="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"); // [!code highlight]
    }
  });
}
```

To show the numbers, replace the layout's `toc` part with a component that renders them, as [Replacing a Part](/theme#replacing-a-part) shows.

### Block IDs [#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](/plugins/feedback). The `id` is a hash of the block's text. `blockId` skips content inside components:

```ts title="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" }]] }),
  };
}
```

```html
<p id="xswgmdo9oeujrejlt0siwu4dq4k5joxgoaehyanigwa" data-block="acme">A paragraph of the page.</p>
```

### BlockIdOptions

| Prop                | Type                                                                | Description                                                                                          |
| ------------------- | ------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- |
| `generateId?`       | `((block: { token: Token; text: string; }) => string) \| undefined` | A block's ID from its text, which is then slugified and made unique. Default: `a sha256 of the text` |
| `shouldGenerate?`   | `((token: Token) => boolean \| "skip") \| undefined`                | `true` gives a token an ID, `false` looks inside it, and `"skip"` skips it and its content.          |
| `addDataAttribute?` | `string \| null \| undefined`                                       | The value of `data-block`, or `null` for none. Default: `"default"`                                  |
