Better parsing of color styles in CodeMobject (#4454)

* fixed problem: default value of color in styles in CodeMobject

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* added accidently removed test

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Update code_mobject.py

Code suggested by maejam

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Henrik Skov Midtiby <hemi@mmmi.sdu.dk>
Co-authored-by: Henrik Skov Midtiby <henrikmidtiby@gmail.com>
This commit is contained in:
Sir James Clark Maxwell 2025-10-26 08:47:47 +01:00 committed by GitHub
commit 3e8f41c9be
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 20 additions and 4 deletions

View file

@ -6,6 +6,7 @@ __all__ = [
"Code",
]
import re
from pathlib import Path
from typing import Any, Literal
@ -169,10 +170,10 @@ class Code(VMobject, metaclass=ConvertToOpenGL):
if child.name == "span":
try:
child_style = child["style"]
if isinstance(child_style, str):
color = child_style.removeprefix("color: ")
else:
color = None
match_ = re.match(
r"color: (#[A-Fa-f0-9]{6}|#[A-Fa-f0-9]{3})", child_style
)
color = None if match_ is None else match_.group(1)
except KeyError:
color = None
current_line_color_ranges.append(

View file

@ -1,4 +1,5 @@
import numpy as np
import pytest
from manim.mobject.text.code_mobject import Code
from manim.utils.color.core import ManimColor
@ -45,3 +46,17 @@ for _ in range(42):
rendered_code.code_lines[0].height,
rendered_code.code_lines[2].height,
)
def test_code_initialization_style_correct_color():
for style in Code.get_styles_list():
try:
Code(
code_string="""# This is a comment.
var = 3
print(var)
""",
formatter_style=style,
)
except ValueError as e:
pytest.fail(f"Code initialization failed for style {style} with error: {e}")