There’s probably an existing tool to do this, but I couldn’t find it this morning. I have some very long README files on GitHub and I wanted a simple Table of Contents for them. I’m too lazy to break most of them up into wikis, so I needed a way to emulate the
[[toc]] tag found in the Gollum wiki platform that GitHub has.
What I ended up with is a script that works from the command line or as a Service. You can pipe Markdown to it, run it on a file, or select it and change it in place with the Service. You just put a
[toc] tag in your document where you want the Table of Contents to go, and then run it. Any headers found after the point where the tag is will be indexed and linked using GitHub-style IDs (dashes, lowercase, no other punctuation).
You can limit the depth of the TOC from the top-level header found in two ways. First, you can just add a number (1-4) to the tag:
[toc 2]. That will keep it to a depth of two levels with the first level being whatever the highest level header is that you have in your document (after the tag). You can also specify it on the command line just by including a number in the arguments, e.g.
github_toc 2 inputfile.md outputfile.md.
As in the example above, you can specify an input and output file. If you specify only one file, it will be read and processed and the output will go to STDOUT for redirection. If you specify a second file, the results will be written to it. Specify the same file twice to process in place. This makes it possible to keep a source file for editing and then output a final README as part of a build process.
Neat trick: if the file you’re processing already has a TOC generated by this script, it will update it. You can skip adding the
[toc] every time.
You can download the command line script here, and the Service is available below.