Skip to content

Commit f5b151a

Browse files
oprypinwaylan
authored andcommitted
Fix edge-case crash in codehilite
If there is an empty `<pre><code></code></pre>` inserted by another extension, there can be an exception. The added test case was crashing before this change.
1 parent 87249be commit f5b151a

File tree

3 files changed

+26
-1
lines changed

3 files changed

+26
-1
lines changed

docs/changelog.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
1717
* Remove legacy import needed only in Python 2 (#1403)
1818
* Fix typo that left the attribute `AdmonitionProcessor.content_indent` unset
1919
(#1404)
20+
* Fix edge-case crash in `codehilite` with an empty `code` tag (#1405).
2021
* Improve and expand type annotations in the code base (#1401).
2122

2223
## [3.5.1] -- 2023-10-31

markdown/extensions/codehilite.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -270,8 +270,11 @@ def run(self, root: etree.Element) -> None:
270270
for block in blocks:
271271
if len(block) == 1 and block[0].tag == 'code':
272272
local_config = self.config.copy()
273+
text = block[0].text
274+
if text is None:
275+
continue
273276
code = CodeHilite(
274-
self.code_unescape(block[0].text),
277+
self.code_unescape(text),
275278
tab_length=self.md.tab_length,
276279
style=local_config.pop('pygments_style', 'default'),
277280
**local_config

tests/test_syntax/extensions/test_code_hilite.py

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

2222
from markdown.test_tools import TestCase
2323
from markdown.extensions.codehilite import CodeHiliteExtension, CodeHilite
24+
from markdown import extensions, treeprocessors
2425
import os
26+
import xml.etree.ElementTree as etree
2527

2628
try:
2729
import pygments # noqa
@@ -762,3 +764,22 @@ def testFormatterLangStrEmptyLang(self):
762764
)
763765
]
764766
)
767+
768+
def testDoesntCrashWithEmptyCodeTag(self):
769+
expected = '<h1>Hello</h1>\n<pre><code></code></pre>'
770+
self.assertMarkdownRenders(
771+
'# Hello',
772+
expected,
773+
extensions=[CodeHiliteExtension(), _ExtensionThatAddsAnEmptyCodeTag()]
774+
)
775+
776+
777+
class _ExtensionThatAddsAnEmptyCodeTag(extensions.Extension):
778+
def extendMarkdown(self, md):
779+
md.treeprocessors.register(_AddCodeTagTreeprocessor(), 'add-code-tag', 40)
780+
781+
782+
class _AddCodeTagTreeprocessor(treeprocessors.Treeprocessor):
783+
def run(self, root: etree.Element):
784+
pre = etree.SubElement(root, 'pre')
785+
etree.SubElement(pre, 'code')

0 commit comments

Comments
 (0)