MDAST Heading Range Utility

4.0.0 · active · verified Sun Apr 19

mdast-util-heading-range is a utility for working with Markdown Abstract Syntax Trees (MDAST) to identify and manipulate content sections defined by headings. It allows developers to find a specific heading, capture all content nodes within its section (up to the next heading of the same or lower depth, or the end of the document), and then apply a handler function to modify or replace that content. The current stable version is 4.0.0, released in a mostly ad-hoc fashion following the syntax-tree ecosystem's release schedule, typically with minor versions for features and patch versions for fixes. Key differentiators include its focus on heading-based content segmentation, offering a programmatic way to update generated sections (like a Table of Contents), and its integration within the broader `unified` and `remark` ecosystem. It is an ESM-only package since version 3.0.0 and requires Node.js 16 or higher as of version 4.0.0.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates finding the 'Foo' heading section and replacing its content with new nodes using the `headingRange` utility.

import {read} from 'to-vfile';
import {remark} from 'remark';
import {headingRange} from 'mdast-util-heading-range';

const markdownContent = `# Foo\n\nBar.\n\n# Baz\n\nOther content.\n\n## Sub Heading\n\nSub content.`;

async function processMarkdown() {
  const file = await remark()
    .use(myPluginThatReplacesFoo)
    .process(String(markdownContent));

  console.log(String(file));
}

/** @type {import('unified').Plugin<[], import('mdast').Root>} */
function myPluginThatReplacesFoo() {
  return function (tree) {
    headingRange(tree, 'Foo', function (start, nodes, end) {
      // This handler receives the 'Foo' heading (start), 
      // nodes between 'Foo' and 'Baz' (nodes), and the 'Baz' heading (end).
      // It replaces the content of the 'Foo' section.
      return [
        start,
        {type: 'paragraph', children: [{type: 'text', value: 'Content updated by mdast-util-heading-range.'}]},
        {type: 'list', children: [{type: 'listItem', children: [{type: 'paragraph', children: [{type: 'text', value: 'New list item.'}]}]}]},
        end
      ]
    })
  }
}

processMarkdown();

view raw JSON →