mdast HTML Comment Zone Utility

6.1.0 · active · verified Sun Apr 19

mdast-zone is a utility within the `syntax-tree` ecosystem designed to manipulate Markdown Abstract Syntax Trees (mdast) by identifying and modifying content sections defined by HTML comments. It provides a `zone` function that takes an mdast tree, a comment name (e.g., 'foo'), and a handler function. This handler receives the `start` comment, the `nodes` between the comments, and the `end` comment, allowing developers to replace or modify the content within these defined zones. The current stable version is 6.1.0, and new releases, including major versions, appear roughly annually, with minor and patch updates in between, demonstrating active maintenance. It differentiates itself from similar utilities like `mdast-util-heading-range` by using hidden HTML comments as markers for sections rather than visible headings, making it suitable for programmatic content generation or manipulation where markers should not be visible in the rendered output. This package is ESM-only and requires Node.js 16+ since v6.0.0.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates how to define a content zone using HTML comments (`<!--foo start-->` and `<!--foo end-->`) and then replace the content within that zone using the `mdast-zone` utility within a `remark` plugin. It logs the original content found and replaces it with a new paragraph.

import {zone} from 'mdast-zone';
import {remark} from 'remark';
import {unified} from 'unified'; // Required for unified.Plugin types

async function processMarkdown() {
  const markdownInput = `<!--foo start-->\n\nFoo\n\n<!--foo end-->`;

  /** @type {import('unified').Plugin<[], import('mdast').Root>} */
  function myPluginThatReplacesFoo() {
    return function (tree) {
      zone(tree, 'foo', function (start, nodes, end) {
        console.log(`Found zone 'foo' with content: '${nodes.map(n => 'value' in n ? n.value : '').join('')}'`);
        return [
          start,
          {type: 'paragraph', children: [{type: 'text', value: 'Bar.'}]},
          end
        ];
      });
    };
  }

  const file = await remark()
    .use(myPluginThatReplacesFoo)
    .process(markdownInput);

  console.log(String(file));
}

processMarkdown();

view raw JSON →