reStructuredText中的内嵌代码高亮显示

179

我知道reStructuredText有这个指令:

.. code:: bash

    gedit pohl.m

渲染代码块的语法高亮,那么有没有办法对内联代码片段进行语法高亮呢:

Do edit the file, type ``gedit pohl.m`` into a terminal.

使用反引号将其标记为代码,但我想像代码块一样用pygments突出它。这可行吗?


7
反引号用来将文本标记为行内字面量,而不是代码块。通常,这部分文本将以等宽字体发布。很抱歉,我不确定如何获取内联代码语法突出显示的片段。 - Chris
2个回答

276

我查看了一些相关内容,偶然发现了重构文本解释文本角色文档。从这个文档中得知:

Interpreted text uses backquotes (`) around the text. An explicit role marker may optionally appear before or after the text, delimited with colons. For example:

This is `interpreted text` using the default role.

This is :title:`interpreted text` using an explicit role.
似乎有一个code role,所以你可以直接输入。
:code:`a = b + c`

为了渲染内联代码块,您可以定义一个自定义角色来获得语法高亮。例如:
.. role:: bash(code)
   :language: bash

你可以像这样使用它:
Here is some awesome bash code :bash:`a = b + c`.

请注意,角色定义必须放在对该角色的引用之前。
请注意,我链接的文档没有提到它所指的docutils版本。代码角色在docutils 0.8.1中不可用(这是我唯一可以测试的版本)。

7
请注意在使用Sphinx时的一个问题:https://dev59.com/dWEi5IYBdhLWcg3wJZVe - Donatello

3

对我来说,我必须在Sphinx的配置目录(即conf.py所在的目录)中创建一个docutils.conf文件。它的内容如下:

[restructuredtext parser]
syntax_highlight = short

有关上述信息的更多信息,请参见this答案

要在全局设置角色,在conf.py文件中,我创建了一个rst_prolog变量。其中的字符串将包含在读取的每个源文件的开头。

rst_prolog = """
.. role:: python(code)
    :language: python
    :class: highlight
"""

在Python中,highlight类是必要的,以进行正确的语法高亮。

有关上述信息的更多信息,请参见this答案。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接