Look for valid parent before appending a section element.

Don't append a `<section>` to an `<admonition>` or other body element,
only to <section>` and `<document>`.
Exception: the base node of a nested parser may become the
new section's parent, if it has no parent (detached node).
It is up to the users (or extension implementing a directive) to
prevent or handle these cases.

git-svn-id: http://svn.code.sf.net/p/docutils/code/trunk@10203 929543f6-e4f2-0310-98a6-ba3bd3dd1d04
This commit is contained in:
milde
2025-08-15 17:38:10 +00:00
parent 4447485ac8
commit c3a99f65a7
3 changed files with 14 additions and 5 deletions

View File

@@ -21,6 +21,11 @@ Release 0.23b0 (unpublished)
- More consistent and concise command line help.
* docutils/nodes.py
- `nodes.Element.section_hierarchy()` now returns only elements
with non-empty `.parent`.
* docutils/parsers/rst/states.py
- Relax "section title" system message from SEVERE to ERROR.

View File

@@ -385,7 +385,12 @@ class RSTState(StateWS):
if newlevel > len(title_styles):
title_styles.append(style)
self.memo.section_level = newlevel
if newlevel <= oldlevel:
if newlevel > oldlevel:
# new section is a subsection: get the current section or base node
while self.parent.parent and not isinstance(
self.parent, (nodes.section, nodes.document)):
self.parent = self.parent.parent
else:
# new section is sibling or higher up in the section hierarchy
self.parent = parent_sections[newlevel-1].parent
return True

View File

@@ -138,7 +138,6 @@ class RSTStateTests(unittest.TestCase):
self.document[-1].pformat())
# new (2nd-level) section title
# TODO: don't append <section> to <paragraph>!
title = self.title_markup('sub 2', '~')
self.state.nested_parse(title, 0, node=paragraph, match_titles=True)
self.assertEqual('<section>\n'
@@ -147,9 +146,9 @@ class RSTStateTests(unittest.TestCase):
' sub\n'
' <paragraph>\n'
' base node\n'
' <section ids="sub-2" names="sub\\ 2">\n'
' <title>\n'
' sub 2\n',
' <section ids="sub-2" names="sub\\ 2">\n'
' <title>\n'
' sub 2\n',
section.pformat())