9th April 2022

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 name=introduction></a>
## 2. Installation<a name=installation></a>
## 3. Directory structure<a name=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 name=(\w+)><\/a>/) {
        printf("\t- [%s](#%s)\n",$1,$2);
    } elsif (/## ([^#]+)<a name=(\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.

Categories: blogging, Perl
Tags: ,
Author: Elmar Klausmeier