Sphinx extension: literal block with leading and/or trailing blank lines?

♀尐吖头ヾ 提交于 2019-12-12 01:27:26

问题


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!


回答1:


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




回答2:


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!



来源:https://stackoverflow.com/questions/34050044/sphinx-extension-literal-block-with-leading-and-or-trailing-blank-lines

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!