0
votes

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!

2

2 Answers

0
votes

I would rather try with CSS margin-top and margin-bottom properties.

0
votes

I found an answer to my own question, but it is far more complicated then I hoped ...

I created a custom node class and added a literal_block instance as a child node. I'm saving the number of empty lines as attributes of the custom node class. Then I created "visit" and "depart" functions (actually only the latter) for HTML and LaTeX that take the numbers from the node attributes and do some un-elegant string replacement on self.body fumbling the newlines into place.

This works fine for both HTML and LaTeX but I'd be happy to hear about a more elegant solution!