, 1 min read

Table of Contents in Saaze

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. Introduction](#introduction)
- [2. Installation](#installation)
- [3. Directory structure](#directorystructure)

The actual content has to define those anchors introduction, installation, etc. This is done like so:

## 1. Introduction<a id=introduction></a>
## 2. Installation<a id=installation></a>
## 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:

#!/bin/perl -W
while (<>) {
    if (/### ([^#]+)<a id=(\w+)><\/a>/) {
        printf("\t- [%s](#%s)\n",$1,$2);
    } elsif (/## ([^#]+)<a id=(\w+)><\/a>/) {
        printf("- [%s](#%s)\n",$1,$2);
    }
}

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=.