summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorCharles de Beauchesne <charles.de.beauchesne@gmail.com>2021-07-27 22:14:58 +0200
committerGitHub <noreply@github.com>2021-07-27 16:14:58 -0400
commit4b20c168bc4afa0a3775080d803e38694fac17b3 (patch)
tree3ac23f815fe29aa4d3db96478c28d7d3ddab0817
parent6f024f5be53d348b17a5da2c3e9c32c37013efd7 (diff)
downloadpython-markdown-4b20c168bc4afa0a3775080d803e38694fac17b3.tar.gz
Better toc detection
Fixes #1160.
-rw-r--r--docs/change_log/index.md1
-rw-r--r--markdown/extensions/toc.py7
-rw-r--r--tests/test_syntax/extensions/test_toc.py8
3 files changed, 15 insertions, 1 deletions
diff --git a/docs/change_log/index.md b/docs/change_log/index.md
index aed19e3..fe40094 100644
--- a/docs/change_log/index.md
+++ b/docs/change_log/index.md
@@ -6,6 +6,7 @@ Python-Markdown Change Log
Under development: version 3.3.5 (a bug-fix release).
* Make the `slugify_unicode` function not remove diacritical marks (#1118).
+* Fix `[toc]` detection when used with `nl2br` extension (#1160)
Feb 24, 2021: version 3.3.4 (a bug-fix release).
diff --git a/markdown/extensions/toc.py b/markdown/extensions/toc.py
index 965ba4a..e4dc378 100644
--- a/markdown/extensions/toc.py
+++ b/markdown/extensions/toc.py
@@ -195,7 +195,12 @@ class TocTreeprocessor(Treeprocessor):
# To keep the output from screwing up the
# validation by putting a <div> inside of a <p>
# we actually replace the <p> in its entirety.
- if c.text and c.text.strip() == self.marker:
+
+ # The <p> element may contain more than a single text content
+ # (nl2br can introduce a <br>). In this situation, c.text returns
+ # the very first content, ignore children contents or tail content.
+ # len(c) == 0 is here to ensure there is only text in the <p>.
+ if c.text and c.text.strip() == self.marker and len(c) == 0:
for i in range(len(p)):
if p[i] == c:
p[i] = elem
diff --git a/tests/test_syntax/extensions/test_toc.py b/tests/test_syntax/extensions/test_toc.py
index 83c990f..6871340 100644
--- a/tests/test_syntax/extensions/test_toc.py
+++ b/tests/test_syntax/extensions/test_toc.py
@@ -21,6 +21,7 @@ License: BSD (see LICENSE.md for details).
from markdown.test_tools import TestCase
from markdown.extensions.toc import TocExtension
+from markdown.extensions.nl2br import Nl2BrExtension
class TestTOC(TestCase):
@@ -561,3 +562,10 @@ class TestTOC(TestCase):
'</h1>', # noqa
extensions=[TocExtension(permalink=True)]
)
+
+ def testNl2brCompatibility(self):
+ self.assertMarkdownRenders(
+ '[TOC]\ntext',
+ '<p>[TOC]<br />\ntext</p>',
+ extensions=[TocExtension(), Nl2BrExtension()]
+ )