如何在markdown模式下制作目录?

Big*_*eld 7 emacs markdown github-flavored-markdown

我在 markdown 模式下使用 emacs 来预览 Markdown 文档,但是在输入 Cx Cx p 后预览的 HTML 页面中没有目录。

cat ~/.emacs

(add-to-list 'load-path "~/.emacs.d")  

(autoload 'markdown-mode "markdown-mode"
   "Major mode for editing Markdown files" t)
(add-to-list 'auto-mode-alist '("\\.markdown\\'" . markdown-mode))
(add-to-list 'auto-mode-alist '("\\.md\\'" . markdown-mode))

(autoload 'gfm-mode "markdown-mode"
   "Major mode for editing GitHub Flavored Markdown files" t)
(add-to-list 'auto-mode-alist '("README\\.md\\'" . gfm-mode))

(custom-set-variables
 '(markdown-command "/usr/bin/pandoc --toc -f markdown_github -t html"))
Run Code Online (Sandbox Code Playgroud)

PS:我可以使用 pandoc 命令pandoc --toc -f markdown_github从 Markdown 文档中制作一个包含目录的 HTML 页面。

怎么解决呢?提前谢谢!

Ehv*_*nce 7

使用melpa 中的markdown-toc包非常简单。只需调用它M-x。

\n\n

来源:\xc2\xa0 http://wikemacs.org/wiki/Markdown#Generate_a_table_of_content

\n\n

如果您有许多相同的标题,则必须区分锚点,并且您将依赖 npm 的markdown-toc。

\n


Jos*_*sad 2

如果您有纪律在标题下插入命名锚点,如下所示:

## My heading
<a name="My heading"></a>
foo bar

My other heading
================
<a name="My other heading"></a>
baz qux
Run Code Online (Sandbox Code Playgroud)

那么下面的函数应该是一个合理的起点(不区分标题级别或任何东西,只是一点点 PoC)。

(defun my/make-markdown-toc ()
  "Makes a markdown ToC at the top of a md document."
  (interactive)
  (save-excursion
    (goto-char (point-min))
    (let ((list-of-headings))
      (while (search-forward-regexp markdown-regex-header nil 'noerror)
    (if (match-string 5)
        (push (match-string 5) list-of-headings))
    (if (match-string 1)
        (push (match-string 1) list-of-headings)))
      (message "I found %s matches" (length list-of-headings))
      (goto-char (point-min))
      (dolist (heading (reverse list-of-headings))
    (insert "1. [" heading "](#" heading ")\n")))))
Run Code Online (Sandbox Code Playgroud)

请注意,繁重的工作只是通过借用 markdown 模式的标题正则表达式来完成。