zwo*_*wol 6 python restructuredtext docutils python-sphinx
考虑一个带有这个骨架的 reStructuredText 文档:
Main Title
==========
text text text text text
Subsection
----------
text text text text text
.. my-import-from:: file1
.. my-import-from:: file2
Run Code Online (Sandbox Code Playgroud)
该my-import-from指令由特定于文档的 Sphinx 扩展提供,它应该读取作为其参数提供的文件,解析嵌入其中的 reST,并将结果作为当前输入文件中的一个部分注入。(类似于 autodoc,但文件格式不同。)我现在的代码如下所示:
class MyImportFromDirective(Directive):
required_arguments = 1
def run(self):
src, srcline = self.state_machine.get_source_and_line()
doc_file = os.path.normpath(os.path.join(os.path.dirname(src),
self.arguments[0]))
self.state.document.settings.record_dependencies.add(doc_file)
doc_text = ViewList()
try:
doc_text = extract_doc_from_file(doc_file)
except EnvironmentError as e:
raise self.error(e.filename + ": " + e.strerror) from e
doc_section = nodes.section()
doc_section.document = self.state.document
# report line numbers within the nested parse correctly
old_reporter = self.state.memo.reporter
self.state.memo.reporter = AutodocReporter(doc_text,
self.state.memo.reporter)
nested_parse_with_titles(self.state, doc_text, doc_section)
self.state.memo.reporter = old_reporter
if len(doc_section) == 1 and isinstance(doc_section[0], nodes.section):
doc_section = doc_section[0]
# If there was no title, synthesize one from the name of the file.
if len(doc_section) == 0 or not isinstance(doc_section[0], nodes.title):
doc_title = nodes.title()
doc_title.append(make_title_text(doc_file))
doc_section.insert(0, doc_title)
return [doc_section]
Run Code Online (Sandbox Code Playgroud)
这是有效的,除了新部分作为当前部分的子项而不是兄弟项注入。换句话说,上面的示例文档生成了一个像这样的 TOC 树:
- 主题
- 小节
- 文件 1
- 文件 2
而不是想要的
- 主题
- 小节
- 文件 1
- 文件 2
我该如何解决?Docutils 文档是......不够充分,特别是在控制部分深度方面。我尝试过的一件显而易见的事情是返回doc_section.children而不是[doc_section]; 完全删除File1和File2从目录树中删除(但确实使文档正文中的节标题看起来适合正确的嵌套级别)。
我不知道如何直接在您的自定义指令中执行此操作。但是,您可以在解析后使用自定义转换来提升树中的File1和节点。File2例如,请参阅以下转换docutils.transforms.frontmatter模块中的转换。
在您的 Sphinx 扩展中,使用Sphinx.add_transform方法来注册自定义转换。
更新:docutils.nodes.pending您还可以通过在节点列表中返回该类的一个或多个实例来直接在指令中注册转换。确保note_pending在这种情况下调用文档的方法(在您的指令中,您可以通过 获取文档self.state_machine.document)。
| 归档时间: |
|
| 查看次数: |
1279 次 |
| 最近记录: |