A community-maintained Python framework for creating mathematical animations.
fix: MathTex double-brace splitting no longer fires on natural LaTeX }} (#4602)
Benjamin Hackl000e7792bd06
diff --git a/docs/source/guides/using_text.rst b/docs/source/guides/using_text.rstindex 739510621..947bbae2e 100644--- a/docs/source/guides/using_text.rst+++ b/docs/source/guides/using_text.rst@@ -389,8 +389,9 @@ Substrings and partsThe TeX mobject can accept multiple strings as arguments. Afterwards you canrefer to the individual parts either by their index (like ``tex[1]``), or by-selecting parts of the tex code. In this example, we set the color-of the ``\bigstar`` using :func:`~.set_color_by_tex`:+using :func:`~.set_color_by_tex`, which matches the argument exactly against+the strings passed to the constructor. In this example, we color the+``\bigstar`` part:.. manim:: LaTeXSubstrings:save_last_frame:@@ -398,25 +399,13 @@ of the ``\bigstar`` using :func:`~.set_color_by_tex`:class LaTeXSubstrings(Scene):def construct(self):tex = Tex('Hello', r'$\bigstar$', r'\LaTeX', font_size=144)- tex.set_color_by_tex('igsta', RED)+ tex.set_color_by_tex(r'$\bigstar$', RED)self.add(tex)-Note that :func:`~.set_color_by_tex` colors the entire substring containing-the Tex, not just the specific symbol or Tex expression. Consider the following example:--.. manim:: IncorrectLaTeXSubstringColoring- :save_last_frame:-- class IncorrectLaTeXSubstringColoring(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"- )- equation.set_color_by_tex("x", YELLOW)- self.add(equation)--As you can see, this colors the entire equation yellow, contrary to what-may be expected. To color only ``x`` yellow, we have to do the following:+Because :func:`~.set_color_by_tex` requires an exact match, it cannot directly+target a token inside a string that was passed as a single argument. To color+every ``x`` in a formula, use ``substrings_to_isolate`` to split the string at+each occurrence first:.. manim:: CorrectLaTeXSubstringColoring:save_last_frame:@@ -430,21 +419,27 @@ may be expected. To color only ``x`` yellow, we have to do the following:equation.set_color_by_tex("x", YELLOW)self.add(equation)-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.+Each isolated occurrence of ``x`` becomes its own sub-mobject that+:meth:`~.set_color_by_tex` can match exactly.If one of the ``substrings_to_isolate`` is in a sub or superscript, it needsto be enclosed by curly brackets.Note that Manim also supports a custom syntax that allows splittinga TeX string into substrings easily: simply enclose parts of your formulathat you want to isolate with double braces. In the string-``MathTex(r"{{ a^2 }} + {{ b^2 }} = {{ c^2 }}")``, the rendered mobject+``MathTex(r"{{ a^2 }} + {{ b^2 }} = {{ c^2 }}")``, the rendered mobjectwill consist of the substrings ``a^2``, ``+``, ``b^2``, ``=``, and ``c^2``.This makes transformations between similar text fragments easyto write using :class:`~.TransformMatchingTex`.+For Manim to recognise a ``{{`` as a group opener, it must appear either+at the very start of the string or be immediately preceded by a whitespace+character. This means that ``{{`` embedded directly after non-whitespace+LaTeX — such as ``\frac{{{n}}}{k}`` or ``a^{{2}}`` — is left untouched,+which prevents accidental splitting of ordinary nested-brace expressions.+To stop a leading ``{{`` from being treated as a group opener, insert a+space between the two braces: ``{{ ... }}`` → ``{ { ... } }``.+Using ``index_labels`` to work with complicated strings=======================================================diff --git a/manim/mobject/text/tex_mobject.py b/manim/mobject/text/tex_mobject.pyindex 18546bce8..8698e024b 100644--- a/manim/mobject/text/tex_mobject.py+++ b/manim/mobject/text/tex_mobject.py@@ -237,6 +237,26 @@ class MathTex(SingleStringMathTex):t = MathTex(r"\int_a^b f'(x) dx = f(b)- f(a)")self.add(t)+ Notes+ -----+ Double-brace notation ``{{ ... }}`` can be used to split a single+ string argument into multiple submobjects without having to pass+ separate strings::++ MathTex(r"{{ a^2 }} + {{ b^2 }} = {{ c^2 }}")++ Each ``{{ ... }}`` group and every piece of text between groups+ becomes its own submobject, which is useful for+ :class:`~.TransformMatchingTex` animations.++ For ``{{`` to be recognised as a group opener it must appear either+ at the very start of the string or be immediately preceded by a+ whitespace character. ``{{`` that follows non-whitespace — such as+ in ``\frac{{{n}}}{k}`` or ``a^{{2}}`` — is left untouched, so+ ordinary nested-brace LaTeX is not accidentally split. To prevent+ an unintentional split, insert a space between the two braces:+ ``{{ ... }}`` → ``{ { ... } }``.+Tests-----Check that creating a :class:`~.MathTex` works::@@ -318,15 +338,94 @@ class MathTex(SingleStringMathTex):tex_strings_validated = [string if isinstance(string, str) else str(string) for string in tex_strings]- # Locate double curly bracers+ # Locate double curly bracers and split on them.tex_strings_validated_two = []for tex_string in tex_strings_validated:- split = re.split(r"{{|}}", tex_string)+ split = self._split_double_braces(tex_string)tex_strings_validated_two.extend(split)if len(tex_strings_validated_two) > len(tex_strings_validated):self.brace_notation_split_occurred = Truereturn [string for string in tex_strings_validated_two if len(string) > 0]+ @staticmethod+ def _split_double_braces(tex_string: str) -> list[str]:+ r"""Split *tex_string* on Manim's ``{{ ... }}`` double-brace notation.++ Rules that avoid false positives on ordinary LaTeX source:++ * ``{{`` is only treated as a group opener when it appears at the very+ start of the string or is immediately preceded by a whitespace+ character. Naturally-occurring ``{{`` in LaTeX is usually preceded+ by non-whitespace (e.g. ``\frac{{{n}}}{k}`` or ``a^{{2}}``), so+ the whitespace guard eliminates the most common false positives+ without any brace-depth bookkeeping on the outer string.++ * Inside an open group the depth of *real* LaTeX braces is tracked.+ ``}}`` only closes the Manim group when the inner depth is zero,+ so ``{{ a^{b^{c}} }}`` is handled correctly.++ * Escape sequences are consumed as two-character units in priority+ order: ``\\`` first (escaped backslash), then ``\{`` / ``\}``+ (escaped braces). This ensures e.g. ``\\}}`` is read as an+ escaped backslash followed by a real ``}}`` rather than as+ ``\`` + ``\}`` + lone ``}``.+ """+ segments: list[str] = []+ current = ""+ i = 0+ inside_manim = False+ inner_depth = 0++ while i < len(tex_string):+ # --- consume escape sequences as atomic units ---+ if tex_string[i] == "\\" and i + 1 < len(tex_string):+ next_ch = tex_string[i + 1]+ if next_ch == "\\" or next_ch in "{}":+ # \\ (escaped backslash) checked before \{ / \} so that+ # the second \ in \\ is never mistaken for an escape prefix.+ current += tex_string[i : i + 2]+ i += 2+ continue++ if not inside_manim:+ # {{ opens a Manim group only at start-of-string or after whitespace.+ if tex_string[i : i + 2] == "{{" and (+ i == 0 or tex_string[i - 1].isspace()+ ):+ segments.append(current)+ current = ""+ inside_manim = True+ inner_depth = 0+ i += 2+ else:+ current += tex_string[i]+ i += 1+ else:+ if tex_string[i] == "{":+ inner_depth += 1+ current += tex_string[i]+ i += 1+ elif (+ tex_string[i] == "}"+ and inner_depth == 0+ and tex_string[i : i + 2] == "}}"+ ):+ # }} at inner depth 0 closes the Manim group.+ segments.append(current)+ current = ""+ inside_manim = False+ i += 2+ elif tex_string[i] == "}":+ inner_depth -= 1+ current += tex_string[i]+ i += 1+ else:+ current += tex_string[i]+ i += 1++ segments.append(current)+ return segments+def _join_tex_strings_with_unique_deliminters(self, tex_strings: list[str], substrings_to_isolate: Iterable[str]) -> str:diff --git a/tests/module/mobject/text/test_texmobject.py b/tests/module/mobject/text/test_texmobject.pyindex ed79633c0..48297abec 100644--- a/tests/module/mobject/text/test_texmobject.py+++ b/tests/module/mobject/text/test_texmobject.py@@ -20,13 +20,122 @@ def test_SingleStringMathTex(config):@pytest.mark.parametrize( # : PT006("text_input", "length_sub"),- [("{{ a }} + {{ b }} = {{ c }}", 5), (r"\frac{1}{a+b\sqrt{2}}", 1)],+ [+ ("{{ a }} + {{ b }} = {{ c }}", 5),+ (r"\frac{1}{a+b\sqrt{2}}", 1),+ # Regression test for https://github.com/ManimCommunity/manim/issues/4601:+ # a string whose only }} comes from closing two nested LaTeX brace groups+ # (not from the {{ }} notation) must not be split.+ (r"\\+\int_{0}^{\frac{Mq}{M+m}}", 1),+ ],)def test_double_braces_testing(text_input, length_sub):t1 = MathTex(text_input)assert len(t1.submobjects) == length_sub+# ---------------------------------------------------------------------------+# Unit tests for MathTex._split_double_braces — no LaTeX compilation needed.+# ---------------------------------------------------------------------------+++ ("tex_string", "expected_segments"),+ [+ # ---- intended notation ----+ # Basic split: each {{ }} group and the text between become segments.+ (+ "{{ a }} + {{ b }}",+ ["", " a ", " + ", " b ", ""],+ ),+ # {{ }} at the very start of the string (no preceding character).+ (+ "{{x}}",+ ["", "x", ""],+ ),+ # Content with arbitrarily nested LaTeX braces: inner }} must NOT close+ # the Manim group early.+ (+ r"{{ a^{b^{c}} }}",+ ["", r" a^{b^{c}} ", ""],+ ),+ # \frac inside a Manim group — the }} from {1}{a} are at inner_depth > 0.+ (+ r"{{ \frac{1}{a} }}",+ ["", r" \frac{1}{a} ", ""],+ ),+ # ---- false-positive guards: {{ not preceded by whitespace ----+ # \text{{word}}: {{ preceded by {, must not split.+ (+ r"\text{{word}}",+ [r"\text{{word}}"],+ ),+ # ^{{\alpha}}: {{ preceded by {, must not split.+ (+ r"^{{\alpha}}",+ [r"^{{\alpha}}"],+ ),+ # +{{a}}: {{ preceded by non-whitespace, must not split.+ (+ r"+{{a}}",+ [r"+{{a}}"],+ ),+ # ---- bug case: }} without any {{ must not split ----+ (+ r"\\+\int_{0}^{\frac{Mq}{M+m}}",+ [r"\\+\int_{0}^{\frac{Mq}{M+m}}"],+ ),+ # ---- backslash escape handling ----+ # \}} — \} consumed as unit, remaining } is a lone close, not }}.+ (+ r"\}}",+ [r"\}}"],+ ),+ # \\}} — \\ consumed as unit, leaving real }} which is not inside any+ # Manim group so it passes through unchanged.+ (+ r"\\}}",+ [r"\\}}"],+ ),+ # \\\}} — \\ consumed, then \} consumed; lone } passes through.+ (+ r"\\\}}",+ [r"\\\}}"],+ ),+ # \\\\}} — two \\ consumed; lone }} passes through (no Manim group open).+ (+ r"\\\\}}",+ [r"\\\\}}"],+ ),+ # Same backslash cases *inside* a Manim group.+ # The escape sequence is placed right before the Manim }} close.+ #+ # {{ a \}}} — \} consumed as escaped brace (content), }} closes the group.+ (+ r"{{ a \}}}",+ ["", r" a \}", ""],+ ),+ # {{ a \\}} — \\ consumed as escaped backslash (content), }} closes.+ (+ r"{{ a \\}}",+ ["", r" a \\", ""],+ ),+ # {{ a \\\}}} — \\ then \} consumed (content), }} closes.+ (+ r"{{ a \\\}}}",+ ["", r" a \\\}", ""],+ ),+ # {{ a \\\\}} — \\ then \\ consumed (content), }} closes.+ (+ r"{{ a \\\\}}",+ ["", r" a \\\\", ""],+ ),+ ],+)+def test_split_double_braces(tex_string, expected_segments):+ assert MathTex._split_double_braces(tex_string) == expected_segments++def test_tex(config):Tex("The horse does not eat cucumber salad.")assert Path(config.media_dir, "Tex", "5384b41741a246bd.svg").exists()