'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.
Solution 1:[1]
MultiMarkdown Composer does seem to generate a table of contents to assist while editing.
There might also be the one or the other library, who can generate TOCs: see Python Markdown TOC Extension.
Solution 2:[2]
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)
Solution 3:[3]
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
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
Solution 4:[4]
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 Contents
option.
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.
Solution 5:[5]
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.
Solution 6:[6]
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
Solution 7:[7]
# 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
Solution 8:[8]
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
Generate table of contents for Markdown files.
Supported Markdown parsers:
- GFM (GitHub Flavored Markdown)
- Redcarpet
Update existing table of contents.
Auto update existing table of contents on save.
Screenshots
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.
: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.
: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
Solution 9:[9]
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
Solution 10:[10]
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
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.
Solution 11:[11]
On Gitlab, markdown supports this : [[_TOC_]]
Solution 12:[12]
In Visual Studio Code (VSCode) you can use the extension Markdown All in One.
Once installed, follow the steps below:
- Press CTRL+SHIFT+P
- Select Markdown: Create Table of Contents
EDIT: nowadays I use DocToc to generate the table of contents, see my other answer for details.
Solution 13:[13]
For the benefit of those of us making README.md
files in Atom (how I found this thread):
apm install markdown-toc
Solution 14:[14]
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
Solution 15:[15]
As an alternative to hand-made link lists, let's give an overview of all available out-of-the-box solutions to insert a table of contents (please comment and extend to keep this up-to-date):
With Gollum v5, markdown supports this:
<!-- assure you have a blank line before -->
[[_TOC_]]
This works in Azure DevOps wiki, too.
Since Gitlab switched from Redcarpet to Kramdown as markdown engine, they now support the following syntax
- TOC
{:toc}
see https://about.gitlab.com/handbook/markdown-guide/#table-of-contents-toc
MultiMarkdown as of 4.7 has a the following macro:
{{TOC}}
according to Jannik's answer:
If your Markdown file is to be displayed in a repo on bitbucket.org, you can use the following at the location where you want your table of contents (more info here):
[TOC]
according to Paul Jurczak's aswer:
The Markdown editor Typora also generates a Table of Contents when you write [TOC]
in your document.
I am aware, that I'm a little late with this answer. However, I missed such an overview myself. And my Edit of Nicolas Thery's answer to extend it to an overview was rejected.
Solution 16:[16]
If you want to use a javascript/node.js tool, take a look at markdown-toc.
Solution 17:[17]
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.
Solution 18:[18]
Typora generates Table of Content by adding [TOC]
to your document.
Solution 19:[19]
If using the Sublime Text editor, the MarkdownTOC plugin works beautifully! See:
Once installed, go to Preferences --> Package Settings --> MarkdownTOC --> Settings -- User, to customize your settings. Here are 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": "<|>|&|'|"|<|>|&|'|"|!|#|$|&|'|\\(|\\)|\\*|\\+|,|/|:|;|=|\\?|@|\\[|\\]|`|\"|\\.|\\\\|<|>|{|}|™|®|©|%",
"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.
For extra information about its usage and limitations, be sure to read my notes about the MarkdownTOC plugin in that readme too.
Solution 20:[20]
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.
Solution 21:[21]
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:
- Emacs: markdown-toc
- Vim: markdown-toc
- Atom: markdown-toc
- VSCode: markdown-toc
Solution 22:[22]
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]
.
Solution 23:[23]
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
Solution 24:[24]
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
Solution 25:[25]
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.
Solution 26:[26]
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
Solution 27:[27]
MultiMarkdown 4.7 has a {{TOC}} macro that inserts a table of contents.
Solution 28:[28]
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
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>
1.1.1. [sub-sub-title](#sub_sub_title)
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
- 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-TitleHeading 4
Solution 29:[29]
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.
Solution 30:[30]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow