extensions/toc

README
Edited: Sunday 22 June 2025

goldmark-toc

Go Reference
CI
codecov

goldmark-toc is an add-on for the goldmark Markdown parser that adds support
for rendering a table-of-contents.

Demo:
A web-based demonstration of the extension is available at
https://abhinav.github.io/gold….

Installation

1go get go.abhg.dev/goldmark/toc@latest

Usage

To use goldmark-toc, import the toc package.

1import "go.abhg.dev/goldmark/toc"

Following that, you have three options for using this package:

  • Extension: This is the easiest way to get a table of contents into your
    document and provides very little control over the output.

  • Transformer: This is the next easiest option and provides more control
    over the output.

  • Manual: This option requires the most work but also provides the most
    control.

Extension

To use this package as a simple Goldmark extension, install the Extender
when constructing the goldmark.Markdown object.

1markdown := goldmark.New(
2    // ...
3    goldmark.WithParserOptions(parser.WithAutoHeadingID()),
4    goldmark.WithExtensions(
5        // ...
6        &toc.Extender{},
7    ),
8)

This will add a “Table of Contents” section to the top of every Markdown
document parsed by this Markdown object.

NOTE: The example above enables parser.WithAutoHeadingID. Without this or
a custom implementation of parser.IDs, none of the headings in the
document will have links generated for them.

Changing the title

If you want to use a title other than “Table of Contents”,
set the Title field of Extender.

1&toc.Extender{
2  Title: "Contents",
3}

You can specify an ID for the title heading with the TitleID option.

1&toc.Extender{
2  Title:   "Contents",
3  TitleID: "toc-header",
4}

Adding an ID

If you want the rendered HTML list to include an id,
set the ListID field of Extender.

1&toc.Extender{
2  ListID: "toc",
3}

This will render:

1<ul id="toc">
2  <!-- ... -->
3</ul>

Limiting the Table of Contents

By default, goldmark-toc will include all headers in the table of contents.
If you want to limit the depth of the table of contents,
use the MinDepth and MaxDepth field.

1&toc.Extender{
2  MinDepth: 2,
3  MaxDepth: 3,
4}

Headers with a level lower or higher than the specified values
will not be included in the table of contents.

Compacting the Table of Contents

The Table of Contents generated by goldmark-toc matches your heading hierarchy
exactly.
This can be a problem if you have multiple levels of difference between items.
For example, if you have the document:

1# h1
2### h3

goldmark-toc will generate a TOC with the equivalent of the following,
resulting in an empty entry between h1 and h3.

1- h1
2  - <blank>
3    - h3

You can use the Compact option to collapse away these intermediate items.

1&toc.Extender{
2  Compact: true,
3}

With this option enabled, the hierarchy above
will render as the equivalent of the following.

1- h1
2  - h3

Transformer

Installing this package as an AST Transformer provides slightly more control
over the output.
To use it, install the AST transformer on the Goldmark Markdown parser.

1markdown := goldmark.New(...)
2markdown.Parser().AddOptions(
3    parser.WithAutoHeadingID(),
4    parser.WithASTTransformers(
5        util.Prioritized(&toc.Transformer{
6            Title: "Contents",
7        }, 100),
8    ),
9)

This will generate a “Contents” section at the top of all Markdown documents
parsed by this parser.

As with the previous example, this enables parser.WithAutoHeadingID to get
auto-generated heading IDs.

Manual

If you use this package manually to generate Tables of Contents, you have a
lot more control over the behavior. This requires a few steps.

Parse Markdown

Parse a Markdown document with goldmark.

1markdown := goldmark.New(...)
2markdown.Parser().AddOptions(parser.WithAutoHeadingID())
3doc := markdown.Parser().Parse(text.NewReader(src))

Note that the parser must be configured to generate IDs for headers or the
headers in the table of contents won’t have anything to point to. This can be
accomplished by adding the parser.WithAutoHeadingID option as in the example
above, or with a custom implementation of goldmark/parser.IDs by using the
snippet below.

1markdown := goldmark.New(...)
2pctx := parser.NewContext(parser.WithIDs(ids))
3doc := parser.Parse(text.NewReader(src), parser.WithContext(pctx))

Build a table of contents

After parsing a Markdown document, inspect it with toc.

1tree, err := toc.Inspect(doc, src)
2if err != nil {
3  // handle the error
4}

If you need to limit the depth of the table of contents,
use the MinDepth and MaxDepth option.

1tree, err := toc.Inspect(doc, src, toc.MinDepth(2), toc.MaxDepth(3))

Generate a Markdown list

You can render the table of contents into a Markdown list with
toc.RenderList or toc.RenderOrderedList.

1list := toc.RenderList(tree)         // will produce <ul>
2list := toc.RenderOrderedList(tree)  // will produce <ol>

This builds a list representation of the table of contents to be rendered as
Markdown or HTML.

You may manipulate the tree before rendering the list.

Render HTML

Finally, render this table of contents along with your Markdown document:

1// Render the table of contents.
2if list != nil {
3    // list will be nil if the table of contents is empty
4    // because there were no headings in the document.
5    markdown.Renderer().Render(output, src, list)
6}
7
8// Render the document.
9markdown.Renderer().Render(output, src, doc)

Alternatively, include the table of contents into your Markdown document in
your desired position and render it using your Markdown renderer.

1// Prepend table of contents to the front of the document.
2if list != nil {
3    doc.InsertBefore(doc, doc.FirstChild(), list)
4}
5
6// Render the document.
7markdown.Renderer().Render(output, src, doc)
Customize TOC attributes

If you want the rendered TOC to have an id or other attributes,
use Node.SetAttribute
on the ast.Node returned by toc.RenderList.

For example, with the following:

1list := toc.RenderList(tree)
2list.SetAttribute([]byte("id"), []byte("toc"))

The output will take the form:

1<ul id="toc">
2  <!-- ... -->
3</ul>