• Stars
    star
    375
  • Rank 109,139 (Top 3 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created about 9 years ago
  • Updated 6 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

plugin to generate a table of contents (TOC)

remark-toc

Build Coverage Downloads Size Sponsors Backers Chat

remark plugin to generate a table of contents.

Contents

What is this?

This package is a unified (remark) plugin to generate a table of contents of the document such as the one above.

When should I use this?

This project is useful when authors are writing docs in markdown that are sometimes quite long and so 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 16+), install with npm:

npm install remark-toc

In Deno with esm.sh:

import remarkToc from 'https://esm.sh/remark-toc@9'

In browsers with esm.sh:

<script type="module">
  import remarkToc from 'https://esm.sh/remark-toc@9?bundle'
</script>

Use

Say we have the following file example.md:

# Pluto

Pluto is a dwarf planet in the Kuiper belt.

## Contents

## History

### Discovery

In the 1840s, Urbain Le Verrier used Newtonian mechanics to predict the
position of…

### Name and symbol

The name Pluto is for the Roman god of the underworld, from a Greek epithet for
Hades…

### Planet X disproved

Once Pluto was found, its faintness and lack of a viewable disc cast doubt…

## Orbit

Pluto’s orbital period is about 248 years…

…and a module example.js:

import {remark} from 'remark'
import remarkToc from 'remark-toc'
import {read} from 'to-vfile'

const file = await remark()
  .use(remarkToc)
  .process(await read('example.md'))

console.error(String(file))

…then running node example.js yields:

# Pluto

Pluto 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

### Discovery

In the 1840s, Urbain Le Verrier used Newtonian mechanics to predict the
position of…

### Name and symbol

The name Pluto is for the Roman god of the underworld, from a Greek epithet for
Hades…

### Planet X disproved

Once Pluto was found, its faintness and lack of a viewable disc cast doubt…

## Orbit

Pluto’s orbital period is about 248 years…

API

This package exports no identifiers. The default export is remarkToc.

unified().use(remarkToc[, options])

Generate a table of contents (TOC).

Looks for the first heading matching options.heading (case insensitive), removes everything between it and an equal or higher next heading, and replaces that with a list representing the rest of the document structure, linking to all further headings.

Parameters
  • options (Options, optional) — configuration
Returns

Transform (Transformer).

Options

Configuration (TypeScript type).

Fields
  • heading (string, default: '(table[ -]of[ -])?contents?|toc') — heading to look for, wrapped in new RegExp('^(' + value + ')$', 'i')
  • maxDepth (number, default: 6) — max heading depth to include in the table of contents; this is inclusive: when set to 3, level three headings are included (those with three hashes, ###)
  • skip (string, optional) — headings to skip, wrapped in new RegExp('^(' + value + ')$', 'i'); any heading matching this expression will not be present in the table of contents
  • parents (Test from unist-util-is, default: tree) — allow headings to be children of certain node types
  • tight (boolean, default: true) — whether to compile list items tightly, otherwise space is added around items
  • ordered (boolean, default: false) — whether to compile list items as an ordered list, otherwise they are unordered
  • prefix (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 sanitizing with rehype-sanitize

Examples

Example: a different heading

The option heading 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 for structure (case-insensitive) headings.

Example: ordered, loose list

The options ordered and tight can be toggled to change the list. The example from before can be changed to generate a tight, ordered list like so:

@@ -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)

Example: including and excluding headings

The options maxDepth, parents, and skip can be used to include and exclude certain headings from list. The example from before can be changed to only include level 1, 2, and 3 headings, to include headings directly in list items, and to exclude headings with the text delta (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))

Example: adding a prefix

The prefix option can set to prepend a string to all links to headings in the generated 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)

Types

This package is fully typed with TypeScript. It exports the additional type Options.

Compatibility

Projects maintained by the unified collective are compatible with maintained versions of Node.js.

When we cut a new major release, we drop support for unmaintained versions of Node. This means we try to keep the current release line, remark-toc@^9, compatible with Node.js 16.

This plugin works with unified version 3+ and remark version 4+.

Security

Use of remark-toc involves user content and changes the tree, so it can open you up for a cross-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 of contents.

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 to rehype (hast) or opened in an unsafe markdown viewer.

Related

Contribute

See contributing.md in remarkjs/.github for ways to get started. See support.md for ways to get help.

This project has a code of conduct. By interacting with this repository, organization, or community you agree to abide by its terms.

License

MIT © Titus Wormer

More Repositories

1

react-markdown

Markdown component for React
JavaScript
12,040
star
2

remark

markdown processor powered by plugins part of the @unifiedjs collective
JavaScript
7,111
star
3

remark-lint

plugins to check (lint) markdown code style
JavaScript
901
star
4

remark-gfm

remark plugin to support GFM (autolink literals, footnotes, strikethrough, tables, tasklists)
JavaScript
593
star
5

remark-react

Legacy plugin to transform to React — please use `remark-rehype` and `rehype-react` instead
JavaScript
523
star
6

awesome-remark

Curated list of awesome remark resources
347
star
7

remark-math

remark and rehype plugins to support math
JavaScript
333
star
8

remark-html

plugin to add support for serializing HTML
JavaScript
298
star
9

remark-frontmatter

remark plugin to support frontmatter (YAML, TOML, and more)
JavaScript
237
star
10

remark-rehype

plugin that turns markdown into HTML to support rehype
JavaScript
234
star
11

remark-directive

remark plugin to support directives
JavaScript
206
star
12

react-remark

React component and hook to use remark to render markdown
TypeScript
170
star
13

remark-github

remark plugin to link references to commits, issues, pull-requests, and users, like on GitHub
JavaScript
163
star
14

strip-markdown

plugin remove Markdown formatting
JavaScript
122
star
15

remark-validate-links

plugin to check that Markdown links and images reference existing files and headings
JavaScript
105
star
16

remark-breaks

plugin to add break support, without needing spaces
JavaScript
101
star
17

remark-man

plugin to compile markdown to man pages
JavaScript
94
star
18

remark-slug

Legacy plugin to add `id`s to headings — please use `rehype-slug`
JavaScript
91
star
19

remark-lint-no-dead-urls

Ensure that external links in your Markdown are alive
JavaScript
72
star
20

remark-unwrap-images

plugin to remove the wrapping paragraph for images
JavaScript
71
star
21

remark-highlight.js

Legacy plugin to highlight code blocks with highlight.js — please use `rehype-highlight` instead
JavaScript
69
star
22

remark-autolink-headings

Legacy remark plugin to automatically add links to headings — please use `rehype-autolink-headings` instead
JavaScript
67
star
23

remark-external-links

Legacy plugin to automatically add target and rel attributes to external links — please use `rehype-external-links` instead
JavaScript
55
star
24

vscode-remark

Lint and format markdown code with remark
JavaScript
51
star
25

remark-vdom

Legacy plugin to compile Markdown to Virtual DOM — please use `remark-rehype` and then something like `rehype-react`
JavaScript
45
star
26

remark-usage

plugin to add a usage example to your readme
JavaScript
40
star
27

remark-footnotes

Legacy plugin to add support for pandoc footnotes — please use `remark-gfm` instead
JavaScript
40
star
28

remark-gemoji

plugin to turn gemoji shortcodes into emoji 👍
JavaScript
37
star
29

remark-textr

plugin to make your typography better with Textr
JavaScript
35
star
30

remark-images

plugin to add a simpler image syntax
JavaScript
31
star
31

remark-embed-images

plugin to embed local images as data URIs
HTML
30
star
32

remark-jsx

A simple way to use React inside Markdown.
JavaScript
28
star
33

remark-language-server

A language server to lint and format markdown files with remark
JavaScript
28
star
34

remark-reference-links

plugin to change links and images to references with separate definitions
JavaScript
25
star
35

remark-contributors

plugin to generate a list of contributors
JavaScript
22
star
36

remark-retext

plugin to transform from remark (Markdown) to retext (natural language)
JavaScript
22
star
37

remark-inline-links

plugin to change references and definitions into normal links and images
JavaScript
20
star
38

remark-license

plugin to generate a license section
JavaScript
19
star
39

remark-defsplit

plugin to change links and images to references with separate definitions
JavaScript
18
star
40

remark-bookmarks

plugin to manage links
JavaScript
15
star
41

remark-comment-config

plugin to configure remark with comments
JavaScript
13
star
42

remark-git-contributors

plugin to generate a list of Git contributors
JavaScript
12
star
43

remark-normalize-headings

plugin to make sure there is a single top level heading in a document by adjusting heading ranks accordingly
JavaScript
11
star
44

remark-squeeze-paragraphs

plugin to remove empty (or white-space only) paragraphs
JavaScript
10
star
45

gulp-remark

Legacy Gulp plugin for remark — please use npm scripts and the like
JavaScript
10
star
46

remark-strip-badges

plugin to strip badges (such as shields.io)
JavaScript
9
star
47

remark-message-control

plugin to enable, disable, and ignore messages
JavaScript
8
star
48

remark-yaml-config

plugin to configure remark with YAML frontmatter
JavaScript
7
star
49

.github

Community health files for remark
TypeScript
7
star
50

remark-heading-gap

plugin to adjust the gap between headings in markdown
JavaScript
5
star
51

ideas

Share ideas for new utilities and tools built with @remarkjs
5
star
52

remark-unlink

plugin to remove all links, images, references, and definitions
JavaScript
5
star
53

grunt-remark

Grunt task for remark
4
star
54

remark-word-wrap

Please use something like https://github.com/prettier/prettier instead
JavaScript
4
star
55

remark-midas

plugin to highlight CSS code blocks with midas
3
star
56

remark-comment-blocks

Use something like https://github.com/3rd-Eden/commenting instead
JavaScript
2
star
57

governance

How @remarkjs and the projects under it are governed
2
star