521

私はメモを取るためにマークダウンを使い始めました。

私はマークダウンノートとその美しいものを見るためにマークを使用しています。

しかし、メモが長くなるにつれて、欲しいものを見つけるのが難しくなります。

マークダウンでテーブルを作成できることは知っていますが、目次を作成したり、セクションにジャンプしたり、マークダウンでページセクションを定義したりできますか?

あるいは、そのようなことを行うことができるマークダウンリーダー/エディターはありますか?検索もあると良い機能でしょう。

要するに、私はそれを私の素晴らしいメモ取りツールにし、本を書くなどのように機能させたいと思っています。

4

41 に答える 41

565

これを試してみることができます。

# 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) 
于 2015-01-14T22:22:06.957 に答える
329

これが便利な方法です。MarkDownエディターでクリック可能な参照を生成する必要があります。

# 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

生産:

目次

  1. 序章
  2. いくつかの段落
    1. サブパラグラフ
  3. 別の段落

これが紹介です

見出し2スタイルでフォーマットされたいくつかの紹介テキスト

いくつかの段落

最初の段落のテキスト

サブパラグラフ

これはサブ段落で、見出し3のスタイルでフォーマットされています

別の段落

2番目の段落のテキスト

于 2015-10-30T09:53:52.910 に答える
107

Visual Studio Codeユーザーにとって、今日(2020年)に使用するのに最適なオプションは、Markdown AllinOneプラグインです。

インストールするには、VS Code Quick Openを起動します(Control/⌘</kbd>+P), paste the following command, and press enter.

ext install yzhang.markdown-all-in-one

また、目次を生成するには、コマンドパレットを開きます(Control/⌘</kbd>+Shift+P) and select the Select Markdown: Create Table of Contentsoption.


もう1つのオプションは、MarkdownTOCプラグインです。

インストールするには、VS Code Quick Openを起動します(Control/⌘</kbd>+P), paste the following command, and press enter.

ext install markdown-toc

また、目次を生成するには、コマンドパレットを開きます(Control/⌘</kbd>+Shift+P) and select the Markdown TOC:Insert/Update option or use Control/⌘</kbd>+MT.

于 2017-05-10T18:50:34.180 に答える
43

MultiMarkdown Composerは、編集中に役立つ目次を生成しているようです。

TOCを生成できるライブラリが1つまたは他にある場合もあります。PythonMarkdownTOC拡張機能を参照してください。

于 2012-08-19T23:38:30.947 に答える
31

マークダウンドキュメントに目次(要約)を作成する方法は2つあります。

1.手動で

# 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.プログラムで

たとえば、要約を生成するスクリプトを使用できます。githubの私のプロジェクトを見てください-summaryMD-

他のscript/npmモジュール(たとえば、doctoc)も試しましたが、アンカーが機能しているTOCを再現する人は誰もいません。

于 2015-04-03T13:28:49.567 に答える
30

このrubyスクリプトを試して、マークダウンファイルから目次を生成することができます。

 #!/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
于 2014-03-02T17:45:48.100 に答える
27
# 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}

マークダウンエクストラを使用する場合は、リンク、ヘッダー、コードフェンス、および画像に特別な属性を追加できることを忘れないでください。
https://michelf.ca/projects/php-markdown/extra/#spe-attr

于 2017-09-08T22:09:11.850 に答える
17

異なるMarkdownパーサーによって生成されたアンカータグは均一ではありません。

MarkdownパーサーGFM(GitHub Flavoured Markdown)またはRedcarpetを使用している場合は、目次を処理するためのVimプラグインを作成しました。

特徴

  1. Markdownファイルの目次を生成します。

    サポートされているMarkdownパーサー:

    • GFM(GitHubフレーバーマークダウン)
    • レッドカーペット
  2. 既存の目次を更新します。

  3. 保存時に既存の目次を自動更新します。

スクリーンショット

vim-markdown-toc

使用法

目次を生成する

目次を追加する行にカーソルを移動し、以下のコマンドを入力します。このコマンドは、カーソルの後に目次に見出しを生成します。

  1. :GenTocGFM

    GFMリンクスタイルで目次を生成します。

    このコマンドは、README.mdなどのGitHubリポジトリのMarkdownファイル、およびGitBookのMarkdownファイルに適しています。

  2. :GenTocRedcarpet

    Redcarpetリンクスタイルで目次を生成します。

    このコマンドは、Jekyllや、MarkdownパーサーとしてRedcarpetを使用する他の場所に適しています。

    ここを表示して、GFMとRedcarpetスタイルのtocリンクの違いを知ることができます。

既存の目次を手動で更新する

通常、これを行う必要はありません。既存の目次は、デフォルトで保存時に自動更新されます。手動で実行する場合は、:UpdateTocコマンドを使用するだけです。

ダウンロードとドキュメント

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

于 2016-10-25T04:57:18.670 に答える
15

pandocまた、「あるマークアップ形式を別の形式に変換する」ために「スイスアーミーナイフ」を使用することもできます。--toc引数を指定すると、出力ドキュメントに目次が自動的に生成されます。

ヒント:html出力に目次が必要な場合-sは、スタンドアロンドキュメントを生成する目次も指定する必要があります。

シェルコマンドラインの例:

./pandoc -s --toc input.md -o output.html
于 2017-02-15T12:32:25.500 に答える
11

Gitlabでは、マークダウンはこれをサポートしています:[[_TOC_]]

于 2019-02-22T14:34:29.237 に答える
11

Visual Studio Code(VSCode)では、拡張機能Markdown AllinOneを使用できます。

インストールしたら、以下の手順に従います。

  1. CTRL++を押しSHIFTますP
  2. マークダウンの選択:目次の作成

編集:最近、私はDocTocを使用して目次を生成しています。詳細については、他の回答を参照してください。

于 2019-04-25T10:36:39.120 に答える
10

AtomREADME.mdでファイルを作成する私たちの利益のために(私がこのスレッドを見つけた方法):

apm install markdown-toc

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

于 2016-07-26T21:45:39.963 に答える
10

このbashワンライナーを使用して生成できます。マークダウンファイルがと呼ばれると仮定します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
于 2018-04-12T13:23:52.823 に答える
10
于 2019-12-05T23:28:15.173 に答える
8

javascript / node.jsツールを使用する場合は、markdown-tocをご覧ください。

于 2014-08-03T07:27:25.627 に答える
6

の拡張機能をコーディングしましたpython-markdown。これは、パーサーを使用して見出しを取得し、TOCをローカルリンクを含むMarkdown形式の順序付けされていないリストとして出力します。ファイルは

...そしてそれはmarkdown/extensions/マークダウンインストールのディレクトリに配置する必要があります。次に、あなたがしなければならないのは、参照として属性を持つアンカー<a>タグをid="..."入力することです-したがって、次のような入力テキストの場合:

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

...拡張子は次のように呼び出すことができます:

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

...次に、この目次をマークダウンドキュメントに貼り付けることができます(または、テキストエディタにショートカットを設定して、現在開いているドキュメントのスクリプトを呼び出し、結果の目次を同じドキュメントに挿入します)。

古いバージョンにはモジュールがないため、上記のコマンドライン呼び出しはこれらのバージョンではpython-markdown機能しないことに注意してください。__main__.py

于 2013-05-21T01:37:37.387 に答える
6

Typoraは、ドキュメントに追加することで目次を生成[TOC]します。

于 2016-10-07T11:27:13.733 に答える
5

マークダウンファイルを解析し、目次をマークダウンリストとして出力するPythonスクリプトを作成しました:md-to-toc

私が見つけた他のスクリプトとは異なり、md-to-tocは重複するタイトルを正しくサポートしています。また、インターネット接続を必要としないため、パブリックリポジトリから入手できるファイルだけでなく、任意のmdファイルで機能します。

于 2015-06-05T04:31:03.700 に答える
5

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 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": "&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.

于 2020-11-03T04:48:56.640 に答える
4

私はちょうど同じことを始めました(Markdownでメモを取ります)。MarkdownPreviewプラグインでSublimeText2を使用しています。組み込みのマークダウンパーサーはをサポートします[TOC]

于 2014-11-12T05:39:04.430 に答える
4

プラグインでテキストエディタを使用するだけです。

あなたのエディタはおそらくあなたのためにこれを処理するためのパッケージ/プラグインを持っています。たとえば、Emacsでは、 markdown-tocTOCジェネレーターをインストールできます。次に、編集しながら、を繰り返し呼び出しますM-x markdown-toc-generate-or-refresh-toc。頻繁に実行したい場合は、キーバインディングの価値があります。ドキュメントをHTMLアンカーで汚染することなく、単純な目次を生成するのが得意です。

他のエディターにも同様のプラグインがあるため、人気のあるリストは次のようになります。

于 2019-12-05T18:09:41.450 に答える
4

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

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.

于 2021-10-06T06:06:52.257 に答える
3

Markdownファイルをbitbucket.orgのリポジトリに表示する場合は、[TOC]目次を配置する場所に追加する必要があります。その後、自動生成されます。詳細はこちら:

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

于 2019-04-11T14:21:06.650 に答える
2

albertodebortoliの回答に基づいて、追加のチェックと句読点の置換を使用して関数を作成しました。

# @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
于 2016-02-13T12:37:55.120 に答える
2

マークダウンの公式ドキュメントは何ですか、わかりません。相互参照は、角かっこだけで書くことも[Heading]、空のかっこで書くこともできます[Heading][]

どちらもpandocを使用して動作します。$__TOC__そこで、mdファイル内のTOCを置き換える簡単なbashスクリプトを作成しました。(envsubstが必要になりますが、これはディストリビューションの一部ではない可能性があります)

#!/bin/bash
filename=$1
__TOC__=$(grep "^##" $filename | sed -e 's/ /1. /;s/^##//;s/#/   /g;s/\. \(.*\)$/. [\1][]/')
export __TOC__
envsubst '$__TOC__' < $filename
于 2016-10-26T07:39:37.490 に答える
2

MultiMarkdown 4.7には、目次を挿入する{{TOC}}マクロがあります。

于 2016-11-16T01:05:20.733 に答える
2

GFMマークダウン目次を自動生成できるmdtoc.rbというRubyスクリプトがあります。これは、ここに掲載されている他のスクリプトと似ていますが、わずかに異なります。

次のような入力Markdownファイルが与えられます:

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

次の目次が生成されます。

$ 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)

このトピックに関する私のブログ投稿も参照してください。

于 2018-09-01T09:45:39.063 に答える
2

私にとって、@ Tumによって提案されたソリューションは、2つのレベルの目次の魅力のように機能します。ただし、第3レベルでは機能しませんでした。最初の2レベルのようにリンクは表示されず、3.5.1. [bla bla bla](#blablabla) <br>代わりにプレーンテキストが表示されます。

私のソリューションは、3レベル以上の目次が必要な人のための@Tum(非常にシンプル)のソリューションへの追加です。

2番目のレベルでは、単純なタブでインデントが正しく行われます。ただし、2つのタブはサポートされていません。&nbsp;代わりに、1つのタブを使用して、3番目のレベルを正しく調整するために必要な数だけ追加する必要があります。

これは4つのレベルを使用した例です(レベルが高くなると、ひどくなります):

# 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

これにより、目次のすべての要素が対応するセクションへのリンクである次の結果が得られます。<br>同じ行ではなく、新しい行を追加するためにも注意してください。

目次

  1. タイトル
    1.1。サブタイトル
           1.1.1。サブ
                     サブタイトル1.1.1.1。サブサブサブタイトル

タイトル

見出し1

字幕

見出し2

サブサブタイトル

見出し3

サブサブサブタイトル

見出し4

于 2019-01-28T03:02:38.593 に答える
2

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.

于 2021-02-12T15:09:02.753 に答える
1

ワークフローによっては、ストラップダウンを確認することをお勧めします

これは、目次の生成を追加する元のフォーク(http://strapdownjs.com )です。

htmlファイルに書き込みたくない場合は、その場でプレーンなマークダウンをラップするために、リポジトリにapache構成ファイルがあります(まだ適切に更新されていない可能性があります)。

于 2014-09-23T13:59:29.947 に答える
1

Eclipseを使用している場合は、Ctrl+ O(アウトライン)ショートカットを使用できます。これにより、目次に相当するものが表示され、セクションタイトルを検索できます(オートコンプリート)。

アウトラインビュー([ウィンドウ]->[ビューの表示]->[アウトライン])を開くこともできますが、オートコンプリート検索はありません。

于 2017-02-06T09:53:05.503 に答える
1

マークダウンの目次を生成する小さなPythonスクリプトであるtoc.pyを使用します。

使用法:

  • Markdownファイル<toc>で、目次を配置する場所を追加します。
  • $python toc.py README.md( README.mdの代わりにマークダウンファイル名を使用してください)

乾杯!

于 2018-08-29T19:24:17.943 に答える
1

私はhttps://github.com/ekalinin/github-markdown-tocを使用しました。これは、マークダウンドキュメントから目次を自動生成するコマンドラインユーティリティを提供します。

プラグイン、マクロ、その他の依存関係はありません。ユーティリティをインストールした後、ユーティリティの出力をドキュメント内の目次が必要な場所に貼り付けるだけです。使い方はとても簡単です。

$ cat README.md | ./gh-md-toc -
于 2019-01-24T19:05:08.300 に答える
1

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.

于 2020-07-04T13:22:45.180 に答える
0

[TOC]は最初の行で使用でき、次に下部で使用できます。必要なのは、タイトルが同じ大きなフォントであることを確認することだけです。目次は自動的に出てきます。(しかし、これは一部のマークダウンエディターにのみ表示されます。すべてを試したわけではありません)

于 2017-12-15T19:27:07.367 に答える
0

スライドの数を追加するだけです!それはマークダウンioslidesとrevealjsプレゼンテーションで動作します

## Table of Contents

 1. [introduction](#3)
 2. [section one](#5)
于 2018-10-16T12:17:35.927 に答える
0

TOCを生成し、見出しをアンカーで強化するために使用する短いPHPコードを次に示します。

$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);

次に、処理されたマークダウンとtocを印刷できます。

   print(implode("\n",$toc));
   print("\n\n");
   print($markdown);
于 2019-09-11T14:24:06.320 に答える
0

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.

于 2021-03-19T14:05:24.660 に答える
0

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.

于 2021-10-28T13:55:01.033 に答える
0

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
于 2021-11-04T06:56:40.750 に答える
-12

ええと...Markdownの見出しを使用してください!?

あれは:

#これは<h1>と同等です

##これは<h2>と同等です

###これは<h3>と同等です

多くの編集者が目次を表示します。見出しタグをgrepして、独自のタグを作成することもできます。

お役に立てば幸いです。

--JF

于 2013-06-19T18:31:55.457 に答える