Skip to content

Commit

Permalink
Fix edge-case crash in codehilite
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
oprypin committed Nov 2, 2023
1 parent 87249be commit fa6d970
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 1 deletion.
1 change: 1 addition & 0 deletions docs/changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
* Remove legacy import needed only in Python 2 (#1403)
* Fix typo that left the attribute `AdmonitionProcessor.content_indent` unset
(#1404)
* Fix edge-case crash in `codehilite` with an empty `code` tag (#1405).
* Improve and expand type annotations in the code base (#1401).

## [3.5.1] -- 2023-10-31
Expand Down
5 changes: 4 additions & 1 deletion markdown/extensions/codehilite.py
Original file line number Diff line number Diff line change
Expand Up @@ -270,8 +270,11 @@ def run(self, root: etree.Element) -> None:
for block in blocks:
if len(block) == 1 and block[0].tag == 'code':
local_config = self.config.copy()
text = block[0].text
if text is None:
continue
code = CodeHilite(
self.code_unescape(block[0].text),
self.code_unescape(text),
tab_length=self.md.tab_length,
style=local_config.pop('pygments_style', 'default'),
**local_config
Expand Down
21 changes: 21 additions & 0 deletions tests/test_syntax/extensions/test_code_hilite.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,9 @@

from markdown.test_tools import TestCase
from markdown.extensions.codehilite import CodeHiliteExtension, CodeHilite
from markdown import extensions, treeprocessors
import os
import xml.etree.ElementTree as etree

try:
import pygments # noqa
Expand Down Expand Up @@ -762,3 +764,22 @@ def testFormatterLangStrEmptyLang(self):
)
]
)

def testDoesntCrashWithEmptyCodeTag(self):
expected = '<h1>Hello</h1>\n<pre><code></code></pre>'
self.assertMarkdownRenders(
'# Hello',
expected,
extensions=[CodeHiliteExtension(), _ExtensionThatAddsAnEmptyCodeTag()]
)


class _ExtensionThatAddsAnEmptyCodeTag(extensions.Extension):
def extendMarkdown(self, md):
md.treeprocessors.register(_AddCodeTagTreeprocessor(), 'add-code-tag', 40)


class _AddCodeTagTreeprocessor(treeprocessors.Treeprocessor):
def run(self, root: etree.Element):
pre = etree.SubElement(root, 'pre')
etree.SubElement(pre, 'code')

0 comments on commit fa6d970

Please sign in to comment.