521

我开始使用markdown做笔记。

我使用标记来查看我的降价笔记及其美丽。

但是随着我的笔记越来越长,我发现很难找到我想要的东西。

我知道markdown可以创建表格,但它是否能够创建目录,跳转到部分,或者在markdown中定义页面部分?

或者,是否有可以做这些事情的降价阅读器/编辑器。搜索也是一个很好的功能。

简而言之,我想让它成为我很棒的笔记工具和功能,就像写书等一样。

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 样式

另一段

第二段文字

于 2015-10-30T09:53:52.910 回答
107

对于Visual Studio Code用户来说,今天( 2020 年)使用的最佳选择是Markdown All in One插件。

要安装它,请启动 VS Code 快速打开 (Control/⌘</kbd>+P), paste the following command, and press enter.

ext install yzhang.markdown-all-in-one

要生成 TOC,请打开命令面板(Control/⌘</kbd>+Shift+P) and select the Select Markdown: Create Table of Contentsoption.


另一种选择是Markdown TOC插件。

要安装它,请启动 VS Code 快速打开 (Control/⌘</kbd>+P), paste the following command, and press enter.

ext install markdown-toc

要生成 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:请参阅Python Markdown TOC Extension

于 2012-08-19T23:38:30.947 回答
31

有两种方法可以在您的降价文档中创建您的TOC (摘要)。

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 -

我也尝试过其他脚本/npm 模块(例如doctoc),但没有人用工作锚重现 TOC。

于 2015-04-03T13:28:49.567 回答
30

您可以尝试使用这个 ruby​​ 脚本从 markdown 文件生成 TOC。

 #!/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}

如果您额外使用 markdown,请不要忘记您可以为链接、标题、代码围栏和图像添加特殊属性。
https://michelf.ca/projects/php-markdown/extra/#spe-attr

于 2017-09-08T22:09:11.850 回答
17

不同 Markdown 解析器生成的锚标签是不均匀的。

如果你正在使用 Markdown 解析器 GFM(GitHub Flavored Markdown)或 Redcarpet,我编写了一个 Vim 插件来处理目录。

特征

  1. 为 Markdown 文件生成目录。

    支持的 Markdown 解析器:

    • GFM(GitHub 风格的 Markdown)
    • 红地毯
  2. 更新现有目录。

  3. 保存时自动更新现有目录。

截图

vim-markdown-toc

用法

生成目录

将光标移动到要附加目录的行,然后在下面键入适合您的命令。该命令将在光标进入目录后生成标题。

  1. :GenTocGFM

    以 GFM 链接样式生成目录。

    此命令适用于 GitHub 存储库中的 Markdown 文件,例如 README.md,以及 GitBook 的 Markdown 文件。

  2. :GenTocRedcarpet

    以 Redcarpet 链接样式生成目录。

    此命令适用于 Jekyll 或其他任何使用 Redcarpet 作为其 Markdown 解析器的地方。

    您可以在此处查看以了解 GFM 和 Redcarpet 样式目录链接之间的区别。

手动更新现有目录

通常你不需要这样做,现有的目录默认会在保存时自动更新。如果要手动执行,只需使用:UpdateToc命令即可。

下载和文件

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

于 2016-10-25T04:57:18.670 回答
15

您还可以使用pandoc瑞士军刀”将“一种标记格式转换为另一种”--toc如果您提供参数,它可以在输出文档中自动生成目录。

提示:如果您想要html输出目录,您还需要提供-s生成独立文档的目录。

示例 shell 命令行:

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

在 Visual Studio Code (VSCode) 中,您可以使用扩展Markdown All in One

安装后,请按照以下步骤操作:

  1. CTRL+ SHIFT+P
  2. 选择Markdown:创建目录

编辑:现在我使用 DocToc 生成目录,有关详细信息,请参阅我的其他答案

于 2019-04-25T10:36:39.120 回答
11

在 Gitlab 上,markdown 支持这个:[[_TOC_]]

于 2019-02-22T14:34:29.237 回答
10

您可以使用这个 bash one-liner 来生成它。假设您的降价文件名为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 回答
10

为了我们这些在AtomREADME.md中制作文件的人的利益(我是如何找到这个线程的):

apm install markdown-toc

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

于 2016-07-26T21:45:39.963 回答
8

如果您想使用 javascript/node.js 工具,请查看markdown-toc

于 2014-08-03T07:27:25.627 回答
6

我刚刚为 编写了一个扩展python-markdown,它使用它的解析器来检索标题,并将 TOC 输出为带有本地链接的 Markdown 格式的无序列表。该文件是

...它应该放在markdown/extensions/markdown安装的目录中。然后,您所要做的就是键入<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

我编写了一个解析markdown文件并将目录输出为markdown列表的python脚本:md-to-toc

与我发现的其他脚本不同,md-to-toc 正确支持重复标题。它也不需要互联网连接,因此它适用于任何 md 文件,而不仅仅是那些可从公共 repo 获得的文件。

于 2015-06-05T04:31:03.700 回答
5

如果使用Sublime Text 编辑器MarkdownTOC 插件效果很好!看:

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

安装后,转到 Preferences --> Package Settings --> MarkdownTOC --> Settings -- User,自定义您的设置。以下是您可以选择的选项:https ://github.com/naokazuterada/MarkdownTOC#configuration 。

我推荐以下内容:

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

要插入目录,只需单击文档顶部要插入目录的位置,然后转到工具 --> Markdown TOC --> 插入目录。

它将插入如下内容:

<!-- MarkdownTOC -->

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

<!-- /MarkdownTOC -->

请注意<!-- -->它为您插入的 HTML 注释。这些是特殊标记,可帮助程序了解 ToC 的位置,以便在您每次保存时自动更新它!所以,让这些完好无损。

要获得额外的花哨,请在其周围添加一些HTML 标记<details><summary>以使 ToC 可折叠/可扩展,如下所示:

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

现在,你得到了这个超酷的效果,如下图所示。在我的主要 eRCaGuy_dotfiles 自述文件中查看它,或者在我的Sublime_Text_editor 自述文件中查看它。

  1. 折叠: 在此处输入图像描述
  2. 扩展: 在此处输入图像描述

有关其使用和限制的更多信息,请务必阅读我在该自述文件中关于MarkdownTOC插件的注释。

于 2020-11-03T04:48:56.640 回答
4

我刚开始做同样的事情(在 Markdown 中做笔记)。我将 Sublime Text 2 与MarkdownPreview 插件一起使用。内置的 markdown 解析器支持[TOC].

于 2014-11-12T05:39:04.430 回答
4

只需使用带有插件的文本编辑器即可。

您的编辑器很可能有一个包/插件来为您处理这个问题。例如,在Emacs中,您可以安装markdown-toc TOC 生成器。然后在您编辑时,只需反复调用M-x markdown-toc-generate-or-refresh-toc. 如果您想经常这样做,那值得一键绑定。它擅长生成简单的 TOC,而不会用 HTML 锚污染您的文档。

其他编辑器也有类似的插件,所以流行的列表是这样的:

于 2019-12-05T18:09:41.450 回答
4

作为手工制作链接列表的替代方案,让我们概述所有可用的开箱即用解决方案以插入目录(请评论并扩展以保持最新):

Gollum v5中,markdown 支持这一点:

<!-- assure you have a blank line before -->
[[_TOC_]]

这也适用于Azure DevOps wiki


由于Gitlab作为降价引擎从Redcarpet切换到 Kramdown ,它们现在支持以下语法

- TOC
{:toc}

https://about.gitlab.com/handbook/markdown-guide/#table-of-contents-toc


从 4.7开始的MultiMarkdown具有以下宏:

{{TOC}}

我知道,我对这个答案有点晚了。但是,我自己错过了这样的概述。我对 Nicolas Thery将其扩展到概述的回答的编辑被拒绝了。

于 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

有一个名为mdtoc.rb的 Ruby 脚本可以自动生成 GFM Markdown 目录,它与此处发布的其他一些脚本相似但略有不同。

给定一个输入 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

基于 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

我不确定,markdown 的官方文档是什么。交叉引用可以只写在括号中[Heading],也可以用空括号写[Heading][]

两者都使用pandoc工作。所以我创建了一个快速的 bash 脚本,它将$__TOC__在 md 文件中替换为它的 TOC。(您将需要 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

这是一个用于生成目录的简单 bash 脚本。不需要特殊的依赖,但是bash.

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

它可以很好地处理标题中的特殊符号、标题中的降价链接并忽略代码块。

于 2021-02-12T15:09:02.753 回答
2

对我来说,@Tum 提出的解决方案就像一个有 2 个级别的目录的魅力。但是,对于第 3 级,它不起作用。它没有像前 2 个级别那样显示链接,而是显示纯文本3.5.1. [bla bla bla](#blablabla) <br>

我的解决方案是对@Tum 解决方案(非常简单)的补充,适用于需要 3 级或更多级目录的人。

在第二层,一个简单的制表符将为您正确缩进。但它不支持 2 个选项卡。相反,您必须使用一个选项卡并&nbsp;自己添加任意数量的选项卡,以便正确对齐第 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

MultiMarkdown 4.7有一个插入目录的 {{TOC}} 宏。

于 2016-11-16T01:05:20.733 回答
1

根据您的工作流程,您可能需要查看捷联

这是原始版本 ( http://strapdownjs.com )的一个分支,它添加了目录的生成。

如果您不想在 html 文件中编写,repo 上有一个 apache 配置文件(可能尚未正确更新)以即时包装纯 markdown。

于 2014-09-23T13:59:29.947 回答
1

我使用了https://github.com/ekalinin/github-markdown-toc,它提供了一个命令行实用程序,可以从 Markdown 文档自动生成目录。

没有插件、宏或其他依赖项。安装实用程序后,只需将实用程序的输出粘贴到文档中您想要目录的位置。使用非常简单。

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

您可以使用DocToc 从命令行生成目录:

doctoc /path/to/file

要使链接与 Bitbucket 生成的锚点兼容,请使用--bitbucket参数运行它。

于 2020-07-04T13:22:45.180 回答
1

使用toc.py,它是一个很小的 ​​python 脚本,它为你的 markdown 生成一个目录。

用法:

  • 在您的 Markdown 文件中添加<toc>您希望放置目录的位置。
  • $python toc.py README.md(使用您的降价文件名而不是README.md

干杯!

于 2018-08-29T19:24:17.943 回答
1

如果您碰巧使用Eclipse,您可以使用Ctrl+ O(大纲)快捷方式,这将显示等效的目录并允许在部分标题中搜索(自动完成)。

您也可以打开大纲视图(窗口 -> 显示视图 -> 大纲),但它没有自动完成搜索。

于 2017-02-06T09:53:05.503 回答
0

我正在使用这个网站Markdown-TOC Creator,其中有些人可以粘贴他的整个 Markdown 条目,并且该网站会自动创建所有必需的标签和 TOC(目录),因此有些人可以轻松地将其复制粘贴到他自己的文档中。

于 2021-03-19T14:05:24.660 回答
0

您可以在第一行然后在底部使用 [TOC],您唯一需要做的就是确保标题使用相同的更大字体。目录会自动出现。(但这只出现在一些markdown编辑器中,我没有全部尝试)

于 2017-12-15T19:27:07.367 回答
0

这是我用来生成目录的简短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);

然后您可以打印处理后的降价和目录:

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

如果您使用的是折扣降价,请启用一个标志-ftoc以自动生成并用于-T添加目录,例如:

markdown -T -ftoc <<EOT
#heading 1

content 1

##heading 2

content 2
EOT

会产生

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

显然你也可以使用markdown -toc,这man没有提到,但USAGE信息确实(由非法选项触发,如markdown -h)。


我花了一段时间阅读源代码来弄清楚这一点,所以我主要是为了将来的我写下来。我在discount包中使用 Arch Linux 上的折扣降价。man并没有真正告诉你这是折扣,而是在下面提到了大卫帕森斯AUTHOR

markdown --version
# markdown: discount 2.2.7
于 2021-11-04T06:56:40.750 回答
0

只需添加幻灯片的数量!它适用于降价 ioslides 和revealjs 演示文稿

## Table of Contents

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

nodejs这是一个生成目录并考虑重复标题的小脚本:

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)

要使用它,您需要注入<toc/>您的降价文件。

以下是如何使用它:

generateTOC('../README.md', '../README_toc.md')

第一个参数是源 markdown 文件,第二个参数是带有 markdown 的文件。

于 2021-10-28T13:55:01.033 回答
-12

嗯...使用 Markdown 的标题!?

那是:

# 这相当于<h1>

## 这相当于 <h2>

### 这相当于<h3>

许多编辑会向您展示目录。您还可以使用 grep 获取标题标签并创建自己的标签。

希望有帮助!

--JF

于 2013-06-19T18:31:55.457 回答