How to force a space in a code block in reStructuredText

In RST, we use some spaces before the block to say that it is a code block. Since Python also uses spaces for code indentation, I would like my RST code code to keep those spaces if I write Python code. How can i do this?

Say we have a class:

class Test(object): 

And we want to write a method called __init__ , which is a member of this class. This method belongs to another block of code, but we want to have a visual key so that readers know that this second block is a continuation of the previous one. I am currently using # to indicate the vertical guideline of a code block as follows:

  def __init__(self): pass # 

Without # , def __init__(self) will be printed with the same level of indentation as class Test(object) . There should be a more elegant way.

+6
source share
3 answers

Ah ... I came across this before;). Alas, I usually use the # trick, alas. If you read the specification, it sounds as if it will always select the main indent. [1]

You can also use alternative syntax:

 :: > def foo(x): > pass 

With a leading ">", which preserves the leading space.

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

EDIT

I just dug the docutils code (it was also very eavesdropping) and can confirm that it will always cross out the general indent, without question. It would be easy to change to change this behavior, but it would make the restructured text non-standard.

0
source

You can also try Line Blocks , which look like this:

 | def foo(x): | pass 

although they are not code examples.

0
source

You need to define your own directive (it is true that the standard directive .. code:: removes spaces, but you can make your own directive that does not):

 import re from docutils.parsers.rst import directives INDENTATION_RE = re.compile("^ *") def measure_indentation(line): return INDENTATION_RE.match(line).end() class MyCodeBlock(directives.body.CodeBlock): EXPECTED_INDENTATION = 3 def run(self): block_lines = self.block_text.splitlines() block_header_len = self.content_offset - self.lineno + 1 block_indentation = measure_indentation(self.block_text) code_indentation = block_indentation + MyCodeBlock.EXPECTED_INDENTATION self.content = [ln[code_indentation:] for ln in block_lines[block_header_len:]] return super(MyCodeBlock, self).run() directives.register_directive("my-code", MyCodeBlock) 

Of course, you can also rewrite the standard directive .. code:: .

0
source

Source: https://habr.com/ru/post/894891/


All Articles