mdast-util-toc: Markdown Table of Contents Utility

7.1.0 · active · verified Sun Apr 19

mdast-util-toc is a utility within the unified (specifically mdast) ecosystem for programmatically generating a table of contents from a markdown abstract syntax tree (AST). It provides a `toc` function that processes an `mdast` tree, identifying headings and constructing a new `mdast` list node representing the table of contents. The package is currently stable at version 7.1.0, with minor and patch releases occurring periodically, and major versions introducing breaking changes like ESM-only support or Node.js version bumps. Key differentiators include its tight integration with the `mdast` AST format, allowing for flexible programmatic manipulation, and its robust options for controlling the TOC generation, such as specifying heading depth (`minDepth`, `maxDepth`), skipping specific headings, and defining parent node types. It's often used indirectly via `remark-toc` for simpler integration into `remark` pipelines, which handles the injection of the generated TOC back into the document. Its focus is purely on AST transformation, making it highly composable.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates how to import the `toc` function and use it to generate a table of contents from a simple mdast syntax tree, configured to include headings up to depth 2.

import {toc} from 'mdast-util-toc';

/** @type {import('mdast').Root} */
const tree = {
  type: 'root',
  children: [
    {type: 'heading', depth: 1, children: [{type: 'text', value: 'Alpha'}]},
    {type: 'heading', depth: 2, children: [{type: 'text', value: 'Bravo'}]},
    {type: 'heading', depth: 3, children: [{type: 'text', value: 'Charlie'}]},
    {type: 'heading', depth: 2, children: [{type: 'text', value: 'Delta'}]},
    {type: 'paragraph', children: [{type: 'text', value: 'Some content here.'}]},
    {type: 'heading', depth: 1, children: [{type: 'text', value: 'Gamma'}]}
  ]
};

// Generate a table of contents for the entire tree
const table = toc(tree, { maxDepth: 2 });

console.dir(table, {depth: 3});

/* Expected Output (simplified):
{
  index: undefined,
  endIndex: undefined,
  map: {
    type: 'list',
    ordered: false,
    spread: true,
    children: [
      { type: 'listItem', spread: true, children: [ [Object] ] }, // Alpha
      { type: 'listItem', spread: true, children: [ [Object], [Object] ] } // Gamma
    ]
  }
}
*/

view raw JSON →