- Notifications
You must be signed in to change notification settings - Fork32
plugin to generate a table of contents (TOC)
License
remarkjs/remark-toc
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
remark plugin to generate a table of contents.
- What is this?
- When should I use this?
- Install
- Use
- API
- Examples
- Types
- Compatibility
- Security
- Related
- Contribute
- License
This package is aunified (remark) plugin to generate a table ofcontents of the document such as the one above.
This project is useful when authors are writing docs in markdown that aresometimes quite long and so would benefit from automated overviews inside them.It is assumed that headings define the structure of documents and that they canbe 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 linkto all following sections.
GitHub and similar services automatically add IDs (and anchors thatlink-to-self) to headings.You can add similar features when combining remark withrehype throughremark-rehype
after this plugin.Then it’s possible to use the rehype pluginsrehype-slug
(forIDs on headings) andrehype-autolink-headings
(foranchors that link-to-self).
This plugin does not generate a table of contents for thewhole document orexpose it to other plugins.You can use the underlying mdast utilitymdast-util-toc
andcreate a plugin yourself to do that and more.
This package isESM only.In Node.js (version 16+), install withnpm:
npm install remark-toc
In Deno withesm.sh
:
importremarkTocfrom'https://esm.sh/remark-toc@9'
In browsers withesm.sh
:
<scripttype="module">importremarkTocfrom'https://esm.sh/remark-toc@9?bundle'</script>
Say we have the following fileexample.md
:
#PlutoPluto is a dwarf planet in the Kuiper belt.##Contents##History###DiscoveryIn the 1840s, Urbain Le Verrier used Newtonian mechanics to predict theposition of…###Name and symbolThe name Pluto is for the Roman god of the underworld, from a Greek epithet forHades…###Planet X disprovedOnce Pluto was found, its faintness and lack of a viewable disc cast doubt…##OrbitPluto’s orbital period is about 248 years…
…and a moduleexample.js
:
import{remark}from'remark'importremarkTocfrom'remark-toc'import{read}from'to-vfile'constfile=awaitremark().use(remarkToc).process(awaitread('example.md'))console.error(String(file))
…then runningnode example.js
yields:
#PlutoPluto is a dwarf planet in the Kuiper belt.##Contents*[History](#history)*[Discovery](#discovery)*[Name and symbol](#name-and-symbol)*[Planet X disproved](#planet-x-disproved)*[Orbit](#orbit)##History###DiscoveryIn the 1840s, Urbain Le Verrier used Newtonian mechanics to predict theposition of…###Name and symbolThe name Pluto is for the Roman god of the underworld, from a Greek epithet forHades…###Planet X disprovedOnce Pluto was found, its faintness and lack of a viewable disc cast doubt…##OrbitPluto’s orbital period is about 248 years…
This package exports no identifiers.The default export isremarkToc
.
Generate a table of contents (TOC).
Looks for the first heading matchingoptions.heading
(case insensitive),removes everything between it and an equal or higher next heading, and replacesthat with a list representing the rest of the document structure, linking toall further headings.
options
(Options
, optional)— configuration
Transform (Transformer
).
Configuration (TypeScript type).
heading
(string
, default:'(table[ -]of[ -])?contents?|toc'
)— heading to look for, wrapped innew RegExp('^(' + value + ')$', 'i')
maxDepth
(number
, default:6
)— max heading depth to include in the table of contents; this is inclusive:when set to3
, level three headings are included (those with three hashes,###
)skip
(string
, optional)— headings to skip, wrapped innew RegExp('^(' + value + ')$', 'i')
;any heading matching this expression will not be present in the table ofcontentsparents
(Test
fromunist-util-is
, default:tree
)— allow headings to be children of certain node typestight
(boolean
, default:true
)— whether to compile list items tightly, otherwise space is added arounditemsordered
(boolean
, default:false
)— whether to compile list items as an ordered list, otherwise they areunorderedprefix
(string
, optional, example:'user-content-'
)— add a prefix to links to headings in the table of contents;useful for example when later going from markdown to HTML and sanitizingwithrehype-sanitize
The optionheading
can be set to search for a different heading.The example from before can be changed to search for different headings like so:
@@ -3,7 +3,7 @@ import remarkToc from 'remark-toc' import {read} from 'to-vfile' const file = await remark()- .use(remarkToc)+ .use(remarkToc, {heading: 'structure'}) .process(await read('example.md')) console.error(String(file))
…that would search forstructure
(case-insensitive) headings.
The optionsordered
andtight
can be toggled to change the list.The example from before can be changed to generate a tight, ordered list likeso:
@@ -3,7 +3,7 @@ import remarkToc from 'remark-toc' import {read} from 'to-vfile' const file = await remark()- .use(remarkToc)+ .use(remarkToc, {ordered: true, tight: false}) .process(await read('example.md')) console.error(String(file))
…that would generate the following list:
1.[History](#history)1.[Discovery](#discovery)2.[Name and symbol](#name-and-symbol)3.[Planet X disproved](#planet-x-disproved)2.[Orbit](#orbit)
The optionsmaxDepth
,parents
, andskip
can be used to include andexclude certain headings from list.The example from before can be changed to only include level 1, 2, and 3headings, to include headings directly in list items, and to exclude headingswith the textdelta
(case-insensitive, full match):
@@ -3,7 +3,7 @@ import remarkToc from 'remark-toc' import {read} from 'to-vfile' const file = await remark()- .use(remarkToc)+ .use(remarkToc, {maxDepth: 3, parents: ['listItem', 'root'], skip: 'delta'}) .process(await read('example.md')) console.error(String(file))
Theprefix
option can set to prepend a string to all links to headings in thegenerated list:
@@ -3,7 +3,7 @@ import remarkToc from 'remark-toc' import {read} from 'to-vfile' const file = await remark()- .use(remarkToc)+ .use(remarkToc, {prefix: 'user-content-'}) .process(await read('example.md')) console.error(String(file))
…that would generate the following list:
*[History](#user-content-history)*[Discovery](#user-content-discovery)*[Name and symbol](#user-content-name-and-symbol)*[Planet X disproved](#user-content-planet-x-disproved)*[Orbit](#user-content-orbit)
This package is fully typed withTypeScript.It exports the additional typeOptions
.
Projects maintained by the unified collective are compatible with maintainedversions of Node.js.
When we cut a new major release, we drop support for unmaintained versions ofNode.This means we try to keep the current release line,remark-toc@^9
, compatiblewith Node.js 16.
This plugin works withunified
version 3+ andremark
version 4+.
Use ofremark-toc
involves user content and changes the tree, so it can openyou up for across-site scripting (XSS) attack.
Existing nodes are copied into the table of contents.The following example shows how an existing script is copied into the table ofcontents.
The following markdown:
#Contents##Bravo<script>alert(1)</script>##Charlie
Yields:
#Contents-[Bravo<script>alert(1)</script>](#bravoscriptalert1script)-[Charlie](#charlie)##Bravo<script>alert(1)</script>##Charlie
This may become a problem if the markdown is later transformed torehype (hast) or opened in an unsafe markdown viewer.
remark-normalize-headings
— make sure that there is only one top-level heading by normalizing headingranksremark-collapse
– make some sections collapsibleremark-contributors
– generate a contributors sectionremark-license
– generate a license sectionremark-package-dependencies
– generate a dependencies sectionremark-usage
– generate a usage section
Seecontributing.md
inremarkjs/.github
for waysto get started.Seesupport.md
for ways to get help.
This project has acode of conduct.By interacting with this repository, organization, or community you agree toabide by its terms.
About
plugin to generate a table of contents (TOC)