From 8288ce939e81843c9f6e9a85d5c4a3282ed74632 Mon Sep 17 00:00:00 2001 From: Naaz nuria Date: Wed, 2 Dec 2026 12:08:48 +0530 Subject: [PATCH 1/2] Escape fenced code classes passed to codehilite `FencedBlockPreprocessor.run` escapes the additional classes of a fenced code block with `_escape_attrib_html` when it writes the `
` tag
itself, but when `codehilite` is enabled it joins them into the
`css_class` option and passes that to `CodeHilite` instead. Neither
`CodeHilite` nor Pygments escapes `cssclass`, so a class token such as
`.x">y` (the `attr_list` scanner allows any character but space,
`=` and `}`) ends up in the `class` attribute verbatim, with or without
Pygments installed.

Escape the classes before they are passed on, so the block renders the
same with `codehilite` as without it. Valid class names are unchanged.
---
 docs/changelog.md                             |  3 +++
 markdown/extensions/fenced_code.py            |  4 ++-
 .../extensions/test_fenced_code.py            | 26 +++++++++++++++++++
 3 files changed, 32 insertions(+), 1 deletion(-)

diff --git a/docs/changelog.md b/docs/changelog.md
index 2020ed858..ad6db367d 100644
--- a/docs/changelog.md
+++ b/docs/changelog.md
@@ -29,6 +29,9 @@ See the [Contributing Guide](contributing.md) for details.
 * The `fenced_code` extension no longer raises `TypeError` for boolean options (e.g.
   `linenums=true`) set with `attr_list` when `codehilite` is not enabled. The values
   are now serialized like any other attribute (#1713).
+* Escape additional classes of a fenced code block when the `fenced_code`
+  extension passes them to the `codehilite` extension, to maintain consistency
+  with the output when `codehilite` is not enabled.
 
 ## [3.11.4] - 2026-11-25
 
diff --git a/markdown/extensions/fenced_code.py b/markdown/extensions/fenced_code.py
index 9ff1b28d7..544509639 100644
--- a/markdown/extensions/fenced_code.py
+++ b/markdown/extensions/fenced_code.py
@@ -133,9 +133,11 @@ def run(self, lines: list[str]) -> list[str]:
                     # Combine classes with `cssclass`. Ensure `cssclass` is at end
                     # as Pygments appends a suffix under certain circumstances.
                     # Ignore ID as Pygments does not offer an option to set it.
+                    # Escape the classes as neither `CodeHilite` nor Pygments
+                    # escapes `cssclass` when writing the `class` attribute.
                     if classes:
                         local_config['css_class'] = '{} {}'.format(
-                            ' '.join(classes),
+                            _escape_attrib_html(' '.join(classes)),
                             local_config['css_class']
                         )
                     highliter = CodeHilite(
diff --git a/tests/test_syntax/extensions/test_fenced_code.py b/tests/test_syntax/extensions/test_fenced_code.py
index 6cbbef693..bbb44c3ca 100644
--- a/tests/test_syntax/extensions/test_fenced_code.py
+++ b/tests/test_syntax/extensions/test_fenced_code.py
@@ -984,6 +984,32 @@ def testFencedLanguageAttrCssclass(self):
             extensions=['codehilite', 'fenced_code']
         )
 
+    def testFencedClassesEscaped(self):
+        # Classes passed on to `codehilite` are escaped like the classes of a block rendered without it.
+        if has_pygments:
+            expected = (
+                '
'
+                '# Some python code\n'
+                '
' + ) + else: + expected = ( + '
'
+                '# Some python code\n'
+                '
' + ) + self.assertMarkdownRenders( + self.dedent( + ''' + ``` { .python .x">y } + # Some python code + ``` + ''' + ), + expected, + extensions=['codehilite', 'fenced_code'] + ) + def testFencedLanguageAttrLinenums(self): if has_pygments: expected = ( From 250b4a8f73150a0da2c7a2f767d49f238346ffdc Mon Sep 17 00:00:00 2001 From: Naaz nuria Date: Fri, 4 Dec 2026 21:54:48 +0530 Subject: [PATCH 2/2] Escape the CSS class in codehilite output without Pygments The previous approach escaped the classes in `fenced_code` before passing them on as `css_class`. Pygments escapes `cssclass` itself as of 2.20.0, so that double-escaped the class attribute for anyone on a current Pygments. Escape in `CodeHilite`'s own `
` output instead, which is
the only branch that writes `cssclass` without escaping it, and leave the
Pygments output alone.

That means the class is only escaped on the Pygments path for Pygments
2.20.0 and later, so raise the version used by the `pygments` tox
environment from 2.7.1 to 2.20.0 and update the expected output for the
Pygments changes in between: the `cssclass` wrapper moved to the outer
element for `linenos='table'`, `hll` now wraps inline line numbers, the
`err`/trailing `x` token spans are gone, `HtmlFormatter.wrap()` lost its
`outfile` argument, and some default styles and lexer aliases changed.
---
 docs/changelog.md                             |  9 +-
 markdown/extensions/codehilite.py             |  2 +-
 markdown/extensions/fenced_code.py            |  4 +-
 .../extensions/test_code_hilite.py            | 86 +++++++++++--------
 .../extensions/test_fenced_code.py            | 29 ++++---
 tox.ini                                       |  2 +-
 6 files changed, 72 insertions(+), 60 deletions(-)

diff --git a/docs/changelog.md b/docs/changelog.md
index ad6db367d..90af2295d 100644
--- a/docs/changelog.md
+++ b/docs/changelog.md
@@ -29,9 +29,12 @@ See the [Contributing Guide](contributing.md) for details.
 * The `fenced_code` extension no longer raises `TypeError` for boolean options (e.g.
   `linenums=true`) set with `attr_list` when `codehilite` is not enabled. The values
   are now serialized like any other attribute (#1713).
-* Escape additional classes of a fenced code block when the `fenced_code`
-  extension passes them to the `codehilite` extension, to maintain consistency
-  with the output when `codehilite` is not enabled.
+* The `codehilite` extension now escapes the CSS class of its non-Pygments
+  output, so that additional classes of a fenced code block are escaped when
+  `fenced_code` passes them on as `css_class`, matching the output when
+  `codehilite` is not enabled. Pygments escapes `cssclass` itself as of version
+  2.20.0, so users who rely on Pygments should update to at least that version
+  to have class names properly escaped.
 
 ## [3.11.4] - 2026-11-25
 
diff --git a/markdown/extensions/codehilite.py b/markdown/extensions/codehilite.py
index 1db9b99e1..75ba35e37 100644
--- a/markdown/extensions/codehilite.py
+++ b/markdown/extensions/codehilite.py
@@ -187,7 +187,7 @@ def hilite(self, shebang: bool = True) -> str:
             if classes:
                 class_str = ' class="{}"'.format(' '.join(classes))
             return '
{}\n
\n'.format( - self.options['cssclass'], + _escape_attrib_html(self.options['cssclass']), class_str, txt ) diff --git a/markdown/extensions/fenced_code.py b/markdown/extensions/fenced_code.py index 544509639..9ff1b28d7 100644 --- a/markdown/extensions/fenced_code.py +++ b/markdown/extensions/fenced_code.py @@ -133,11 +133,9 @@ def run(self, lines: list[str]) -> list[str]: # Combine classes with `cssclass`. Ensure `cssclass` is at end # as Pygments appends a suffix under certain circumstances. # Ignore ID as Pygments does not offer an option to set it. - # Escape the classes as neither `CodeHilite` nor Pygments - # escapes `cssclass` when writing the `class` attribute. if classes: local_config['css_class'] = '{} {}'.format( - _escape_attrib_html(' '.join(classes)), + ' '.join(classes), local_config['css_class'] ) highliter = CodeHilite( diff --git a/tests/test_syntax/extensions/test_code_hilite.py b/tests/test_syntax/extensions/test_code_hilite.py index da65b2bb3..f0a25ba02 100644 --- a/tests/test_syntax/extensions/test_code_hilite.py +++ b/tests/test_syntax/extensions/test_code_hilite.py @@ -58,7 +58,7 @@ def test_codehilite_defaults(self): if has_pygments: # Odd result as no `lang` given and a single comment is not enough for guessing. expected = ( - '
# A Code Comment\n'
+                '
# A Code Comment\n'
                 '
' ) else: @@ -87,7 +87,7 @@ def test_codehilite_guess_lang(self): def test_codehilite_guess_lang_plain_text(self): if has_pygments: expected = ( - '
plain text\n'
+                '
plain text\n'
                 '
' ) else: @@ -100,12 +100,10 @@ def test_codehilite_guess_lang_plain_text(self): def test_codehilite_set_lang(self): if has_pygments: - # Note an extra `` is added to end of code block when `lang` explicitly set. - # Compare with expected output for `test_guess_lang`. Not sure why this happens. expected = ( '
<?php '
                 'print("Hello World"'
-                '); ?>\n'
+                '); ?>\n'
                 '
' ) else: @@ -168,10 +166,10 @@ def test_codehilite_lang_prefix(self): def test_codehilite_linenos_true(self): if has_pygments: expected = ( - '
1
' - '
plain text\n'
-                '
\n' - '
' + '
' + '
1
' + '
plain text\n'
+                '
' ) else: expected = ( @@ -209,10 +207,10 @@ def test_codehilite_linenos_none(self): def test_codehilite_linenos_table(self): if has_pygments: expected = ( - '
1
' - '
plain text\n'
-                '
\n' - '
' + '
' + '
1
' + '
plain text\n'
+                '
' ) else: expected = ( @@ -237,10 +235,10 @@ def test_codehilite_linenos_inline(self): def test_codehilite_linenums_true(self): if has_pygments: expected = ( - '
1
' - '
plain text\n'
-                '
\n' - '
' + '
' + '
1
' + '
plain text\n'
+                '
' ) else: expected = ( @@ -275,6 +273,20 @@ def test_codehilite_set_css_class(self): ) self.assertOutputEquals('plain text', expected, lang='text', css_class='override') + def test_codehilite_set_cssclass_escaped(self): + if has_pygments: + # Pygments escapes `cssclass` itself as of version 2.20.0. + expected = ( + '
plain text\n'
+                '
' + ) + else: + expected = ( + '
plain text\n'
+                '
' + ) + self.assertOutputEquals('plain text', expected, lang='text', cssclass='over">ride') + def test_codehilite_linenostart(self): if has_pygments: expected = ( @@ -293,9 +305,9 @@ def test_codehilite_linenos_hl_lines(self): if has_pygments: expected = ( '
'
-                '1line 1\n'
+                '1line 1\n'
                 '2line 2\n'
-                '3line 3\n'
+                '3line 3\n'
                 '
' ) else: @@ -385,7 +397,7 @@ def testBasicCodeHilite(self): if has_pygments: # Odd result as no `lang` given and a single comment is not enough for guessing. expected = ( - '
# A Code Comment\n'
+                '
# A Code Comment\n'
                 '
' ) else: @@ -402,12 +414,11 @@ def testBasicCodeHilite(self): def testLinenumsTrue(self): if has_pygments: expected = ( - '' - '' - '
1
'
-                '# A Code Comment\n'
-                '
\n' - '
' + '
' + '' + '
1
'
+                '# A Code Comment\n'
+                '
' ) else: expected = ( @@ -443,7 +454,7 @@ def testLinenumsFalse(self): def testLinenumsNone(self): if has_pygments: expected = ( - '
# A Code Comment\n'
+                '
# A Code Comment\n'
                 '
' ) else: @@ -460,12 +471,11 @@ def testLinenumsNone(self): def testLinenumsNoneWithShebang(self): if has_pygments: expected = ( - '' - '' - '
1
'
+                '
' + '' + '
1
'
                 '# A Code Comment\n'
-                '
\n' - '
' + '
' ) else: expected = ( @@ -656,7 +666,7 @@ def testUnknownOption(self): if has_pygments: # Odd result as no `lang` given and a single comment is not enough for guessing. expected = ( - '
# A Code Comment\n'
+                '
# A Code Comment\n'
                 '
' ) else: @@ -674,12 +684,12 @@ def testMultipleBlocksSameStyle(self): if has_pygments: # See also: https://github.com/Python-Markdown/markdown/issues/1240 expected = ( - '
'
-                '# First Code Block\n'
+                '
'
+                '# First Code Block\n'
                 '
\n\n' '

Normal paragraph

\n' - '
'
-                '# Second Code Block\n'
+                '
'
+                '# Second Code Block\n'
                 '
' ) else: @@ -731,7 +741,7 @@ def testFormatterLangStrGuessLang(self): if has_pygments: expected = ( '
'
-                '<?php '
+                '<?php '
                 'print('
                 '"Hello World"'
                 '); ?>\n'
diff --git a/tests/test_syntax/extensions/test_fenced_code.py b/tests/test_syntax/extensions/test_fenced_code.py
index bbb44c3ca..d97239f49 100644
--- a/tests/test_syntax/extensions/test_fenced_code.py
+++ b/tests/test_syntax/extensions/test_fenced_code.py
@@ -985,7 +985,8 @@ def testFencedLanguageAttrCssclass(self):
         )
 
     def testFencedClassesEscaped(self):
-        # Classes passed on to `codehilite` are escaped like the classes of a block rendered without it.
+        # Classes passed on to `codehilite` as `css_class` are escaped like the classes of a block
+        # rendered without it. With Pygments, the escaping is done by Pygments itself.
         if has_pygments:
             expected = (
                 '
'
@@ -1013,12 +1014,11 @@ def testFencedClassesEscaped(self):
     def testFencedLanguageAttrLinenums(self):
         if has_pygments:
             expected = (
-                ''
-                ''
-                '
1
'
+                '
' + '' + '
1
'
                 '# Some python code\n'
-                '
\n' - '
' + '
' ) else: expected = ( @@ -1066,8 +1066,8 @@ def testFencedLanguageAttrNoclasses(self): if has_pygments: expected = ( '
' - '
'
-                '# Some python code\n'
+                '
'
+                '# Some python code\n'
                 '
' ) else: @@ -1091,12 +1091,12 @@ def testFencedMultipleBlocksSameStyle(self): if has_pygments: # See also: https://github.com/Python-Markdown/markdown/issues/1240 expected = ( - '
'
-                '# First Code Block\n'
+                '
'
+                '# First Code Block\n'
                 '
\n\n' '

Normal paragraph

\n' - '
'
-                '# Second Code Block\n'
+                '
'
+                '# Second Code Block\n'
                 '
' ) else: @@ -1135,8 +1135,9 @@ def testFencedMultipleBlocksSameStyle(self): def testCustomPygmentsFormatter(self): if has_pygments: class CustomFormatter(pygments.formatters.HtmlFormatter): - def wrap(self, source, outfile): - return self._wrap_div(self._wrap_code(source)) + def wrap(self, source): + # `HtmlFormatter.format_unencoded` applies `_wrap_div` around `wrap`. + return self._wrap_code(source) def _wrap_code(self, source): yield 0, '' diff --git a/tox.ini b/tox.ini index de9467f7e..edce22715 100644 --- a/tox.ini +++ b/tox.ini @@ -14,7 +14,7 @@ commands = [testenv:pygments] # Run tests with pygments installed (override deps only). setenv = - PYGMENTS_VERSION = 2.7.1 + PYGMENTS_VERSION = 2.20.0 deps = pytidylib pygments=={env:PYGMENTS_VERSION}