question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Generate TOC (table of contents)

See original GitHub issue

Is it possible to automatically generate table content of all headings, like by placing some html markup on a page ? Something like that :

<div class="summary"></div>

Issue Analytics

  • State:open
  • Created 3 years ago
  • Reactions:3
  • Comments:14 (3 by maintainers)

github_iconTop GitHub Comments

5reactions
robertvanhoeselcommented, May 7, 2021

If you want to generate a ToC that respects heading levels, the following will create a markdown formatted TOC for you using the Marked parser and default slugger. It returns a list indented with each heading level, linking to the anchor of each heading in the document.

import marked from "marked";

const parseToc = (md: string) => {
    const toc: { level: number; text: string; slug: string }[] = [];

    const renderer = new marked.Renderer();

    renderer.heading = (text, level, raw, slugger) => {
        const slug = slugger.slug(raw);
        toc.push({ level, text, slug });
        return text;
    };

    marked(md, { renderer });

    return toc
        .map((t) => `${Array(t.level).join("  ")}- [${t.text}](#${t.slug})`)
        .join("\n\n");
};

So something like

# Heading 1
Foo bar

## Subheading 2
Baz bar

### Subheading 3
Baz bar

# An other heading 1

Will be transformed to…

- [Heading 1](#heading-1)
  - [Subheading 2](#subheading-2)
    - [Subheading 3](#subheading-3)
- [An other heading 1](#an-other-heading-1)

To use it with md-to-pdf read the file, parse its ToC and prefix it to the content option.


    const md = fs.readFileSync(file, "UTF-8");

    let toc = parseToc(md);

    const pdf = await mdToPdf(
        {
            content: toc + '\n\n' + md
        },
        // ... etc

image

1reaction
robertvanhoeselcommented, Apr 7, 2022

@designel

The parseToc(md) function takes a markdown string, walks over all headings (# title) and then returns a string of markdown that can be used directly as a table of contents. You run it separately or before rendering the PDF.

You can prepend the new piece of markdown to the actual MD you pass to Marked to render the final PDF.

How it works:

The ‘renderer’ is an config object for marked that takes plugins. We create a plugin that overrides the default header rendering and instead takes all the info about that heading and puts it in an array. Level is the header level (i.e. # Level 1, ## level 2.

  const toc: { level: number; text: string; slug: string }[] = [];
  renderer.heading = (text, level, raw, slugger) => {
        const slug = slugger.slug(raw); // This creates a unique ID which we can use to link to the header
        toc.push({ level, text, slug });
        return text;
    };

Which basically creates something like

const toc = [
{ "level": 1, "text": "Heading 1", id: "#heading-1" },
{ "level": 2, "text": "Subheading 2", id: "#subheading-2" },
{ "level": 3, "text": "Subheading 3", id: "#subheading-3" },
{ "level": 1, "text": "An other heading 1", id: "#an-other-heading-1" },
]

This piece turns the above data into markdown:

return toc
        .map((t) => `${Array(t.level).join("  ")}- [${t.text}](#${t.slug})`)
        .join("\n\n");

creates:

- [Heading 1](#heading-1)
 - [Subheading 2](#subheading-2)
   - [Subheading 3](#subheading-3)
- [An other heading 1](#an-other-heading-1)
Read more comments on GitHub >

github_iconTop Results From Across the Web

GitHub Wiki TOC generator
GitHub Wiki TOC generator​​ This page uses markdown-toc library to generate your MarkDown TOC online.
Read more >
How To: Create a Clickable Table of Contents (TOC)
Under Styles at the top (when you are on the Home window in Word), click on Heading 1 (do this for each section...
Read more >
HOWTO-use Microsoft Word Table of Content (TOC) Generator
Microsoft Word TOC generator is a very useful tool to automatically generate and update the table of contents for a Microsoft Word document....
Read more >
How to create / update a table of contents in Microsoft Word
So now you have assigned the first main section of your document. Keep it up! Go on scrolling through the text and selecting...
Read more >
Word Tips: How to Create a Table of Contents in Word
Now for the easy part! Once you've applied heading styles, you can insert your table of contents in just a few clicks. Navigate...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found