Original post is here: eklausmeier.goip.de
Assume you write a longer blog post with multiple headings. Then you probably want to have a table of contents at the head of your text, so readers can easily navigate and have a better overview of the content. This blog contains mostly shorter posts, so usually there is no need for a table of content. Exceptions are, for example, Simplified Saaze, or On Differential Forms.
Having a table of content in Markdown can be done like this:
1- [1. Introduction](#introduction)
2- [2. Installation](#installation)
3- [3. Directory structure](#directorystructure)
The actual content has to define those anchors introduction
, installation
, etc. This is done like so:
1## 1. Introduction<a id=introduction></a>
2## 2. Installation<a id=installation></a>
3## 3. Directory structure<a id=directorystructure></a>
I.e., you mix classical Markdown with plain HTML.
Having only two or three headings, then you can simply write this instantly. Once you have more than 10, below 7 lines of Perl will generate the table of content:
1#!/bin/perl -W
2while (<>) {
3 if (/### ([^#]+)<a id=(\w+)><\/a>/) {
4 printf("\t- [%s](#%s)\n",$1,$2);
5 } elsif (/## ([^#]+)<a id=(\w+)><\/a>/) {
6 printf("- [%s](#%s)\n",$1,$2);
7 }
8}
Above short regular expressions will not cope for headings embedded in code-sections.
Alternatively, a simple vim macro will also do the desired.
Added 09-Jun-2022: Exchanged name=
with id=
. W3C validator for HTML5 triggers a warning message for name=
.