Skip to content

Commit

Permalink
Relax Pygments parsing on lexing failures
Browse files Browse the repository at this point in the history
  • Loading branch information
AA-Turner committed Aug 12, 2023
1 parent 7e9a206 commit 7d8df06
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 11 deletions.
1 change: 1 addition & 0 deletions CHANGES
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ Bugs fixed
* #11546: Translated nodes identical to their original text are now marked
with the ``translated=True`` attribute.
* #10049: html: Change "Permalink" to "Link" for title text in link anchors.
* #4225: Relax Pygments parsing on lexing failures.

Testing
-------
Expand Down
22 changes: 14 additions & 8 deletions sphinx/highlighting.py
Original file line number Diff line number Diff line change
Expand Up @@ -164,17 +164,23 @@ def highlight_block(self, source: str, lang: str, opts: dict | None = None,
formatter = self.get_formatter(**kwargs)
try:
hlsource = highlight(source, lexer, formatter)
except ErrorToken:
except ErrorToken as err:
# this is most probably not the selected language,
# so let it pass unhighlighted
# so let it pass un highlighted
if lang == 'default':
pass # automatic highlighting failed.
lang = 'none' # automatic highlighting failed.
else:
logger.warning(__('Could not lex literal_block %r as "%s". '
'Highlighting skipped.'), source, lang,
type='misc', subtype='highlighting_failure',
location=location)
lexer = self.get_lexer(source, 'none', opts, force, location)
logger.warning(
__('Lexing literal_block %r as "%s" resulted in an error at token: %r. '
'Retrying in relaxed mode.'),
source, lang, str(err),
type='misc', subtype='highlighting_failure',
location=location)
if force:
lang = 'none'
else:
force = True
lexer = self.get_lexer(source, lang, opts, force, location)
hlsource = highlight(source, lexer, formatter)

if self.dest == 'html':
Expand Down
6 changes: 3 additions & 3 deletions tests/test_highlighting.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,8 +97,8 @@ def test_default_highlight(logger):

# python: raises error if highlighting failed
ret = bridge.highlight_block('reST ``like`` text', 'python')
logger.warning.assert_called_with('Could not lex literal_block %r as "%s". '
'Highlighting skipped.',
'reST ``like`` text', 'python',
logger.warning.assert_called_with('Lexing literal_block %r as "%s" resulted in an error at token: %r. '
'Retrying in relaxed mode.',
'reST ``like`` text', 'python', '`',
type='misc', subtype='highlighting_failure',
location=None)

0 comments on commit 7d8df06

Please sign in to comment.