【问题标题】:Markdown to create pages and table of contents?Markdown 创建页面和目录?
【发布时间】:2012-08-10 12:07:37
【问题描述】:

我开始用markdown做笔记了。

我使用 ma​​rked 来查看我的降价笔记及其精美。

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

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

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

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

【问题讨论】:

  • 如果你想使用 javascript/node.js 工具,试试marked-toc
  • @jonschlinkert 你应该提交它作为答案!目前,答案仅建议非免费或 Python 的工具。不是一个很好的选择。
  • 我应该提一下,在 LaTeX 中这是通过\tableofcontents 实现的。如果要重新发明轮子,最好复制好的部分。
  • 类似地,reStructuredText 有一个用于 table of contents 的内置指令,最简单的形式看起来就像 .. contents::

标签: markdown tableofcontents


【解决方案1】:

如果你碰巧使用Eclipse,你可以使用Ctrl+O(大纲)快捷键,这将显示对应的表格内容并允许在章节标题中搜索(自动完成)。

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

【讨论】:

    【解决方案2】:

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

    用法:

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

    干杯!

    【讨论】:

    • 您的脚本很好,但它不会在每个标题之前创建一个锚点。至少在 bitbucket 中是必需的。
    【解决方案3】:

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

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

    $ cat README.md | ./gh-md-toc -
    

    【讨论】:

      【解决方案4】:

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

      doctoc /path/to/file
      

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

      【讨论】:

        【解决方案5】:

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

        【讨论】:

        • Typora Markdown 是这样。可能还有其他人?
        【解决方案6】:

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

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

        【讨论】:

          【解决方案7】:

          这是一个简短的 PHP 代码,我使用它来生成 TOC,并使用锚来丰富任何标题:

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

          然后就可以打印处理后的markdown和toc了:

             print(implode("\n",$toc));
             print("\n\n");
             print($markdown);
          

          【讨论】:

            【解决方案8】:

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

            【讨论】:

              【解决方案9】:

              如果您使用Discount降价,启用标志-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 -tocman 没有提到,但USAGE 信息会(由markdown -h 等非法选项触发)。


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

              markdown --version
              # markdown: discount 2.2.7
              

              【讨论】:

                【解决方案10】:

                这是一个小的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)
                

                要使用它,您需要在 Markdown 文件中注入 &lt;toc/&gt;

                这里是你如何使用它:

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

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

                【讨论】:

                  【解决方案11】:

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

                  即:

                  #这相当于

                  ## 这相当于

                  ### 这相当于

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

                  希望有帮助!

                  --JF

                  【讨论】:

                  • 对我来说似乎是重复的答案。
                  猜你喜欢
                  • 2018-10-22
                  • 1970-01-01
                  • 2021-06-26
                  • 1970-01-01
                  • 2023-03-24
                  • 2021-12-02
                  • 2020-02-25
                  • 2021-10-31
                  • 2015-02-28
                  相关资源
                  最近更新 更多