Is it possible to generate an automatic Table of Contents using Github Flavoured Markdown?
This is a not a direct answer to this question as so many people have provided workarounds. I don't think generating a TOC has been officially supported by Github yet to-date. If you want GitHub to render a Table of Contents on their GFM preview pages automatically, please participate the discussion on the official feature request issue.
Gitdown is a markdown preprocessor for Github.
Using Gitdown you can:
Gitdown streamlines common tasks associated with maintaining a documentation page for a GitHub repository.
Using it is straightforward:
var Gitdown = require('gitdown');
Gitdown
// Gitdown flavored markdown.
.read('.gitdown/README.md')
// GitHub compatible markdown.
.write('README.md');
You can either have it as a separate script or have it as part of the build script routine (such as Gulp).
It's not possible, except for the workarounds proposed.
I proposed Kramdown TOC extension and other possibilities to support@github.com and Steven! Ragnarök replied with the usual:
Thanks for the suggestion and links. I'll add it to our internal feature request list for the team to see.
Let's upvote this question until it happens.
Another workaround is to use Asciidoc instead of Markdown, which does render TOCs. I've moved to this approach for my content nowadays.
A very convenient way to achieve a table of contents for a mardown file when working with Visual Studio Code is the extension Markdown-TOC.
It can add a toc to existing markdown files and even keep the toc up-to-date on saving.
It's not automatic, but it uses Notepad++ regular expressions:
Replace all first by the second (removes all lines not having headers)
^##(#?)(#?)(.*?)$(.|\r|\n)*?(?=^##|\z)
-\1\2 [\3](#\3)\n
Then (converts headers III to spaces)
-##
-
Then (converts headers II to spaces)
-#
-
Then (remove unused chars at the beginning and at the end of link title)
\[ *((?:(?![ .:#!\?;]*\])[^#])*)[ #:!\?;]*\]
[\1]
Then (convert last tokens lowercase and dash instead of spaces)
\]([^ \r\n]*) ([^\r\n ]*)
]\L\1-\2
Remove unused final pounds and initial dashes:
(?:()[-:;!\?#]+$|(\]#)-)
\1\2
Remove useless chars in links:
(\].*?)(?:\(|\))
\1
And finally add parenthesis around final links:
\](?!\()(.*?)$
\]\(\1\)
And voilà! You can even put this in a global macro if you repeat it enough time.
Majority of other answers require to install some tool. I found a quick and easy online solution https://imthenachoman.github.io/nGitHubTOC.
For any markdown input it generates table of content output. You can specify minimum and maximum heading level.
The source code is located at https://github.com/imthenachoman/nGitHubTOC