Markdown to create pages and table of contents?

2019-01-29 15:20发布

问题:

I started to use mardown 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.

回答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.



回答2:

You can give this a try.

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

## Example
## Example2
## Third Example


回答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

  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



回答4:

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

#!/usr/bin/env ruby

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

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


回答5:

# 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



回答6:

For the Visual Studio Code users, a good idea is use the Markdown TOC plugin.

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

ext install markdown-toc

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



回答7:

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.



回答8:

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



回答9:

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



回答10:

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.



回答11:

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

  • md_toc.py (was md_toc.py)

... 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.



回答12:

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

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



回答13:

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


回答14:

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].



回答15:

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



回答16:

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


回答17:

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


回答18:

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



回答19:

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.



回答20:

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


回答21:

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.



回答22:

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!



回答23:

There is a Ruby script called gen_markdown_toc.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:

$ gen_markdown_toc.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.



回答24:

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)



回答25:

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

## Table of Contents

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


回答26:

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 -


回答27:

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



回答28:

Um... use Markdown's headings!?

That is:

# This is the equivalent of < h1 >

## This is the equivalent of < h2>

### This is the equivalent of < h3>

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

Hope that helps!

--JF



标签: markdown