9

在我正在编写的一些 sphinx 文档中,我包含了来自辅助文件的代码示例,如下所示:

.. literalinclude:: mymodule.py
   :pyobject: MyClass
   :linenos:

这个特定的文档是一个教程,其中的类是逐步建立的。我想做的是包括整个类或单个方法,并且只强调该部分感兴趣的行。这样可以保留上下文,但有趣的部分一目了然。现在我只使用了文本中的行号,这还可以,但远非理想。

查看 sphinx 和 pygments 的文档和代码,我没有找到明显的方法来做到这一点。我不反对修补它们或做一些棘手的事情conf.py,但我想知道是否有人解决了这个问题。

4

2 回答 2

7

Sphinx 现在有一个emphasize-lines文字指令包括:

http://sphinx-doc.org/markup/code.html#includes

于 2012-04-17T20:26:44.447 回答
2

You could patch sphinx's LiteralInclude directive in sphinx/directives/code.py

  • There you would need to do something such that when you include code you can specify a start/end line to emphasize in this snippet.
  • The second step would require creating some ways to highlight things differently. The simplest approach is that the part with no emphasis is not highlighted and the part with emphasis is highlighted. That would avoid doing more complex hacking of the styles and highlighting.

This gives for instance a new lines-emphasis option in the literalinclude directive that you can use this way:

.. literalinclude:: ../sphinx/directives/code.py
   :pyobject: Highlight
   :lines-emphasis: 6,13

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):

.. literalinclude:: ../sphinx/directives/code.py
   :language: none
   :lines: 0-36
.. literalinclude:: ../sphinx/directives/code.py
   :lines: 36-46
.. literalinclude:: ../sphinx/directives/code.py
   :language: none
   :lines: 37-

... and using the patched sphinx:

.. literalinclude:: ../sphinx/directives/code.py
   :lines-emphasis: 37,47

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

于 2010-03-27T14:29:30.577 回答