README
remark-toc
remark plugin to generate a table of contents.
Contents
- What is this?
- When should I use this?
- Install
- Use
- API
- Examples
- Types
- Compatibility
- Security
- Related
- Contribute
- License
What is this?
This package is a unified (remark) plugin to generate a table of contents of the document such as the one above.
unified is a project that transforms content with abstract syntax trees (ASTs). remark adds support for markdown to unified. mdast is the markdown AST that remark uses. This is a remark plugin that transforms mdast.
When should I use this?
This project is useful when authors are writing docs in markdown that are
sometimes quite long and hence would benefit from automated overviews inside
them.
It is assumed that headings define the structure of documents and that they can
be linked to.
When this plugin is used, authors can add a certain heading (say, ## Contents
)
to documents and this plugin will populate those sections with lists that link
to all following sections.
GitHub and similar services automatically add IDs (and anchors that
link-to-self) to headings.
You can add similar features when combining remark with rehype through
remark-rehype
after this plugin.
Then it’s possible to use the rehype plugins rehype-slug
(for
IDs on headings) and rehype-autolink-headings
(for
anchors that link-to-self).
This plugin does not generate a table of contents for the whole document or
expose it to other plugins.
You can use the underlying mdast utility mdast-util-toc
and
create a plugin yourself to do that and more.
Install
This package is ESM only. In Node.js (version 12.20+, 14.14+, or 16.0+), install with npm:
npm install remark-toc
In Deno with Skypack:
import remarkToc from 'https://cdn.skypack.dev/remark-toc@8?dts'
In browsers with Skypack:
<script type="module">
import remarkToc from 'https://cdn.skypack.dev/remark-toc@8?min'
</script>
Use
Say we have the following file, example.md
:
# Alpha
## Table of contents
## Bravo
### Charlie
## Delta
And our module, example.js
, looks as follows:
import {read} from 'to-vfile'
import {remark} from 'remark'
import remarkToc from 'remark-toc'
main()
async function main() {
const file = await remark()
.use(remarkToc)
.process(await read('example.md'))
console.log(String(file))
}
Now, running node example
yields:
# Alpha
## Table of contents
* [Bravo](#bravo)
* [Charlie](#charlie)
* [Delta](#delta)
## Bravo
### Charlie
## Delta
API
This package exports no identifiers.
The default export is remarkToc
.
unified().use(remarkToc[, options])
Generate a table of contents. Looks for a certain heading, removes everything between it and an equal or higher heading, and replaces that with a list representing the document structure, linking to all further headings.
options
Configuration (optional).
options.heading
Pattern text of heading to look for (string
, default:
'toc|table[ -]of[ -]contents?'
).
Wrapped in new RegExp('^(' + options.heading + ')