使用 Sphinx 与 Markdown 而不是 reST

发布于 2024-08-25 11:39:30 字数 68 浏览 7 评论 0 原文

我讨厌休息,但喜欢狮身人面像。 Sphinx 有没有办法读取 Markdown 而不是 reStructuredText?

I hate reST but love Sphinx. Is there a way that Sphinx reads Markdown instead of reStructuredText?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(12

堇色安年 2024-09-01 11:39:30

您可以在同一个 Sphinx 项目中使用 Markdown 和 reStructuredText。
Sphinx 文档 中简洁地记录了如何执行此操作。

安装myst-parserpip install myst-parser),然后编辑conf.py

# simply add the extension to your list of extensions
extensions = ['myst_parser']

source_suffix = ['.rst', '.md']

我创建了一个小型示例项目Github (serra/sphinx-with-markdown) 演示其工作原理。它使用 Sphinx 版本 3.5.4 和 myst-parser 版本 0.14.0。

事实上,MyST 解析器 允许您用 Markdown 编写整个 Sphinx 文档。它支持指令并具有多个扩展,您可以通过 conf.py 中的配置启用。

MyST 解析器需要 Sphinx 2.1 或更高版本。对于早期版本的 Sphinx,您可以使用 recommonmark 在 Sphinx 中使用 Markdown。查看此答案的早期修订以了解具体方法。

You can use Markdown and reStructuredText in the same Sphinx project.
How to do this is succinctly documented in the Sphinx documentation.

Install myst-parser (pip install myst-parser) and then edit conf.py:

# simply add the extension to your list of extensions
extensions = ['myst_parser']

source_suffix = ['.rst', '.md']

I've created a small example project on Github (serra/sphinx-with-markdown) demonstrating how (and that) it works. It uses Sphinx version 3.5.4 and myst-parser version 0.14.0.

In fact, MyST parser allows you to write your entire Sphinx documentation in Markdown. It supports directives and has several extensions you can enable through configuration in conf.py.

MyST parser requires Sphinx 2.1 or later. For earlier versions of Sphinx, you could use Markdown in Sphinx using recommonmark. Checkout earlier revisions of this answer to find out how.

蛮可爱 2024-09-01 11:39:30

“正确”的方法是编写 docutils用于降价的解析器。 (加上一个 Sphinx 选项来选择解析器。)这样做的好处是立即支持所有 docutils 输出格式(但您可能不关心这一点,因为大多数情况下都已经存在类似的 Markdown 工具)。
无需从头开始开发解析​​器即可实现此目的的方法:

  1. 您可以欺骗并编写一个使用 Pandoc< 的“解析器” /a> 将 markdown 转换为 RST 并将其传递给 RST 解析器:-)。


  2. 您可以使用现有的 markdown->XML 解析器并将结果(使用 XSLT?)转换为 docutils 架构。

  3. 你可以使用一些现有的python markdown解析器,它可以让你定义一个自定义渲染器并使其构建 docutils 节点树。

  4. 您可以分叉现有的 RST 阅读器,删除与 Markdown 无关的所有内容并更改不同的语法(this比较可能有帮助)...
    编辑:我不推荐这条路线,除非你准备好对其进行大量测试。 Markdown 已经有太多细微不同的方言,这可能会导致另一种......


更新: https://github.com/sgenoud/remarkdown 是 docutils 的 Markdown 阅读器。它没有采用任何上述快捷方式,而是使用 Parsley PEG 语法,灵感来自 peg-markdown

更新:https://github.com/readthedocs/recommonmark 是另一个 docutils 阅读器, ReadTheDocs 原生支持。 源自 remarkdown,但使用 CommonMark-py 解析器。

  • 可以将特定的或多或少自然的 Markdown 语法转换为适当的结构,例如目录树的链接列表。
  • 没有角色的通用本机语法。
  • 支持使用 ```eval_rst 防护块 以及指令 DIRECTIVE_NAME:: ... 的简写。

更新MyST 是另一个 docutins/Sphinx 阅读器。基于 markdown-it-py,兼容 CommonMark。

  • 具有角色的通用 {ROLE_NAME}`...` 语法。
  • 具有带有 ```{DIRECTIVE_NAME} ... 防护块的指令的通用语法。

所有情况下,您都需要发明 Markdown 的扩展来表示 Sphinx 指令和角色。虽然您可能不需要全部,但像 .. toctree:: 这样的一些是必不可少的。
我认为这是最难的部分。 Sphinx 扩展之前的 reStructuredText 已经比 Markdown 更丰富了。即使是大量扩展的 markdown,例如 pandoc 的,也大多是 rST 功能的子集放。有很多内容需要涵盖!

在实现方面,最简单的事情是添加通用构造来表达任何文档角色/指令。语法灵感的明显候选者是:

  • 属性语法,pandoc 和其他一些实现已经允许许多内联和块构造。例如 `foo`{.method} -> `foo`:方法:
  • HTML/XML。从 foo 到仅插入 docutils 内部 XML 的最笨方法!
  • 某种 YAML 指令?

但是这样的通用映射不会是最 Markdown 的解决方案......

这也意味着您不能只重用 Markdown 解析器而不以某种方式扩展它。 Pandoc 通过支持自定义过滤器,再次不负文档转换瑞士军刀的声誉。 (事实上​​,如果我要解决这个问题,我会尝试在 docutils 读取器/变压器/写入器和 pandoc 读取器/过滤器/写入器之间建立一个通用桥梁。这超出了您的需要,但回报将比 sphinx/ 广泛得多markdown。)


另一种疯狂的想法:不是扩展 markdown 来处理 Sphinx,而是扩展 reStructuredText 以支持(大部分)markdown 的超集!美妙之处在于您将能够按原样使用 Sphinx 的任何功能,同时能够以 Markdown 格式编写大部分内容。

已经存在相当多的语法重叠;最值得注意的是链接语法不兼容。我认为如果您添加对 Markdown 链接和 ### 样式标头的 RST 支持,并将默认的 `backticks` 角色更改为文字,并且可能将缩进块更改为均值文字(RST 现在支持 > ... 进行引用),您将获得支持大多数 Markdown 的可用内容。

The "proper" way to do that would be to write a docutils parser for markdown. (Plus a Sphinx option to choose the parser.) The beauty of this would be instant support for all docutils output formats (but you might not care about that, as similar markdown tools already exist for most).
Ways to approach that without developing a parser from scratch:

  1. You could cheat and write a "parser" that uses Pandoc to convert markdown to RST and pass that to the RST parser :-).

  2. You can use an existing markdown->XML parser and transform the result (using XSLT?) to the docutils schema.

  3. You could take some existing python markdown parser that lets you define a custom renderer and make it build docutils node tree.

  4. You could fork the existing RST reader, ripping out everything irrelevant to markdown and changing the different syntaxes (this comparison might help)...
    EDIT: I don't recommend this route unless you're prepared to heavily test it. Markdown already has too many subtly different dialects and this will likely result in yet-another-one...


UPDATE: https://github.com/sgenoud/remarkdown is a markdown reader for docutils. It didn't take any of the above shortcuts but uses a Parsley PEG grammar inspired by peg-markdown.

UPDATE: https://github.com/readthedocs/recommonmark and is another docutils reader, natively supported on ReadTheDocs. Derived from remarkdown but uses the CommonMark-py parser.

  • It can convert specific more-or-less natural Markdown syntaxes to appropriate structures e.g. list of links to a toctree.
  • Doesn't have generic native syntax for roles.
  • Supports embedding any rST content, including directives, with an ```eval_rst fenced block as well as a shorthand for directives DIRECTIVE_NAME:: ....

UPDATE: MyST is yet another docutins/Sphinx reader. Based on markdown-it-py, CommonMark compatible.

  • Has a generic {ROLE_NAME}`...` syntax for roles.
  • Has a generic syntax for directives with ```{DIRECTIVE_NAME} ... fenced blocks.

In all cases, you'll need to invent extensions of Markdown to represent Sphinx directives and roles. While you may not need all of them, some like .. toctree:: are essential.
This I think is the hardest part. reStructuredText before the Sphinx extensions was already richer than markdown. Even heavily extended markdown, such as pandoc's, is mostly a subset of rST feature set. That's a lot of ground to cover!

Implementation-wise, the easiest thing is adding a generic construct to express any docutils role/directive. The obvious candidates for syntax inspiration are:

  • Attribute syntax, which pandoc and some other implementations already allow on many inline and block constructs. For example `foo`{.method} -> `foo`:method:.
  • HTML/XML. From <span class="method">foo</span> to the kludgiest approach of just inserting docutils internal XML!
  • Some kind of YAML for directives?

But such a generic mapping will not be the most markdown-ish solution...

This also means you can't just reuse a markdown parser without extending it somehow. Pandoc again lives up to its reputation as the swiss army knife of document conversion by supporting custom filters. (In fact, if I were to approach this I'd try to build a generic bridge between docutils readers/transformers/writers and pandoc readers/filters/writers. It's more than you need but the payoff would be much wider than just sphinx/markdown.)


Alternative crazy idea: instead of extending markdown to handle Sphinx, extend reStructuredText to support (mostly) a superset of markdown! The beauty is you'll be able to use any Sphinx features as-is, yet be able to write most content in markdown.

There is already considerable syntax overlap; most notably link syntax is incompatible. I think if you add support to RST for markdown links, and ###-style headers, and change default `backticks` role to literal, and maybe change indented blocks to mean literal (RST supports > ... for quotations nowdays), you'll get something usable that supports most markdown.

黑寡妇 2024-09-01 11:39:30

2021 年 5 月更新: recommonmark 已弃用,转而使用 myst-parser(感谢 astrojuanlu)

更新:现在已正式支持并记录在 sphinx 文档

看起来 Sphinx 已经有了一个基本的实现,但消息还没有传开。 查看 github 问题评论

安装依赖项:

pip install commonmark recommonmark

调整 conf. py

source_parsers = {
    '.md': 'recommonmark.parser.CommonMarkParser',
}
source_suffix = ['.rst', '.md']

Update May 2021: recommonmark is deprecated in favour of myst-parser (thanks astrojuanlu)

Update: this is now officially supported and documented in the sphinx docs.

It looks like a basic implementation has made it's way into Sphinx but word has not gotten round yet. See github issue comment

install dependencies:

pip install commonmark recommonmark

adjust conf.py:

source_parsers = {
    '.md': 'recommonmark.parser.CommonMarkParser',
}
source_suffix = ['.rst', '.md']
沒落の蓅哖 2024-09-01 11:39:30

这不使用 Sphinx,但 MkDocs 将使用 Markdown 构建您的文档。我也讨厌 rst,但到目前为止我真的很喜欢 MkDocs。

This doesn't use Sphinx, but MkDocs will build your documentation using Markdown. I also hate rst, and have really enjoyed MkDocs so far.

一个人的旅程 2024-09-01 11:39:30

Markdown 和 ReST 做不同的事情。

RST 提供了一个用于处理文档的对象模型。

Markdown 提供了一种雕刻文本位的方法。

想要引用 sphinx 项目中的 Markdown 内容,使用 RST 来消除较大文档的整体信息架构和流程,这似乎是合理的。让 Markdown 发挥它的作用,让作者专注于撰写文本。

有没有办法引用 Markdown 域,只是按原样雕刻内容? RST/sphinx 似乎已经处理了像 toctree 这样的功能,而没有在 markdown 中重复它们。

Markdown and ReST do different things.

RST provides an object model for working with documents.

Markdown provides a way to engrave bits of text.

It seems reasonable to want to reference your bits of Markdown content from your sphinx project, using RST to stub out the overall information architecture and flow of a larger document. Let markdown do what it does, which is allow writers to focus on writing text.

Is there a way to reference a markdown domain, just to engrave the content as-is? RST/sphinx seems to have taken care of features like toctree without duplicating them in markdown.

清引 2024-09-01 11:39:30

我建议使用 MyST Markdown。这是 Markdown 的一种风格,旨在引入 reStructuredText 的主要功能。 MyST 代表Markedly Structured Text,可以被认为是“rST but with Markdown”。

MyST 是 CommonMark 标准的超集,它通过 < 定义为 CommonMark 离散扩展的集合代码>markdown-it-py包)。这意味着 CommonMark 语法可以开箱即用地与 MyST 一起使用,但如果您愿意,您也可以使用更多语法功能。

MyST 具有适用于 reStructuredText 中几乎所有功能的语法,并且针对完整的 Sphinx 测试套件进行了测试,以确保可以重新创建相同的功能。例如:

以下是如何在 MyST 中编写指令

```{directivename} directive options
:key: value
:key2: value2

Directive content
```

以下是如何在 MyST 中编写角色

Here's some text and a {rolename}`role content`

MyST Markdown 的 Sphinx 解析器也有一些很好的特定于 Sphinx 的内容功能,例如使用 Markdown 链接语法 ([some text](somelink)) 来处理 Sphinx 中的交叉引用。例如,您可以在 MyST 中定义一个标签,并引用它,如下所示:

(my-label)=
# My header

Some text and a [cross reference](my-label).

有关 MyST Markdown 语法的更完整列表,一个很好的参考是 Jupyter Book cheatsheet,其中列出了许多常见文档需求以及完成它的相应 MyST 语法。 (MyST 是作为 Jupyter Book 的一个组件创建的,尽管从技术角度来看它是一个完全独立的项目)。

MyST 现在是Sphinx 文档中推荐的 Sphinx Markdown 工具以及ReadTheDocs文档

要将 MyST 解析器添加到您的 Sphinx 文档中,只需执行以下操作:

pip install myst-parser

并在 conf.py 中添加:

extensions = [
  ...
  "myst_parser",
  ...
]

您的 Sphinx 文档现在将能够解析 CommonMark markdown 以及扩展的 MyST Markdown 语法!查看 MyST 文档 了解更多信息!

我希望这有助于澄清一些事情!

I recommend using MyST Markdown. This is a flavor of Markdown that was designed to bring in the major features of reStructuredText. MyST stands for Markedly Structured Text, and can be thought of as "rST but with Markdown".

MyST is a superset of the CommonMark standard, and it is defined as a collection of discrete extensions to CommonMark via the markdown-it-py package). This means that CommonMark syntax works out-of-the-box with MyST, but you can also use more syntax features if you wish.

MyST has syntax for virtually every feature in reStructuredText, and it is tested against the full Sphinx test suite to ensure that the same functionality can be re-created. For example:

Here is how you write a directive in MyST:

```{directivename} directive options
:key: value
:key2: value2

Directive content
```

And here is how you write a role in MyST

Here's some text and a {rolename}`role content`

The Sphinx parser for MyST Markdown also has some nice Sphinx-specific features, like using Markdown link syntax ([some text](somelink)) to also handle cross-references in Sphinx. So for example, you can define a label in MyST, and reference it, like so:

(my-label)=
# My header

Some text and a [cross reference](my-label).

For a more complete list of MyST Markdown syntax, a good reference is the Jupyter Book cheatsheet, which has a list of many common document needs and the respective MyST syntax to accomplish it. (MyST was created as a component of Jupyter Book, though it exists as a totally standalone project from a technical perspective).

MyST is now the recommended Markdown tool for Sphinx in the Sphinx docs as well as the ReadTheDocs documentation.

To add the MyST Parser to your Sphinx documentation, simply do the following:

pip install myst-parser

And in conf.py, add:

extensions = [
  ...
  "myst_parser",
  ...
]

Your Sphinx documentation will now be able to parse CommonMark markdown as well as the extended MyST Markdown syntax! Check out the MyST Documentation for more information!

I hope that this helps clarify some things!

饭团 2024-09-01 11:39:30

现在正式支持:http://www.sphinx-doc.org/ en/stable/markdown.html

另请参阅 https:// /myst-parser.readthedocs.io/en/latest/syntax/Optional.html 用于扩展,包括 linkify 使 URL 自动链接。

This is now officially supported: http://www.sphinx-doc.org/en/stable/markdown.html

See also https://myst-parser.readthedocs.io/en/latest/syntax/optional.html for extensions, including linkify to make urls automatic links.

眼泪淡了忧伤 2024-09-01 11:39:30

我采纳了 Beni 的建议,使用 pandoc 来完成这项任务。安装后,以下脚本会将源目录中的所有 Markdown 文件转换为 rst 文件,以便您可以在 Markdown 中编写所有文档。希望这对其他人有用。

#!/usr/bin/env python
import os
import subprocess

DOCUMENTATION_SOURCE_DIR = 'documentation/source/'
SOURCE_EXTENSION = '.md'
OUTPUT_EXTENSION = '.rst'

for _, __, filenames in os.walk(DOCUMENTATION_SOURCE_DIR):
    for filename in filenames:
        if filename.endswith('.md'):
            filename_stem = filename.split('.')[0]
            source_file = DOCUMENTATION_SOURCE_DIR + filename_stem + SOURCE_EXTENSION
            output_file = DOCUMENTATION_SOURCE_DIR + filename_stem + OUTPUT_EXTENSION
            command = 'pandoc -s {0} -o {1}'.format(source_file, output_file)
            print(command)
            subprocess.call(command.split(' '))

I went with Beni's suggestion of using pandoc for this task. Once installed the following script will convert all markdown files in the source directory to rst files, so that you can just write all your documentation in markdown. Hope this is useful for others.

#!/usr/bin/env python
import os
import subprocess

DOCUMENTATION_SOURCE_DIR = 'documentation/source/'
SOURCE_EXTENSION = '.md'
OUTPUT_EXTENSION = '.rst'

for _, __, filenames in os.walk(DOCUMENTATION_SOURCE_DIR):
    for filename in filenames:
        if filename.endswith('.md'):
            filename_stem = filename.split('.')[0]
            source_file = DOCUMENTATION_SOURCE_DIR + filename_stem + SOURCE_EXTENSION
            output_file = DOCUMENTATION_SOURCE_DIR + filename_stem + OUTPUT_EXTENSION
            command = 'pandoc -s {0} -o {1}'.format(source_file, output_file)
            print(command)
            subprocess.call(command.split(' '))
辞慾 2024-09-01 11:39:30

这是一个新选项。 MyST 向 Markdown 添加了一些功能,允许 Sphinx 像 rst 一样构建文档。
https://myst-parser.readthedocs.io/en/latest/

Here’s a new option. MyST adds some features to Markdown that allow Sphinx to build docs like rst does.
https://myst-parser.readthedocs.io/en/latest/

一向肩并 2024-09-01 11:39:30

有一个解决方法。
sphinx-quickstart.py 脚本生成一个 Makefile。
每次您想要生成文档以将 Markdown 转换为 reStructuredText 时,您都可以轻松地从 Makefile 调用 Pandoc。

There is a workaround.
The sphinx-quickstart.py script generates a Makefile.
You can easily invoke Pandoc from the Makefile every time you'd like to generate the documentation in order to convert Markdown to reStructuredText.

淡笑忘祈一世凡恋 2024-09-01 11:39:30

请注意,以下 Maven 插件完全支持使用 ma​​ven 和嵌入式 Sphinx + MarkDown 支持构建文档:

https://trustin.github.io/sphinx-maven-plugin/index.html

<plugin>
  <groupId>kr.motd.maven</groupId>
  <artifactId>sphinx-maven-plugin</artifactId>
  <version>1.6.1</version>
  <configuration>
    <outputDirectory>${project.build.directory}/docs</outputDirectory>
  </configuration>
  <executions>
    <execution>
      <phase>package</phase>
      <goals>
        <goal>generate</goal>
      </goals>
    </execution>
  </executions>
</plugin>

Note that building documentation using maven and embedded Sphinx + MarkDown support is fully supported by following maven plugin :

https://trustin.github.io/sphinx-maven-plugin/index.html

<plugin>
  <groupId>kr.motd.maven</groupId>
  <artifactId>sphinx-maven-plugin</artifactId>
  <version>1.6.1</version>
  <configuration>
    <outputDirectory>${project.build.directory}/docs</outputDirectory>
  </configuration>
  <executions>
    <execution>
      <phase>package</phase>
      <goals>
        <goal>generate</goal>
      </goals>
    </execution>
  </executions>
</plugin>
秋叶绚丽 2024-09-01 11:39:30

这是对 recommonmark 方法的更新。

pip install recommonmark

我个人使用 Sphinx 3.5.1,因此

# for Sphinx-1.4 or newer
extensions = ['recommonmark']

请查看官方文档此处

This is an update to the recommonmark approach.

pip install recommonmark

Personally I use Sphinx 3.5.1, so

# for Sphinx-1.4 or newer
extensions = ['recommonmark']

Check the official doc here.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文