docs(text): document whitespace-stripped indexing in Text#4866
Conversation
Text.__init__ strips spaces/newlines from self.text and never creates submobjects for whitespace, so slicing (text[a:b]) and the t2c/t2s/t2w/t2f/t2g '[a:b]' syntax silently index into that stripped copy rather than the original string, with no warning. Add a docstring callout explaining this and pointing to substring-keyed t2c/etc. as the unaffected alternative. Refs ManimCommunity#4864
chopan050
left a comment
There was a problem hiding this comment.
Thanks for the extra documentation!
I just made a local test, however, and the behavior for t2c and similar parameters does consider the whitespace, so the docstring has to mention this.
If text = Text("Hello World"), then, indeed, text[5] refers to the "W", not the whitespace. Thus, text[3:7] gets the 4 letters "l", "o", "W", "o". However, when using t2c={"[3:7]": RED}, this does consider the whitespace and paints "l", "o", "", "W" in red.
In other words:
class ColoringText(Scene):
def construct(self):
text = Text("Hello World", t2c={"[3:7]": RED})
self.play(Write(text))
self.play(text[3:7].animate.set_color(BLUE))
self.wait()starts with the "Hello World" text where "lo W" (without the second "o") is colored in red, and then "lo Wo" (with the second "o") gets colored in blue.
Reviewer (chopan050) pointed out on PR ManimCommunity#4866 that t2c/t2s/t2w/t2f/t2g slice syntax (e.g. t2c={'[3:7]': RED}) indexes into the original text with whitespace included, not the whitespace-stripped text as the previous wording implied -- the opposite of how direct object slicing (my_text[3:5]) behaves. Verified both behaviors empirically and reworded the warning to describe each convention correctly.
|
@chopan050 thanks for the careful test! You're right that the two paths disagree, so I've reworked the warning to document both conventions explicitly:
This matches the |
Summary
Textstrips whitespace/newlines from its internalself.textafter construction, and never creates submobjects for whitespace characters (nothing to render). SinceTextdoesn't override__getitem__, slicing (text[a:b]) and the[a:b]slice syntax int2c/t2s/t2w/t2f/t2gend up indexing into that whitespace-stripped copy — not the string the user actually passed in — with no warning or error.This PR adds a docstring callout on
Textexplaining the behavior and pointing to substring-keyedt2c/etc. (matched by text search, unaffected by this) as the recommended alternative when the target substring is known ahead of time.No behavior changes — docs only.
Fixes #4864
Test plan
uv run pre-commit run --files manim/mobject/text/text_mobject.pypasses (ruff, mypy, codespell)Text(...)still imports/constructs normallyText.__doc__includes the new warning block)