Skip to content

The animation engine for agents: blazingly fast math and 3D videos with Manim's Python API, on a Rust GPU core.

Python

Close a double-brace group at the }} that closes its own braces

japbcoelho84e82b44eda6
diff --git a/docs/content/changelog.md b/docs/content/changelog.md
index d1129190..dc814ef0 100644
--- a/docs/content/changelog.md
+++ b/docs/content/changelog.md
@@ -57,6 +57,7 @@ The notable changes to ManimGX, release by release. The format follows
- Name a partite layout's vertex that is not in the graph, and a vertex's keywords or an edge's `tip_config` that are not a mapping, in the error raised.
- Preserve the benchmark comparison images' aspect ratios when PyPI narrows the README table.
- Credit Filament, whose code the 3D lighting is adapted from, in the README and the wheels' third-party notices.
+- End a `{{…}}` part of a `MathTex` or `Tex` at the `}}` that closes its own braces: `MathTex(r"V={{\tfrac{1}{3}}}B")` split at the fraction's `}}`, so the part was `\tfrac{1}{3` and `get_part_by_tex(r"\tfrac{1}{3}")` found nothing. An escaped brace (`\{` or `\}`) no longer opens or closes a part.
## 0.1.1
diff --git a/docs/content/user-guide/coming-from-manim-ce.md b/docs/content/user-guide/coming-from-manim-ce.md
index 87550346..5f477fac 100644
--- a/docs/content/user-guide/coming-from-manim-ce.md
+++ b/docs/content/user-guide/coming-from-manim-ce.md
@@ -18,6 +18,8 @@ code behaves. This page shows where it is different.
- You don't install LaTeX. `Tex` and `MathTex` convert their LaTeX to
[Typst](https://typst.app), which the engine sets. LaTeX packages and `\def` don't
convert.
+- Double braces make a part wherever they are: `m.MathTex("x={{y}}")` has two parts.
+ Manim CE makes one only at the string's start or after a space.
## The frame
diff --git a/src/manimgx/mobjects/text.py b/src/manimgx/mobjects/text.py
index 39219577..6f2b534b 100644
--- a/src/manimgx/mobjects/text.py
+++ b/src/manimgx/mobjects/text.py
@@ -1131,24 +1131,44 @@ def _standalone(tex: str) -> str:
return "{" * max(0, closes - opens) + tex + "}" * max(0, opens - closes)
-_BRACES = re.compile("{{(.*?)}}")
_HOLE = 0xE000 # private-use characters: mitex passes them through as they are
+_TOKENS = re.compile(r"\\([a-zA-Z]+)|\\.|([{}])")
+_DEPTH = {"{": 1, "}": -1, "begin": 1, "end": -1, "left": 1, "right": -1}
+
+
+def _split_braces(tex: str) -> list[str]:
+ """The string split at its `{{…}}`: what is outside them and what each holds, in turn,
+ starting outside. A group ends at the first `}}` where its own braces are closed, so it
+ may hold braces of its own: `{{\\tfrac{1}{3}}}` holds `\\tfrac{1}{3}`. An escaped brace
+ is no brace, and a `{{` never closed is as written."""
+ pieces: list[str] = []
+ at = depth = 0
+ for token in _TOKENS.finditer(tex):
+ inside = len(pieces) % 2 == 1 # the pieces alternate, starting outside
+ if token.start() < at:
+ continue # the second brace of a pair
+ if depth == 0 and tex.startswith("}}" if inside else "{{", token.start()):
+ pieces.append(tex[at : token.start()])
+ at = token.start() + 2
+ elif inside:
+ depth += _DEPTH.get(token[2], 0)
+ if len(pieces) % 2: # a `{{` never closed
+ return [*pieces[:-1], pieces[-1] + tex[at - 2 :]]
+ return [*pieces, tex[at:]]
+
+
def _isolate_braces(strings: list[str], math: bool) -> list[str]:
"""CE's double braces: `{{…}}` sets what it holds apart as a part of its own. In math,
where spaces mean nothing, once they split anything every part is stripped; text keeps
its spaces, so its strings still join into the text as written."""
- pieces = [p for s in strings for p in _BRACES.split(s)]
+ pieces = [p for s in strings for p in _split_braces(s)]
if math and len(pieces) > len(strings):
pieces = [p.strip() for p in pieces]
return [p for p in pieces if p]
-_TOKENS = re.compile(r"\\([a-zA-Z]+)|\\.|([{}])")
-_DEPTH = {"{": 1, "}": -1, "begin": 1, "end": -1, "left": 1, "right": -1}
-
-
def _balanced(tex: str) -> bool:
"""Does the LaTeX stand on its own: every group, environment and delimiter it opens closed
in it, and none closed that it did not open? (mitex closes what is left open, so a
@@ -1362,11 +1382,14 @@ class MathTex(Typst):
The strings are one formula, joined by `arg_separator` and typeset whole, so parting
a formula moves none of its glyphs. Each string is a part, a
[MathTexPart][manimgx.MathTexPart] of the glyphs it adds, and double braces set a
- part apart within a string: `MathTex("{{a^2}} + {{b^2}} = {{c^2}}")` has the five
- parts of the first example below. A string that stands on its own (its braces,
- environments and `\left`…`\right` closed within it) holds exactly its glyphs. The
- rest, such as a fraction's bar or the glyphs of a fragment like `"^2"`, go to the
- first fragment between the standing strings around them: in
+ part apart within a string, wherever they are:
+ `MathTex("{{a^2}} + {{b^2}} = {{c^2}}")` has the five parts of the first example
+ below. A part ends at the `}}` that closes its own braces, so it may hold braces of
+ its own (`{{\tfrac{1}{3}}}`); an escaped brace (`\{`) is no brace, and a `{{` never
+ closed is as written. A string that stands on its own (its braces, environments and
+ `\left`…`\right` closed within it) holds exactly its glyphs. The rest, such as a
+ fraction's bar or the glyphs of a fragment like `"^2"`, go to the first fragment
+ between the standing strings around them: in
`MathTex(r"\frac{", "a", "}{", "b", "}")` the bar is the closing `"}"`'s, where TeX
draws it, and in `MathTex(r"e^{i", r"\pi}")`, split inside a term, every glyph is
the first part's. A formula whose parts can't be told apart raises ValueError.
diff --git a/tests/unit/mobjects/test_text.py b/tests/unit/mobjects/test_text.py
index 0a56b47a..945cf7ee 100644
--- a/tests/unit/mobjects/test_text.py
+++ b/tests/unit/mobjects/test_text.py
@@ -37,6 +37,7 @@ from hypothesis import strategies as st
import manimgx as m
from manimgx.drawing import typesetting as tc
+from manimgx.mobjects.text import _split_braces
def _pitch(first: m.Mobject, second: m.Mobject) -> float:
@@ -189,6 +190,37 @@ def test_double_braces_set_a_part_apart() -> None:
assert [len(part) for part in eq] == [2, 1, 1, 0, 1, 1]
+def test_double_braces_hold_braces_of_their_own() -> None:
+ """A group ends at the `}}` that closes it, not at the first `}}` within it."""
+ eq = m.MathTex(r"V={{\tfrac{1}{3}}}{{B}}\cdot{{h}}")
+ assert eq.tex_strings == ["V=", r"\tfrac{1}{3}", "B", r"\cdot", "h"]
+ assert eq.get_part_by_tex(r"\tfrac{1}{3}") is not None
+
+
+def test_an_escaped_brace_neither_opens_nor_closes_a_part() -> None:
+ eq = m.MathTex(r"{{\{x\}}}\cup\{{{y}}\}")
+ assert eq.tex_strings == [r"\{x\}", r"\cup\{", "y", r"\}"]
+
+
[email protected]("tex", ["a{{b", r"{{\frac{1}{2}}"])
+def test_double_braces_never_closed_are_as_written(tex: str) -> None:
+ assert m.MathTex(tex).tex_strings == [tex]
+
+
+def test_doubled_braces_of_tex_make_parts_too() -> None:
+ """Double braces set a part apart wherever they are, so `x^{{2}}` is "x^" and "2":
+ parts that cannot be told apart."""
+ with pytest.raises(ValueError, match="cannot tell these parts apart"):
+ m.MathTex(r"x^{{2}}")
+
+
+@given(st.text(alphabet="{}\\ab"))
+def test_a_string_split_at_double_braces_joins_back_into_itself(tex: str) -> None:
+ pieces = _split_braces(tex)
+ groups = (p if i % 2 == 0 else "{{" + p + "}}" for i, p in enumerate(pieces))
+ assert "".join(groups) == tex
+
+
@pytest.mark.parametrize(
("strings", "counts"),
[