"""Test the Pygments highlighting bridge.""" from __future__ import annotations from typing import TYPE_CHECKING from unittest import mock import pygments import pytest from pygments.formatters.html import HtmlFormatter from pygments.lexer import RegexLexer from pygments.token import Name, Text from sphinx.highlighting import PygmentsBridge if TYPE_CHECKING: from collections.abc import Iterable from typing import TextIO from pygments.token import _TokenType from sphinx.testing.util import SphinxTestApp if tuple(map(int, pygments.__version__.split('.')[:2])) < (2, 18): from pygments.formatter import Formatter Formatter.__class_getitem__ = classmethod(lambda cls, name: cls) # type: ignore[attr-defined] class MyLexer(RegexLexer): name = 'testlexer' tokens = { 'root': [ ('a', Name), ('b', Text), ], } class MyFormatter(HtmlFormatter[str]): def format( self, tokensource: Iterable[tuple[_TokenType, str]], outfile: TextIO, ) -> None: outfile.writelines(tok[1] for tok in tokensource) @pytest.mark.sphinx('html', testroot='root') def test_add_lexer(app: SphinxTestApp) -> None: app.add_lexer('test', MyLexer) bridge = PygmentsBridge('html') ret = bridge.highlight_block('ab', 'test') assert 'ab' in ret def test_detect_interactive() -> None: bridge = PygmentsBridge('html') blocks = [ """ >>> testing() True """, ] for block in blocks: ret = bridge.highlight_block(block.lstrip(), 'python') assert ret.startswith('
print '
'"Hello sphinx world"\nreST ``like`` text\nprint'
'('
'"Hello sphinx world"'
')\nprint'
'('
'"Hello sphinx world"'
')\n