A community-maintained Python framework for creating mathematical animations.
fix(text): raise a clear error instead of IndexError on glyph/char mismatch (#4868)
Javier Carreiraf52c60bddb90
diff --git a/manim/mobject/text/text_mobject.py b/manim/mobject/text/text_mobject.pyindex 7ec61ff9f..d9477925b 100644--- a/manim/mobject/text/text_mobject.py+++ b/manim/mobject/text/text_mobject.py@@ -652,6 +652,18 @@ class Text(SVGMobject):)chars.add(space)else:+ if submobjects_char_index >= len(self.submobjects):+ raise ValueError(+ f"Text {self.original_text!r} rendered fewer glyph(s) "+ "than its non-space characters even with "+ "disable_ligatures=True. This usually means the chosen "+ "font implements some of its ligatures through an "+ "OpenType feature that isn't disabled (e.g. 'calt', "+ "used for programming ligatures like '<=' or '->' by "+ "fonts such as Fira Code), so characters and glyphs no "+ "longer correspond one-to-one. Try a different font to "+ "work around this."+ )chars.add(self.submobjects[submobjects_char_index])submobjects_char_index += 1return charsdiff --git a/tests/module/mobject/text/test_text_mobject.py b/tests/module/mobject/text/test_text_mobject.pyindex 2e656b90a..a94b587c8 100644--- a/tests/module/mobject/text/test_text_mobject.py+++ b/tests/module/mobject/text/test_text_mobject.py@@ -3,6 +3,8 @@ from __future__ import annotationsfrom contextlib import redirect_stdoutfrom io import StringIO+import pytest+from manim.mobject.text.text_mobject import MarkupText, Text@@ -32,3 +34,31 @@ def test_font_warnings():# check random string (should be warning)assert warning_printed("Manim!" * 3, warn_missing_font=True)+++def test_gen_chars_raises_clear_error_on_glyph_mismatch():+ """``_gen_chars`` should raise a clear, actionable error instead of an+ opaque ``IndexError`` when a font renders fewer glyphs than there are+ non-space characters. This happens when a font implements some of its+ ligatures (e.g. programming ligatures like ``<=``) through an OpenType+ feature that ``disable_ligatures`` doesn't disable, such as ``calt``+ (see issue #3237). This test simulates that mismatch directly, without+ depending on any particular font being installed.+ """+ text = Text("ab", disable_ligatures=True)+ # Simulate a font that merged "ab" into a single ligature glyph.+ text.submobjects = text.submobjects[:1]+ with pytest.raises(ValueError, match="glyph"):+ text._gen_chars()+++def test_gen_chars_handles_spaces_with_disable_ligatures():+ """``_gen_chars`` must not raise for ordinary text containing spaces when+ ``disable_ligatures=True``. Spaces are rendered as their own glyph, so the+ number of submobjects legitimately exceeds the number of non-space+ characters; this should not be mistaken for a glyph/char mismatch.+ """+ text = Text("fl ligature", disable_ligatures=True)+ chars = text._gen_chars()+ # One entry per character of the (whitespace-stripped) indexing text.+ assert len(chars) == len(text.text)