【问题标题】:Sphinx: how to cross-reference a target generated by a custom directiveSphinx:如何交叉引用自定义指令生成的目标
【发布时间】:2020-04-22 15:59:32
【问题描述】:

我在交叉引用自定义指令生成的部分时遇到问题。

指令如下:

from docutils import nodes
from docutils.parsers import rst


class TestDirective(rst.Directive):

    has_content = False
    required_arguments = 1
    option_spec = {}

    def run(self):
        my_arg = self.arguments[0]

        target_node = nodes.target('', '', refid=nodes.make_id(my_arg))
        section = nodes.section(
            '',
            nodes.title(text=my_arg),
            ids=[nodes.make_id(my_arg)],
            names=[nodes.fully_normalize_name(my_arg)])

        return [target_node, section]


def setup(app):
   app.add_directive('mytest', TestDirective)

下面是它的使用方法:

=============
Test document
=============

.. mytest:: section1

Section 1 content.


.. _section2:

section2
========

Section 2 content.

现在,以下仅适用于section2

Here are links to :ref:`section1` and :ref:`section2`.

该链接仅针对section2 正确生成,我收到以下错误:

test.rst:19: WARNING: undefined label: section1 (if the link has no caption the
label must precede a section header)

我怎样才能做到这一点?

【问题讨论】:

  • 我想问一下你在哪里读到定义from docutils.parsers import rst的API?我尝试对此进行调查,并让代码在一定程度上运行,但没有记录的 API,我查看了 docutils 源代码,找不到时间来尝试理解这一切。如果你能推荐一些可以缓解这部分研究的东西,我可能会再试一次。
  • @bad_coder:嗯,实际上来自Sphinx tutorial
  • @bad_coder:好的!
  • @abey 我回答了我自己的帖子。您可能会发现它很有用。这是一种折磨。见stackoverflow.com/questions/64146870/…

标签: python python-sphinx cross-reference docutils


【解决方案1】:

您似乎混淆了引用标签和指令的功能。

要清楚术语,请在您的标记中:

  • 有效的部分在section title(带有装饰下划线的“section2”)之前有一个reference label.. _section2:)。这提供了一个可以通过interpreted text role (:ref:`section2`) 链接的目标。这是常规的 Sphinx 样板。
  • 不起作用的部分是您的自定义指令 (.. mytest::) 和它的单个必需参数 (section1) 并且没有内容块(指令后面没有缩进文本)。
  • Section 1 content.”行是一个独立的段落。

也许您想要一个自定义解释文本角色来提供特殊功能,或者是 roles.XRefRole 子类,还是 autosectionlabel extension


编辑

:ref: 角色适用于任意位置(“标签”,无论是什么意思) 但你也可以通过:any:once it is registered交叉引用自定义对象:

def setup(app):
    app.add_directive('mytest', TestDirective)

    app.add_object_type(
        directivename='mytest',
        rolename='banana',
    )

然后是 ReST 内容:

See :any:`section1` which is a TestDirective.

Or also works via the rolename :banana:`section1`.

Many would agree 所有这些功能都没有很好的记录。

【讨论】:

  • 感谢您的回答。我想我的术语是正确的。我的问题是:如何从自定义指令(如果可能的话)生成与匹配的“参考标签”配对的“章节标题”?
  • 我正在尝试做同样的事情。用头撞墙。
  • @natersoz:如果你发现了什么,请告诉我!
  • 我在搜索中没有找到 abey 的问题 - 并写了我自己的问题。请参阅stackoverflow.com/questions/64146870/… 这包含项目代码,该代码使用 todo 指令(链接在问题中)尝试与 OP 在 github 上的一个小示例项目中要求的相同的事情。
  • 指令创建一个可以在指令内访问的引用,但不能从 .rst 文件中引用。如果我理解 abbey 的问题,那么我们在问同样的问题。
猜你喜欢
  • 2021-07-13
  • 1970-01-01
  • 2011-01-29
  • 1970-01-01
  • 1970-01-01
  • 2015-07-14
  • 2019-07-06
  • 2021-01-16
相关资源
最近更新 更多