有没有办法在reStructuredText中组成标准文本角色?例如,将字符串格式化为文字和强字符?
以下内容没有达到我的希望:
**``text``**
``**text**``
:strong:`:literal:`text``
:literal:`:strong:`text``
不,这不可能直接实现。传递到实现角色的函数(参数
text
)的内容不会被进一步解析。
请参阅创建 reStructuredText 解释文本角色。
也就是说,如果您愿意,您可以实现您的自己的第一个角色,该角色将通过
nested_parse()
进一步解析文本 - 但这不是您在这里要问的。
来自
docutils/docutils/parsers/rst/roles.py
的评论表明嵌套
您询问的解析功能已经/正在计划/建议,但尚未实施
目前已实施。
# Once nested inline markup is implemented, this and other methods should
# recursively call inliner.nested_parse().
(以下特此在CC0下发布。)
如果您有能力扩展解析器(例如,如果您使用 Sphinx),则可以添加解析其内容的自定义 role。 (请注意,这适用于简单的事情,例如粗体/斜体和替换,但如果您尝试嵌套角色或类似的疯狂行为,很可能会失败。
我用这个:
from docutils import nodes
from docutils.parsers.rst.states import Struct
def make_parsed_text_role(class_names=[], node_class=nodes.inline):
def parsed_text_role(name, rawtext, text, lineno, inliner,
options={}, content=[]):
# Prepare context for nested parsing
memo = Struct(document=inliner.document,
reporter=inliner.reporter,
language=inliner.language)
# Create parent node
options['classes'] = class_names
parent = node_class(rawtext, '', **options)
# Parse role text for markup and add to parent
processed, messages = inliner.parse(text, lineno, memo, parent)
parent += processed
# Return parent node, and any messages from nested parsing
return [parent], messages
return parsed_text_role
您可以通过 Sphinx
conf.py
使用它,如下所示:
# Configuration file for the Sphinx documentation builder (conf.py).
project = 'My Documentation'
# ...
# ...paste the above code here...
def setup(app):
app.add_role('foo', make_parsed_text_role(class_names=['foo']))
在您的文档中,您可以这样写:
This is :foo:`some **bold** text`!
在 HTML 中,这将生成一个
<span class="foo">
,至少对于默认的 nodes.inline
节点类是这样。生成器模式的使用是可选的,但如果您想制作一大堆这些自定义角色,它会非常方便。
受到@Matthew的回答的启发,我为此编写了一个Sphinx扩展,它可以:
首先,从 PyPI 下载扩展:
pip install sphinxnotes-comboroles
然后,将扩展名添加到你的conf.py中的扩展配置项中:
extensions = [
# …
'sphinxnotes.comboroles',
# …
]
要创建“粗体代码”角色,请继续添加以下配置,该配置告诉扩展将角色
strong
和literal
组合成一个新角色strong_literal
:
comboroles_roles = {
'strong_literal': ['strong', 'literal'],
}
最后,你可以在这里看到渲染结果:
您可以查看https://sphinx.silverrainz.me/comboroles/index.html了解更多详情。