views:

170

answers:

1

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.

+1  A: 

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

Philippe Ombredanne