unified

Project: inokawa/remark-extract-toc

Package: remark-extract-toc@1.1.0

  1. remark plugin to store table of contents
  1. remark 213
  2. markdown 152
  3. unist 132
  4. rehype 91
  5. mdast 87
  6. hast 75
  7. retext 42
  8. nlcst 15
  9. table 13
  10. list 12
  11. toc 4
  12. of 3
  13. contents 3

remark-extract-toc

npm npm check

remark plugin to store table of contents.

This plugin extracts only Heading from mdast markdown, then converts them to a nested object tree keeping the depth.

Install

npm install remark-extract-toc

Usage

var unified = require("unified");
var markdown = require("remark-parse");
var extractToc = require("remark-extract-toc");

var fs = require("fs");
var text = fs.readFileSync("example.md", "utf8");

var processor = unified().use(markdown).use(extractToc);

var node = processor.parse(text);
var tree = processor.runSync(node);
console.log(tree);

This example.md

# Alpha

aaaa

## Bravo

bbbb

### Charlie

cccc

## Delta

dddd

will be converted by this library like...

[
  {
    depth: 1,
    value: "Alpha",
    children: [
      {
        depth: 2,
        value: "Bravo",
        children: [{ depth: 3, value: "Charlie", children: [] }],
      },
      {
        depth: 2,
        value: "Delta",
        children: [],
      },
    ],
  },
]

API

remark().use(toc[, options])

Options

KeyDefaultTypeDescription
flattenfalsebooleanIf true, toc is extracted as a list not nested.
keys[]string[]Add extra field to tree object. For example, use remark-slug to add id and set { keys: ["data"] }.

License

MIT