このスケルトンを持つ reStructuredText ドキュメントを考えてみましょう:
Main Title
==========
text text text text text
Subsection
----------
text text text text text
.. my-import-from:: file1
.. my-import-from:: file2
この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]
これは機能しますが、新しいセクションが兄弟ではなく、現在のセクションの子として挿入されることを除きます。つまり、上記のサンプル ドキュメントは、次のような TOC ツリーを生成します。
- メインタイトル
- サブセクション
- ファイル1
- ファイル2
希望の代わりに
- メインタイトル
- サブセクション
- ファイル1
- ファイル2
これを修正するにはどうすればよいですか? Docutils のドキュメントは ... 特にセクションの深さの制御に関して不十分です。私が試した明らかなことの1つは、doc_section.children
の代わりに戻ることです[doc_section]
。TOC ツリーから完全に削除File1
さFile2
れます (ただし、ドキュメントの本文のセクション ヘッダーが適切なネスト レベルにあるように見えます)。