[markdown] Markdown to create pages and table of contents?

I started to use markdown to take notes.

I use marked to view my markdown notes and its beautiful.

But as my notes get longer I find it difficult to find what I want.

I know markdown can create tables, but is it able to create table of contents, that jumps to sections, or define page sections in markdown?

Alternatively, are there markdown readers/editors that could do such things. Search would be good feature to have too.

In short, I want to make it my awesome note taking tool and functions much like writing a book etc.

This question is related to markdown

The answer is


For the benefit of those of us making README.md files in Atom (how I found this thread):

apm install markdown-toc

https://atom.io/packages/markdown-toc


I just coded an extension for python-markdown, which uses its parser to retrieve headings, and outputs a TOC as Markdown-formatted unordered list with local links. The file is

... and it should be placed in markdown/extensions/ directory in the markdown installation. Then, all you have to do, is type anchor <a> tags with an id="..." attribute as a reference - so for an input text like this:

$ cat test.md 
Hello
=====

## <a id="sect one"></a>SECTION ONE ##

something here

### <a id='sect two'>eh</a>SECTION TWO ###

something else

#### SECTION THREE

nothing here

### <a id="four"></a>SECTION FOUR

also...

... the extension can be called like this:

$ python -m markdown -x md_toc test.md 
* Hello
    * [SECTION ONE](#sect one)
        * [SECTION TWO](#sect two)
            * SECTION THREE
        * [SECTION FOUR](#four)

... and then you can paste back this toc in your markdown document (or have a shortcut in your text editor, that calls the script on the currently open document, and then inserts the resulting TOC in the same document).

Note that older versions of python-markdown don't have a __main__.py module, and as such, the command line call as above will not work for those versions.


If your Markdown file is to be displayed in a repo on bitbucket.org, you should add [TOC] at the location where you want your table of contents. It will then be auto-generated. More info here:

https://confluence.atlassian.com/bitbucket/add-a-table-of-contents-to-a-wiki-221451163.html


You could also use pandoc, the "swiss-army knife" for converting "one markup format into another". It can automatically generate a table of content in the output document if you supply the --toc argument.

Hint: If you want a table of contents in html output, you also need to supply -s which generates a standalone document.

Example shell command line:

./pandoc -s --toc input.md -o output.html

# Table of Contents
1. [Example](#example)
2. [Example2](#example2)
3. [Third Example](#third-example)

## Example [](#){name=example}
## Example2 [](#){name=example2}
## [Third Example](#){name=third-example}

If you use markdown extra, don't forget you can add special attributes to links, headers, code fences, and images.
https://michelf.ca/projects/php-markdown/extra/#spe-attr


I wrote a python script that parses a markdown file and outputs a table of contents as a markdown list: md-to-toc

Unlike other scripts I've found, md-to-toc correctly supports duplicate titles. It also doesn't require an internet connection, so it works on any md file, not just those available from a public repo.


Just add the number of slide ! it work with markdown ioslides and revealjs presentation

## Table of Contents

 1. [introduction](#3)
 2. [section one](#5)

If you want to use a javascript/node.js tool, take a look at markdown-toc.


For me, the solution proposed by @Tum works like a charm for a table of contents with 2 levels. However, for the 3rd level it didn't work. It didn't display the link as for the first 2 levels, it displays the plain text 3.5.1. [bla bla bla](#blablabla) <br> instead.

My solution is an addition to the solution of @Tum (which is very simple) for people who need a table of contents with 3 levels or more.

On the second level, a simple tab will do the indent correctly for you. But it doesn't support 2 tabs. Instead, you have to use one tab and add as many &nbsp; as needed yourself in order to align the 3rd level correctly.

Here's an example using 4 levels (higher the levels, awful it becomes):

# Table of Contents
1. [Title](#title) <br>
    1.1. [sub-title](#sub_title) <br>
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;1.1.1. [sub-sub-title](#sub_sub_title)
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;1.1.1.1. [sub-sub-sub-title](#sub_sub_sub_title)

# Title <a name="title"></a>
Heading 1

## Sub-Title <a name="sub_title"></a>
Heading 2

### Sub-Sub-Title <a name="sub_sub_title"></a>
Heading 3

#### Sub-Sub-Sub-Title <a name="sub_sub_sub_title"></a>
Heading 4

This gives the following result where every element of the table of contents is a link to its corresponding section. Note also the <br> in order to add a new line instead of being on the same line.

Table of Contents

  1. Title
    1.1. Sub-Title
           1.1.1. Sub-Sub-Title
                     1.1.1.1. Sub-Sub-Sub-Title

Title

Heading 1

Sub-Title

Heading 2

Sub-Sub-Title

Heading 3

Sub-Sub-Sub-Title

Heading 4


MultiMarkdown 4.7 has a {{TOC}} macro that inserts a table of contents.


Um... use Markdown's headings!?

That is:

# This is the equivalent of < h1 >

## This is the equivalent of < h4>

### This is the equivalent of < h4>

Many editors will show you a TOC. You can also grep for the heading tags and create your own.

Hope that helps!

--JF


Depending on your workflow, you might want to look at strapdown

That's a fork of the original one (http://strapdownjs.com) that adds the generation of the table of content.

There's an apache config file on the repo (might not be properly updated yet) to wrap plain markdown on the fly, if you prefer not writing in html files.


Here is a short PHP code I use to generate the TOC, and enrich any headings with anchor:

$toc = []; //initialize the toc to an empty array
$markdown = "... your mardown content here...";

$markdown = preg_replace_callback("/(#+)\s*([^\n]+)/",function($matches) use (&$toc){
    static $section = [];
    $h = strlen($matches[1]);

    @$section[$h-1]++;
    $i = $h;
    while(isset($section[$i])) unset($section[$i++]);

    $anchor = preg_replace('/\s+/','-', strtolower(trim($matches[2])));

    $toc[] = str_repeat('  ',$h-1)."* [".implode('.',$section).". {$matches[2]}](#$anchor)";
    return str_repeat('#',$h)." <strong>".implode('.',$section).".</strong> ".$matches[2]."\n<a name=\"$anchor\"></a>\n";
}, $markdown);

You can then print the processed markdown and toc:

   print(implode("\n",$toc));
   print("\n\n");
   print($markdown);

Anchor tags generated by different Markdown parsers are not even.

If you are working with Markdown parsers GFM (GitHub Flavored Markdown) or Redcarpet, I wrote a Vim plugin to handle table of contents.

Features

  1. Generate table of contents for Markdown files.

    Supported Markdown parsers:

    • GFM (GitHub Flavored Markdown)
    • Redcarpet
  2. Update existing table of contents.

  3. Auto update existing table of contents on save.

Screenshots

vim-markdown-toc

Usage

Generate table of contents

Move the cursor to the line you want to append table of contents, then type a command below suit you. The command will generate headings after the cursor into table of contents.

  1. :GenTocGFM

    Generate table of contents in GFM link style.

    This command is suitable for Markdown files in GitHub repositories, like README.md, and Markdown files for GitBook.

  2. :GenTocRedcarpet

    Generate table of contents in Redcarpet link style.

    This command is suitable for Jekyll or anywhere else use Redcarpet as its Markdown parser.

    You can view here to know differences between GFM and Redcarpet style toc links.

Update existing table of contents manually

Generally you don't need to do this, existing table of contents will auto update on save by default. If you want do it manually, just use :UpdateToc command.

Downloads and documents

https://github.com/mzlogin/vim-markdown-toc


On Gitlab, markdown supports this : [[_TOC_]]


If you happen to use Eclipse you can use the Ctrl+O (outline) shortcut, this will show the equivalent of the table of contents and allow to search in section titles (autocomplete).

You can also open the Outline view (Window -> Show View -> Outline) but it has no autocomplete search.


I just started doing the same thing (take notes in Markdown). I use Sublime Text 2 with the MarkdownPreview plugin. The built-in markdown parser supports [TOC].


You can generate it using this bash one-liner. Assumes your markdown file is called FILE.md.

echo "## Contents" ; echo ; 
cat FILE.md | grep '^## ' | grep -v Contents | sed 's/^## //' | 
  while read -r title ; do 
    link=$(echo $title | tr 'A-Z ' 'a-z-') ; 
    echo "- [$title](#$link)" ; 
    done

You can use the [TOC] at the first line and then on the bottom, the only thing you need to do is making sure that the titles are in the same bigger font. The table of content would come out automatically. ( But this only appear in some markdown editors, I didn't try all)


You can use DocToc to generate the table of contents from command line with:

doctoc /path/to/file

To make links compatible with anchors generated by Bitbucket, run it with the --bitbucket argument.


In Visual Studio Code (VSCode) you can use the extension Markdown All in One.

Once installed, follow the steps below:

  1. Press CTRL+SHIFT+P
  2. Select Markdown: Create Table of Contents

EDIT: nowadays I use DocToc to generate the table of contents, see my other answer for details.


I am not sure, what is the official documentation for markdown. Cross-Reference can be written just in brackets [Heading], or with empty brackets [Heading][].

Both works using pandoc. So I created a quick bash script, that will replace $__TOC__ in md file with its TOC. (You will need envsubst, that might not be part of your distro)

#!/bin/bash
filename=$1
__TOC__=$(grep "^##" $filename | sed -e 's/ /1. /;s/^##//;s/#/   /g;s/\. \(.*\)$/. [\1][]/')
export __TOC__
envsubst '$__TOC__' < $filename

As mentioned in other answers, there are multiple ways to generate a table of contents automatically. Most are open source software and can be adapted to your needs.

What I was missing is, however, a visually attractive formatting for a table of contents, using the limited options that Markdown provides. We came up with the following:

Code

## Content

**[1. Markdown](#heading--1)**

  * [1.1. Markdown formatting cheatsheet](#heading--1-1)
  * [1.2. Markdown formatting details](#heading--1-2)

**[2. BBCode formatting](#heading--2)**

  * [2.1. Basic text formatting](#heading--2-1)

      * [2.1.1. Not so basic text formatting](#heading--2-1-1)

  * [2.2. Lists, Images, Code](#heading--2-2)
  * [2.3. Special features](#heading--2-3)

----

Inside your document, you would place the target subpart markers like this:

<div id="heading--1-1"/>
### 1.1. Markdown formatting cheatsheet

Depending on where and how you use Markdown, the following should also work, and provides nicer-looking Markdown code:

### 1.1. Markdown formatting cheatsheet <a name="heading--1-1"/>

Example rendering

Content

1. Markdown

2. BBCode formatting


Advantages

  • You can add as many levels of chapters and sub-chapters as you need. In the Table of Contents, these would appear as nested unordered lists on deeper levels.

  • No use of ordered lists. These would create an indentation, would not link the number, and cannot be used to create decimal classification numbering like "1.1.".

  • No use of lists for the first level. Here, using an unordered list is possible, but not necessary: the indentation and bullet just add visual clutter and no function here, so we don't use a list for the first ToC level at all.

  • Visual emphasis on the first-level sections in the table of content by bold print.

  • Short, meaningful subpart markers that look "beautiful" in the browser's URL bar such as #heading--1-1 rather than markers containing transformed pieces of the actual heading.

  • The code uses H2 headings (## …) for sections, H3 headings (### …) for sub-headings etc.. This makes the source code easier to read because ## … provides a stronger visual clue when scrolling through compared to the case where sections would start with H1 headings (# …). It is still logically consistent as you use the H1 heading for the document title itself.

  • Finally, we add a nice horizontal rule to separate the table of contents from the actual content.

For more about this technique and how we use it inside the forum software Discourse, see here.


Typora generates Table of Content by adding [TOC] to your document.


There is a Ruby script called mdtoc.rb that can auto-generate a GFM Markdown Table of Contents, and it is similar but slightly different to some other scripts posted here.

Given an input Markdown file like:

# Lorem Ipsum

Lorem ipsum dolor sit amet, mei alienum adipiscing te, has no possit delicata. Te nominavi suavitate sed, quis alia cum no, has an malis dictas explicari. At mel nonumes eloquentiam, eos ea dicat nullam. Sed eirmod gubergren scripserit ne, mei timeam nonumes te. Qui ut tale sonet consul, vix integre oportere an. Duis ullum at ius.

## Et cum

Et cum affert dolorem habemus. Sale malis at mel. Te pri copiosae hendrerit. Cu nec agam iracundia necessitatibus, tibique corpora adipisci qui cu. Et vix causae consetetur deterruisset, ius ea inermis quaerendum.

### His ut

His ut feugait consectetuer, id mollis nominati has, in usu insolens tractatos. Nemore viderer torquatos qui ei, corpora adipiscing ex nec. Debet vivendum ne nec, ipsum zril choro ex sed. Doming probatus euripidis vim cu, habeo apeirian et nec. Ludus pertinacia an pro, in accusam menandri reformidans nam, sed in tantas semper impedit.

### Doctus voluptua

Doctus voluptua his eu, cu ius mazim invidunt incorrupte. Ad maiorum sensibus mea. Eius posse sonet no vim, te paulo postulant salutatus ius, augue persequeris eum cu. Pro omnesque salutandi evertitur ea, an mea fugit gloriatur. Pro ne menandri intellegam, in vis clita recusabo sensibus. Usu atqui scaevola an.

## Id scripta

Id scripta alterum pri, nam audiam labitur reprehendunt at. No alia putent est. Eos diam bonorum oportere ad. Sit ad admodum constituto, vide democritum id eum. Ex singulis laboramus vis, ius no minim libris deleniti, euismod sadipscing vix id.

It generates this table of contents:

$ mdtoc.rb FILE.md 
#### Table of contents

1. [Et cum](#et-cum)
    * [His ut](#his-ut)
    * [Doctus voluptua](#doctus-voluptua)
2. [Id scripta](#id-scripta)

See also my blog post on this topic.


Just use your text editor with a plugin.

Your editor quite possibly has a package/plugin to handle this for you. For example, in Emacs, you can install markdown-toc TOC generator. Then as you edit, just repeatedly call M-x markdown-toc-generate-or-refresh-toc. That's worth a key binding if you want to do it often. It's good at generating a simple TOC without polluting your doc with HTML anchors.

Other editors have similar plugins, so the popular list is something like:


There are 2 way to create your TOC (summary) in your markdown document.

1. Manually

# My Table of content
- [Section 1](#id-section1)
- [Section 2](#id-section2)

<div id='id-section1'/>
## Section 1
<div id='id-section2'/>
## Section 2

2. Programmatically

You can use for example a script that generate summary for you, take a look to my project on github - summarizeMD -

I've tried also other script/npm module (for example doctoc) but no one reproduce a TOC with working anchors.


You could try this ruby script to generate the TOC from a markdown file.

 #!/usr/bin/env ruby

require 'uri'

fileName = ARGV[0]
fileName = "README.md" if !fileName

File.open(fileName, 'r') do |f|
  inside_code_snippet = false
  f.each_line do |line|
    forbidden_words = ['Table of contents', 'define', 'pragma']
    inside_code_snippet = !inside_code_snippet if line.start_with?('```')
    next if !line.start_with?("#") || forbidden_words.any? { |w| line =~ /#{w}/ } || inside_code_snippet

    title = line.gsub("#", "").strip
    href = URI::encode title.gsub(" ", "-").downcase
    puts "  " * (line.count("#")-1) + "* [#{title}](\##{href})"
  end
end

I have used https://github.com/ekalinin/github-markdown-toc which provides a command line utility that auto-generates the table of contents from a markdown document.

No plugins, or macros or other dependencies. After installing the utility, just paste the output of the utility to the location in the document where you want your table of contents. Very simple to use.

$ cat README.md | ./gh-md-toc -

If using the Sublime Text editor, the MarkdownTOC plugin works beautifully! See:

  1. https://packagecontrol.io/packages/MarkdownTOC
  2. https://github.com/naokazuterada/MarkdownTOC

Once installed, go to Preferences --> Package Settings --> MarkdownTOC --> Settings -- User, to customize your settings. Here's the options you can choose: https://github.com/naokazuterada/MarkdownTOC#configuration.

I recommend the following:

{
  "defaults": {
    "autoanchor": true,
    "autolink": true,
    "bracket": "round",
    "levels": [1,2,3,4,5,6],
    "indent": "\t",
    "remove_image": true,
    "link_prefix": "",
    "bullets": ["-"],
    "lowercase": "only_ascii",
    "style": "ordered",
    "uri_encoding": true,
    "markdown_preview": ""
  },
  "id_replacements": [
    {
      "pattern": "\\s+",
      "replacement": "-"
    },
    {
      "pattern": "&lt;|&gt;|&amp;|&apos;|&quot;|&#60;|&#62;|&#38;|&#39;|&#34;|!|#|$|&|'|\\(|\\)|\\*|\\+|,|/|:|;|=|\\?|@|\\[|\\]|`|\"|\\.|\\\\|<|>|{|}|™|®|©|%",
      "replacement": ""
    }
  ],
  "logging": false
}

To insert a table of contents, simply click at the top of the document where you'd like to insert the table of contents, then go to Tools --> Markdown TOC --> Insert TOC.

It will insert something like this:

<!-- MarkdownTOC -->

1. [Helpful Links:](#helpful-links)
1. [Sublime Text Settings:](#sublime-text-settings)
1. [Packages to install](#packages-to-install)

<!-- /MarkdownTOC -->

Note the <!-- --> HTML comments it inserts for you. These are special markers that help the program know where the ToC is so that it can automatically update it for you every time you save! So, leave these intact.

To get extra fancy, add some <details> and <summary> HTML tags around it to make the ToC collapsible/expandable, like this:

<details>
<summary><b>Table of Contents</b> (click to open)</summary>
<!-- MarkdownTOC -->

1. [Helpful Links:](#helpful-links)
1. [Sublime Text Settings:](#sublime-text-settings)
1. [Packages to install](#packages-to-install)

<!-- /MarkdownTOC -->
</details>

Now, you get this super cool effect, as shown below. See it in action in my main eRCaGuy_dotfiles readme here, or in my Sublime_Text_editor readme here.

  1. Collapsed: enter image description here
  2. Expanded: enter image description here

For extra information about its usage and limitations, be sure to read my notes about the MarkdownTOC plugin in that readme too.


For the Visual Studio Code users the best option to use today (2020) is the Markdown All in One plugin.

To install it, launch the VS Code Quick Open (Control/?+P), paste the following command, and press enter.

ext install yzhang.markdown-all-in-one

And to generate the TOC, open the command palette (Control/?+Shift+P) and select the Select Markdown: Create Table of Contentsoption.


Another option is the Markdown TOC plugin.

To install it, launch the VS Code Quick Open (Control/?+P), paste the following command, and press enter.

ext install markdown-toc

And to generate the TOC, open the command palette (Control/?+Shift+P) and select the Markdown TOC:Insert/Update option or use Control/?+MT.


Based on albertodebortoli answer created the function with additional checks and substitution of punctuation marks.

# @fn       def generate_table_of_contents markdown # {{{
# @brief    Generates table of contents for given markdown text
#
# @param    [String]  markdown Markdown string e.g. File.read('README.md')
#
# @return   [String]  Table of content in markdown format.
#
def generate_table_of_contents markdown
  table_of_contents = ""
  i_section = 0
  # to track markdown code sections, because e.g. ruby comments also start with #
  inside_code_section = false
  markdown.each_line do |line|
    inside_code_section = !inside_code_section if line.start_with?('```')

    forbidden_words = ['Table of contents', 'define', 'pragma']
    next if !line.start_with?('#') || inside_code_section || forbidden_words.any? { |w| line =~ /#{w}/ }

    title = line.gsub("#", "").strip
    href = title.gsub(/(^[!.?:\(\)]+|[!.?:\(\)]+$)/, '').gsub(/[!.,?:; \(\)-]+/, "-").downcase

    bullet = line.count("#") > 1 ? " *" : "#{i_section += 1}."
    table_of_contents << "  " * (line.count("#") - 1) + "#{bullet} [#{title}](\##{href})\n"
  end
  table_of_contents
end

Use toc.py which is a tiny python script which generates a table-of-contents for your markdown.

Usage:

  • In your Markdown file add <toc> where you want the table of contents to be placed.
  • $python toc.py README.md (Use your markdown filename instead of README.md)

Cheers!


Here is a simple bash script to generate Table of Contents. Requires no special dependencies, but bash.

https://github.com/Lirt/markdown-toc-bash

It handles well special symbols inside of headings, markdown links in headings and ignores code blocks.


You can give this a try.

# Table of Contents
1. [Example](#example)
2. [Example2](#example2)
3. [Third Example](#third-example)
4. [Fourth Example](#fourth-examplehttpwwwfourthexamplecom)


## Example
## Example2
## Third Example
## [Fourth Example](http://www.fourthexample.com) 

Here's a useful method. Should produce clickable references in any MarkDown editor.

# Table of contents
1. [Introduction](#introduction)
2. [Some paragraph](#paragraph1)
    1. [Sub paragraph](#subparagraph1)
3. [Another paragraph](#paragraph2)

## This is the introduction <a name="introduction"></a>
Some introduction text, formatted in heading 2 style

## Some paragraph <a name="paragraph1"></a>
The first paragraph text

### Sub paragraph <a name="subparagraph1"></a>
This is a sub paragraph, formatted in heading 3 style

## Another paragraph <a name="paragraph2"></a>
The second paragraph text

Produces:

Table of contents

  1. Introduction
  2. Some paragraph
    1. Sub paragraph
  3. Another paragraph

This is the introduction

Some introduction text, formatted in heading 2 style

Some paragraph

The first paragraph text

Sub paragraph

This is a sub paragraph, formatted in heading 3 style

Another paragraph

The second paragraph text