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:: .
source share