My blog

View on GitHub
28 August 2018

Auto-generating Markdown tables of contents

by Alex Harvey

I recently spent some time automating the generation of Markdown tables-of-contents for compatibility with my open source projects in Github and also Gitlab Cloud. In the process, I reviewed a number of auto table-of-contents options by Markdown flavour and version, which I will document here.

Github Markdown

Github uses Github Flavoured Markdown (GFM), which is based on the CommonMark spec. GFM is documented here. As such, a table of contents is something you are expected to write yourself in Markdown, using inline links.

For example:

#### Table of contents

1. [Section 1](#section-1)
2. [Section 2](#section-2)
    - [Subsection a](#subsection-a)
    - [Subsection b](#subsection-b)

There are tools out there to auto-generate tables of contents e.g. markdown-toc, but I wanted something simpler and I wrote my own Ruby script to do it. My script is gen_markdown_toc.rb.

To use it (on a Mac):

gen_markdown_toc.rb | pbcopy

Then copy the generated text in your Markdown file where you want the table of contents to appear.

Gitlab Markdown

As of now, Gitlab Cloud Markdown uses GFM as well, or at least the version of Gitlab Cloud that I tested this on does.

Note that Gitlab’s docs here reveal that until recently Gitlab used Kramdown under the hood (see below). I discovered this page here that explains why they migrated away from Kramdown and thereby broke the useful table of contents feature.

Bitbucket Markdown

According to documentation here, Bitbucket’s Markdown is also based on CommonMark, so I would expect my script to work on Bitbucket too.

Kramdown Markdown

Meanwhile, other versions of Markdown have built in features to auto-generate tables of contents. Kramdown documented here is a Ruby implementation of Markdown that makes tables of contents a lot easier. If you are using Kramdown, you just need to add this:

* Table of contents

This Jekyll blog uses Kramdown Markdown for example.

RedCarpet Markdown

RedCarpet documented here is another flavour that makes auto-generation of tables of contents easy. It is apparently used in Gitlab’s Wikis. Just add this for a table of contents:

* Table of contents

Typora Markdown

Another flavour is Typora Markdown documented here. For a ToC you can write:


End note

These are all the Markdown formats I am aware of. I would like to keep this page up to date and to that end I welcome feedback and updates.

tags: markdown