Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix edge-case crash in codehilite #1405

Merged
merged 1 commit into from
Nov 3, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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')