The animation engine for agents: blazingly fast math and 3D videos with Manim's Python API, on a Rust GPU core.
Python
Implement text and number mobjects
Sina Atalay3d75736ce0e6
diff --git a/src/manimgx/drawing/typesetting.py b/src/manimgx/drawing/typesetting.pyindex 1268694d..07929285 100644--- a/src/manimgx/drawing/typesetting.py+++ b/src/manimgx/drawing/typesetting.py@@ -36,8 +36,9 @@ Typst: its message is Typst's (or mitex's), each error with the bytes of the souis at, counted from the start of the whole document typeset — a page setup and thepreamble come before the code."""-# a row's columns (see rust/engine/src/typeset.rs): a glyph's origin is its source node-# (start, end) and the bytes of the node's text its cluster draws (start, end)+# a row's columns (see rust/engine/src/typeset.rs): an item's origin is its source node (start,+# end; its own, else the innermost element around it from the source) and the bytes of the+# node's text a glyph's cluster draws (start, end)KIND, KEY, PLACEMENT, FILL, STROKE, WIDTH, ADVANCE, NODE, DRAWN = (0,1,diff --git a/src/manimgx/mobjects/numbers.py b/src/manimgx/mobjects/numbers.pynew file mode 100644index 00000000..7bde5e26--- /dev/null+++ b/src/manimgx/mobjects/numbers.py@@ -0,0 +1,483 @@+# SPDX-FileCopyrightText: 2026 Academa, Inc.+# SPDX-FileCopyrightText: 2024 the Manim Community Developers+# SPDX-FileCopyrightText: 2018 3Blue1Brown LLC+# SPDX-License-Identifier: MIT++"""Ported from Manim CE 0.21 (MIT)."""++from __future__ import annotations++__all__ = ["DecimalNumber", "Integer", "Variable", "index_labels"]+from typing import ClassVar, Self, Unpack++import numpy as np++from manimgx.caches import Memo+from manimgx.constants import DEFAULT_FONT_SIZE, DOWN, LEFT, ORIGIN, RIGHT, UP+from manimgx.drawing.geometry import Blend+from manimgx.drawing.paint import BLACK, Paint, Style+from manimgx.mobject import Mobject, ValueTracker, VGroup, VMobject, copied, prototype+from manimgx.mobjects.text import MathTex, SingleStringMathTex, Text+from manimgx.typing import ManimTextLabel, Vector3DLike++# a string's glyphs laid out (CE's procedure, run once per string and layout): what laying out+# sets on the number, copied in by every later layout of the same string+_ROWS: Memo[tuple[object, ...], dict[str, object]] = Memo(1 << 12)+_ROW = ("submobjects", "initial_height", "background_rectangle")+++class NumberStyle(Style, total=False):+ """How a number is written: [DecimalNumber][manimgx.DecimalNumber]'s keywords but+ its number of decimal places, for the classes that pass them on.++ Beyond these, they take the [style keywords][manimgx.drawing.paint.Style].+ """++ mob_class: type[ManimTextLabel]+ """The class each character is typeset with (default [MathTex][manimgx.MathTex])."""+ include_sign: bool+ """Whether a number that is not negative is written with a plus sign (default+ False)."""+ group_with_commas: bool+ """Whether the digits before the decimal point are grouped in threes by commas,+ 12,345 (default True)."""+ digit_buff_per_font_unit: float+ """The gap between characters, per unit of font size: 0.001, the default, is 0.048+ scene units at font size 48."""+ show_ellipsis: bool+ """Whether "…" follows the number, for a value that goes on (default False)."""+ unit: str | None+ r"""A unit after the number, in LaTeX math: `"^\circ"` for degrees, `r"\text{ m}"`;+ one that starts with "^" is raised to the number's top (default None)."""+ unit_buff_per_font_unit: float+ """The gap before the unit, beyond the gap between characters, per unit of font+ size (default 0)."""+ include_background_rectangle: bool+ """Whether a background rectangle is behind the number (default False)."""+ edge_to_fix: Vector3DLike+ """The edge, as a direction, that stays where it is when a new value changes the+ number's width (default LEFT: it grows to the right)."""+ font_size: float+ """The characters' font size, as `mob_class` measures it (default 48)."""+++class DecimalNumberOptions(NumberStyle, total=False):+ """[DecimalNumber][manimgx.DecimalNumber]'s keywords, for the classes that pass them+ on: a number line's labels.++ Beyond these, they take the+ [number keywords][manimgx.mobjects.numbers.NumberStyle].+ """++ num_decimal_places: int+ """How many digits follow the decimal point (default 2)."""+++class DecimalNumber(VMobject):+ r"""A number, written with a fixed number of decimal places: white and filled+ unless styled.++ Its parts are its characters, in order, each typeset by `mob_class`: the sign, the+ digits, the commas and the decimal point; then "…" and the unit, if any (and a+ background rectangle before them all, if asked for). The number shown is rounded (a+ negative one that rounds to zero loses its sign, in either component of a complex+ number), and a complex one is written `a+bi`.+ [set_value][manimgx.DecimalNumber.set_value] shows another+ number, keeping the font size, the color and the edge `edge_to_fix` where they are:+ driven by a [value tracker][manimgx.ValueTracker], or by+ [ChangeDecimalToValue][manimgx.ChangeDecimalToValue], the number counts on screen.++ Args:+ number: The number to show; a complex one too.+ num_decimal_places: How many digits follow the decimal point.+ mob_class: The class each character is typeset with.+ include_sign: Whether a number that is not negative is written with a plus+ sign.+ group_with_commas: Whether the digits before the decimal point are grouped in+ threes by commas.+ digit_buff_per_font_unit: The gap between characters, per unit of font size+ (0.001: 0.048 scene units at 48).+ show_ellipsis: Whether "…" follows the number.+ unit: A unit after the number, in LaTeX math (`"^\circ"`, `r"\text{ m}"`); one+ that starts with "^" is raised to the number's top.+ unit_buff_per_font_unit: The gap before the unit, beyond the gap between+ characters, per unit of font size.+ include_background_rectangle: Whether a background rectangle is behind the+ number.+ edge_to_fix: The edge, as a direction, that stays where it is when a new value+ changes the number's width.+ font_size: The characters' font size, as `mob_class` measures it.++ Examples:+ ```python+ import manimgx as m+++ class DecimalNumberExample(m.Scene):+ def construct(self) -> None:+ numbers = m.VGroup(+ m.DecimalNumber(3.14159),+ m.DecimalNumber(1234567.891, num_decimal_places=1),+ m.DecimalNumber(42, include_sign=True, color=m.YELLOW),+ m.DecimalNumber(90, num_decimal_places=0, unit=r"^\circ"),+ m.DecimalNumber(3.14159, num_decimal_places=4, show_ellipsis=True),+ )+ self.add(numbers.arrange(m.DOWN, buff=0.4).scale(1.5))+ ```+ """++ defaults: ClassVar[Style] = {"stroke_width": 0, "fill_opacity": 1.0}++ @prototype+ def __init__(+ self,+ number: float = 0,+ num_decimal_places: int = 2,+ mob_class: type[ManimTextLabel] = MathTex,+ include_sign: bool = False,+ group_with_commas: bool = True,+ digit_buff_per_font_unit: float = 0.001,+ show_ellipsis: bool = False,+ unit: str | None = None,+ unit_buff_per_font_unit: float = 0,+ include_background_rectangle: bool = False,+ edge_to_fix: Vector3DLike = LEFT,+ font_size: float = DEFAULT_FONT_SIZE,+ **kwargs: Unpack[Style],+ ):+ if font_size <= 0:+ raise ValueError("font_size must be greater than 0.")+ super().__init__(**kwargs)+ self.number = number+ self.num_decimal_places = num_decimal_places+ self.include_sign = include_sign+ self.mob_class = mob_class+ self.group_with_commas = group_with_commas+ self.digit_buff_per_font_unit = digit_buff_per_font_unit+ self.show_ellipsis = show_ellipsis+ self.unit = unit+ self.unit_buff_per_font_unit = unit_buff_per_font_unit+ self.include_background_rectangle = include_background_rectangle+ self.edge_to_fix = edge_to_fix+ self._font_size = font_size+ self._set_submobjects_from_number(number)+ self.init_colors()++ @property+ def font_size(self) -> float:+ """The number's font size: the one it was made with, times how much it has been+ scaled since. Set it, to a positive size, to scale the number to it."""+ return_value: float = self.height / self.initial_height * self._font_size+ return return_value++ @font_size.setter+ def font_size(self, font_val: float) -> None:+ if font_val <= 0:+ raise ValueError("font_size must be greater than 0.")+ elif self.height > 0:+ self.scale(font_val / self.font_size)++ def _row_key(self, shown: str) -> tuple[object, ...]:+ """The displayed row, before placement and final repaint."""+ return (+ type(self),+ shown,+ self.mob_class,+ self._font_size,+ self.digit_buff_per_font_unit,+ self.unit,+ self.unit_buff_per_font_unit,+ self.include_background_rectangle,+ self.show_ellipsis,+ )++ def _set_submobjects_from_number(self, number: float) -> tuple[object, ...]:+ """The glyphs of `number` about the origin at the constructed font size: laid out once per+ string and layout, then copied."""+ self.number = number+ shown = self._get_num_string(number)+ key = self._row_key(shown)+ # The layout is independent of paint; the cached ellipsis starts in its ink.+ cache_key = (*key, str(self.get_color()) if self.show_ellipsis else None)+ if not self.include_background_rectangle:+ self.__dict__.pop("background_rectangle", None)+ row = _ROWS.get(cache_key)+ if row is None:+ self._lay_out(shown)+ _ROWS.keep(+ cache_key,+ copied(+ {+ name: self.__dict__[name]+ for name in _ROW+ if name in self.__dict__+ }+ ),+ )+ else:+ self.__dict__.update(copied(row))+ return key++ def _lay_out(self, num_string: str) -> None:+ self.submobjects = []+ # Size the constructed labels: constructing at that size rounds their points+ # differently, enough to move a number line's coordinates in rendered frames.+ self.add(+ *(+ self.mob_class(char).set(font_size=self._font_size)+ for char in num_string+ )+ )+ if self.show_ellipsis:+ self.add(+ SingleStringMathTex("\\dots", color=self.get_color()).set(+ font_size=self._font_size+ )+ )+ self.arrange(+ buff=self.digit_buff_per_font_unit * self._font_size, aligned_edge=DOWN+ )+ unit_sign = None+ if self.unit is not None:+ unit_sign = SingleStringMathTex(self.unit).set(font_size=self._font_size)+ self.add(+ unit_sign.next_to(+ self,+ direction=RIGHT,+ buff=(self.unit_buff_per_font_unit + self.digit_buff_per_font_unit)+ * self._font_size,+ aligned_edge=DOWN,+ )+ )+ self.move_to(ORIGIN)+ for i, c in enumerate(num_string):+ if c == "-" and len(num_string) > i + 1:+ self[i].align_to(self[i + 1], UP)+ self[i].shift(self[i + 1].height * DOWN / 2)+ elif c == ",":+ self[i].shift(self[i].height * DOWN / 2)+ if unit_sign is not None and self.unit and self.unit.startswith("^"):+ unit_sign.align_to(self, UP)+ self.initial_height: float = self.height+ if self.include_background_rectangle:+ self.add_background_rectangle()++ def _get_num_string(self, number: float | complex) -> str:+ return self._get_formatter().format(number)++ def _get_formatter(+ self, field_name: str = "", include_sign: bool | None = None+ ) -> str:+ sign = self.include_sign if include_sign is None else include_sign+ commas = "," if self.group_with_commas else ""+ return (+ f"{{{field_name}:{'+' if sign else ''}z{commas}.{self.num_decimal_places}f}}"+ )++ _shown: (+ tuple[tuple[object, ...], tuple[tuple[Mobject, Blend, Paint], ...]] | None+ ) = None++ def get_value(self) -> float:+ """The number shown, as it was given: not rounded."""+ return self.number++ def increment_value(self, delta_t: float = 1) -> Self:+ """Show the number plus `delta_t`.++ Args:+ delta_t: What to add.+ """+ return self.set_value(self.get_value() + delta_t)++ def set_value(self, number: float) -> Self:+ """Show another number, keeping the look: the font size, the edge `edge_to_fix`+ where it is, and the color — every character takes the number's own, so a color+ given to single characters is not kept.++ Args:+ number: The number to show.++ Examples:+ ```python+ import manimgx as m+++ class DecimalNumberSetValueExample(m.Scene):+ def construct(self) -> None:+ tracker = m.ValueTracker(0)+ number = m.DecimalNumber(0, font_size=144).shift(2 * m.LEFT)+ number.add_updater(lambda n: n.set_value(tracker.get_value()))+ self.add(number)+ self.play(tracker.animate.set_value(100), run_time=3)+ ```+ """+ # every glyph takes the number's own color, as CE's `init_colors` repaints them.+ # A number still as it was left showing the same string is left alone: its+ # members' geometry and paint are values, so "as it was left" is the same objects+ shown = self._get_num_string(number)+ key = self._row_key(shown)+ last = self._shown+ if last is not None and last[0] == key:+ family = self.get_family()+ if len(family) == len(last[1]) and all(+ m is was and m._geometry is g and m.paint is p+ for m, (was, g, p) in zip(family, last[1], strict=True)+ ):+ self.number = number+ return self+ old_font_size = self.font_size+ move_to_point = self.get_edge_center(self.edge_to_fix)+ key = self._set_submobjects_from_number(number)+ self.font_size = old_font_size+ self.move_to(move_to_point, self.edge_to_fix)+ self.init_colors()+ self._shown = (+ key,+ tuple((m, m._geometry, m.paint) for m in self.get_family()),+ )+ return self+++class Integer(DecimalNumber):+ """An integer: a [DecimalNumber][manimgx.DecimalNumber] with no decimal places,+ white and filled unless styled.++ A number with a fractional part is shown rounded, and+ [get_value][manimgx.Integer.get_value] rounds it too.++ Args:+ number: The number to show.+ num_decimal_places: How many digits follow the decimal point: none unless+ given.++ Examples:+ ```python+ import manimgx as m+++ class IntegerExample(m.Scene):+ def construct(self) -> None:+ count = m.Integer(0, font_size=144).shift(1.5 * m.LEFT)+ self.add(count)+ self.play(m.ChangeDecimalToValue(count, 1000), run_time=3)+ ```+ """++ def __init__(+ self,+ number: float = 0,+ num_decimal_places: int = 0,+ **kwargs: Unpack[NumberStyle],+ ) -> None:+ super().__init__(number=number, num_decimal_places=num_decimal_places, **kwargs)++ def get_value(self) -> int:+ """The number shown: the number given, rounded to an integer."""+ return int(np.round(super().get_value()))+++class Variable(VMobject):+ """A named value: a label, "=", and a number that shows a value tracker's value.++ Its parts are its [label][manimgx.Variable.label], followed by "=", and its+ [value][manimgx.Variable.value], a [DecimalNumber][manimgx.DecimalNumber] or an+ [Integer][manimgx.Integer] that shows its [tracker][manimgx.Variable.tracker]'s+ value at every frame: animate the tracker, and the number counts.++ Args:+ var: The value it starts with.+ label: The label: a string, typeset as math ([MathTex][manimgx.MathTex]), or a+ text or math mobject.+ var_type: The number's class: DecimalNumber or a subclass, such as Integer.+ num_decimal_places: How many digits follow the decimal point. Integer classes+ use their own precision defaults instead.+ **kwargs: [Style keywords][manimgx.drawing.paint.Style] of the group itself; its+ parts keep their own (color them through `label` and `value`).++ Examples:+ ```python+ import manimgx as m+++ class VariableExample(m.Scene):+ def construct(self) -> None:+ x = m.Variable(2.0, "x", num_decimal_places=3)+ y = m.Variable(4.0, "x^2", num_decimal_places=3)+ self.add(m.VGroup(x, y).arrange(m.DOWN, buff=0.5).scale(2))+ t = x.tracker+ y.add_updater(lambda v: v.tracker.set_value(t.get_value() ** 2))+ self.play(t.animate.set_value(5), run_time=3, rate_func=m.linear)+ ```+ """++ def __init__(+ self,+ var: float,+ label: str | MathTex | Text | SingleStringMathTex,+ var_type: type[DecimalNumber] = DecimalNumber,+ num_decimal_places: int = 2,+ **kwargs: Unpack[Style],+ ):+ self.label = MathTex(label) if isinstance(label, str) else label+ """The label, followed by "=", one of its submobjects."""+ equals = MathTex("=").next_to(self.label, RIGHT)+ self.label.add(equals)+ self.tracker = ValueTracker(var)+ """The value tracker the number shows: set or animate it to change the+ number."""+ self.value = (+ var_type(self.tracker.get_value())+ if issubclass(var_type, Integer)+ else var_type(+ self.tracker.get_value(), num_decimal_places=num_decimal_places+ )+ )+ """The number, which shows the tracker's value at every frame."""+ self.value.add_updater(self._update_value).next_to(self.label, RIGHT)+ super().__init__(**kwargs)+ self.add(self.label, self.value)++ def _update_value(self, value: DecimalNumber) -> None:+ value.set_value(self.tracker.get_value())+++def index_labels(+ mobject: Mobject, label_height: float = 0.15, **kwargs: Unpack[NumberStyle]+) -> VGroup:+ r"""Number the submobjects of a mobject: an [Integer][manimgx.Integer] at the center+ of each, on a dark outline, to find a part's index.++ A debugging help: add the labels to the scene to see them; they don't follow the+ mobject.++ Args:+ mobject: The mobject whose submobjects are numbered, from 0.+ label_height: Each label's height, in scene units.+ **kwargs: [Number keywords][manimgx.mobjects.numbers.NumberStyle] (a black+ background stroke 5 wide unless given).++ Returns:+ A new group of the labels, in order.++ Examples:+ ```python+ import manimgx as m+++ class IndexLabelsExample(m.Scene):+ def construct(self) -> None:+ formula = m.MathTex(r"\binom{2n}{n+2}", font_size=144)+ formula[0][1:3].set_color(m.YELLOW)+ formula[0][3:6].set_color(m.RED)+ self.add(formula, m.index_labels(formula[0], label_height=0.3))+ ```+ """+ kwargs.setdefault("background_stroke_width", 5)+ kwargs.setdefault("background_stroke_color", BLACK)+ labels = VGroup()+ for n, submob in enumerate(mobject):+ label = Integer(n, **kwargs)+ label.height = label_height+ labels.add(label.move_to(submob))+ return labelsdiff --git a/src/manimgx/mobjects/text.py b/src/manimgx/mobjects/text.pynew file mode 100644index 00000000..7f6cc437--- /dev/null+++ b/src/manimgx/mobjects/text.py@@ -0,0 +1,1803 @@+"""Typeset mobjects from Typst, literal Unicode, and LaTeX source.++Typst documents as mobjects: every glyph and shape of the layout becomes a part (a glyph its+outline, shared per font and glyph, placed where Typst put it). After CE 0.21 (MIT).++CE's Pango text classes, typeset by Typst: one submobject per non-space glyph, in reading+order, sized so a font-size-48 capital has CE's height.++The text is set literally, as Typst strings. Slant and weight (`t2s`, `t2w`) change the layout,+so they are set as runs; color does not: every glyph knows the characters it draws,+so `gradient`, `t2g` and `t2c` color it by character, and a glyph whose characters differ in+color is cut at its carets. A key is a slice "[a:b]" or each occurrence of a string; a key that+occurs nowhere picks nothing.++CE's LaTeX classes, typeset by Typst: LaTeX converted by mitex, so `MathTex("a", "=", "b")[i]`+is part i. A MathTex's parts are one formula; Tex's are set one after another, each labelled.++"""++from __future__ import annotations++__all__ = [+ "BulletedList",+ "MathTex",+ "MathTexOptions",+ "MathTexPart",+ "MathTypst",+ "Paragraph",+ "SingleStringMathTex",+ "Tex",+ "Text",+ "TextOptions",+ "Title",+ "Typst",+ "TypstGlyph",+ "TypstOptions",+]++import bisect+import re+import unicodedata+from collections.abc import Iterable, Mapping, Sequence+from pathlib import Path+from typing import Literal, Self, Unpack++import numpy as np++from manimgx import _engine+from manimgx.caches import Memo+from manimgx.constants import (+ DEFAULT_FONT_SIZE,+ MED_LARGE_BUFF,+ MED_SMALL_BUFF,+ NORMAL,+ SCALE_FACTOR_PER_FONT_POINT,+ SMALL_BUFF,+)+from manimgx.drawing.geometry import (+ EMPTY,+ Blend,+ Shape,+ _pathops,+ _to_path,+ extent,+ interpolate,+ placed_box,+)+from manimgx.drawing.paint import (+ WHITE,+ Colors,+ Look,+ ManimColor,+ ParsableManimColor,+ Repaint,+ color_gradient,+)+from manimgx.drawing.typesetting import (+ ADVANCE,+ DRAWN,+ FILL,+ GLYPH,+ KEY,+ KIND,+ NODE,+ PLACEMENT,+ STROKE,+ WIDTH,+ Layout,+ TypstError,+ typeset,+ typst_string,+)+from manimgx.mobject import Mobject, Pivot, VGroup, VMobject, _append_path, prototype+from manimgx.typing import Vector3DLike++_MANIMGRP_PREAMBLE = "#let manimgrp(lbl, body) = [#box(body) #label(lbl)]"+++_HEX: Memo[tuple[float, ...], str] = Memo(1 << 12)+++def _ink(rgba: np.ndarray, color: str) -> str:+ """A paint Typst gave: its default ink (black) is `color`."""+ return color if not rgba[:3].any() else _hex(rgba)+++def _hex(rgba: np.ndarray) -> str:+ key = tuple(rgba[:3])+ color = _HEX.get(key)+ if color is None:+ r, g, b = (round(c * 255) for c in key)+ color = _HEX.keep(key, f"#{r:02x}{g:02x}{b:02x}")+ return color+++class TypstOptions(Look, Repaint, total=False):+ """[Typst][manimgx.Typst]'s keywords, for the classes that pass them on: text and+ LaTeX.++ Beyond these, they take the [look keywords][manimgx.drawing.paint.Look], and the+ [paint keywords][manimgx.drawing.paint.Repaint], which paint over the colors the+ typesetting gives the parts.+ """++ font_size: float+ """The size of the text: an em is `font_size / 96` scene units, 0.5 at the default,+ 48 (a [Text][manimgx.Text] is sized by its capitals instead: 0.449 units tall at+ 48)."""+ typst_preamble: str+ """Typst code set before the document: `#set` and `#show` rules, `#let`+ definitions, imports (default "")."""+ font_paths: list[str | Path] | None+ """Directories of font files (.ttf, .otf, .ttc, .otc), searched with their+ subdirectories before the fonts manimgx ships; a path to a file adds nothing+ (default None)."""+ should_center: bool+ """Whether the mobject is centered on the origin (default True)."""+ height: float | None+ """The height to scale the mobject to, in scene units, instead of sizing it by+ `font_size` (default None)."""+ width: float | None+ """The width to scale the mobject to, in scene units, instead of sizing it by+ `font_size`; with a `height` too, the width is set last (default None)."""+ package_path: str | Path | None+ """The directory Typst packages are imported from, which holds them as+ `namespace/name/version` directories: `#import "@preview/name:1.0.0"` reads+ `preview/name/1.0.0` (default None: none but mitex, which manimgx's engine holds).+ Nothing is downloaded."""+++class TypstGlyph(VMobject):+ """One glyph as Typst set it, a part of a typeset mobject: its outline, placed, and+ which characters of the source it draws.++ `node` is where the glyph's source node starts in the Typst code (-1 if it isn't+ from the code), `drawn` the bytes of that node's text it draws, `key` its outline,+ `x_advance` its width in font units.+ """++ # Immutable float64 bytes, shared by copies; absent for ordinary glyphs.+ _carets: bytes = b""++ node: int+ """Where the source node the glyph came from starts in the Typst code, in bytes; -1+ if it came from elsewhere (a package's code)."""+ drawn: tuple[int, int]+ """The bytes of that node's text the glyph's cluster draws, from and to: of a string+ literal, the bytes of its value."""+ key: int+ """The provenance key of its outline and font carets, the same in every process.+ Assigning a key does not change the live glyph's outline or carets."""+ x_advance: float+ """Its advance, the width it takes in the line, in font units: a ligature's carets+ divide it."""+++class Typst(VMobject):+ r"""A Typst document, typeset in the engine: every glyph and shape of its layout is+ a part, white unless styled.++ The code is Typst markup, a document's body on a page as large as what it holds:+ `*strong*`, `_emphasis_`, math between `$` signs, `#set` and `#show` rules, and the+ rest of Typst. The parts are what Typst lays out, in document order, spaces+ excluded: glyphs ([TypstGlyph][manimgx.mobjects.text.TypstGlyph]) and+ shapes (a rule, a fraction's bar, a box). A labelled box, `#box[…] <name>`, is a+ group: [select][manimgx.Typst.select] gives it. Packages are imported from+ `package_path` (and mitex, `@preview/mitex:0.2.7`, from manimgx's engine), never+ downloaded; code Typst can't typeset raises a+ [TypstError][manimgx.drawing.typesetting.TypstError].++ Text is set in Libertinus Serif and math in New Computer Modern Math, Typst's+ defaults, unless the code sets another font. The fonts are those manimgx ships, so a+ document looks the same on every machine: Typst's own (these two, New Computer+ Modern and DejaVu Sans Mono), Noto Sans, and Noto faces for the scripts those lack,+ from Arabic, Hebrew and Devanagari to Chinese, Japanese and Korean, with symbols and+ emoji; a character a font lacks is set in one that has it. Fonts in `font_paths`+ come first, and a system font is read only for a family the code names that none of+ these has. A paragraph's direction and the forms of Han characters follow the code's+ `lang` and `dir` (`#set text(lang: "ja")`, `#set text(dir: rtl)`); a+ [Text][manimgx.Text] sets them from its characters.++ What Typst paints in its default ink, black, takes `color`, and the colors the code+ sets are kept, unless paint keywords (`fill_color` and the rest) paint over every+ part. A document is typeset once: the same code is read back from a cache on disk,+ in any process.++ Args:+ typst_code: The document: Typst markup.+ font_size: The size of the text: an em is `font_size / 96` scene units (0.5 at+ 48).+ typst_preamble: Typst code set before the document: rules, definitions,+ imports.+ font_paths: Directories of font files, searched, with their subdirectories,+ before the fonts manimgx ships.+ should_center: Whether the mobject is centered on the origin.+ height: The height to scale the mobject to, in scene units; None to size it by+ `font_size`.+ width: The width to scale it to, in scene units, after `height`; None to size+ it by `font_size`.+ package_path: The directory Typst packages are imported from (as+ `namespace/name/version` directories), besides mitex, which manimgx's+ engine holds; None for none but mitex.+ font_scale: How much larger than `font_size` the text is set: the layout is+ scaled by `font_size * font_scale`, while+ [font_size][manimgx.Typst.font_size] reads `font_size`. A+ [Text][manimgx.Text] sets it to its font's own scale, which makes a capital+ as tall in every font.+ color: The color of Typst's default ink, black; None for white.+ fill_color: A fill color for every part; None keeps the typeset ones.+ fill_opacity: A fill opacity for every part, from 0 to 1; None keeps the+ typeset ones.+ stroke_color: A stroke color for every part; None keeps the typeset ones.+ stroke_opacity: A stroke opacity for every part, from 0 to 1; None keeps the+ typeset ones.+ stroke_width: A stroke width for every part, in hundredths of a scene unit;+ None keeps the typeset ones, which scale with the mobject.++ Examples:+ ```python+ import manimgx as m+++ class TypstExample(m.Scene):+ def construct(self) -> None:+ document = m.Typst(+ "*Typst* markup, _typeset_ in the engine:\n\n"+ "$ sum_(k=1)^n k = (n(n+1))/2 $\n\n"+ "with #text(fill: orange)[colors of its own]",+ font_size=64,+ )+ self.play(m.Write(document))+ ```+ """++ @prototype+ def __init__(+ self,+ typst_code: str,+ *,+ font_size: float = DEFAULT_FONT_SIZE,+ typst_preamble: str = "",+ font_paths: list[str | Path] | None = None,+ should_center: bool = True,+ height: float | None = None,+ width: float | None = None,+ package_path: str | Path | None = None,+ font_scale: float = 1.0,+ color: Colors | None = None,+ fill_color: Colors | None = None,+ fill_opacity: float | Sequence[float] | None = None,+ stroke_color: Colors | None = None,+ stroke_opacity: float | Sequence[float] | None = None,+ stroke_width: float | None = None,+ **kwargs: Unpack[Look],+ ):+ super().__init__(stroke_color=None, fill_color=None, **kwargs)+ self.set_color(WHITE if color is None else color)+ # how much larger than font_size the text is set (a font's calibration: see Text)+ self._font_scale = font_scale+ self.typst_code = typst_code+ """The Typst code the mobject was typeset from."""+ self.typst_preamble = typst_preamble+ """The Typst code set before it."""+ # unless a stroke width is given, a stroke keeps its share of its part's size as+ # typeset: (part, its size and its stroke width as typeset)+ self._strokes_scale = stroke_width is None+ self._strokes: list[tuple[VMobject, float, float]] = []+ # A height overrides font sizing; width is fitted afterward in either case.+ placed = should_center and height is None+ self.initial_height = self._build(+ typeset(+ typst_code,+ typst_preamble,+ font_paths=font_paths,+ package_path=package_path,+ ),+ font_size * font_scale * SCALE_FACTOR_PER_FONT_POINT if placed else None,+ )+ self.set_style(+ fill_color=fill_color,+ fill_opacity=fill_opacity,+ stroke_color=stroke_color,+ stroke_opacity=stroke_opacity,+ stroke_width=stroke_width,+ )+ if should_center and not placed:+ self.center()+ if height is not None:+ self.set(height=height)+ elif not placed:+ self.font_size = font_size+ if width is not None:+ self.set(width=width)++ def _build(self, layout: Layout, scale: float | None) -> float:+ """Every glyph and shape of the layout, in document order, Typst's black ink painted this+ mobject's color, and the labelled groups. With `scale`, parts are built in place (the ink+ centered and scaled). Returns the ink's height as typeset."""+ rows = layout.rows+ # each part's placement (a glyph) or points (a shape), and the ink box around them all:+ # the one box, its curves' tight box+ places: list[np.ndarray] = []+ low, high = np.full(2, np.inf), np.full(2, -np.inf)+ for row in rows:+ if row[KIND] == GLYPH:+ _, outline, _ = layout.glyphs[int(row[KEY])]+ assert outline is not None+ a, b, c, d, e, f = row[PLACEMENT]+ place = np.array([[a, c, 0.0, e], [b, d, 0.0, f], [0.0, 0.0, 1.0, 0.0]])+ ink = placed_box(place, outline, True)[:, :2]+ else:+ place = layout.shapes[int(row[KEY])]+ ink = extent(place, True)[:, :2]+ places.append(place)+ if len(ink):+ low, high = np.minimum(low, ink.min(axis=0)), np.maximum(+ high, ink.max(axis=0)+ )+ height = float(high[1] - low[1]) if high[1] >= low[1] else 0.0+ if scale is not None and height > 0:+ shift = np.array([*((low + high) / 2), 0.0])+ for k, place in enumerate(places):+ if place.shape == (3, 4): # a glyph's placement+ place = place * scale+ place[:, 3] -= shift * scale+ else: # a shape's points+ place = (place - shift) * scale+ places[k] = place+ else:+ scale = None+ ink_color = self.color.to_hex()+ parts: list[VMobject] = []+ for row, place in zip(rows, places):+ fill, stroke = row[FILL], row[STROKE]+ if row[KIND] == GLYPH:+ key = int(row[KEY])+ _, outline, carets = layout.glyphs[key]+ assert outline is not None+ # its color is its ink: both brushes, as `color=` means+ glyph = TypstGlyph(+ color=_ink(fill, ink_color),+ fill_opacity=float(fill[3]),+ stroke_width=0,+ )+ glyph._geometry = Blend(((place, outline),), len(outline.array))+ node, drawn = row[NODE], row[DRAWN]+ glyph.node = int(node[0]) - layout.body if node[0] >= 0 else -1+ glyph.drawn = (int(drawn[0]), int(drawn[1]))+ glyph.key, glyph.x_advance = key, float(row[ADVANCE])+ if carets:+ glyph._carets = carets+ part: VMobject = glyph+ else:+ part = VMobject(+ color=_ink(fill, ink_color) if fill[0] >= 0 else ink_color,+ fill_opacity=float(fill[3]) if fill[0] >= 0 else 0.0,+ stroke_width=0,+ )+ part.points = place+ if stroke[0] >= 0 and row[WIDTH] > 0:+ size = max(part.width, part.height)+ width = float(row[WIDTH])+ part.set_stroke(+ _ink(stroke, ink_color),+ opacity=float(stroke[3]),+ width=None if scale is None else width * scale * 100,+ )+ if self._strokes_scale and size > 0:+ self._strokes.append((part, size / (scale or 1.0), width))+ parts.append(part)+ self.add(*parts)+ self.labels: dict[str, VGroup] = {} # the parts inside each `<label>`+ for label, members in layout.labels:+ group = self.labels.setdefault(label, VGroup())+ group.add(*(parts[i] for i in members))+ return height++ def select(self, key: str | int) -> VGroup:+ """Find the parts of a labelled group: of every group with that label, as one.++ A label names a box in the code, `#box[…] <name>`; a+ [MathTypst][manimgx.MathTypst] makes a group of `{{ … }}` too, named by+ `{{ … : name }}` or numbered in order. An unknown label raises KeyError, a+ number out of range IndexError.++ Args:+ key: The label; or the number of a MathTypst's unnamed `{{ … }}` group, from+ 0.++ Returns:+ A new group of the parts themselves (not copies), in order.++ Examples:+ ```python+ import manimgx as m+++ class TypstSelectExample(m.Scene):+ def construct(self) -> None:+ text = m.Typst(+ "Label a #box[box] <noun> to #box[select] <verb> it",+ font_size=96,+ )+ text.select("noun").set_color(m.YELLOW)+ text.select("verb").set_color(m.BLUE)+ self.add(text)+ ```+ """+ label = f"_grp-{key}" if isinstance(key, int) else key+ if label not in self.labels:+ error = IndexError if isinstance(key, int) else KeyError+ raise error(f"no group {key!r}; labels: {list(self.labels)}")+ return self.labels[label]++ @property+ def font_size(self) -> float:+ """The mobject's effective font size, including scaling. Explicit width or height+ determines this size when given at construction. Set it to a positive size to+ scale the mobject to it."""+ return (+ self.height+ / self.initial_height+ / SCALE_FACTOR_PER_FONT_POINT+ / self._font_scale+ )++ @font_size.setter+ def font_size(self, val: float) -> None:+ if val <= 0:+ raise ValueError("font_size must be greater than 0.")+ if self.height > 0:+ self.scale(val / self.font_size)++ def scale(+ self,+ scale_factor: float | Vector3DLike,+ scale_stroke: bool = False,+ **kwargs: Unpack[Pivot],+ ) -> Self:+ """Scale the mobject and its whole family about a point, as+ [Mobject.scale][manimgx.Mobject.scale] does; the strokes the typesetting drew (a+ rule, a box's outline) keep their share of their part's size, unless the mobject+ was made with a `stroke_width`.++ Args:+ scale_factor: The factor: 2 doubles the mobject's size, 0.5 halves it; or+ its factors along x, y and z.+ scale_stroke: Whether the other strokes' widths scale too, by the factor.+ **kwargs: [Pivot keywords][manimgx.mobject.Pivot].+ """+ result = super().scale(scale_factor, scale_stroke=scale_stroke, **kwargs)+ self._scale_strokes()+ return result++ def _scale_strokes(self) -> None:+ """Each typeset stroke's width, its share of its part's size again."""+ if not self._strokes_scale:+ return+ for part, typeset_size, typeset_width in self._strokes:+ if typeset_size > 0:+ width = typeset_width * max(part.width, part.height) / typeset_size+ part.set_stroke(width=width * 100, family=False) # in 1/100 units++ def init_colors(self, propagate_colors: bool = True) -> Self:+ # Its parts are painted from the layout's ink; constructor style is not reused.+ self.__dict__.pop("style", None)+ return self+++_MANIMGRP = "#let manimgrp(lbl, body) = [#box(body) #label(lbl)]"+# a string, `{{`, `}}`, a bracket, or a run of anything else: strings and content blocks hold no groups+_TOKEN = re.compile(r'"(?:\\[\s\S]|[^"\\])*"?|\{\{|\}\}|[\[\]]|[^"\[\]{}]+|[{}]')+_LABELLED = re.compile(r"^(.*)\s*:\s*([a-zA-Z_][a-zA-Z0-9_-]*)\s*$", re.DOTALL)+++def _groups(expression: str) -> tuple[str, list[str]]:+ """The expression with each `{{ body }}` or `{{ body : label }}` as `manimgrp(label, body)`+ (unlabelled groups numbered `_grp-0`, `_grp-1`…), and the labels in order. A group runs to+ its matching `}}`; one never closed stays as written, with all that follows it."""+ tokens = _TOKEN.findall(expression)+ out: list[str] = []+ labels: list[str] = []+ i = brackets = auto = 0+ while i < len(tokens):+ token = tokens[i]+ i += 1+ if token == "[":+ brackets += 1+ elif token == "]" and brackets:+ brackets -= 1+ elif token == "{{" and not brackets:+ depth, inner, j = 1, 0, i+ while j < len(tokens) and depth:+ t, j = tokens[j], j + 1+ if t == "[":+ inner += 1+ elif t == "]" and inner:+ inner -= 1+ elif t in ("{{", "}}") and not inner:+ depth += 1 if t == "{{" else -1+ if depth:+ out.append("{{" + "".join(tokens[i:]))+ break+ content, i = "".join(tokens[i : j - 1]), j+ if match := _LABELLED.match(content):+ body, label = match.group(1).strip(), match.group(2)+ else:+ body, label, auto = content.strip(), f"_grp-{auto}", auto + 1+ labels.append(label)+ out.append(f'manimgrp("{label}", {body})')+ continue+ out.append(token)+ return "".join(out), labels+++class MathTypst(Typst):+ """A formula in Typst's math syntax, typeset in display style: its parts are its+ glyphs and shapes, white unless styled.++ `MathTypst("x^2 + y^2")` typesets `$ x^2 + y^2 $`, in New Computer Modern Math.+ Double braces make groups, which [select][manimgx.Typst.select] gives: `{{ x^2 }}`+ is numbered, 0 the first, and `{{ x^2 : square }}` is named "square"; the braces are+ not typeset.++ Args:+ math_expression: The formula, in Typst math.++ Examples:+ ```python+ import manimgx as m+++ class MathTypstExample(m.Scene):+ def construct(self) -> None:+ formula = m.MathTypst(+ "{{ a^2 : a }} + {{ b^2 : b }} = {{ c^2 : c }}", font_size=144+ )+ formula.select("a").set_color(m.BLUE)+ formula.select("b").set_color(m.GREEN)+ formula.select("c").set_color(m.YELLOW)+ self.play(m.Write(formula))+ ```+ """++ @prototype+ def __init__(self, math_expression: str, **kwargs: Unpack[TypstOptions]):+ processed, labels = _groups(math_expression)+ preamble = kwargs.get("typst_preamble", "")+ if labels and _MANIMGRP not in preamble:+ kwargs["typst_preamble"] = (+ f"{_MANIMGRP}\n{preamble}" if preamble else _MANIMGRP+ )+ super().__init__(f"$ {processed} $", **kwargs)+++DEFAULT_FONT = ( # embedded in Typst: identical text on every machine+ "New Computer Modern"+)+_SANS = ("Noto Sans", "Noto Sans Hebrew") # Typst's own fallback sets Hebrew in a serif+# CSS's and Pango's generic families, as faces manimgx ships (lowercase keys)+_GENERIC: dict[str, tuple[str, ...]] = {+ "serif": (DEFAULT_FONT,),+ "sans-serif": _SANS,+ "sans": _SANS,+ "monospace": ("DejaVu Sans Mono",),+ "mono": ("DejaVu Sans Mono",),+}+# the scripts that decide a CJK text's language (its Han characters' regional forms)+_KANA = re.compile("[\u3040-\u30ff\u31f0-\u31ff]")+_HANGUL = re.compile("[\u1100-\u11ff\u3130-\u318f\uac00-\ud7af]")+_HAN = re.compile("[\u3400-\u9fff\uf900-\ufaff\U00020000-\U0003ffff]")+_CE_CAP_HEIGHT_PER_POINT = 0.8979 / 96 # CE Text("A", font_size=96).height, measured+# The space between lines, in ems, for a line_spacing of -1: CE's default (its baselines are+# meant to be font_size * (1 + 0.3) apart)+_LINE_SPACING = 0.3+_WEIGHTS = {+ "THIN": 100,+ "ULTRALIGHT": 200,+ "LIGHT": 300,+ "SEMILIGHT": 350,+ "BOOK": 380,+ "NORMAL": 400,+ "MEDIUM": 500,+ "SEMIBOLD": 600,+ "BOLD": 700,+ "ULTRABOLD": 800,+ "HEAVY": 900,+ "ULTRAHEAVY": 950,+}+# CE's slants (any other is upright)+_SLANTS = {"ITALIC": "italic", "OBLIQUE": "oblique"}+_SLICE = re.compile(r"\[(-?\d*):(-?\d*)\]") # CE's slice keys, "[a:b]"+_FAR = 1e6 # a cut's outer edges, in font units: past any glyph's ink++type Style = tuple[str, str]+"""A run's CE weight and CE slant."""+++def _arguments(style: Style) -> str:+ """Typst's text arguments for a style."""+ weight, slant = style+ return (+ f"weight: {_WEIGHTS.get(weight.upper(), 400)},"+ f' style: "{_SLANTS.get(slant.upper(), "normal")}"'+ )+++def _fonts(font: str) -> str:+ """Typst's font list for a CE font name: a generic family's faces, or the family named+ and then manimgx's default face (for a family no font has, or a character it lacks).+ Typst falls back among manimgx's fonts after them."""+ families = _GENERIC.get(font.lower(), (font, DEFAULT_FONT))+ return f"({''.join(f'{typst_string(f)}, ' for f in dict.fromkeys(families))})"+++def _rules(text: str) -> str:+ """The Typst rules a text's characters call for: a right-to-left paragraph when its first+ strong character is (Unicode's rule, UAX #9 P2-P3; Typst takes a paragraph's direction+ from its language), and a CJK text's language, which picks its Han characters' regional+ forms: Japanese with kana, Korean with hangul, else Chinese (Simplified)."""+ rules = ""+ for ch in text:+ kind = unicodedata.bidirectional(ch)+ if kind in ("R", "AL"):+ rules += "#set text(dir: rtl)\n"+ if kind in ("L", "R", "AL"):+ break+ if _KANA.search(text):+ rules += '#set text(lang: "ja")\n'+ elif _HANGUL.search(text):+ rules += '#set text(lang: "ko")\n'+ elif _HAN.search(text):+ rules += '#set text(lang: "zh")\n'+ return rules+++def _find(text: str, key: str) -> list[range]:+ """The characters of `text` a key picks, as CE defines them: "[a:b]" is a slice of the text+ as written; any other key, each occurrence of it (not overlapping)."""+ match = _SLICE.fullmatch(key)+ if match is not None:+ start, stop = (int(g) if g else None for g in match.groups())+ return [range(*slice(start, stop).indices(len(text)))]+ spans = []+ at = text.find(key) if key else -1+ while at != -1:+ spans.append(range(at, at + len(key)))+ at = text.find(key, at + len(key))+ return spans+++def _literal(+ text: str,+ tab_width: int,+ out: list[str],+ runs: dict[int, list[int]],+ at: int,+ first: int,+) -> int:+ """Append `text` as a Typst string (set literally; tabs as `tab_width` spaces) and record,+ for each byte of its value, the character it came from. Return where the string ends.+ """+ value: list[str] = []+ chars: list[int] = []+ for k, ch in enumerate(text):+ piece = " " * tab_width if ch == "\t" else ch+ value.append(piece)+ chars.extend([first + k] * len(piece.encode()))+ literal = "#" + typst_string("".join(value))+ runs[at + 1] = chars # the string's node starts after the "#"+ out.append(literal)+ return at + len(literal.encode())+++def _lines(line_spacing: float) -> str:+ """The Typst rules that set lines on a baseline grid: baselines (1 + line_spacing) em+ apart, whatever the glyphs on them (-1: CE's default, 0.3). A line's box is its baseline,+ so the leading is the whole pitch."""+ gap = _LINE_SPACING if line_spacing == -1 else line_spacing+ return (+ '#set text(top-edge: "baseline", bottom-edge: "baseline")\n'+ f"#set par(leading: {1 + gap}em)\n"+ )+++def _calibration(font: str, kwargs: TypstOptions) -> float:+ """A capital's exact measured scale, reusing Typst's cached construction."""+ options: TypstOptions = {"font_size": DEFAULT_FONT_SIZE}+ if "font_paths" in kwargs:+ options["font_paths"] = kwargs["font_paths"]+ probe = Typst(f"#text(font: {_fonts(font)})[H]", **options)+ target = _CE_CAP_HEIGHT_PER_POINT * DEFAULT_FONT_SIZE+ return target / probe.height if probe.height > 0 else 1.0+++class TextOptions(TypstOptions, total=False):+ """[Text][manimgx.Text]'s keywords, for the classes that pass them on:+ [Paragraph][manimgx.Paragraph].++ Beyond these, they take the+ [Typst keywords][manimgx.mobjects.text.TypstOptions].+ """++ line_spacing: float+ """The space between lines, in ems: a text's baselines are `1 + line_spacing` ems+ apart, whatever the glyphs on them (default -1: 0.3)."""+ font: str+ """The font family: one manimgx ships (New Computer Modern, Libertinus Serif,+ DejaVu Sans Mono, Noto Sans, …), "serif", "sans-serif" or "monospace", one in+ `font_paths`, or else one of the system's; a family found nowhere falls back to New+ Computer Modern (default "": New Computer Modern)."""+ slant: str+ """The slant: `NORMAL`, `ITALIC` or `OBLIQUE` (default `NORMAL`)."""+ weight: str+ """The weight, by name, from `THIN` through `NORMAL` and `BOLD` to `ULTRAHEAVY`+ (default `NORMAL`); the font's nearest weight is used."""+ t2c: Mapping[str, ParsableManimColor] | None+ """A color for each key: a slice `"[a:b]"` of the text as written, spaces included,+ or a string, each occurrence of it (default None)."""+ t2g: Mapping[str, Sequence[ParsableManimColor]] | None+ """A gradient for each key: its colors spread along the characters the key picks, as+ `t2c` picks them (default None)."""+ t2s: Mapping[str, str] | None+ """A slant for each key, picking characters as `t2c` does (default None)."""+ t2w: Mapping[str, str] | None+ """A weight for each key, picking characters as `t2c` does (default None)."""+ gradient: Sequence[ParsableManimColor] | None+ """Colors spread along the whole text, character by character, spaces included+ (default None)."""+ tab_width: int+ """How many spaces a tab is set as (default 4)."""+ disable_ligatures: bool+ """Whether every character is a glyph of its own, with no ligatures (default False:+ "fi" may be one glyph)."""+++class Text(Typst):+ """Text in a font, typeset by Typst as it is written: white unless styled.++ Spaces stay, a newline breaks the line, a tab is `tab_width` spaces, and nothing is+ markup ("= Title" is no heading). The lines are set on a grid: their baselines are+ `1 + line_spacing` ems apart, whatever the glyphs on them. The parts are the glyphs,+ in reading order, spaces excluded: `Text("Hello")[0]` is the "H", a+ [TypstGlyph][manimgx.mobjects.text.TypstGlyph]. A ligature is one glyph+ (the "ffi" of "office", in the default font) unless `disable_ligatures`.++ A text is set in one font, from the fonts manimgx ships, so it looks the same on+ every machine: New Computer Modern unless `font` names another. "serif",+ "sans-serif" (or "sans") and "monospace" (or "mono") are New Computer Modern, Noto+ Sans and DejaVu Sans Mono. Fonts in `font_paths` come first; a family neither they+ nor manimgx have is read from the system's fonts, and one found nowhere falls back+ to New Computer Modern. A character the font lacks is set in another font that has+ it: manimgx ships Noto faces for Arabic, Hebrew, the Indic scripts, Thai, Chinese,+ Japanese, Korean and more, with symbols and emoji. In any font, a capital is 0.449+ scene units tall at the default size, 48, and in proportion at others: each font is+ scaled to that, and `font_size` still reads the size asked for.++ A text whose first letter is from a right-to-left script (Arabic, Hebrew) is set as+ a right-to-left paragraph, its lines lined up on the right. A Chinese, Japanese or+ Korean text takes its language from its characters (Japanese with kana, Korean with+ hangul, else Chinese), which gives its Han characters their regional forms.++ Keys pick characters: a slice `"[a:b]"` of the text as written, spaces included, or+ a string, each occurrence of it (a key that occurs nowhere picks nothing). `t2s` and+ `t2w` set what they pick in another slant or weight; `gradient`, then `t2g`, then+ `t2c` color it, each over the one before. Color never changes the layout: the text+ is laid out once, and each glyph takes the color of the characters it draws — a+ ligature that a color boundary crosses is cut there, each piece in its characters'+ color. A custom glyph's path-building methods also construct its color pieces.++ Args:+ text: The text, as written.+ line_spacing: The space between lines, in ems: the baselines are+ `1 + line_spacing` ems apart; -1 for 0.3.+ font: The font family, or "serif", "sans-serif" or "monospace"; "" for New+ Computer Modern.+ slant: `NORMAL`, `ITALIC` or `OBLIQUE`.+ weight: A weight by name, from `THIN` through `NORMAL` and `BOLD` to+ `ULTRAHEAVY`; the font's nearest weight is used.+ t2c: A color for each key.+ t2g: A gradient for each key: its colors spread along what the key picks.+ t2s: A slant for each key.+ t2w: A weight for each key.+ gradient: Colors spread along the whole text, character by character, spaces+ included.+ tab_width: How many spaces a tab is set as.+ disable_ligatures: Whether every character is a glyph of its own.+ **kwargs: [Typst keywords][manimgx.mobjects.text.TypstOptions]:+ `font_size` (48 unless given), `color`, `width` or `height`, and the rest.++ Examples:+ ```python+ import manimgx as m+++ class TextExample(m.Scene):+ def construct(self) -> None:+ texts = m.VGroup(+ m.Text("New Computer Modern"),+ m.Text("sans-serif: Noto Sans", font="sans-serif"),+ m.Text("monospace: DejaVu Sans Mono", font="monospace"),+ m.Text("Libertinus Serif", font="Libertinus Serif"),+ m.Text("bold and italic", weight=m.BOLD, slant=m.ITALIC),+ )+ self.add(texts.arrange(m.DOWN, buff=0.5).scale(1.3))+ ```++ ```python+ import manimgx as m+++ class TextScriptsExample(m.Scene):+ def construct(self) -> None:+ texts = m.VGroup(+ m.Text("Ελληνικά, кириллица"),+ m.Text("مرحبا بالعالم"),+ m.Text("สวัสดีชาวโลก"),+ m.Text("你好,世界"),+ m.Text("こんにちは、世界"),+ m.Text("안녕하세요, 세계"),+ )+ self.add(texts.arrange(m.DOWN, buff=0.4).scale(1.2))+ ```++ ```python+ import manimgx as m+++ class TextColoringExample(m.Scene):+ def construct(self) -> None:+ words = {"red": m.RED, "green": m.GREEN, "blue": m.BLUE}+ word = {"gradient": (m.RED, m.YELLOW)}+ texts = m.VGroup(+ m.Text("red, green and blue", t2c=words),+ m.Text("a slice of the text", t2c={"[2:7]": m.YELLOW}),+ m.Text("a gradient along it all", gradient=(m.BLUE, m.GREEN)),+ m.Text("a gradient in one word", t2g=word),+ )+ self.add(texts.arrange(m.DOWN, buff=0.5).scale(1.3))+ ```+ """++ @prototype+ def __init__(+ self,+ text: str,+ line_spacing: float = -1,+ font: str = "",+ slant: str = NORMAL,+ weight: str = NORMAL,+ t2c: Mapping[str, ParsableManimColor] | None = None,+ t2g: Mapping[str, Sequence[ParsableManimColor]] | None = None,+ t2s: Mapping[str, str] | None = None,+ t2w: Mapping[str, str] | None = None,+ gradient: Sequence[ParsableManimColor] | None = None,+ tab_width: int = 4,+ disable_ligatures: bool = False,+ **kwargs: Unpack[TypstOptions],+ ) -> None:+ if kwargs.get("fill_opacity") is None: # not given, None too+ kwargs["fill_opacity"] = 1.0+ self.text = text+ """The text, as it was written."""+ self.original_text = text+ self.font = font+ self.slant, self.weight = slant, weight+ chars = text # the text as written, as characters+ family = font or DEFAULT_FONT+ base: Style = (weight, slant)+ styles: list[Style] | None = None+ if t2w or t2s:+ styles = [base] * len(chars)+ for field, mapping in enumerate((t2w, t2s)):+ for key, value in (mapping or {}).items():+ for span in _find(chars, key):+ for i in span:+ style = list(styles[i])+ style[field] = value+ styles[i] = (style[0], style[1])+ ligatures = ", ligatures: false" if disable_ligatures else ""+ head = f"#text(font: {_fonts(family)}, {_arguments(base)}{ligatures})["+ body, runs = self._source(text, tab_width, len(head.encode()), base, styles)+ rules = _rules(text) + (_lines(line_spacing) if "\n" in text else "")+ if rules:+ kwargs["typst_preamble"] = rules + kwargs.get("typst_preamble", "")+ # set larger by its font's calibration, so font_size stays the size asked for+ super().__init__(+ f"{head}{body}]", font_scale=_calibration(family, kwargs), **kwargs+ )+ self._chars = chars+ self._clusters = self._characters(runs)+ colors: dict[int, ManimColor] = {}+ if gradient:+ colors |= dict(enumerate(color_gradient(list(gradient), len(chars))))+ for key, stops in (t2g or {}).items():+ for span in _find(chars, key):+ if span:+ colors |= dict(zip(span, color_gradient(list(stops), len(span))))+ for key, color in (t2c or {}).items():+ for span in _find(chars, key):+ colors |= dict.fromkeys(span, ManimColor(color))+ if colors:+ self._paint(colors)++ def _source(+ self,+ text: str,+ tab_width: int,+ at: int,+ base: Style,+ styles: list[Style] | None,+ ) -> tuple[str, dict[int, list[int]]]:+ """The Typst code setting the text (from byte `at`): a string per run of one style, and for+ each string where it starts and the character each byte of its value came from.+ """+ out: list[str] = []+ runs: dict[int, list[int]] = {}+ if styles is None or not text:+ _literal(text, tab_width, out, runs, at, 0)+ return "".join(out), runs+ start = 0+ for end in range(1, len(text) + 1):+ if end < len(text) and styles[end] == styles[start]:+ continue+ opener = (+ "" if styles[start] == base else f"#text({_arguments(styles[start])})["+ )+ out.append(opener)+ at += len(opener.encode())+ at = _literal(text[start:end], tab_width, out, runs, at, start)+ if opener:+ out.append("]")+ at += 1+ start = end+ return "".join(out), runs++ def _characters(self, runs: dict[int, list[int]]) -> list[range]:+ """Each part's characters: those its glyph's cluster draws, through the string it came+ from (none for a part not from the text: a list's marker, an underline)."""+ clusters = []+ for part in self.submobjects:+ drawn: list[int] = []+ if isinstance(part, TypstGlyph) and part.node in runs:+ drawn = runs[part.node][part.drawn[0] : part.drawn[1]]+ clusters.append(range(drawn[0], drawn[-1] + 1) if drawn else range(0))+ return clusters++ def _paint(self, colors: Mapping[int, ManimColor]) -> None:+ """Each glyph takes its characters' colors (a grapheme's color: its first character's);+ a glyph of several colors is cut at its carets."""+ graphemes = _engine.graphemes(self._chars)+ for part, chars in zip(self.submobjects, self._clusters):+ if not chars:+ continue+ heads = graphemes[+ bisect.bisect_left(graphemes, chars.start) : bisect.bisect_left(+ graphemes, chars.stop+ )+ ]+ if not heads or heads[0] != chars.start:+ heads.insert(0, chars.start)+ paints = [colors.get(i) for i in heads]+ if len(set(paints)) == 1:+ if paints[0] is not None:+ part.set_color(paints[0])+ elif isinstance(part, TypstGlyph):+ rtl = unicodedata.bidirectional(self._chars[chars.start]) in ("R", "AL")+ _cut(part, paints[::-1] if rtl else paints)+++def _cut(glyph: TypstGlyph, paints: list[ManimColor | None]) -> None:+ """Cut a glyph at its carets (the font's, else equal parts) into pieces of one color each; the+ glyph becomes their group."""+ n = len(paints)+ carets: np.ndarray | tuple[float, ...] = np.frombuffer(glyph._carets, dtype="<f8")+ if len(carets) != n - 1:+ carets = tuple(glyph.x_advance * k / n for k in range(1, n))+ edges = [-_FAR, *carets, _FAR]+ runs: list[tuple[float, float, ManimColor | None]] = []+ for k, paint in enumerate(paints):+ if runs and runs[-1][2] == paint:+ runs[-1] = (runs[-1][0], edges[k + 1], paint)+ else:+ runs.append((edges[k], edges[k + 1], paint))+ ((placement, outline),) = glyph._geometry.terms+ tolerance = VMobject.tolerance_for_point_equality+ whole = _to_path(Blend.of(outline.array).points(), tolerance)+ pieces = []+ for x0, x1, paint in runs:+ corners = np.array(+ [+ [x0, -_FAR, 0],+ [x1, -_FAR, 0],+ [x1, _FAR, 0],+ [x0, _FAR, 0],+ [x0, -_FAR, 0],+ ]+ )+ strip = np.empty((16, 3))+ for i, alpha in enumerate(np.linspace(0, 1, 4)):+ strip[i::4] = interpolate(corners[:-1], corners[1:], alpha)+ result = _pathops().op(+ whole,+ _to_path(Blend.of(strip).points(), tolerance),+ _pathops().PathOp.INTERSECTION,+ )+ piece = glyph.copy()+ piece._geometry = EMPTY+ _append_path(piece, result)+ local = piece.points+ piece._geometry = Blend(((placement, Shape(np.array(local))),), len(local))+ if paint is not None:+ piece.set_color(paint)+ pieces.append(piece)+ glyph._geometry = EMPTY+ glyph.add(*pieces)+++class Paragraph(VGroup):+ """Lines of text set as one paragraph: on one grid of baselines, each line at the+ paragraph's start or where `alignment` puts it.++ The lines are one [Text][manimgx.Text] (`lines_text`), joined by newlines, so they+ share its grid: their baselines are `1 + line_spacing` ems apart (1.3 unless+ `line_spacing` is given). The paragraph's parts are its lines, from the top, each+ the group of its glyphs.++ Args:+ *text: The lines: each string is one, or several, split at its newlines.+ alignment: "left", "center" or "right" to line the lines up on that side or+ center them; None to start each at the paragraph's start (the left, for+ left-to-right text).++ Examples:+ ```python+ import manimgx as m+++ class ParagraphExample(m.Scene):+ def construct(self) -> None:+ lines = ("Twinkle, twinkle,", "little star,", "how I wonder")+ paragraphs = m.VGroup(+ m.Paragraph(*lines),+ m.Paragraph(*lines, alignment="center", line_spacing=1),+ m.Paragraph(*lines, alignment="right"),+ )+ self.add(paragraphs.arrange(buff=0.8).scale(0.85))+ ```+ """++ def __init__(+ self,+ *text: str,+ alignment: Literal["left", "center", "right"] | None = None,+ **kwargs: Unpack[TextOptions],+ ) -> None:+ joined = "\n".join(text)+ if alignment is not None: # Typst's alignments of these names+ kwargs["typst_preamble"] = f"#set align({alignment})\n" + kwargs.get(+ "typst_preamble", ""+ )+ self.lines_text = whole = Text(joined, **kwargs)+ """The lines as one [Text][manimgx.Text], joined by newlines: the paragraph's+ lines group its glyphs."""+ # the parts are the lines, each the group of its glyphs (CE's structure)+ starts = [0, *(i + 1 for i, ch in enumerate(joined) if ch == "\n")]+ lines: list[list[Mobject]] = [[] for _ in starts]+ for part, chars in zip(whole.submobjects, whole._clusters):+ lines[bisect.bisect_right(starts, chars.start) - 1].append(part)+ super().__init__(*(VGroup(*line) for line in lines))+ self.alignment = alignment+++# LaTeX is converted to Typst by mitex, compiled into the engine; the package gives its scope.+# LaTeX sets its text in Computer Modern, as its math (Typst's default text face is Libertinus)+_IMPORT = (+ '#import "@preview/mitex:0.2.7": mitex-scope\n'+ '#set text(font: "New Computer Modern")\n'+)+++def _standalone(tex: str) -> str:+ """CE's `_modify_special_strings`: make a lone LaTeX fragment typeset on its own."""+ tex = tex.strip()+ if tex in ("\\over", "\\overline", "\\sqrt", "\\sqrt{") or tex.endswith(+ ("_", "^", "dot")+ ):+ tex += "{\\quad}"+ if tex in ("\\substack", ""):+ tex = "\\quad"+ if tex.startswith("\\\\"):+ tex = tex.replace("\\\\", "\\quad\\\\")+ lefts, rights = (+ len([s for s in tex.split(k)[1:] if s and s[0] in "(){}[]|.\\"])+ for k in ("\\left", "\\right")+ )+ if lefts != rights:+ tex = tex.replace("\\left", "\\big").replace("\\right", "\\big")+ opens = tex.count("{") - tex.count("\\{") + tex.count("\\\\{")+ closes = tex.count("}") - tex.count("\\}") + tex.count("\\\\}")+ 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+++def _isolate_braces(strings: list[str]) -> list[str]:+ """CE's double braces: `{{…}}` sets what it holds apart as a part of its own; once they+ split anything, every part is stripped."""+ pieces = [p for s in strings for p in _BRACES.split(s)]+ if 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+ piece converting on its own does not tell.)"""+ depth = 0+ for command, brace in _TOKENS.findall(tex):+ depth += _DEPTH.get(command or brace, 0)+ if depth < 0:+ return False+ return depth == 0+++def _one_formula(pieces: list[str], separator: str) -> tuple[str, str, set[int]]:+ """The pieces as one formula: the Typst math code of their joined LaTeX; the same code+ with each piece that stands on its own (a `hole`) boxed and labelled `p{i}`, to tell its+ glyphs apart; and those pieces. The holes are converted on their own, in the joined+ LaTeX's skeleton, so the formula's code is checked to be what the whole converts to:+ telling the pieces apart never changes the formula."""+ whole = _engine.mitex_math(separator.join(pieces))+ holes: dict[int, str] = {}+ for i, piece in enumerate(pieces):+ if not _balanced(piece) or piece.lstrip()[:1] in ("^", "_", "'", ""):+ continue # a fragment, or an attachment to what comes before+ try:+ holes[i] = _engine.mitex_math(piece)+ except TypstError:+ continue+ skeleton = _engine.mitex_math(+ separator.join(+ chr(_HOLE + i) if i in holes else p for i, p in enumerate(pieces)+ )+ )+ found = [ord(c) - _HOLE for c in skeleton if _HOLE <= ord(c) < _HOLE + len(pieces)]+ plain = boxed = skeleton+ for i, code in holes.items():+ plain = plain.replace(chr(_HOLE + i), code)+ boxed = boxed.replace(chr(_HOLE + i), f'#manimgrp("p{i}", ${code}$)')+ if found != sorted(holes) or "".join(plain.split()) != "".join(whole.split()):+ raise ValueError(f"MathTex cannot tell these parts apart: {pieces}")+ return plain, boxed, set(holes)+++_MITEX = 'mode: "math", scope: mitex-scope'+++def _math(latex: str) -> str:+ converted = typst_string(_engine.mitex_math(latex))+ return f"eval({converted}, {_MITEX})"+++def _text(latex: str) -> str:+ converted = typst_string(_engine.mitex_text(latex))+ return f'eval({converted}, mode: "markup", scope: mitex-scope)'+++class SingleStringMathTex(Typst):+ r"""One LaTeX formula, typeset in the engine, whose parts are its glyphs: white+ unless styled.++ The LaTeX is converted to Typst as a [MathTex][manimgx.MathTex]'s is, and set in+ display style; the parts are not grouped by strings, so `formula[i]` is its i-th+ glyph (or shape, such as a fraction's bar), in the order Typst sets them.++ Args:+ tex_string: The formula, in LaTeX.+ organize_left_to_right: Whether to order the parts by their centers, from left+ to right, rather than as Typst sets them.+ tex_environment: Any environment (the default, "align*") sets the string as+ math; None as LaTeX text, math between `$` signs.++ Examples:+ ```python+ import manimgx as m+++ class SingleStringMathTexExample(m.Scene):+ def construct(self) -> None:+ formula = m.SingleStringMathTex(r"e^{i\pi} + 1 = 0", font_size=144)+ formula[1:3].set_color(m.YELLOW)+ self.add(formula, m.index_labels(formula, label_height=0.3))+ ```+ """++ @prototype+ def __init__(+ self,+ tex_string: str,+ organize_left_to_right: bool = False,+ tex_environment: str | None = "align*",+ **kwargs: Unpack[TypstOptions],+ ) -> None:+ self.tex_string = tex_string = str(tex_string)+ """The LaTeX the formula was typeset from."""+ self.tex_environment = tex_environment+ body = (+ f"$ #{_math(tex_string)} $" if tex_environment else f"#{_text(tex_string)}"+ )+ kwargs["typst_preamble"] = _IMPORT + kwargs.get("typst_preamble", "")+ super().__init__(body, **kwargs)+ if organize_left_to_right:+ self.submobjects.sort(key=lambda m: m.get_x())+++class MathTexPart(VGroup):+ """One of a [MathTex][manimgx.MathTex]'s parts: the glyphs one of its strings adds+ to the formula, as a group that knows the string.++ Args:+ tex_string: The LaTeX it was typeset from.+ *members: Its glyphs.+ """++ def __init__(self, tex_string: str, *members: Mobject) -> None:+ super().__init__(*members)+ self.tex_string = tex_string+ """The LaTeX the part was typeset from."""+++class MathTexOptions(TypstOptions, total=False):+ """[MathTex][manimgx.MathTex]'s keywords, for the classes that pass them on:+ [Tex][manimgx.Tex], [BulletedList][manimgx.BulletedList], [Title][manimgx.Title] and+ labels.++ Beyond these, they take the+ [Typst keywords][manimgx.mobjects.text.TypstOptions].+ """++ arg_separator: str+ """What joins the strings into `tex_string`, the formula a MathTex is typeset as+ (default " "; "" for a Tex, whose strings are typeset one after another)."""+ substrings_to_isolate: Iterable[str] | None+ """Substrings to make parts of their own: each string is split around every+ occurrence of each (default None)."""+ tex_to_color_map: Mapping[str, ParsableManimColor] | None+ """A color for each substring, which is made a part of its own, as+ `substrings_to_isolate` makes it, and colored (default None)."""+ tex_environment: str | None+ """How the strings are read: with a name containing "align" ("align*", a MathTex's+ default), as math; with any other ("center", a Tex's default, which also centers the+ lines), or None, as LaTeX text, math between `$` signs."""+++class MathTex(Typst):+ r"""LaTeX math, typeset in the engine, a part per string: `MathTex("a^2", "+",+ "b^2")[2]` is the $b^2$, to color, move or match with another formula.++ There is no LaTeX installation: the LaTeX is converted to Typst (by mitex, part of+ the engine) and typeset in display style, in New Computer Modern Math, white unless+ styled. Most of LaTeX's math converts: fractions, roots, sums and integrals,+ matrices (`pmatrix`, `bmatrix`, `array`), `cases` and `aligned`, accents, `\mathbb`+ and the other alphabets, `\text`, `\left` and `\right`, `\color`, `\newcommand`.+ Packages don't — `\usepackage` and their commands, such as `\ce` or `\SI` — nor does+ `\def`: a command mitex doesn't know raises a+ [TypstError][manimgx.drawing.typesetting.TypstError].++ 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+ `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.++ `substrings_to_isolate` and `tex_to_color_map` split the strings further;+ [set_color_by_tex][manimgx.MathTex.set_color_by_tex] and+ [get_part_by_tex][manimgx.MathTex.get_part_by_tex] find parts by their LaTeX, and+ [TransformMatchingTex][manimgx.TransformMatchingTex] moves each part to the part+ written the same way in another formula. Read as text (see [Tex][manimgx.Tex]), the+ strings are typeset one after another instead.++ Args:+ *tex_strings: The formula, in LaTeX: a string per part (a number is written as+ a string), and a part per `{{…}}` within one.+ arg_separator: What joins the strings into `tex_string`, the formula they are+ typeset as.+ substrings_to_isolate: Substrings to make parts of their own: each string is+ split around every occurrence of each.+ tex_to_color_map: A color for each substring, which is made a part of its own+ and colored.+ tex_environment: How the strings are read: with a name containing "align" (the+ default, "align*"), as math; with any other, or None, as LaTeX text, math+ between `$` signs.++ Examples:+ ```python+ import manimgx as m+++ class MathTexExample(m.Scene):+ def construct(self) -> None:+ formula = m.MathTex("a^2", "+", "b^2", "=", "c^2", font_size=144)+ formula[0].set_color(m.BLUE)+ formula[2].set_color(m.GREEN)+ formula[4].set_color(m.YELLOW)+ self.play(m.Write(formula))+ ```++ ```python+ import manimgx as m+++ class MathTexLatexExample(m.Scene):+ def construct(self) -> None:+ limit = r"\lim_{n \to \infty} \left(1 + \frac{1}{n}\right)^n = e"+ formulas = m.VGroup(+ m.MathTex(r"\int_0^1 x^2 \, dx = \frac{1}{3}"),+ m.MathTex(r"\begin{pmatrix} a & b \\ c & d \end{pmatrix}"),+ m.MathTex(limit),+ m.MathTex(r"\sum_{n=1}^\infty \frac{1}{n^2} = \frac{\pi^2}{6}"),+ )+ self.add(formulas.arrange_in_grid(rows=2, buff=1).scale(1.3))+ ```+ """++ @prototype+ def __init__(+ self,+ *tex_strings: str | float,+ arg_separator: str = " ",+ substrings_to_isolate: Iterable[str] | None = None,+ tex_to_color_map: Mapping[str, ParsableManimColor] | None = None,+ tex_environment: str | None = "align*",+ **kwargs: Unpack[TypstOptions],+ ) -> None:+ self.tex_to_color_map = dict(tex_to_color_map or {})+ isolate = list(substrings_to_isolate or []) + list(self.tex_to_color_map)+ strings = _isolate_braces([str(s) for s in tex_strings])+ self.tex_strings = (+ [p for s in strings for p in _split(s, isolate)] if isolate else strings+ )+ """The strings, a part's each: the arguments, split at `{{…}}` and around the+ isolated substrings."""+ self.arg_separator = arg_separator+ self.tex_string = arg_separator.join(self.tex_strings)+ """The LaTeX of the whole formula: the strings, joined by `arg_separator`."""+ self.tex_environment = tex_environment+ fn = _math if tex_environment and "align" in tex_environment else _text+ preamble = f"{_IMPORT}{_MANIMGRP_PREAMBLE}\n"++ def body(strings: list[str]) -> str:+ if fn is _math: # a part's box would drop to text style; keep display style+ parts = " ".join(+ f'#manimgrp("p{i}", $display(#{_math(_standalone(s))})$)'+ for i, s in enumerate(strings)+ )+ return f"$ {parts} $"+ return self._set(+ [+ f'manimgrp("p{i}", {_text(_standalone(s))})'+ for i, s in enumerate(strings)+ ]+ )++ formula = None+ if (+ fn is _math and len(self.tex_strings) > 1+ ): # one formula, its parts told apart+ formula = _one_formula(self.tex_strings, arg_separator)+ source = f"$ #eval({typst_string(formula[0])}, {_MITEX}) $"+ else:+ try:+ source = body(self.tex_strings)+ if len(self.tex_strings) != 1: # a lone part's fallback is itself+ typeset(source, preamble)+ except (+ TypstError+ ): # the parts are not LaTeX on their own (e.g. a split environment)+ source = body([self.tex_string])+ kwargs["typst_preamble"] = preamble + kwargs.get("typst_preamble", "")+ super().__init__(source, **kwargs)+ if formula is None:+ self._regroup_by_labels()+ else:+ self._regroup_by_twin(+ f"$ #eval({typst_string(formula[1])}, {_MITEX} + (manimgrp:"+ " manimgrp)) $",+ formula[2],+ kwargs["typst_preamble"],+ kwargs.get("font_paths"),+ kwargs.get("package_path"),+ )+ for tex, c in self.tex_to_color_map.items():+ self.set_color_by_tex(tex, c)++ def _set(self, parts: list[str]) -> str:+ """The text parts (Typst expressions, each a labelled group) as the document sets them:+ one run of text, centered in the "center" environment."""+ joined = " ".join(f"#{part}" for part in parts)+ return (+ f"#align(center)[{joined}]" if self.tex_environment == "center" else joined+ )++ def _regroup_by_labels(self) -> None:+ groups: list[Mobject] = []+ for i, s in enumerate(self.tex_strings):+ members = self.labels.get(f"p{i}", VGroup())+ groups.append(MathTexPart(s, *members))+ if any(len(g) for g in groups):+ self.submobjects = groups++ def _regroup_by_twin(+ self,+ twin: str,+ holes: set[int],+ preamble: str,+ font_paths: list[str | Path] | None,+ package_path: str | Path | None,+ ) -> None:+ """Parts from the formula's boxed twin, which draws what the formula draws in the same+ order: a hole's glyphs and shapes are labelled; the rest belong to the piece between+ the holes around them (the first, if several are)."""+ other = typeset(+ twin, preamble, font_paths=font_paths, package_path=package_path+ )+ rows = other.rows+ leaves = list(self.submobjects)+ if len(rows) != len(leaves) or any(+ (row[KIND] == GLYPH) != isinstance(leaf, TypstGlyph)+ for row, leaf in zip(rows, leaves, strict=True)+ ):+ raise ValueError(+ f"MathTex cannot tell these parts apart: {self.tex_strings}"+ )+ hole_of = {+ row: int(label[1:])+ for label, members in other.labels+ if label.startswith("p") and label[1:].isdigit()+ for row in members+ }+ count = len(self.tex_strings)+ groups: list[list[Mobject]] = [[] for _ in range(count)]+ start, before = 0, -1+ for k in range(len(leaves) + 1):+ hole = count if k == len(leaves) else hole_of.get(k)+ if hole is None:+ continue+ if start < k: # this unlabelled run lies between the same two holes+ piece = next(+ (i for i in range(before + 1, hole) if i not in holes),+ max(before, 0),+ )+ groups[piece].extend(leaves[start:k])+ if k < len(leaves):+ groups[hole].append(leaves[k])+ start, before = k + 1, hole+ self.submobjects = [+ MathTexPart(s, *members)+ for s, members in zip(self.tex_strings, groups, strict=True)+ ]++ def get_parts_by_tex(+ self, tex: str, substring: bool = True, case_sensitive: bool = True+ ) -> VGroup:+ """Find the parts whose LaTeX contains `tex`, or is it.++ Args:+ tex: The LaTeX to look for.+ substring: Whether a part whose LaTeX contains `tex` matches; if not, only+ one whose LaTeX is `tex`.+ case_sensitive: Whether upper and lower case differ.++ Returns:+ A new group of the parts themselves, in order.+ """++ def match(s: str) -> bool:+ a, b = (tex, s) if case_sensitive else (tex.lower(), s.lower())+ return a in b if substring else a == b++ return VGroup(+ *(+ m+ for m in self.submobjects+ if isinstance(m, MathTexPart) and match(m.tex_string)+ )+ )++ def get_part_by_tex(+ self, tex: str, substring: bool = True, case_sensitive: bool = True+ ) -> Mobject | None:+ r"""Find the first part whose LaTeX contains `tex`, or is it.++ Args:+ tex: The LaTeX to look for.+ substring: Whether a part whose LaTeX contains `tex` matches; if not, only+ one whose LaTeX is `tex`.+ case_sensitive: Whether upper and lower case differ.++ Returns:+ The part itself, or None if none matches.++ Examples:+ ```python+ import manimgx as m+++ class MathTexGetPartByTexExample(m.Scene):+ def construct(self) -> None:+ formula = m.MathTex(+ r"\sin^2\theta", "+", r"\cos^2\theta", "=", "1", font_size=120+ )+ self.add(formula)+ self.play(m.Indicate(formula.get_part_by_tex(r"\cos")))+ ```+ """+ parts = self.get_parts_by_tex(tex, substring, case_sensitive)+ return parts[0] if len(parts) else None++ def index_of_part(self, part: Mobject) -> int:+ """Find where a part is among the formula's parts; a mobject that is not one+ raises ValueError.++ Args:+ part: One of the parts.++ Returns:+ Its index, from 0.+ """+ return self.submobjects.index(part)++ def set_color_by_tex(+ self,+ tex: str,+ color: ParsableManimColor,+ substring: bool = True,+ case_sensitive: bool = True,+ ) -> Self:+ """Color the parts whose LaTeX contains `tex`, or is it.++ Args:+ tex: The LaTeX to look for.+ color: Their color.+ substring: Whether a part whose LaTeX contains `tex` matches; if not, only+ one whose LaTeX is `tex`.+ case_sensitive: Whether upper and lower case differ.++ Examples:+ ```python+ import manimgx as m+++ class MathTexSetColorByTexExample(m.Scene):+ def construct(self) -> None:+ formula = m.MathTex(+ "x + y = y + x", substrings_to_isolate=["x", "y"], font_size=144+ )+ formula.set_color_by_tex("x", m.YELLOW)+ formula.set_color_by_tex("y", m.BLUE)+ self.add(formula)+ ```+ """+ for part in self.get_parts_by_tex(tex, substring, case_sensitive):+ part.set_color(color)+ return self++ def set_color_by_tex_to_color_map(+ self,+ texs_to_color_map: Mapping[str, ParsableManimColor],+ substring: bool = True,+ case_sensitive: bool = True,+ ) -> Self:+ """Color parts by their LaTeX: for each entry, the parts whose LaTeX contains+ it, or is it.++ Args:+ texs_to_color_map: A color for each piece of LaTeX, applied in order.+ substring: Whether a part whose LaTeX contains a piece matches; if not, only+ one whose LaTeX is the piece.+ case_sensitive: Whether upper and lower case differ.+ """+ for tex, color in texs_to_color_map.items():+ self.set_color_by_tex(tex, color, substring, case_sensitive)+ return self+++def _split(s: str, isolate: list[str]) -> list[str]:+ parts = [s]+ for sub in sorted(isolate, key=len, reverse=True):+ out: list[str] = []+ for p in parts:+ if p in isolate:+ out.append(p)+ continue+ pieces = p.split(sub)+ for k, piece in enumerate(pieces):+ if piece:+ out.append(piece)+ if k < len(pieces) - 1:+ out.append(sub)+ parts = out+ return [p for p in parts if p.strip()]+++class Tex(MathTex):+ r"""LaTeX text, typeset in the engine and centered, a part per string: math goes+ between `$` signs.++ It is a [MathTex][manimgx.MathTex] that reads its strings as LaTeX text: bold+ (`\textbf`), italics (`\emph`, `\textit`), line breaks (`\\`) and inline math+ convert. The text is set in New Computer Modern, as LaTeX sets it, the math in New+ Computer Modern Math; white unless styled. The strings are typeset one after+ another, each on its own, a space apart; if one doesn't typeset on its own, the+ text is typeset whole, and its glyphs are the first part's.++ Args:+ *tex_strings: The text, in LaTeX: a string per part.+ **kwargs: [MathTex keywords][manimgx.mobjects.text.MathTexOptions]:+ the strings are joined by "" and read in a "center" environment unless+ `arg_separator` and `tex_environment` say otherwise.++ Examples:+ ```python+ import manimgx as m+++ class TexExample(m.Scene):+ def construct(self) -> None:+ text = m.Tex(+ r"\textbf{Bold}, \emph{emphasized},\\ and math: $e^{i\pi} = -1$",+ font_size=96,+ )+ self.play(m.Write(text))+ ```+ """++ def __init__(+ self, *tex_strings: str | float, **kwargs: Unpack[MathTexOptions]+ ) -> None:+ kwargs.setdefault("arg_separator", "")+ kwargs.setdefault("tex_environment", "center")+ super().__init__(*tex_strings, **kwargs)+++_BULLET = "bullet"+++class BulletedList(Tex):+ r"""A bulleted list: an item per line, each after a bullet, lined up on the left.++ Typst sets the items as a list: each bullet is a centered dot (LaTeX's `\cdot` at+ twice its size), `SMALL_BUFF` from its item, and the items are `buff` apart, in+ scene units at the list's font size. Each item is LaTeX text (math between `$`+ signs) and a part of its own, its bullet first: `items[1]` is the second item.+ `height` and `width` scale the list as set.++ Args:+ *items: The items, in LaTeX.+ buff: The space between items, in scene units.++ Examples:+ ```python+ import manimgx as m+++ class BulletedListExample(m.Scene):+ def construct(self) -> None:+ items = m.BulletedList(+ "Typeset in the engine",+ "No LaTeX installation",+ r"Math too: $a^2 + b^2 = c^2$",+ font_size=72,+ )+ self.add(items)+ self.play(items.animate.fade_all_but(1))+ ```+ """++ # the list's lengths are a set rule of the preamble, so part of what a construction+ # is keyed by; the bullet is CE's (dot_scale_factor 2), and so is the structure++ def __init__(+ self,+ *items: str,+ buff: float = MED_LARGE_BUFF,+ **kwargs: Unpack[MathTexOptions],+ ) -> None:+ self.buff = buff+ pt = 1 / (+ kwargs.get("font_size", DEFAULT_FONT_SIZE) * SCALE_FACTOR_PER_FONT_POINT+ )+ kwargs["typst_preamble"] = (+ f"#set list(marker: [#box(scale(200%, $dot.c$))<{_BULLET}>], indent: 0pt,"+ f" body-indent: {SMALL_BUFF * pt}pt, spacing: {buff * pt}pt)\n"+ + kwargs.get("typst_preamble", "")+ )+ kwargs.setdefault("tex_environment", None)+ super().__init__(*items, **kwargs)+ # the bullets, one glyph each, in their items' order+ bullets = self.labels.get(_BULLET, VGroup())+ for part, bullet in zip(self.submobjects, bullets.submobjects, strict=True):+ part.add_to_back(bullet)++ def _set(self, parts: list[str]) -> str:+ return f"#list({', '.join(parts)})"++ def fade_all_but(self, index: int, opacity: float = 0.5) -> Self:+ """Fade every item but one: the others' fill to `opacity`, the one's to 1.++ Args:+ index: The item's index, from 0.+ opacity: The other items' fill opacity, from 0 to 1.+ """+ part = self.submobjects[index]+ for other in self.submobjects:+ other.set_fill(opacity=1 if other is part else opacity)+ return self+++class Title(Tex):+ """A title: LaTeX text at the top of the frame, over a line across it.++ The line is the last part, and the title's `underline`; a `color` colors it with+ the text, as [set_color][manimgx.Mobject.set_color] would.++ Args:+ *text_parts: The title, in LaTeX: a string per part.+ include_underline: Whether a line is drawn under the title.+ match_underline_width_to_text: Whether the line is as wide as the title; if+ not, it spans the frame but 1 unit at each side.+ underline_buff: The gap between the title and the line, in scene units.++ Examples:+ ```python+ import manimgx as m+++ class TitleExample(m.Scene):+ def construct(self) -> None:+ title = m.Title(r"The Pythagorean theorem: $a^2 + b^2 = c^2$")+ self.play(m.Write(title))+ ```+ """++ def __init__(+ self,+ *text_parts: str,+ include_underline: bool = True,+ match_underline_width_to_text: bool = False,+ underline_buff: float = MED_SMALL_BUFF,+ **kwargs: Unpack[MathTexOptions],+ ) -> None:+ from manimgx.config import config+ from manimgx.constants import DOWN, LEFT, RIGHT, UP+ from manimgx.mobjects.shapes import Line++ super().__init__(*text_parts, **kwargs)+ self.to_edge(UP)+ if include_underline:+ underline = Line(LEFT, RIGHT).next_to(self, DOWN, buff=underline_buff)+ underline.width = (+ self.width if match_underline_width_to_text else config.frame_width - 2+ )+ color = kwargs.get("color")+ if color is not None: # color= colors the whole title, as set_color does+ underline.set_color(color)+ self.add(underline)+ self.underline = underline+ """The line under the title, its last part (a title made without one has+ none)."""diff --git a/tests/unit/mobjects/test_numbers.py b/tests/unit/mobjects/test_numbers.pynew file mode 100644index 00000000..e76dbbf1--- /dev/null+++ b/tests/unit/mobjects/test_numbers.py@@ -0,0 +1,225 @@+"""A number spells its value, and set to a value it is the number made with it.++- Its characters are its value rounded to its places (half to even, on the value's exact+ binary digits, as decimal arithmetic rounds them: another algorithm than the formatting+ manimgx uses; a displayed zero has no sign), grouped by commas and signed as asked, whether+ it was made with the value or set to it from another; a numpy scalar by its own value, an+ integer to a whole. A complex number spells each of its parts so, the second signed, and is+ written `a+bi`.+- Set to a value, a number is the number made with that value and with its attributes as they+ are now (its unit, its characters' class, its gaps, its ellipsis, its background), at the+ font size it has and with the edge it fixes where it was.+- A number's font size is positive.+- A variable shows its tracker's value in the number class it was asked for.+"""++from collections.abc import Callable+from decimal import ROUND_HALF_EVEN, Decimal++import numpy as np+import pytest+from hypothesis import example, given+from hypothesis import strategies as st++import manimgx as m+from manimgx.mobjects.numbers import DecimalNumberOptions+++def spelled(value: float, places: int, sign: bool = False, commas: bool = False) -> str:+ """The value to its places, half to even on its exact binary digits, a zero unsigned."""+ rounded = Decimal(float(value)).quantize(+ Decimal(1).scaleb(-places), rounding=ROUND_HALF_EVEN+ )+ if rounded == 0:+ rounded = abs(rounded)+ return f"{rounded:{'+' if sign else ''}{',' if commas else ''}.{places}f}"+++def written(number: m.DecimalNumber) -> str:+ characters = []+ for part in number:+ assert isinstance(part, m.MathTex)+ characters.append(part.tex_string)+ return "".join(characters)+++# (and the values a hair either side of a rounding: the hunt's regressions)+values = st.floats(-1e7, 1e7) | st.sampled_from([-0.005, -0.0005, -0.001, 0.005, 2.5])+SCALARS = [float, np.float64, np.float32, np.longdouble]+++@given(+ value=values,+ before=values,+ places=st.integers(0, 4),+ sign=st.booleans(),+ commas=st.booleans(),+ scalar=st.sampled_from(SCALARS),+ whole=st.booleans(),+)+@example(+ value=-0.005, before=1, places=2, sign=False, commas=True, scalar=float, whole=False+)+@example(+ value=-0.005,+ before=1,+ places=2,+ sign=True,+ commas=True,+ scalar=np.float32,+ whole=False,+)+@example(+ value=-0.001, before=1, places=2, sign=True, commas=False, scalar=float, whole=False+)+@example(+ value=-1234.125,+ before=0,+ places=2,+ sign=False,+ commas=True,+ scalar=float,+ whole=False,+)+def test_a_number_spells_its_value(+ value: float,+ before: float,+ places: int,+ sign: bool,+ commas: bool,+ scalar: type[float],+ whole: bool,+) -> None:+ value = scalar(value)+ options: DecimalNumberOptions = {"include_sign": sign, "group_with_commas": commas}+ if whole:+ made = m.Integer(value, **options)+ places = 0+ else:+ made = m.DecimalNumber(value, **(options | {"num_decimal_places": places}))+ assert written(made) == spelled(value, places, sign, commas)+ assert made.get_value() == (round(value) if whole else value)+ made.set_value(before)+ made.set_value(value) # (set to it from another)+ assert written(made) == spelled(value, places, sign, commas)+++@given(+ real=values,+ imaginary=values,+ places=st.integers(0, 3),+ sign=st.booleans(),+ commas=st.booleans(),+ scalar=st.sampled_from([complex, np.complex64, np.complex128, np.clongdouble]),+)+@example(real=-0.0, imaginary=2, places=2, sign=False, commas=True, scalar=complex)+@example(+ real=-0.001, imaginary=-0.001, places=2, sign=False, commas=True, scalar=complex+)+@example(+ real=-0.005, imaginary=-0.005, places=2, sign=True, commas=True, scalar=complex+)+def test_a_complex_number_spells_each_part(+ real: float,+ imaginary: float,+ places: int,+ sign: bool,+ commas: bool,+ scalar: Callable[[complex], complex],+) -> None:+ value = scalar(complex(real, imaginary))+ number = m.DecimalNumber(+ value, # ty: ignore[invalid-argument-type] # (typed float, documented complex too)+ num_decimal_places=places,+ include_sign=sign,+ group_with_commas=commas,+ )+ parts = spelled(value.real, places, sign, commas) + spelled(+ value.imag, places, True, commas+ )+ assert written(number) == parts + "i"+++LAYOUTS: dict[str, DecimalNumberOptions] = {+ "plain": {},+ "with a unit": {"unit": "m"},+ "with a superscript unit": {"unit": "^2"},+ "of text": {"mob_class": m.Text},+ "spaced": {"digit_buff_per_font_unit": 0.015},+ "with a spaced unit": {"unit": "m", "unit_buff_per_font_unit": 0.025},+ "with an ellipsis": {"show_ellipsis": True},+ "on a background": {"include_background_rectangle": True},+}+PLAIN: DecimalNumberOptions = {+ "unit": None,+ "mob_class": m.MathTex,+ "digit_buff_per_font_unit": 0.001,+ "unit_buff_per_font_unit": 0,+ "show_ellipsis": False,+ "include_background_rectangle": False,+}+++@given(+ before=st.sampled_from(sorted(LAYOUTS)),+ after=st.sampled_from(sorted(LAYOUTS)),+ first=st.sampled_from([7.125, -3, 82.5]),+ value=st.sampled_from([7.125, -3, 1234.5]),+ scale=st.floats(0.5, 2),+ shift=st.sampled_from([m.ORIGIN, m.UP, 2 * m.LEFT + m.DOWN]),+ edge=st.sampled_from([m.LEFT, m.RIGHT, m.DOWN]),+)+def test_a_number_set_to_a_value_is_the_one_made_with_it_where_it_was(+ before: str,+ after: str,+ first: float,+ value: float,+ scale: float,+ shift: np.ndarray,+ edge: np.ndarray,+) -> None:+ look: DecimalNumberOptions = {"edge_to_fix": edge, "color": m.RED}+ number = m.DecimalNumber(first, **(LAYOUTS[before] | look))+ number.scale(scale).shift(shift).set_value(first) # (set, and left as it was)+ for name, setting in (PLAIN | LAYOUTS[after]).items():+ setattr(number, name, setting)+ fixed, size = number.get_critical_point(edge), number.font_size+ number.set_value(value)+ made = m.DecimalNumber(value, **(LAYOUTS[after] | look))+ made.font_size = size+ made.move_to(fixed, edge)+ parts, wanted = number.get_family(), made.get_family()+ assert [type(part) for part in parts] == [type(part) for part in wanted]+ for part, like in zip(parts, wanted, strict=True):+ np.testing.assert_allclose(part.points, like.points, atol=1e-9)+ np.testing.assert_array_equal(part.paint.fill, like.paint.fill)+ np.testing.assert_array_equal(part.paint.stroke, like.paint.stroke)++[email protected]("font_size", [0, -1])+def test_numbers_require_positive_font_sizes(font_size: float) -> None:+ with pytest.raises(ValueError, match="font_size"):+ m.DecimalNumber(7, font_size=font_size)+++class _Decimal(m.DecimalNumber):+ pass+++class _Integer(m.Integer):+ pass++[email protected]("kind", [m.DecimalNumber, m.Integer, _Decimal, _Integer])+def test_a_variable_shows_its_tracker_in_the_number_class_asked_for(+ kind: type[m.DecimalNumber],+) -> None:+ variable = m.Variable(1.125, "x", var_type=kind, num_decimal_places=3)+ assert type(variable.value) is kind+ places = 0 if issubclass(kind, m.Integer) else 3 # (an integer has no places)+ assert variable.value.num_decimal_places == places+ assert written(variable.value) == spelled(1.125, places)+ variable.tracker.set_value(2.875)+ variable.update()+ assert variable.value.number == 2.875+ assert written(variable.value) == spelled(2.875, places)diff --git a/tests/unit/mobjects/test_text.py b/tests/unit/mobjects/test_text.pynew file mode 100644index 00000000..5da0e626--- /dev/null+++ b/tests/unit/mobjects/test_text.py@@ -0,0 +1,374 @@+"""Text is set by Typst as its API says.++- A bulleted list is a Typst list: each item is a part, its bullet first, left of its text;+ `buff` is the space between items, added to the pitch of their baselines.+- Lines lie on a baseline grid: `line_spacing` is the space between them in ems, so their+ baselines are (1 + line_spacing) em apart (-1: CE's default, 0.3).+- A paragraph is one text of its lines, on that grid: its rows partition its glyphs (an empty+ line an empty row), each row at its start or where `alignment` puts it.+- A MathTex is one formula: its strings joined and typeset once, so parting it (into+ arguments, or with `{{…}}`) moves no glyph; a part is the ink its string adds to the+ formula (a fragment such as `\\frac{` adds none), colored apart from the others; an empty+ string is no part.+- A Tex is one text the same way, its strings joined by nothing unless `arg_separator` says:+ `Tex("Fade", "In")` reads "FadeIn", as Manim CE sets it; strings within one formula of a text+ cannot be told apart, and the spaces that isolating leaves alone stay.+- A document Typst cannot set raises Typst's error, once, however it is parted.+- A capital is as tall in every font environment: whatever fonts, in whatever order, given or+ by default, it is set at its calibrated height.+- A typeset mobject made to a width or a height is that size, and its font size is what the+ size makes it; a text's font size is the size asked for; resized, it reads back what it was+ set to. Its rules' widths scale with it unless set; fitted before coloring, a text keeps its+ ligatures' shapes.+- A title's color is its underline's too.++Baselines are read off capitals "H", whose ink sits on the baseline.+"""++from pathlib import Path+from typing import Literal++import numpy as np+import pytest+from hypothesis import assume, given, settings+from hypothesis import strategies as st++import manimgx as m+from manimgx.drawing import typesetting as tc+++def _pitch(first: m.Mobject, second: m.Mobject) -> float:+ """How far below the first capital's baseline the second's is."""+ return first.get_bottom()[1] - second.get_bottom()[1]+++def test_a_list_item_is_a_part_with_its_bullet_first() -> None:+ items = m.BulletedList("H", "H", "H")+ assert [len(part) for part in items] == [2, 2, 2]+ for bullet, letter in items:+ assert bullet.get_right()[0] < letter.get_left()[0]+ assert letter.get_bottom()[1] < bullet.get_y() < letter.get_top()[1]++[email protected]("buff", [0.2, 0.5, 1.5])+def test_buff_is_the_space_added_between_items(buff: float) -> None:+ tight = m.BulletedList("H", "H", buff=0)+ spaced = m.BulletedList("H", "H", buff=buff)+ gap = _pitch(spaced[0][1], spaced[1][1]) - _pitch(tight[0][1], tight[1][1])+ assert gap == pytest.approx(buff, abs=1e-6)++[email protected]("line_spacing", [-1, 0.5, 1, 4])+def test_line_spacing_is_the_space_between_lines_in_ems(line_spacing: float) -> None:+ solid = m.Text("H\nH", line_spacing=0)+ spaced = m.Text("H\nH", line_spacing=line_spacing)+ gap = 0.3 if line_spacing == -1 else line_spacing+ assert _pitch(*spaced) / _pitch(*solid) == pytest.approx(1 + gap)++[email protected]("alignment", [None, "left", "center", "right"])+def test_a_paragraph_is_one_text_its_lines_aligned(+ alignment: Literal["left", "center", "right"] | None,+) -> None:+ lines = m.Paragraph("H", "HHH", alignment=alignment, line_spacing=1)+ assert [len(line) for line in lines] == [1, 3]+ assert _pitch(lines[0][0], lines[1][0]) == pytest.approx(+ _pitch(*m.Text("H\nH", line_spacing=1))+ )+ side = {"center": m.ORIGIN, "right": m.RIGHT}.get(alignment or "left", m.LEFT)+ first, second = (line.get_critical_point(side)[0] for line in lines)+ assert first == pytest.approx(second)+ # its rows partition its glyphs: an empty line an empty row, a ligature one glyph+ paragraph = m.Paragraph(+ "", "office", "", "ffi שלום", "", alignment=alignment, t2c={"f": m.RED}+ )+ assert len(paragraph) == 5+ assert all(not paragraph[i] for i in (0, 2, 4))+ glyphs = [glyph for row in paragraph for glyph in row]+ assert len({id(glyph) for glyph in glyphs}) == len(glyphs)+ assert {id(glyph) for glyph in glyphs} == {+ id(glyph) for glyph in paragraph.lines_text+ }+++def test_a_titles_color_is_its_underlines_too() -> None:+ """Title(color=c) is Title().set_color(c): the underline included."""+ given = m.Title("Title", color=m.RED)+ painted = m.Title("Title").set_color(m.RED)+ assert given.underline.get_color() == painted.underline.get_color() == m.RED+++def _leaves(mob: m.Mobject) -> list[np.ndarray]:+ return [leaf.points for part in mob for leaf in part]+++ ("strings", "counts"),+ [+ (("a", "+", "b", "=", "c"), (1, 1, 1, 1, 1)),+ (+ (r"\frac{", "a", "}{", "b", "}"),+ (0, 1, 0, 1, 1),+ ), # (the bar: the closing brace's)+ ((r"e^{i", r"\pi}"), (3, 0)), # (a group's ink: its opening string's)+ (("x", "^2"), (1, 1)),+ (("a", "_n", "+", "b", "^{n+1}"), (1, 1, 1, 1, 3)),+ ((r"\sum_{n=0}^{", "N", "}", "x^n"), (1, 1, 3, 2)),+ ((r"\quad", "x"), (0, 1)),+ (+ (+ r"\begin{aligned}",+ r"\dot{x} &= \sigma(y - x)\\",+ r"\dot{y} &= \rho x",+ r"\end{aligned}",+ ),+ (0, 9, 5, 0),+ ),+ ((r"\left[ \mu \frac{", "u", r"}{2} \right]", "+ 1"), (2, 1, 3, 2)),+ ],+)+def test_a_math_tex_is_one_formula_its_strings_draw(+ strings: tuple[str, ...], counts: tuple[int, ...]+) -> None:+ parted = m.MathTex(*strings)+ whole = m.MathTex(parted.tex_string)+ for part, string in zip(parted, strings, strict=True):+ assert isinstance(part, m.MathTexPart)+ assert part.tex_string == string+ assert tuple(len(part) for part in parted) == counts+ mine, theirs = _leaves(parted), _leaves(whole)+ assert len(mine) == len(theirs)+ for a, b in zip(mine, theirs, strict=True):+ np.testing.assert_allclose(a, b, atol=1e-9)+ for part, string in zip(parted, strings, strict=True):+ assert parted.get_part_by_tex(string, substring=False) is part+ if len(part): # (colored apart from the others)+ part.set_color(m.YELLOW)+ assert all(leaf.get_color() == m.YELLOW for leaf in part)+ others = (leaf for other in parted if other is not part for leaf in other)+ assert all(leaf.get_color() == m.WHITE for leaf in others)+ part.set_color(m.WHITE)+++def test_an_empty_string_is_no_part() -> None:+ formula = m.MathTex("", "H", "")+ assert formula.tex_strings == ["H"]+ assert formula.select("p0") is not formula[0]+ assert formula.select("p0")[0] is formula[0][0]+++def test_double_braces_set_a_part_apart() -> None:+ """A fraction's bar is the ink of the brace that closes it, as in TeX."""+ eq = m.MathTex(r"{{x^2}} + \frac{ {{b}} }{ {{a}} }")+ parts = [part for part in eq if isinstance(part, m.MathTexPart)]+ assert [part.tex_string for part in parts] == [+ "x^2",+ r"+ \frac{",+ "b",+ "}{",+ "a",+ "}",+ ]+ assert [len(part) for part in eq] == [2, 1, 1, 0, 1, 1]+++ ("strings", "counts"),+ [+ (("Fade", "In"), (4, 2)),+ (("of", "fice"), (2, 2)), # one ligature, "ffi": the first string's+ (("x", "+", "y"), (1, 1, 1)), # "+" read alone would begin an enumeration+ (("Profit ", "+ 10"), (5, 3)), # "fi" is one glyph+ (("polka ", "dot"), (5, 3)), # text, not a formula's `\dot`, whole or parted+ (("Area ", r"$\sqrt{x}$"), (4, 3)), # the radical and its bar are the root's+ ((r"\textbf{", "Bold", "} type"), (0, 4, 4)),+ ((r"\textcolor{", "red}{RED}"), (3, 0)), # (neither sets alone)+ (("{{Hello}} {{World}}",), (5, 0, 5)),+ (("First apply ", "$A$", " then ", r"$\sqrt{B}$"), (10, 1, 4, 3)),+ (("Concrete", r" $\to$ ", "Abstract graph"), (8, 1, 13)),+ ],+)+def test_a_tex_is_one_text_its_strings_draw(+ strings: tuple[str, ...], counts: tuple[int, ...]+) -> None:+ parted = m.Tex(*strings)+ whole = m.Tex(parted.tex_string)+ assert parted.tex_string == "".join(parted.tex_strings)+ assert tuple(len(part) for part in parted) == counts+ mine, theirs = _leaves(parted), _leaves(whole)+ assert len(mine) == len(theirs)+ for a, b in zip(mine, theirs, strict=True):+ np.testing.assert_array_equal(a, b)+++def test_a_separators_glyphs_are_the_string_befores() -> None:+ parted = m.Tex("a", "b", arg_separator=", ")+ assert [len(part) for part in parted] == [2, 1]+ for a, b in zip(_leaves(parted), _leaves(m.Tex("a, b")), strict=True):+ np.testing.assert_array_equal(a, b)+++def test_text_keeps_the_spaces_that_isolating_leaves_alone() -> None:+ text = m.Tex("x y", tex_to_color_map={"x": m.RED, "y": m.BLUE})+ assert text.tex_strings == ["x", " ", "y"]+ assert [part.get_color() for part in text if len(part)] == [m.RED, m.BLUE]+ formula = m.MathTex("x y", tex_to_color_map={"x": m.RED, "y": m.BLUE})+ assert formula.tex_strings == ["x", "y"]++[email protected]("strings", [("$", "x", "$"), ("$a", "+", "b$")])+def test_strings_within_one_formula_of_a_text_cannot_be_told_apart(+ strings: tuple[str, ...],+) -> None:+ with pytest.raises(ValueError, match="cannot tell these parts apart"):+ m.Tex(*strings)+++# characters that neither Typst nor LaTeX reads as markup, so a string reads alone as it does+# within a text+_PLAIN = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ,;:()"+++@settings(max_examples=max(10, settings().max_examples // 4))+@given(st.lists(st.text(_PLAIN, max_size=6), min_size=1, max_size=4))+def test_parting_a_text_moves_none_of_its_glyphs(strings: list[str]) -> None:+ parted = m.Tex(*strings)+ mine, theirs = _leaves(parted), _leaves(m.Tex(parted.tex_string))+ assert len(mine) == len(theirs)+ for a, b in zip(mine, theirs, strict=True):+ np.testing.assert_array_equal(a, b)+ # each string is the glyphs it draws alone, unless a glyph (a ligature) spans two+ alone = [len(m.Tex(s)[0]) for s in parted.tex_strings]+ assume(sum(alone) == len(theirs))+ assert [len(part) for part in parted] == alone++[email protected]("kind", [m.Tex, m.MathTex])[email protected]("strings", [("H",), ("H", "I")])+def test_a_document_typst_cannot_set_raises_its_error_once(+ kind: type[m.MathTex], strings: tuple[str, ...]+) -> None:+ with pytest.raises(tc.TypstError) as raised:+ kind(*strings, typst_preamble="#missing_preflight_function()\n")+ assert str(raised.value).count("unknown variable: missing_preflight_function") == 1+++def test_a_capital_is_as_tall_in_every_font_environment(+ two_fonts: tuple[str, str],+) -> None:+ first, second = two_fonts+ capitals: list[m.Text] = []+ for paths in ([first, second], [second, first], [first], [second]):+ as_strings: list[str | Path] = list(paths)+ as_paths: list[str | Path] = [Path(path) for path in paths]+ for fonts in (as_strings, as_paths):+ capitals.append(m.Text("H", font="Noto Sans", font_paths=fonts))+ try:+ for default in (first, second):+ m.Typst.set_default(font_paths=[default])+ capitals.append(m.Text("H", font="Noto Sans")) # (by default)+ capitals.append(m.Text("HH", font="Noto Sans")) # (another text)+ capitals.append(m.Text("H", font="Noto Sans", font_paths=None))+ capitals.append(m.Text("H", font="Noto Sans", font_paths=[]))+ finally:+ m.Typst.set_default()+ assert [capital.height for capital in capitals] == pytest.approx(+ [0.44895] * len(capitals)+ )+ assert [capital.font_size for capital in capitals] == pytest.approx(+ [48] * len(capitals)+ )+ # (the fonts differ, by the widths calibration leaves: the law has something to see)+ one, other = (m.Text("HH", font="Noto Sans", font_paths=[p]) for p in two_fonts)+ assert one.width != pytest.approx(other.width)+++KINDS = [m.Typst, m.MathTex, m.Text, m.BulletedList]+++@settings(max_examples=40)+@given(+ kind=st.sampled_from(KINDS),+ size=st.floats(12, 96),+ should_center=st.booleans(),+ width=st.none() | st.floats(0.5, 5),+ height=st.none() | st.floats(0.3, 3),+)+def test_a_typeset_mobject_made_to_a_size_is_that_size(+ kind: type[m.Typst],+ size: float,+ should_center: bool,+ width: float | None,+ height: float | None,+) -> None:+ reference = kind("Hi", font_size=48)+ made = kind("Hi", font_size=size) # (a text's font size: the size asked for)+ assert made.font_size == pytest.approx(size)+ assert made.height == pytest.approx(reference.height * size / 48)+ assume(width is not None or height is not None)+ text = kind(+ "Hi", font_size=size, should_center=should_center, width=width, height=height+ )+ if width is not None: # (a width, given, wins)+ assert text.width == pytest.approx(width)+ else:+ assert text.height == pytest.approx(height)+ assert text.font_size == pytest.approx(48 * text.height / reference.height)+ previous = text.font_size+ text.scale(1.7)+ assert text.font_size == pytest.approx(1.7 * previous)+ text.font_size = 36+ assert text.font_size == pytest.approx(36)+ text.width = 2.2+ assert text.width == pytest.approx(2.2)+ assert text.font_size == pytest.approx(48 * text.height / reference.height)+ text.height = 0.8+ assert text.height == pytest.approx(0.8)+ assert text.font_size == pytest.approx(48 * 0.8 / reference.height)++[email protected]("fixed_stroke", [None, 3])[email protected](("width", "height"), [(2, None), (None, 1.5), (2, 1.5)])+def test_fitted_typeset_rules_scale_unless_stroke_width_is_explicit(+ fixed_stroke: float | None, width: float | None, height: float | None+) -> None:+ reference = m.Typst("$ frac(a,b) $", stroke_width=fixed_stroke)+ text = m.Typst(+ "$ frac(a,b) $", stroke_width=fixed_stroke, width=width, height=height+ )+ originals = [+ part+ for part in reference.family_members_with_points()+ if part.get_stroke_width() > 0+ ]+ rules = [+ part+ for part in text.family_members_with_points()+ if part.get_stroke_width() > 0+ ]+ assert len(originals) == len(rules) > 0+ scale = text.height / reference.height if fixed_stroke is None else 1+ for before, after in zip(originals, rules, strict=True):+ assert after.get_stroke_width() == pytest.approx(+ before.get_stroke_width() * scale+ )+ widths = [part.get_stroke_width() for part in rules]+ text.font_size = text.font_size * 1.3+ for part, width in zip(rules, widths, strict=True):+ assert part.get_stroke_width() == pytest.approx(+ width * (1.3 if fixed_stroke is None else 1)+ )+++def test_fitting_text_before_coloring_ligatures_preserves_their_geometry() -> None:+ expected = m.Text("office", t2c={"f": m.RED}).scale_to_fit_width(2)+ actual = m.Text("office", t2c={"f": m.RED}, width=2)+ before, after = (+ expected.family_members_with_points(),+ actual.family_members_with_points(),+ )+ assert len(before) == len(after)+ for original, fitted in zip(before, after, strict=True):+ np.testing.assert_array_equal(fitted.points, original.points)+ assert fitted.get_color() == original.get_color()