As far as I can tell, it is not possible to create a literal text block (e.g. with the code-block
directive) that starts or ends with a blank line, because this would be ambiguous with regard to the reStructuredText syntax.
That's OK.
But now I want to create a custom directive that uses docutils
's literal_block()
node, and I want (within the code of my directive) to add empty lines at the beginning and/or end of the directive's contents.
Since this isn't possible in reStructuredText syntax, I'm planning to use the directive's options to specify the number of blank lines, but that's not my problem and not part of my question. Just in case you're wondering ...
Here's a minimal example of what I want to do:
import docutils
class MyDirective(docutils.parsers.rst.Directive):
has_content = True
def run(self):
text = '\n\n' + '\n'.join(self.content.data) + '\n\n'
node = docutils.nodes.literal_block(text, text)
print(node)
return [node]
def setup(app):
app.add_directive('mydirective', MyDirective)
It can be used like this:
.. mydirective::
Hello, world!
This works, but the newlines I added in the directive are somehow swallowed by Sphinx (in both HTML and LaTeX output).
How can I avoid that?
The newlines are actually stored in the node
object (as can be seen in the output of print()
), but they seem to get lost somewhere later during Sphinx processing.
I don't know enough about the Sphinx machinery to track this down on my own, any help would be very much appreciated!