If you find remark-flexible-toc useful in your projects, consider supporting my work.
Your sponsorship means a lot 💖
Be the first sponsor and get featured here and on my sponsor wall.
Thank you for supporting open source! 🙌
This package is a unified (remark) plugin to expose the table of contents via Vfile.data or via an option reference in markdown.
unified is a project that transforms content with abstract syntax trees (ASTs) using the new parser micromark. remark adds support for markdown to unified. mdast is the Markdown Abstract Syntax Tree (AST) which is a specification for representing markdown in a syntax tree.
This plugin is a remark plugin that doesn't transform the MDAST but gets info from the MDAST.
remark-flexible-toc is useful if you want to get the table of contents (TOC) from the markdown/MDX document. It exposes the table of contents (TOC) in two ways:
- by adding a
tocobject intoVfile.data - by mutating a reference array if provided in the options
This package is suitable for ESM only. In Node.js (version 16+), install with npm:
npm install remark-flexible-tocor
yarn add remark-flexible-tocSay we have the following file, example.md, which consists some headings.
# The Main Heading
## Section
### Subheading 1
### Subheading 2Say example.js looks as followings (two ways):
import { read } from "to-vfile";
import remark from "remark";
import gfm from "remark-gfm";
import remarkRehype from "remark-rehype";
import rehypeStringify from "rehype-stringify";
import remarkFlexibleToc from "remark-flexible-toc";
main();
async function main() {
const file = await remark()
.use(gfm)
.use(remarkFlexibleToc)
.use(remarkRehype)
.use(rehypeStringify)
.process(await read("example.md"));
console.log(file.data.toc);
}import { read } from "to-vfile";
import remark from "remark";
import gfm from "remark-gfm";
import remarkRehype from "remark-rehype";
import rehypeStringify from "rehype-stringify";
import remarkFlexibleToc from "remark-flexible-toc";
main();
async function main() {
const toc = [];
const file = await remark()
.use(gfm)
.use(remarkFlexibleToc, {tocRef: toc})
.use(remarkRehype)
.use(rehypeStringify)
.process(await read("example.md"));
console.log(toc);
}Now, running both node example.js you will see that the same table of contents (TOC) is logged in the console:
[
{
depth: 2,
href: "#section",
numbering: [1, 1],
parent: "root",
value: "Section",
},
{
depth: 3,
href: "#subheading-1",
numbering: [1, 1, 1],
parent: "root",
value: "Subheading 1",
},
{
depth: 3,
href: "#subheading-2",
numbering: [1, 1, 2],
parent: "root",
value: "Subheading 2",
},
]Without remark-flexible-toc, there wouldn't be any toc key in the file.data:
All options are optional.
type HeadingParent =
| "root"
| "blockquote"
| "footnoteDefinition"
| "listItem"
| "container"
| "mdxJsxFlowElement";
type HeadingDepth = 1 | 2 | 3 | 4 | 5 | 6;
use(remarkFlexibleToc, {
tocName?: string; // default: "toc"
tocRef?: TocItem[]; // default: []
maxDepth?: HeadingDepth; // default: 6
skipLevels?: HeadingDepth[]; // default: [1]
skipParents?: Exclude<HeadingParent, "root">[]; // default: []
exclude?: string | string[];
prefix?: string;
callback?: (toc: TocItem[]) => undefined;
} as FlexibleTocOptions);It is a string option in which the table of contents (TOC) is placed in the vfile.data.
By default it is toc, meaningly the TOC is reachable via vfile.data.toc.
use(remarkFlexibleToc, {
tocName: "headings";
});Now, the TOC is accessable via vfile.data.headings.
It is an array of reference option for getting the table of contents (TOC), which is the second way of getting the TOC from remark-flexible-toc.
The reference array should be an empty array, if not, it is emptied by the plugin.
If you use typescript, the array reference should be const toc: TocItem[] = [].
const toc = [];
use(remarkFlexibleToc, {
tocRef: toc; // `remark-flexible-toc` mutates the array of reference
});Now, the TOC is accessable via toc.
It is a number option for indicating the max heading depth to include in the TOC.
By default it is 6. Meaningly, there is no restriction by default.
use(remarkFlexibleToc, {
maxDepth: 4;
});The maxDepth option is inclusive: when set to 4, level fourth headings are included, but fifth and sixth level headings will be skipped.
It is an array option to indicate the heading levels to be skipped.
By default it is [1] since the first level heading is not expected to be in the TOC.
use(remarkFlexibleToc, {
skipLevels: [1, 2, 4, 5, 6];
});Now, the TOC consists only the third level headings.
By default it is an empty array []. The array may contain the parent values blockquote, footnoteDefinition, listItem, container, mdxJsxFlowElement.
use(remarkFlexibleToc, {
skipParents: ["blockquote"];
});Now, the headings in the <blockquote> will not be added into the TOC.
It is a string or string[] option. The plugin wraps the string(s) in new RegExp('^(' + value + ')$', 'i'), so any heading matching this expression will not be present in the TOC. The RegExp checks exact (not contain) matching and case insensitive as you see.
The option has no default value.
use(remarkFlexibleToc, {
exclude: "The Subheading";
});Now, the heading "The Subheading" will not be included in to the TOC, but forexample "The Subheading Something" will be included.
It is a string option to add a prefix to hrefs of the TOC items. It is useful for example when later going from markdown to HTML and sanitizing with rehype-sanitize.
The option has no default value.
use(remarkFlexibleToc, {
prefix: "text-prefix-";
});Now, all TOC items' hrefs will start with that prefix like #text-prefix-the-subheading.
It is a callback function callback?: (toc: TocItem[]) => undefined; which takes the TOC items as an argument and returns nothing. It is usefull for logging the TOC, forexample, or modifing the TOC. It is allowed that the callback function is able to mutate the TOC items !
The option has no default value.
use(remarkFlexibleToc, {
callback: (toc) => {
console.log(toc);
};
});Now, each time when you compile the source, the TOC will be logged into the console for debugging purpose.
type TocItem = {
value: string; // heading text
href: string; // produced uniquely by "github-slugger" using the value of the heading
depth: HeadingDepth; // 1 | 2 | 3 | 4 | 5 | 6
numbering: number[]; // explained below
parent: HeadingParent; // "root"| "blockquote" | "footnoteDefinition" | "listItem" | "container" | "mdxJsxFlowElement"
data?: Record<string, unknown>; // Other remark plugins may store custom data in "node.data.hProperties" like "id" etc.
};Note
If there is a remark plugin before remark-flexible-toc in the plugin chain, which provides custom id for headings like remark-heading-id, that custom id takes precedence for href.
remark-flexible-toc uses github-slugger internally for producing unique links. Then, it is possible you to use rehype-slug (forIDs on headings) and rehype-autolink-headings (for anchors that link-to-self) because they use the same github-slugger.
As an example for the unique heading links (notice the same heading texts).
# The Main Heading
## Section
### Subheading
## Section
### SubheadingThe github-slugger produces unique links with using a counter mechanism internally, and the TOC item's hrefs is going to be unique.
[
{
depth: 2,
href: "#section",
numbering: [1, 1],
parent: "root",
value: "Section",
},
{
depth: 3,
href: "#subheading",
numbering: [1, 1, 1],
parent: "root",
value: "Subheading",
},
{
depth: 2,
href: "#section-1",
numbering: [1, 2],
parent: "root",
value: "Section",
},
{
depth: 3,
href: "#subheading-1",
numbering: [1, 2, 1],
parent: "root",
value: "Subheading",
},
]remark-flexible-toc produces always the numbering for TOC items in case you show the ordered TOC.
The numbering of a TOC item is an array of number. The numbers in the numbering corresponds the level of the headers. With that structure, you know which header is under which header.
[1, 1]
[1, 2]
[1, 2, 1]
[1, 2, 2]
[1, 3]The first number of the numbering is related with the fist level headings.
The second number of the numbering is related with the second level headings.
And so on...
If yo haven't included the first level header into the TOC, you can slice the numbering with 1 so as to second level headings starts with 1 and so on..
tocItem.numbering.slice(1);You can join the numbering as you wish. It is up to you to combine the numbering with dot, or dash.
tocItem.numbering.join(".");
tocItem.numbering.join("-");This plugin does not modify the mdast (markdown abstract syntax tree), collects data from the mdast and adds information into the vfile.data if required.
This package is fully typed with TypeScript. The plugin exports the types FlexibleTocOptions, HeadingParent, HeadingDepth, TocItem.
This plugin works with unified version 6+ and remark version 7+. It is compatible with mdx version 2+.
Use of remark-flexible-toc does not involve rehype (hast) or user content so there are no openings for cross-site scripting (XSS) attacks.
I like to contribute the Unified / Remark / MDX ecosystem, so I recommend you to have a look my plugins.
remark-flexible-code-titles– Remark plugin to add titles or/and containers for the code blocks with customizable propertiesremark-flexible-containers– Remark plugin to add custom containers with customizable properties in markdownremark-ins– Remark plugin to addinselement in markdownremark-flexible-paragraphs– Remark plugin to add custom paragraphs with customizable properties in markdownremark-flexible-markers– Remark plugin to add custommarkelement with customizable properties in markdownremark-flexible-toc– Remark plugin to expose the table of contents viavfile.dataor via an option referenceremark-mdx-remove-esm– Remark plugin to remove import and/or export statements (mdxjsEsm)
rehype-pre-language– Rehype plugin to add language information as a property topreelementrehype-highlight-code-lines– Rehype plugin to add line numbers to code blocks and allow highlighting of desired code linesrehype-code-meta– Rehype plugin to copycode.data.metatocode.properties.metastringrehype-image-toolkit– Rehype plugin to enhance Markdown image syntax![]()and Markdown/MDX media elements (<img>,<audio>,<video>) by auto-linking bracketed or parenthesized image URLs, wrapping them in<figure>with optional captions, unwrapping images/videos/audio from paragraph, parsing directives in title for styling and adding attributes, and dynamically converting images into<video>or<audio>elements based on file extension.
recma-mdx-escape-missing-components– Recma plugin to set the default value() => nullfor the Components in MDX in case of missing or not provided so as not to throw an errorrecma-mdx-change-props– Recma plugin to change thepropsparameter into the_propsin thefunction _createMdxContent(props) {/* */}in the compiled source in order to be able to use{props.foo}like expressions. It is useful for thenext-mdx-remoteornext-mdx-remote-clientusers innextjsapplications.recma-mdx-change-imports– Recma plugin to convert import declarations for assets and media with relative links into variable declarations with string URLs, enabling direct asset URL resolution in compiled MDX.recma-mdx-import-media– Recma plugin to turn media relative paths into import declarations for both markdown and html syntax in MDX.recma-mdx-import-react– Recma plugin to ensure gettingReactinstance from the arguments and to make the runtime props{React, jsx, jsxs, jsxDev, Fragment}is available in the dynamically imported components in the compiled source of MDX.recma-mdx-html-override– Recma plugin to allow selected raw HTML elements to be overridden via MDX components.recma-mdx-interpolate– Recma plugin to enable interpolation of identifiers wrapped in curly braces within thealt,src,href, andtitleattributes of markdown link and image syntax in MDX.
MIT License © ipikuka