Skip to main content

How to Generate a Table of Contents in a Kramdown Document

Here's how to generate a table of contents in kramdown.



# Heading
{:.no_toc} 

## Table of Contents
{:.no_toc}

* TOC 
{:toc} 

Introduction

The kramdown gem converts a kramdown file into html. It generates the id tags for each heading and uses them to generate a table of contents for a document. This becomes obvious if you take a file written in kramdown and convert it to html.

kramdown input-file.md > output-file.html

The ids are put on the generated html for all headings.

How To Automatically Generate A Table of Contents

Typically, you will want to have a numbered list for your table of contents or a bulleted list of entries. This is done by either writing 1. TOC or * TOC at the place in your file where you want the table of contents to be located. Underneath this line, specify the table of contents itself:



{:toc}

You can have either a numbered list of items or a bulleted list, in the normal way for lists:



1. TOC 
{:toc} 

* TOC 
{:toc} 

If you do not want a heading to be included in the table of contents, put:



`{:.no_toc}

Underneath the entry you want to exclude from the table of contents, often your top-level heading.

Notes

I have noticed that there is either a bug or an accidental omission in the generation of the toc. For example,, given headings like this:



# First level one heading
## First level two heading 
## Second level two heading 
## Third level two heading
# Second level one heading

I would expect the second level one heading to be a member of the list of level one headings, but it is left hanging in between two lists of second level headings, and is a member of no list. This bug makes sub-lists and then a return to a lower level further down impossible.

So you will need to have all headings which go to make up a table of contents the same level.

A bit annoying but it beats constantly scrolling up and down a document as you write it to try to remember the order of the headings and their names.