diff --git a/markdown/extensions/toc.py b/markdown/extensions/toc.py index 21f98ba1d..0e9b2b9b8 100644 --- a/markdown/extensions/toc.py +++ b/markdown/extensions/toc.py @@ -137,11 +137,17 @@ def __init__(self, md, config): self.header_rgx = re.compile("[Hh][123456]") - def iterparent(self, root): - ''' Iterator wrapper to get parent and child all at once. ''' - for parent in root.iter(): - for child in parent: - yield parent, child + def iterparent(self, node): + ''' Iterator wrapper to get allowed parent and child all at once. ''' + + # We do not allow the marker inside a header as that + # would causes an enless loop of placing a new TOC + # inside previously generated TOC. + for child in node: + if not self.header_rgx.match(child.tag) and child.tag not in ['pre', 'code']: + yield node, child + for p, c in self.iterparent(child): + yield p, c def replace_marker(self, root, elem): ''' Replace marker with elem. ''' @@ -153,11 +159,7 @@ def replace_marker(self, root, elem): # To keep the output from screwing up the # validation by putting a
# we actually replace the
in its entirety. - # We do not allow the marker inside a header as that - # would causes an enless loop of placing a new TOC - # inside previously generated TOC. - if c.text and c.text.strip() == self.marker and \ - not self.header_rgx.match(c.tag) and c.tag not in ['pre', 'code']: + if c.text and c.text.strip() == self.marker: for i in range(len(p)): if p[i] == c: p[i] = elem diff --git a/tests/test_extensions.py b/tests/test_extensions.py index 5a04e6447..aee9bac2a 100644 --- a/tests/test_extensions.py +++ b/tests/test_extensions.py @@ -845,6 +845,41 @@ def testUniqueFunc(self): self.assertEqual(unique('foo', ids), 'foo_1') self.assertEqual(ids, set(['foo', 'foo_1'])) + def testTocInHeaders(self): + + text = '[TOC]\n#[TOC]' + self.assertEqual( + self.md.convert(text), + '