Skip to content

Commit 4b20c16

Browse files
authored
Better toc detection
Fixes #1160.
1 parent 6f024f5 commit 4b20c16

File tree

3 files changed

+15
-1
lines changed

3 files changed

+15
-1
lines changed

docs/change_log/index.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ Python-Markdown Change Log
66
Under development: version 3.3.5 (a bug-fix release).
77

88
* Make the `slugify_unicode` function not remove diacritical marks (#1118).
9+
* Fix `[toc]` detection when used with `nl2br` extension (#1160)
910

1011
Feb 24, 2021: version 3.3.4 (a bug-fix release).
1112

markdown/extensions/toc.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -195,7 +195,12 @@ def replace_marker(self, root, elem):
195195
# To keep the output from screwing up the
196196
# validation by putting a <div> inside of a <p>
197197
# we actually replace the <p> in its entirety.
198-
if c.text and c.text.strip() == self.marker:
198+
199+
# The <p> element may contain more than a single text content
200+
# (nl2br can introduce a <br>). In this situation, c.text returns
201+
# the very first content, ignore children contents or tail content.
202+
# len(c) == 0 is here to ensure there is only text in the <p>.
203+
if c.text and c.text.strip() == self.marker and len(c) == 0:
199204
for i in range(len(p)):
200205
if p[i] == c:
201206
p[i] = elem

tests/test_syntax/extensions/test_toc.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121

2222
from markdown.test_tools import TestCase
2323
from markdown.extensions.toc import TocExtension
24+
from markdown.extensions.nl2br import Nl2BrExtension
2425

2526

2627
class TestTOC(TestCase):
@@ -561,3 +562,10 @@ def testPermalinkWithExtendedLatinInID(self):
561562
'</h1>', # noqa
562563
extensions=[TocExtension(permalink=True)]
563564
)
565+
566+
def testNl2brCompatibility(self):
567+
self.assertMarkdownRenders(
568+
'[TOC]\ntext',
569+
'<p>[TOC]<br />\ntext</p>',
570+
extensions=[TocExtension(), Nl2BrExtension()]
571+
)

0 commit comments

Comments
 (0)