简体   繁体   English

github-flavored-markdown 中的自动 TOC

[英]Automatic TOC in github-flavoured-markdown

是否可以使用Github Flavored Markdown生成自动目录?

I created two options to generate a toc for github-flavored-markdown:我创建了两个选项来为 github-flavored-markdown 生成目录:

DocToc Command Line Tool ( source ) requires node.js DocToc 命令行工具 ( source ) 需要node.js

Installation: 安装:

npm install -g doctoc

Usage: 用法:

doctoc . to add table of contents to all markdown files in the current and all sub directories.将目录添加到当前和所有子目录中的所有降价文件。

DocToc WebApp DocToc WebApp

If you want to try it online first, go to the doctoc site, paste the link of the markdown page and it will generate a table of content that you can insert at the top of your markdown file. 如果您想先在线尝试,请转到 doctoc站点,粘贴 markdown 页面的链接,它将生成一个目录,您可以将其插入到 markdown 文件的顶部。

Github Wikis and Anchors Github Wiki 和锚点

As Matthew Flaschen pointed out in the comments below, for its wiki pages GitHub previously didn't generate the anchors that doctoc depends on.正如 Matthew Flaschen 在下面的评论中指出的那样,对于其 wiki 页面,GitHub 以前没有生成doctoc所依赖的锚点。

UPDATE: However, they fixed this issue .更新:但是,他们解决了这个问题

GitHub Pages (which is basically a wrapper for Jekyll) appears to use kramdown , which implements all of Maruku , and therefore has support for an automatically generated table of contents via a toc attribute: GitHub Pages(基本上是 Jekyll 的包装器) 似乎使用 kramdown ,它实现了所有Maruku ,因此支持通过toc属性自动生成的目录

* auto-gen TOC:
{:toc}

The first line just starts an unordered list and is actually thrown away.第一行只是开始一个无序列表,实际上被丢弃了。

This results in a nested set of unordered lists, using the headers in the document.这会使用文档中的标题生成一组嵌套的无序列表。

Note: this should work for GitHub Pages, not GitHub Flavored Markdown (GFM) as used in comments or wiki pages.注意:这应该适用于 GitHub Pages,而不适用于评论或 wiki 页面中使用的 GitHub Flavored Markdown (GFM)。 AFAIK a solution doesn't exist for that. AFAIK 对此不存在解决方案。

If you edit Markdown files with Vim, you can try this plugin vim-markdown-toc .如果你用 Vim 编辑 Markdown 文件,你可以试试这个插件vim-markdown-toc

The usage is simple, just move your cursor to the place you want to append Table of Contents and run :GenTocGFM , done!用法很简单,只需将光标移动到要附加目录的位置并运行:GenTocGFM ,完成!

Screenshots:截图:

vim-markdown-toc

Features:特征:

  1. Generate toc for Markdown files.为 Markdown 文件生成目录。 (Support GitHub Flavored Markdown and Redcarpet) (支持 GitHub Flavored Markdown 和 Redcarpet)

  2. Update existing toc.更新现有目录。

  3. Auto update toc on save.保存时自动更新目录。

Update March 2021: GitHub added an official workaround 2021 年 3 月更新:GitHub 添加了官方解决方法

READMEs now show a ToC like this as you scroll down into them:当您向下滚动到自述文件时,自述文件现在会显示这样的 ToC:

在此处输入图像描述

demo: https://github.com/cirosantilli/test-git-web-interface/tree/master/d演示: https ://github.com/cirosantilli/test-git-web-interface/tree/master/d

It does not render inside the document as I wanted for better Ctrl + F, but it is better than nothing.它不会像我想要的那样在文档中呈现更好的 Ctrl + F,但总比没有好。

Also also works for non-README as well now, eg: https://github.com/cirosantilli/test-git-web-interface/blob/master/md.md现在也适用于非自述文件,例如: https ://github.com/cirosantilli/test-git-web-interface/blob/master/md.md

They also added a repository setting to enable disable that.他们还添加了一个存储库设置来启用禁用它。 It's so weird, who would ever want to disable it?这太奇怪了,谁会想要禁用它? Underhttps://github.com/cirosantilli/test-git-web-interface/settings Features:https://github.com/cirosantilli/test-git-web-interface/settings下功能:

Table of contents目录

Autogenerate table of contents for Markdown files in this repository.自动为此存储库中的 Markdown 文件生成目录。 The table of contents will be displayed near the top of the file.目录将显示在文件顶部附近。

Original answer原始答案

It's not possible, except for the workarounds proposed.这是不可能的,除了建议的解决方法。

I proposed Kramdown TOC extension and other possibilities to support@github.com and Steven!我向 support@github.com 和Steven提出了Kramdown TOC 扩展和其他可能性! Ragnarök replied with the usual:诸神黄昏以平常的方式回答:

Thanks for the suggestion and links.感谢您的建议和链接。 I'll add it to our internal feature request list for the team to see.我会将它添加到我们的内部功能请求列表中,以供团队查看。

Let's upvote this question until it happens.让我们支持这个问题,直到它发生。

Another workaround is to use Asciidoc instead of Markdown, which does render TOCs .另一种解决方法是使用 Asciidoc 而不是 Markdown, 后者会渲染 TOC I've moved to this approach for my content nowadays.我现在已经转向这种方法来处理我的内容。

It's not automatic, but it uses Notepad++ regular expressions:它不是自动的,但它使用 Notepad++ 正则表达式:

Replace all first by the second (removes all lines not having headers)将所有第一个替换为第二个(删除所有没有标题的行)

^##(#?)(#?)(.*?)$(.|\r|\n)*?(?=^##|\z)
-\1\2 [\3](#\3)\n

Then (converts headers III to spaces)然后(将标题 III 转换为空格)

-##
        -

Then (converts headers II to spaces)然后(将标题 II 转换为空格)

-#
    -

Then (remove unused chars at the beginning and at the end of link title)然后(删除链接标题开头和结尾未使用的字符)

\[ *((?:(?![ .:#!\?;]*\])[^#])*)[ #:!\?;]*\]
[\1]

Then (convert last tokens lowercase and dash instead of spaces)然后(将最后一个标记转换为小写和破折号而不是空格)

\]([^ \r\n]*) ([^\r\n ]*)
]\L\1-\2

Remove unused final pounds and initial dashes:删除未使用的最终磅数和初始破折号:

(?:()[-:;!\?#]+$|(\]#)-)
\1\2

Remove useless chars in links:删除链接中的无用字符:

(\].*?)(?:\(|\))
\1

And finally add parenthesis around final links:最后在最终链接周围添加括号:

\](?!\()(.*?)$
\]\(\1\)

And voilà!瞧! You can even put this in a global macro if you repeat it enough time.如果你重复足够的时间,你甚至可以把它放在一个全局宏中。

Github Flavored Markdown uses RedCarpet as their Markdown engine. Github Flavored Markdown 使用 RedCarpet 作为他们的 Markdown 引擎。 From the RedCarpet repo :红地毯回购

:with_toc_data - add HTML anchors to each header in the output HTML, to allow linking to each section. :with_toc_data - 将 HTML 锚点添加到输出 HTML 中的每个标题,以允许链接到每个部分。

It seems in that you'd need to get at the renderer level to set this flag, which isn't possible on Github obviously.似乎您需要在渲染器级别设置此标志,这显然在 Github 上是不可能的。 However, the latest update to Github Pages, it seems that automatic anchoring is turned on for headers, creating linkable headings.但是,Github Pages 的最新更新,似乎为标题打开了自动锚定,创建了可链接的标题。 Not exactly what you want, but it might help you create a TOC for your doc a bit easier (albeit manually).不完全是您想要的,但它可能会帮助您更轻松地为您的文档创建目录(尽管是手动的)。

A very convenient way to achieve a table of contents for a mardown file when working with Visual Studio Code is the extension Markdown-TOC .在使用 Visual Studio Code 时,为 mardown 文件获取目录的一种非常方便的方法是扩展Markdown-TOC

It can add a toc to existing markdown files and even keep the toc up-to-date on saving.它可以将目录添加到现有的降价文件中,甚至可以在保存时使目录保持最新。

在此处输入图像描述

It is possible to generate a webpage automatically with http://documentup.com/ from the README.md file.可以使用README.md文件中的http://documentup.com/自动生成网页。 It's not creating a TOC, but for many it might solve the reason for wanting to create a TOC.它不是创建 TOC,但对许多人来说,它可能解决了想要创建 TOC 的原因。

Another alternative to Documentup is Flatdoc: http://ricostacruz.com/flatdoc/ Documentup 的另一个替代方案是 Flatdoc: http: //ricostacruz.com/flatdoc/

Gitdown is a markdown preprocessor for Github. Gitdown是 Github 的降价预处理器。

Using Gitdown you can:使用 Gitdown,您可以:

  • Generate Table of Contents生成目录
  • Find dead URLs and Fragment Identifiers查找死 URL 和片段标识符
  • Include variables包括变量
  • Include files包含文件
  • Get file size获取文件大小
  • Generate Badges生成徽章
  • Print Date打印日期
  • Print information about the repository itself打印关于存储库本身的信息

Gitdown streamlines common tasks associated with maintaining a documentation page for a GitHub repository. Gitdown 简化了与维护 GitHub 存储库的文档页面相关的常见任务。

Using it is straightforward:使用它很简单:

var Gitdown = require('gitdown');

Gitdown
    // Gitdown flavored markdown.
    .read('.gitdown/README.md')
    // GitHub compatible markdown.
    .write('README.md');

You can either have it as a separate script or have it as part of the build script routine (such as Gulp ).您可以将其作为单独的脚本,也可以将其作为构建脚本例程的一部分(例如Gulp )。

使用coryfklein/doctoc ,这是thlorenz/doctoc的一个分支,它不会将“使用DocToc生成”添加到每个目录中。

npm install -g coryfklein/doctoc

Majority of other answers require to install some tool.大多数其他答案需要安装一些工具。 I found a quick and easy online solution https://imthenachoman.github.io/nGitHubTOC .我找到了一个快速简单的在线解决方案https://imthenachoman.github.io/nGitHubTOC

For any markdown input it generates table of content output.对于任何降价输入,它都会生成内容输出表。 You can specify minimum and maximum heading level.您可以指定最小和最大航向级别。

The source code is located at https://github.com/imthenachoman/nGitHubTOC源代码位于https://github.com/imthenachoman/nGitHubTOC

My colleague @schmiedc and I have created a GreaseMonkey script that installs a new TOC button left of the h1 button which uses the excellent markdown-js library to add/refresh a table of contents.我的同事@schmiedc 和我创建了一个 GreaseMonkey 脚本,它在h1按钮左侧安装了一个新的TOC按钮,该按钮使用出色的markdown-js库来添加/刷新目录。

The advantage over solutions like doctoc is that it integrates into GitHub's wiki editor and does not need users to work on their command-line (and require users to install tools like node.js ).与 doctoc 之类的解决方案相比,它的优势在于它集成到 GitHub 的 wiki 编辑器中,并且不需要用户在他们的命令行上工作(并且需要用户安装诸如node.js之类的工具)。 In Chrome, it works by drag 'n dropping into the Extensions page, in Firefox you will need to install the GreaseMonkey extension.在 Chrome 中,它通过拖放到扩展页面中来工作,在 Firefox 中,您需要安装 GreaseMonkey 扩展。

It will work with plain markdown (ie it does not handle code blocks correctly, as that is a GitHub extension to markdown).它将与普通的降价一起工作(即它不能正确处理代码块,因为那是降价的 GitHub 扩展)。 Contributions welcome.欢迎投稿。

This is a not a direct answer to this question as so many people have provided workarounds.这不是对这个问题的直接答案,因为很多人都提供了解决方法。 I don't think generating a TOC has been officially supported by Github yet to-date.我认为到目前为止,Github 还没有正式支持生成 TOC。 If you want GitHub to render a Table of Contents on their GFM preview pages automatically, please participate the discussion on the official feature request issue .如果您希望 GitHub 在其 GFM 预览页面上自动呈现目录,请参与官方功能请求问题的讨论。

Shameless "borrow" of this SO answer .这个 SO 答案的无耻“借用”。

You can do this with Pandoc .你可以用Pandoc做到这一点。

pandoc -s --toc input.md -o input_toc.md 

Note: the order of the input and output files is important here.注意:输入和输出文件的顺序在这里很重要。

Currently it's not possible using markdown syntax (see the ongoing discussion at GitHub ), however you can use some external tools such as:目前无法使用 markdown 语法(请参阅GitHub 上正在进行的讨论),但是您可以使用一些外部工具,例如:


Alternatively use AsciiDoc instead (eg README.adoc ), eg或者使用AsciiDoc代替(例如README.adoc ),例如

:toc: macro
:toc-title:
:toclevels: 99
# Title

## A

### A2

## B

### B2

as suggested in this comment .正如本评论中所建议的那样。 Check the demo here .此处查看演示。

For Github's Texteditor Atom check out this awesome plugin (or "package" in Atom-lingo), which generates "TOC (table of contents) of headlines from parsed markdown" files:对于Github 的 Texteditor Atom ,请查看这个很棒的插件(或 Atom-lingo 中的“包”),它从已解析的降价文件中生成“TOC(目录)标题”

markdown-toc降价目录

Once installed as Atom-package you can use the shortcut ctrl-alt-c to insert a TOC based on your markdown-doc-structure at the current cursor position...一旦作为 Atom-package 安装,您可以使用快捷键ctrl-alt-c在当前光标位置根据您的 markdown-doc-structure 插入 TOC ...

Screenshots:截图:

在此处输入图像描述

Atom Keybindings原子键绑定

markdown-toc gives you the following default key-bindings to control the plugin in Atom: markdown-toc 为您提供以下默认键绑定来控制 Atom 中的插件:

  • ctrl-alt-c => create TOC at cursor position ctrl-alt-c => 在光标位置创建目录
  • ctrl-alt-u => update TOC ctrl-alt-u => 更新目录
  • ctrl-alt-r => delete TOC ctrl-alt-r => 删除目录

Plugin Features (from the project's README)插件功能(来自项目的自述文件)

  • Auto linking via anchor tags, eg # A 1#a-1通过锚标签自动链接,例如# A 1#a-1
  • Depth control [1-6] with depthFrom:1 and depthTo:6深度控制 [1-6] 与depthFrom:1depthTo:6
  • Enable or disable links with withLinks:1使用withLinks:1启用或禁用链接
  • Refresh list on save with updateOnSave:1使用updateOnSave:1在保存时刷新列表
  • Use ordered list (1. ..., 2. ...) with orderedList:0使用有序列表 (1. ..., 2. ...) 和orderedList:0

Here's a shell script I threw together today for this.这是我今天为此编写的一个 shell 脚本。 Might need to tweak it for your needs, but it should be a good starting point.可能需要根据您的需要对其进行调整,但这应该是一个很好的起点。

cat README.md \
    | sed -e '/```/ r pf' -e '/```/,/```/d' \
    | grep "^#" \
    | tail -n +2 \
    | tr -d '`' \
    | sed 's/# \([a-zA-Z0-9`. -]\+\)/- [\1](#\L\1)/' \
    | awk -F'(' '{for(i=2;i<=NF;i++)if(i==2)gsub(" ","-",$i);}1' OFS='(' \
    | sed 's/^####/      /' \
    | sed 's/^###/    /' \
    | sed 's/^##/  /' \
    | sed 's/^#//'

If anyone knows a better way to do those final # replacements, please add a comment.如果有人知道更好的方法来完成最后的 # 替换,请添加评论。 I tried various things and wasn't happy with any, so I just brute forced it.我尝试了各种各样的事情,但对任何事情都不满意,所以我只是蛮力的。

There's now a GitHub Action accomplishing this:现在有一个 GitHub Action 来完成这个:

https://github.com/marketplace/actions/toc-generator https://github.com/marketplace/actions/toc-generator

  1. Specify location of TOC (option) eg README.md指定目录(选项)的位置,例如README.md
<!-- START doctoc -->
<!-- END doctoc -->
  1. Setup workflow eg .github/workflows/toc.yml设置工作流程,例如.github/workflows/toc.yml
on: push
name: TOC Generator
jobs:
  generateTOC:
    name: TOC Generator
    runs-on: ubuntu-latest
    steps:
      - uses: technote-space/toc-generator@v2

Update 2022-02 2022-02 更新

In VSCode, check out extension "Markdown All in One".在 VSCode 中,查看扩展“Markdown All in One”。 It will generate and update the TOC of markdown automatically.它会自动生成和更新markdown的TOC。

  1. Install Extension.安装扩展。
  2. Place cursor at where you want to insert TOC.将光标放在要插入 TOC 的位置。
  3. Run command "Markdown All in One: Create Table of Contents"运行命令“Markdown All in One:创建目录”
  4. Enjoy!享受!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM