Search code examples
pythonwhitespacerestructuredtext

How to force whitespace in code block in reStructuredText


In RST, we use some whitespaces in front of a block to say this is a code block. Because Python also uses whitespace to indent a code block, I would like my RST code block to preserve those whitespaces if I were writing Python code. How can I do that?

Let's say we have a class:

class Test(object):

And we want to write a method called __init__ that is a member of this class. This method belongs to another code block but we want to have some visual clue so that readers know that this second block is a continuation of the previous one. At the moment, I use # to mark the vertical guide line of a code block like this:

    def __init__(self):
        pass
#

Without the #, def __init__(self) would be printed at the same indentation level as class Test(object). There's gotta be more elegant way.


Solution

  • Ah... I've run into this before ;). The # trick is usually what I use, alas. If you read the spec it sounds like it will always take away the leading indent. [1]

    You could also use an alternate syntax:

    ::
    
    >     def foo(x):
    >         pass
    

    With the leading ">" that will preserve leading space.

    [1] : http://docutils.sourceforge.net/docs/ref/rst/restructuredtext.html#indented-literal-blocks

    EDIT

    Just dug through the docutils code (this has been bugging me a lot too) and can confirm that it will always strip out the common indent, no questions asked. It would be easy to modify to change this behavior but that would make the resulting restructured text non-standard.