Skip to content

Commit

Permalink
Merge pull request #336 from ryanvilbrandt/reset-toc
Browse files Browse the repository at this point in the history
Reset _toc when convert is run
  • Loading branch information
nicholasserra committed Nov 25, 2019
2 parents ead6a09 + 83f8068 commit f13abba
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 1 deletion.
4 changes: 3 additions & 1 deletion lib/markdown2.py
Expand Up @@ -202,6 +202,8 @@ class Markdown(object):
html_spans = None
html_removed_text = "[HTML_REMOVED]" # for compat with markdown.py

_toc = None

# Used to track when we're inside an ordered or unordered list
# (see _ProcessListItems() for details):
list_level = 0
Expand Down Expand Up @@ -274,6 +276,7 @@ def reset(self):
self._count_from_header_id = defaultdict(int)
if "metadata" in self.extras:
self.metadata = {}
self._toc = None

# Per <https://developer.mozilla.org/en-US/docs/HTML/Element/a> "rel"
# should only be used in <a> tags with an "href" attribute.
Expand Down Expand Up @@ -1530,7 +1533,6 @@ def header_id_from_text(self, text, prefix, n):

return header_id

_toc = None
def _toc_add_entry(self, level, id, name):
if level > self._toc_depth:
return
Expand Down
46 changes: 46 additions & 0 deletions test/test_markdown2.py
Expand Up @@ -291,6 +291,52 @@ def test_russian(self):
'<h2>%s</h2>\n' % ko)
test_russian.tags = ["unicode", "issue3"]

def test_toc_with_persistent_object(self):
"""
Tests that the toc is the same every time it's run on HTML, even if the Markdown object isn't disposed of.
"""
md = markdown2.Markdown(extras=["toc"])
html = """
# Header 1
## Header 1.1
## Header 1.2
### Header 1.3
# Header 2
## Header 2.1
"""
expected_toc_html = """<ul>
<li><a href="#header-1">Header 1</a>
<ul>
<li><a href="#header-11">Header 1.1</a></li>
<li><a href="#header-12">Header 1.2</a>
<ul>
<li><a href="#header-13">Header 1.3</a></li>
</ul></li>
</ul></li>
<li><a href="#header-2">Header 2</a>
<ul>
<li><a href="#header-21">Header 2.1</a></li>
</ul></li>
</ul>
"""
self.assertEqual(expected_toc_html, md.convert(html).toc_html)
# Do it again, to check if the toc_html is just appended rather than replaced
self.assertEqual(expected_toc_html, md.convert(html).toc_html)
# Create different html, and confirm toc_html is replaced
html = """
# I'm new html
## I don't have to be long, just different
"""
expected_toc_html = """<ul>
<li><a href="#im-new-html">I'm new html</a>
<ul>
<li><a href="#i-dont-have-to-be-long-just-different">I don't have to be long, just different</a></li>
</ul></li>
</ul>
"""
self.assertEqual(expected_toc_html, md.convert(html).toc_html)
test_toc_with_persistent_object.tags = ["toc", "issue208"]


class DocTestsTestCase(unittest.TestCase):
def test_api(self):
Expand Down

0 comments on commit f13abba

Please sign in to comment.