unified

Project: inokawa/remark-extract-toc

Package: remark-extract-toc@1.1.0

  1. Dependents: 0
  2. remark plugin to store table of contents
  1. remark 193
  2. markdown 99
  3. rehype 77
  4. mdast 56
  5. unist 47
  6. retext 40
  7. hast 27
  8. list 10
  9. table 8
  10. nlcst 5
  11. of 3
  12. toc 2
  13. contents 2

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