如何在自定义 python-sphinx 指令/扩展中使用现有指令?

2024-03-01

我想创建一个自定义的Directive使用现有指令(code-block在这个例子中)在它的实现中。

reStructuredText 中的手动等效项是:

.. mydirective:: py

   .. code-block: py
        
      print("Hello world")     

不过,我想要code-block内创建my-directive的定义。我找到了一个硬编码适当的示例reStructuredText对于现有指令(如下),但这取决于解析器使用rST.

class MyDirective(Directive):
    has_content = True

    def run(self):
        # Do custom stuff...

        # Use code-block Directive
        new_content = [
            '.. tab:: {}'.format(json.dumps(tab_args)),
            '   {}'.format(tab_name),
            '',
            '   .. code-block:: {}'.format(lang),
        ]

        if 'linenos' in self.options:
            new_content.append('      :linenos:')

        new_content.append('')

        for idx, line in enumerate(new_content):
            self.content.data.insert(idx, line)
            self.content.items.insert(idx, (None, idx))

        node = nodes.container()
        self.state.nested_parse(self.content, self.content_offset, node)
        return node.children

我如何以独立于解析器的方式实现它?


最后我的解决方案是:

from sphinx.directives.code import CodeBlock


class CodeTabDirective(CodeBlock):
    """ Tab directive with a codeblock as its content"""

    def run(self):
        self.assert_has_content()
        
        code_block = super().run()[0]

        # Set anything required by OtherDirective

        node = OtherDirective.run(self)[0]  # Generates container
        node.append(code_block)  # Put code block inside container

        return [node]

Where OtherDirective是另一项现有指令。

我无法子类化这两个指令并通过以下方式使用它们的功能super,因为我需要调用一个名为的方法run来自两者。

Update

您可以在中看到最终的解决方案代码选项卡指令 https://github.com/executablebooks/sphinx-tabs/blob/de7e7126198aac5e9598e099f9a2f4cd8e089e55/sphinx_tabs/tabs.py#L181 of sphinx-tabs.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在自定义 python-sphinx 指令/扩展中使用现有指令? 的相关文章

随机推荐