在我正在编写的一些 sphinx 文档中,我包含了来自辅助文件的代码示例,如下所示:
.. literalinclude:: mymodule.py
:pyobject: MyClass
:linenos:
这个特定的文档是一个教程,其中的类是逐步构建的。我想做的是包含整个类或单个方法,并仅强调该部分感兴趣的行。这样,上下文就得以保留,但有趣的部分一目了然。现在我只能引用文本中的行号,这还可以,但远非理想。
查看 sphinx 和 pygments 的文档和代码,我没有找到明显的方法来做到这一点。我不反对修补它们或在 conf.py
中做一些棘手的事情,但我想知道是否有人解决了这个问题。
In some sphinx docs I am writing, I am including code samples from an ancillary file like so:
.. literalinclude:: mymodule.py
:pyobject: MyClass
:linenos:
This particular doc is a tutorial, where the classes are build up step by step. What I would like to do is include the entire class or a single method, and emphasize only the lines of interest to that section. That way the context is preserved but the interesting parts are obvious at a glance. Right now I have resorted to just referring to line numbers in the text, which is ok, but far from ideal.
Looking at the docs and code for sphinx and pygments I don't find an obvious way to do this. I'm not opposed to patching them or doing something tricky in conf.py
, but I wondered if anyone had solved this.
发布评论
评论(2)
Sphinx 现在为 emphasize-lines 选项rel="nofollow noreferrer">
literalinclude
指令。该选项在“其他选项”下提到。详细信息位于
代码块
。Sphinx now has an
emphasize-lines
option for theliteralinclude
directive.The option is mentioned under "Additional options". The details are in the documentation for
code-block
.您可以在 sphinx/directives/code.py 中修补 sphinx 的 LiteralIninclude 指令
例如,这在literalinclude指令中提供了一个新的lines-emphasis选项,您可以这样使用:
其中line-emphasis是相对于包含的代码的起始行、结束行,第一行是1。
在pypi上使用sphinx 0.6.5 .python.org/pypi/Sphinx/0.6.5 作为快速修补代码的基础。py 在那里: http://paste.pocoo.org/show/194456/
请注意,以下内容是等效的:
使用标准 sphinx(几乎是 S.Lott 建议的那样):
...并使用修补的 sphinx:
因此,它可能不正是您正在寻找的东西。该补丁为代码的每个突出显示或未突出显示的部分创建一个新节点。其中每一个都将由 Sphinx 呈现为单独的 <<分区>且<预>部分。为了超越这一点,您可能需要创建一个样式表,以更好地重点摘录这些行。进一步的黑客可能需要深入 Sphinx 和 Pygments 的内部,才能直接在那里生成无缝的强调风格:这不是微不足道的。
/HTH
You could patch sphinx's LiteralInclude directive in sphinx/directives/code.py
This gives for instance a new lines-emphasis option in the literalinclude directive that you can use this way:
where line-emphasis is a start line, end line relative to the included code, first line is 1.
Using sphinx 0.6.5 at pypi.python.org/pypi/Sphinx/0.6.5 as a base a quicky patched code.py is there: http://paste.pocoo.org/show/194456/
Note that the following would be equivalent:
Using the standard sphinx (pretty much what S.Lott suggested):
... and using the patched sphinx:
Therefore it may no be exactly what you are looking for. The patch creates a new node for each of the highlighted or not highlighted sections of the code. Each of these will be rendered by Sphinx as a separate < div > and < pre > section. To go beyond this you may want to create a stylesheet that would better excerpt the lines with emphasis. Further hacks might need to go deep in the guts of Sphinx and Pygments to have a seamless emphasized style generated directly there: not trivial.
/HTH