mdast-util-toc

Generate a Table of Contents from a mdast tree.
Installation
npm:
npm install mdast-util-toc
mdast-util-toc is also available as an AMD, CommonJS, and globals module, uncompressed and compressed.
Usage
Dependencies:
var remark = require('remark');
var toc = require('mdast-util-toc');
Parse:
var node = remark().parse([
'# Alpha',
'',
'## Bravo',
'',
'### Charlie',
'',
'## Delta',
''
].join('\n'));
TOC:
var result = toc(node);
Yields:
{ index: null,
endIndex: null,
map:
{ type: 'list',
ordered: false,
children: [ { type: 'listItem', loose: true, children: [Object] } ] } }
API
toc(node[, options])
Generate a Table of Contents from a Markdown document.
-
If specified, looks for the first heading containing the
headingoption (case insensitive, supports alt/title attributes for links and images too), and returns a table of contents for all following headings. -
If no
headingis specified, creates a table of contents for all headings innode.
Links to headings are based on GitHub’s style. Only top-level headings (those not in blockquotes or lists), are used. The given node is not modified.
options
-
heading(string?) — Heading to look for, wrapped innew RegExp('^(' + value + ')$', 'i'); -
maxDepth(number?, default:6) — Maximum heading depth to include in the table of contents, This is inclusive, thus, when set to3, level three headings, are included (those with three hashes,###); -
tight(boolean?, default:false) — Whether to compile list-items tightly.
Returns
An object with the following properties:
-
index(number?) — Position of theheadinginnode.-1if no heading was found,nullif no heading was given; -
endIndex(number?) — Position of the last node afterheadingbefore the TOC starts.-1if no heading was found,nullif no heading was given, same asindexif there are no nodes betweenheadingand the first heading in the TOC; -
map(Node?) — List node representing the generated table of contents.nullif no table of contents could be created, either because noheadingdidn’t exist, or no following headings were found.