Correctly get lexer for language
`get_lexer_by_name` doesn't actually get the lexer by its name...
This commit is contained in:
parent
c7e56ab038
commit
c56cc2f995
2 changed files with 16 additions and 5 deletions
|
@ -3,7 +3,7 @@ from typing import Iterator
|
|||
from django.utils.safestring import mark_safe
|
||||
from pygments import highlight
|
||||
from pygments.formatters.html import HtmlFormatter
|
||||
from pygments.lexers import get_all_lexers, get_lexer_by_name
|
||||
from pygments.lexers import find_lexer_class, get_all_lexers
|
||||
from wagtail.blocks import (
|
||||
BooleanBlock,
|
||||
CharBlock,
|
||||
|
@ -21,11 +21,11 @@ def get_language_choices() -> Iterator[tuple[str, str]]:
|
|||
|
||||
class CodeStructValue(StructValue):
|
||||
def code(self) -> str:
|
||||
lexer = get_lexer_by_name(self.get("language"))
|
||||
lexer = find_lexer_class(self["language"])()
|
||||
formatter = HtmlFormatter(
|
||||
linenos=None,
|
||||
)
|
||||
return mark_safe(highlight(self.get("source"), lexer, formatter))
|
||||
return mark_safe(highlight(self["source"], lexer, formatter))
|
||||
|
||||
|
||||
class CodeBlock(StructBlock):
|
||||
|
|
|
@ -1,10 +1,11 @@
|
|||
from django.test import TestCase
|
||||
from django.test import SimpleTestCase
|
||||
from django.urls import reverse
|
||||
|
||||
from .blocks import CodeStructValue, get_language_choices
|
||||
from .utils import PYGMENTS_VERSION_SLUG
|
||||
|
||||
|
||||
class PygmentsStylesTestCase(TestCase):
|
||||
class PygmentsStylesTestCase(SimpleTestCase):
|
||||
url = reverse("code-block:styles")
|
||||
|
||||
def test_accessible(self) -> None:
|
||||
|
@ -15,3 +16,13 @@ class PygmentsStylesTestCase(TestCase):
|
|||
|
||||
def test_url_contains_version(self) -> None:
|
||||
self.assertIn(PYGMENTS_VERSION_SLUG, self.url)
|
||||
|
||||
|
||||
class CodeStructValueTestCase(SimpleTestCase):
|
||||
def test_highlights(self) -> None:
|
||||
for language, _ in get_language_choices():
|
||||
with self.subTest(language):
|
||||
block = CodeStructValue(
|
||||
None, [("source", "test"), ("language", language)]
|
||||
)
|
||||
self.assertIsInstance(block.code(), str)
|
||||
|
|
Loading…
Reference in a new issue