Reputation: 17457
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.
Upvotes: 750
Views: 836341
Reputation: 537
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):
(those, that are supported by more than 1)
[[_TOC_]]
The following syntax gains more and more popularity:
<!-- assure you have a blank line before -->
[[_TOC_]]
This works
[TOC]
another one:
[TOC]
This works
There are also some other individual syntax solutions: see the engines / tools below:
GitLab uses GitLab Flavoured Markdown (GLFM), and understands the following both:
[[_TOC_]]
or
[TOC]
(see the GLFM doc and the wiki doc)
Please also note the sentence from the first link:
We do our best to render the Markdown faithfully here, however the GitLab documentation website and the GitLab handbook use a different Markdown processor.
In the past, after they switched from Redcarpet to Kramdown as markdown engine, they supported the following (now obsolete) syntax:
- TOC
{:toc}
MultiMarkdown as of 4.7 has a the following macro:
{{TOC}}
Joplin note app added some features to the CommonMark specification by own plugins. For a table of contents you may use any of:
${toc}
, [[toc]]
, [toc]
, [[_toc_]]
(case-insensitive)
according to Jannik's answer:
If your Markdown file is to be displayed in a repo on bitbucket.org, you can use [TOC]
at the location where you want your table of contents (more info here).
according to Paul Jurczak's answer:
The Markdown editor Typora also generates a Table of Contents when you write [TOC]
in your document.
Please also note Gabriel Staples' answer with a little HowTo for the text editor Sublime Text.
Currently (05/23), none of the mentioned are supported by a Sharepoint Online Markdown webpart.
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.
Upvotes: 23
Reputation: 15237
For Visual Studio Code users, the best option to use today (2024) is the Markdown All in One plugin (extension).
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
To generate the TOC, open the command palette (Control/⌘+Shift+P) and select the Markdown All in One: 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
To generate the TOC, open the command palette (Control/⌘+Shift+P) and select the Markdown TOC: Insert/Update
option or use Control/⌘+MT.
Upvotes: 184
Reputation: 16749
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:
Content
(Quote formatting added to mark the example. Live usage will omit that, so will not have a grey bar to the left.)
## 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 a nicer-looking Markdown code:
### 1.1. Markdown formatting cheatsheet <a name="heading--1-1"/>
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 contents 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.
Upvotes: 24
Reputation: 7575
Here's a useful method which should produce clickable references in any Markdown editor:
<a name="foo"></a>
.[Foo](#foo)
.So this:
# 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 this:
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
Upvotes: 483
Reputation: 10264
Use your text editor with a plugin.
Your editor likely has a package/plugin to handle this for you. For example, in Emacs, you can install markdown-toc TOC generator. Then as you edit, repeatedly call M-x markdown-toc-generate-or-refresh-toc
when you change titles/sections. 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:
Upvotes: 7
Reputation: 52449
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.
Upvotes: 8
Reputation: 6487
In Visual Studio Code (VSCode) you can use the extension Markdown All in One.
Once installed, follow the steps below:
EDIT: nowadays I use DocToc to generate the table of contents, see my other answer for details.
Upvotes: 19
Reputation: 3949
If IntelliJ user do: , command n
or control n
gives option to create or update the table of contents. Reference: read here
Upvotes: 4
Reputation: 423
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: --toc
requires -s
(which generates a standalone document), otherwise the table of contents will not be generated.
Example shell command line:
./pandoc -s --toc input.md -o output.md
Upvotes: 27
Reputation: 14591
This is a small nodejs
script which generates the table of contents and takes into account repeated titles:
const fs = require('fs')
const { mdToPdf } = require('md-to-pdf');
const stringtoreplace = '<toc/>'
const processTitleRepetitions = (contents, titleMap) => {
for (const content of contents) {
titleMap[content.link] = typeof titleMap[content.link] === 'undefined'
? 0
: titleMap[content.link] + 1
if (titleMap[content.link] > 0) {
content.link = `${content.link}-${titleMap[content.link]}`
}
}
}
const convertContentToPdf = async (targetFile) => {
const pdf = await mdToPdf({path: targetFile}).catch(console.error)
if(pdf) {
const pdfFile = `${targetFile.replace(/\.md/, '')}.pdf`
fs.writeFileSync(pdfFile, pdf.content)
return pdfFile
}
throw new Error("PDF generation failed.")
}
const generateTOC = (file, targetFile) => {
// Extract headers
const fileContent = fs.readFileSync(file, 'utf-8')
const titleLine = /((?<=^)#+)\s(.+)/
const contents = fileContent.split(/\r?\n/).
map(line => line.match(titleLine)).
filter(match => match).
filter(match => match[1].length > 1).
map(regExpMatchArray => {
return {
level: regExpMatchArray[1].length, text: regExpMatchArray[2],
link: '#' + regExpMatchArray[2].replace(/(\s+|[.,\/#!$%^&*;:{}=\-_`~()]+)/g, '-').toLowerCase(),
}
})
const titleMap = {}
processTitleRepetitions(contents, titleMap)
// Write content
let toctext = '## Table of Contents\n'
// Find the toplevel to adjust the level of the table of contents.
const topLevel = contents.reduce((maxLevel, content) => Math.min(content['level'], maxLevel), 1000)
levelCounter = {}
contents.forEach(item => {
let currentLevel = parseInt(item.level)
levelCounter[currentLevel] = levelCounter[currentLevel] ? levelCounter[currentLevel] + 1 : 1
Object.entries(levelCounter).forEach(e => {
if(currentLevel < parseInt(e[0])) {
levelCounter[e[0]] = 0
}
})
const level = Array(currentLevel - topLevel).fill('\t').join('')
const text = `${levelCounter[currentLevel]}. [${item['text']}](${item['link']}) \n`
toctext += level + text
})
const updatedContent = fileContent.toString().replace(stringtoreplace, toctext)
fs.writeFileSync(targetFile, updatedContent)
convertContentToPdf(targetFile).then((pdfFile) => {
console.info(`${pdfFile} has been generated.`)
})
}
const args = process.argv.slice(2)
if(args.length < 2) {
console.error("Please provide the name of the markdown file from which the headers should be extracted and the name of the file with the new table of contents")
console.info("Example: node MD_TOC.js <source_md> <target_md>")
process.exit(1)
}
const source_md = args[0]
const target_md = args[1]
generateTOC(source_md, target_md)
To use it you will need to inject <toc/>
in your markdown file.
Here is how you can use it:
generateTOC('../README.md', '../README_toc.md')
The first argument is the source markdown file and the second one the file with the markdown.
Upvotes: 0
Reputation: 965
If you're using Discount markdown, enable a flag -ftoc
to auto-generate and use -T
to prepend a table of contents, e.g.:
markdown -T -ftoc <<EOT
#heading 1
content 1
##heading 2
content 2
EOT
will produce
<ul>
<li><a href="#heading-1">heading 1</a>
<ul>
<li><a href="#heading-2">heading 2</a></li>
</ul>
</li>
</ul>
<a name="heading-1"></a>
<h1>heading 1</h1>
...
Apparently you can use markdown -toc
as well, which the man
does not mention, but the USAGE
info does (trigger by illegal option like markdown -h
).
It took me a while reading the source to figure this out, so I'm writing it down mostly for future me. I'm using discount markdown on Arch Linux, from the discount
package. man
doesn't really tell you it's discount, but mentions David Parsons under AUTHOR
.
markdown --version
# markdown: discount 2.2.7
Upvotes: -1
Reputation: 81
I am using this website Markdown-TOC Creator where some can paste his whole markdown entry and the website is automtically creating all the required tags and TOC (table of content) so some can easily copy paste it into his own document.
Upvotes: 1
Reputation: 497
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.
Upvotes: 4
Reputation: 508
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
Upvotes: 3
Reputation: 6487
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.
Upvotes: 2
Reputation: 15472
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.
Upvotes: 3
Reputation: 1209
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);
Upvotes: 0
Reputation: 1838
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
Upvotes: 31
Reputation: 13490
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)
Upvotes: 737
Reputation: 466
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
Upvotes: 4
Reputation: 5014
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.
Heading 1
Heading 2
Heading 3
Sub-Sub-Sub-TitleHeading 4
Upvotes: 3
Reputation: 2309
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 -
Upvotes: 1
Reputation: 63
Just add the number of slide ! it work with markdown ioslides and revealjs presentation
## Table of Contents
1. [introduction](#3)
2. [section one](#5)
Upvotes: 0
Reputation: 2340
Use toc.py which is a tiny python script which generates a table-of-contents for your markdown.
Usage:
<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!
Upvotes: 1
Reputation: 904
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
Upvotes: 11
Reputation: 6878
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.
Upvotes: 49
Reputation: 11
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)
Upvotes: 0
Reputation: 391
# 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
Upvotes: 29
Reputation: 16999
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.
Upvotes: 1