Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
57 commits
Select commit Hold shift + click to select a range
b88b358
Extracted the method get_mob_from_shape_element
henrikmidtiby Nov 13, 2025
e8e003a
Moved more functionality to get_mob_from_shape_element
henrikmidtiby Nov 13, 2025
f9f7138
More cleanup
henrikmidtiby Nov 13, 2025
1a9212b
Parse the svg file while maintaining the group structure.
henrikmidtiby Nov 13, 2025
bd78c43
Make the svg groups available
henrikmidtiby Nov 13, 2025
494708e
Merge branch 'main' into maintain_groups_from_svg
henrikmidtiby Dec 8, 2025
9e364e3
Handle PERF401 issue
henrikmidtiby Dec 8, 2025
9059479
[pre-commit.ci] pre-commit autoupdate (#4506)
pre-commit-ci[bot] Dec 15, 2025
66f456e
Added an example of the issue
henrikmidtiby Dec 15, 2025
d6c6f5d
Experimenting with coloring elements from the latex equation
henrikmidtiby Dec 15, 2025
96db1b0
...
henrikmidtiby Dec 16, 2025
fe411af
Regular expression can now match more than one object
henrikmidtiby Dec 16, 2025
68395df
Process the string by applying the substrings in the order they match
henrikmidtiby Dec 16, 2025
4499c73
Code refactoring and added type annotations
henrikmidtiby Dec 16, 2025
751c718
...
henrikmidtiby Dec 16, 2025
73a08e4
Added a lot of test cases
henrikmidtiby Dec 16, 2025
b9e313e
More examples
henrikmidtiby Dec 16, 2025
63a4c19
More examples
henrikmidtiby Dec 17, 2025
a651d95
Use matched_strings_and_ids to simplify existing methods
henrikmidtiby Dec 17, 2025
b8c9123
Remove unused code
henrikmidtiby Dec 17, 2025
86a1b46
Update get_part_by_tex to use matched_strings_and_ids
henrikmidtiby Dec 17, 2025
1c2d113
This is required for test_MathTable to pass
henrikmidtiby Dec 17, 2025
d9bc03f
Ensure that self.texstring is set.
henrikmidtiby Dec 17, 2025
64894a7
Merge branch 'main' into MathTexFromScratch
henrikmidtiby Dec 17, 2025
d12bde7
Added more examples from exising issues in the github repo
henrikmidtiby Dec 18, 2025
63f786f
Ensure that latex groups are maintained by adding an additional pair …
henrikmidtiby Dec 18, 2025
d8a4b43
ExampleScene -> Scene
henrikmidtiby Dec 19, 2025
bb41f5c
Added comment
henrikmidtiby Dec 19, 2025
c9b6c52
_break_up_by_substrings
henrikmidtiby Dec 19, 2025
0afc9b8
Refactor code
henrikmidtiby Dec 19, 2025
e2f3203
Added comment to example
henrikmidtiby Dec 19, 2025
f0a4bf9
Handle integer inputs well.
henrikmidtiby Dec 19, 2025
3fd3adc
Expose the original tex_string
henrikmidtiby Dec 19, 2025
f06991e
Do not treat the content of substrings_to_isolate as regular expressi…
henrikmidtiby Dec 19, 2025
c11dcc3
Updated examples
henrikmidtiby Dec 19, 2025
c11799a
Update examples
henrikmidtiby Dec 19, 2025
ada86f1
Fix SVMobject caching issue.
henrikmidtiby Dec 22, 2025
919bfee
Remove traces from brace_notation_split_occurred
henrikmidtiby Dec 22, 2025
b7d1c83
Simplify MathTex::_break_up_by_substrings
henrikmidtiby Dec 22, 2025
ca6f0c1
Fix small issue in tex that in some cases moved elements a tiny bit a…
henrikmidtiby Dec 22, 2025
d7ddee8
No use of regular expressions for locate substrings.
henrikmidtiby Dec 22, 2025
654f877
Updated notes to the set of test cases
henrikmidtiby Dec 22, 2025
ee93305
Handle issues with the center environment.
henrikmidtiby Dec 22, 2025
01e1f25
Add example
henrikmidtiby Dec 22, 2025
084745d
Fix issue with rectangles (e.g. from sqrt)
henrikmidtiby Dec 22, 2025
e4d19cb
ConvertToOpenGL
henrikmidtiby Dec 22, 2025
3b7da3b
Reduce the number of nesting levels.
henrikmidtiby Dec 23, 2025
d2ea3f9
Use the specified arg_seperator
henrikmidtiby Dec 23, 2025
e98c514
Deal with the double curly brace markup
henrikmidtiby Dec 23, 2025
2d6bfee
Code cleanup
henrikmidtiby Dec 23, 2025
3e99987
Code cleanup
henrikmidtiby Dec 23, 2025
ba58cd0
Rollback a few changes
henrikmidtiby Dec 23, 2025
4025934
Code cleanup
henrikmidtiby Dec 23, 2025
5b69c36
Merge branch 'main' into MathTexFromScratch
henrikmidtiby Jan 13, 2026
e928a0c
Adjust paths the generated artefacts in tests that rely on MathTex
henrikmidtiby Jan 13, 2026
bbdd0bb
Added a remark to the using text guide on enclosing snippets in curly…
henrikmidtiby Jan 13, 2026
800cfa6
Added space around the numerator argument to frac to avoid having dou…
henrikmidtiby Jan 13, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion docs/source/guides/using_text.rst
Original file line number Diff line number Diff line change
Expand Up @@ -424,7 +424,7 @@ may be expected. To color only ``x`` yellow, we have to do the following:
class CorrectLaTeXSubstringColoring(Scene):
def construct(self):
equation = MathTex(
r"e^x = x^0 + x^1 + \frac{1}{2} x^2 + \frac{1}{6} x^3 + \cdots + \frac{1}{n!} x^n + \cdots",
r"e^{x} = x^0 + x^1 + \frac{1}{2} x^2 + \frac{1}{6} x^3 + \cdots + \frac{1}{n!} x^n + \cdots",
substrings_to_isolate="x"
)
equation.set_color_by_tex("x", YELLOW)
Expand All @@ -434,6 +434,8 @@ By setting ``substrings_to_isolate`` to ``x``, we split up the
:class:`~.MathTex` into substrings automatically and isolate the ``x`` components
into individual substrings. Only then can :meth:`~.set_color_by_tex` be used
to achieve the desired result.
If one of the ``substrings_to_isolate`` is in a sub or superscript, it needs
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we attempt to strengthen the parser to make this not necessary? Perhaps not at first.

to be enclosed by curly brackets.

Note that Manim also supports a custom syntax that allows splitting
a TeX string into substrings easily: simply enclose parts of your formula
Expand Down
114 changes: 80 additions & 34 deletions manim/mobject/svg/svg_mobject.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,12 @@
from ..geometry.line import Line
from ..geometry.polygram import Polygon, Rectangle, RoundedRectangle
from ..opengl.opengl_compatibility import ConvertToOpenGL
from ..types.vectorized_mobject import VMobject
from ..types.vectorized_mobject import VGroup, VMobject

__all__ = ["SVGMobject", "VMobjectFromSVGPath"]


SVG_HASH_TO_MOB_MAP: dict[int, VMobject] = {}
SVG_HASH_TO_MOB_MAP: dict[int, SVGMobject] = {}


def _convert_point_to_3d(x: float, y: float) -> np.ndarray:
Expand Down Expand Up @@ -127,6 +127,7 @@ def __init__(
self.stroke_color = stroke_color
self.stroke_opacity = stroke_opacity # type: ignore[assignment]
self.stroke_width = stroke_width # type: ignore[assignment]
self.id_to_vgroup_dict: dict[str, VGroup] = {}
if self.stroke_width is None:
self.stroke_width = 0

Expand Down Expand Up @@ -170,6 +171,7 @@ def init_svg_mobject(self, use_svg_cache: bool) -> None:
if hash_val in SVG_HASH_TO_MOB_MAP:
mob = SVG_HASH_TO_MOB_MAP[hash_val].copy()
self.add(*mob)
self.id_to_vgroup_dict = mob.id_to_vgroup_dict
return

self.generate_mobject()
Expand Down Expand Up @@ -203,8 +205,9 @@ def generate_mobject(self) -> None:
svg = se.SVG.parse(modified_file_path)
modified_file_path.unlink()

mobjects = self.get_mobjects_from(svg)
mobjects, mobject_dict = self.get_mobjects_from(svg)
self.add(*mobjects)
self.id_to_vgroup_dict = mobject_dict
self.flip(RIGHT) # Flip y

def get_file_path(self) -> Path:
Expand Down Expand Up @@ -258,7 +261,9 @@ def generate_config_style_dict(self) -> dict[str, str]:
result[svg_key] = str(svg_default_dict[style_key])
return result

def get_mobjects_from(self, svg: se.SVG) -> list[VMobject]:
def get_mobjects_from(
self, svg: se.SVG
) -> tuple[list[VMobject], dict[str, VGroup]]:
"""Convert the elements of the SVG to a list of mobjects.

Parameters
Expand All @@ -267,36 +272,77 @@ def get_mobjects_from(self, svg: se.SVG) -> list[VMobject]:
The parsed SVG file.
"""
result: list[VMobject] = []
for shape in svg.elements():
# can we combine the two continue cases into one?
if isinstance(shape, se.Group): # noqa: SIM114
continue
elif isinstance(shape, se.Path):
mob: VMobject = self.path_to_mobject(shape)
elif isinstance(shape, se.SimpleLine):
mob = self.line_to_mobject(shape)
elif isinstance(shape, se.Rect):
mob = self.rect_to_mobject(shape)
elif isinstance(shape, (se.Circle, se.Ellipse)):
mob = self.ellipse_to_mobject(shape)
elif isinstance(shape, se.Polygon):
mob = self.polygon_to_mobject(shape)
elif isinstance(shape, se.Polyline):
mob = self.polyline_to_mobject(shape)
elif isinstance(shape, se.Text):
mob = self.text_to_mobject(shape)
elif isinstance(shape, se.Use) or type(shape) is se.SVGElement:
continue
else:
logger.warning(f"Unsupported element type: {type(shape)}")
continue
if mob is None or not mob.has_points():
continue
self.apply_style_to_mobject(mob, shape)
if isinstance(shape, se.Transformable) and shape.apply:
self.handle_transform(mob, shape.transform)
result.append(mob)
return result
stack: list[tuple[se.SVGElement, int]] = []
stack.append((svg, 1))
group_id_number = 0
vgroup_stack: list[str] = ["root"]
vgroup_names: list[str] = ["root"]
vgroups: dict[str, VGroup] = {"root": VGroup()}
while len(stack) > 0:
element, depth = stack.pop()
# Reduce stack heights
vgroup_stack = vgroup_stack[0:(depth)]
try:
group_name = str(element.values["id"])
except Exception:
group_name = f"numbered_group_{group_id_number}"
group_id_number += 1
vg = VGroup()
vgroup_names.append(group_name)
vgroup_stack.append(group_name)
vgroups[group_name] = vg

if isinstance(element, (se.Group, se.Use)):
stack.extend((subelement, depth + 1) for subelement in element[::-1])
# Add element to the parent vgroup
try:
if isinstance(
element,
(
se.Path,
se.SimpleLine,
se.Rect,
se.Circle,
se.Ellipse,
se.Polygon,
se.Polyline,
se.Text,
),
):
mob = self.get_mob_from_shape_element(element)
if mob is not None:
result.append(mob)
for parent_name in vgroup_stack[:-1]:
vgroups[parent_name].add(mob)
except Exception as e:
print(e)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

logger.error with a bit more context?


return result, vgroups

def get_mob_from_shape_element(self, shape: se.SVGElement) -> VMobject | None:
if isinstance(shape, se.Path):
mob: VMobject | None = self.path_to_mobject(shape)
elif isinstance(shape, se.SimpleLine):
mob = self.line_to_mobject(shape)
elif isinstance(shape, se.Rect):
mob = self.rect_to_mobject(shape)
elif isinstance(shape, (se.Circle, se.Ellipse)):
mob = self.ellipse_to_mobject(shape)
elif isinstance(shape, se.Polygon):
mob = self.polygon_to_mobject(shape)
elif isinstance(shape, se.Polyline):
mob = self.polyline_to_mobject(shape)
elif isinstance(shape, se.Text):
mob = self.text_to_mobject(shape)
else:
logger.warning(f"Unsupported element type: {type(shape)}")
mob = None
if mob is None or not mob.has_points():
return mob
self.apply_style_to_mobject(mob, shape)
if isinstance(shape, se.Transformable) and shape.apply:
self.handle_transform(mob, shape.transform)
return mob

@staticmethod
def handle_transform(mob: VMobject, matrix: se.Matrix) -> VMobject:
Expand Down
10 changes: 5 additions & 5 deletions manim/mobject/table.py
Original file line number Diff line number Diff line change
Expand Up @@ -1078,11 +1078,11 @@ def construct(self):
[[0,30,45,60,90],
[90,60,45,30,0]],
col_labels=[
MathTex(r"\frac{\sqrt{0}}{2}"),
MathTex(r"\frac{\sqrt{1}}{2}"),
MathTex(r"\frac{\sqrt{2}}{2}"),
MathTex(r"\frac{\sqrt{3}}{2}"),
MathTex(r"\frac{\sqrt{4}}{2}")],
MathTex(r"\frac{ \sqrt{0} }{2}"),
MathTex(r"\frac{ \sqrt{1} }{2}"),
MathTex(r"\frac{ \sqrt{2} }{2}"),
MathTex(r"\frac{ \sqrt{3} }{2}"),
MathTex(r"\frac{ \sqrt{4} }{2}")],
row_labels=[MathTex(r"\sin"), MathTex(r"\cos")],
h_buff=1,
element_to_mobject_config={"unit": r"^{\circ}"})
Expand Down
Loading