Skip to content

armgit / manim

Public Imported from GitHub
0

A community-maintained Python framework for creating mathematical animations.

Rename `TypstMath` to `MathTypst` to match existing `Tex` / `MathTex` coupling (#4925)

Benjamin Hackl70a298c09457
diff --git a/agents/typst_selector.md b/agents/typst_selector.md
deleted file mode 100644
index 5f3d37396..000000000
--- a/agents/typst_selector.md
+++ /dev/null
@@ -1,382 +0,0 @@
-# Design: Sub-Expression Selection for `Typst` / `TypstMath`
-
-## Problem Statement
-
-Users need to interact with individual parts of a Typst-rendered expression:
-color a variable, animate the numerator of a fraction, morph one sub-expression
-into another, etc. The `MathTex` class solves this with:
-
-1. **`{{ ... }}` double-brace notation** — splits the TeX string into named
- submobject groups at compile time.
-2. **`substrings_to_isolate` / `get_part_by_tex`** — identifies submobjects
- whose TeX source matches a given string.
-
-Both mechanisms ultimately rely on injecting `\special{dvisvgm:raw <g id='...'>}`
-markers into the LaTeX source so that the resulting SVG contains `<g>` elements
-with known `id` attributes, which SVGMobject's parser maps to `VGroup`
-sub-trees via `id_to_vgroup_dict`.
-
-We need an analogous mechanism for Typst.
-
-## Key Discovery: `data-typst-label` in SVG Output
-
-Typst's SVG renderer (`typst-svg` crate) already emits a `data-typst-label`
-attribute on `<g>` elements whenever a `GroupItem` (hard frame) carries a
-label. The relevant code path:
-
-```rust
-// typst-svg/src/lib.rs — render_group()
-if let Some(label) = group.label {
- svg.init().attr("data-typst-label", label.resolve());
-}
-```
-
-A **hard frame** is created by the `box` element (and `block`, etc.). Crucially,
-`box` can be used inline inside math mode, and labels can be attached to it.
-
-### Proof of Concept
-
-The following Typst helper wraps content in a labeled `box`:
-
-```typst
-#let grp(lbl, body) = [#box(body) #label(lbl)]
-```
-
-When used in math:
-
-```typst
-$ #grp("numerator", $a + b$) / #grp("denom", $c - d$) = #grp("result", $x$) $
-```
-
-The compiled SVG contains:
-
-```xml
-<g class="typst-group" ... data-typst-label="numerator">
- <!-- glyphs for a + b -->
-</g>
-<g class="typst-group" ... data-typst-label="denom">
- <!-- glyphs for c - d -->
-</g>
-<g class="typst-group" ... data-typst-label="result">
- <!-- glyph for x -->
-</g>
-```
-
-**Nesting works.** A `grp` wrapping a fraction that itself contains `grp`-ed
-sub-parts produces nested `data-typst-label` groups:
-
-```typst
-$ #grp("whole-frac", $frac(#grp("numerator", $a + b$), #grp("denom", $c - d$))$) $
-```
-
-SVG output:
-
-```xml
-<g ... data-typst-label="whole-frac">
- <g ... data-typst-label="numerator"> ... </g>
- <g ... data-typst-label="denom"> ... </g>
- <path class="typst-shape" ... /> <!-- fraction bar -->
-</g>
-```
-
-### SVG Parser Compatibility
-
-Manim uses `svgelements` to parse SVGs. The library preserves
-`data-typst-label` in the `values` dictionary of `Group` objects, and it
-propagates to child elements. Manim's `SVGMobject.get_mobjects_from()` already
-iterates over groups and builds `id_to_vgroup_dict` keyed by the `id` attribute.
-Extending this to also key by `data-typst-label` is straightforward.
-
-## Proposed Interface
-
-### 1. Explicit Groups via `{{ ... }}` Notation (Compile-Time)
-
-Mirror the `MathTex` double-brace convention. Users write:
-
-```python
-eq = TypstMath("{{ a + b }} / {{ c - d }} = {{ x }}")
-```
-
-The pre-processor splits on `{{ ... }}` (reusing the same whitespace-guard
-rules as `MathTex._split_double_braces`) and wraps each group in a labeled
-`box` call:
-
-```typst
-$ #box[$a + b$] <_grp-0> / #box[$c - d$] <_grp-1> = #box[$x$] <_grp-2> $
-```
-
-Each group gets an auto-generated label (`_grp-0`, `_grp-1`, ...).
-The `data-typst-label` attributes then appear in the SVG, and
-`SVGMobject.get_mobjects_from()` can map them to `VGroup` entries in
-`label_to_vgroup_dict` (or reuse `id_to_vgroup_dict`).
-
-These groups become sub-mobjects of the `TypstMath` instance, accessible by
-index:
-
-```python
-eq[0] # VGroup for "a + b"
-eq[1] # VGroup for "c - d"
-eq[2] # VGroup for "x"
-```
-
-(Non-group content between groups — like `/` and `=` — also becomes
-its own submobject, mirroring `MathTex` behavior.)
-
-**For `Typst` (text mode):** the same `{{ ... }}` notation applies, but the
-wrapper is `#box[...]` without math delimiters.
-
-### 2. Named Groups via Labels
-
-Users can also assign explicit label names for retrieval by name:
-
-```python
-eq = Typst(
- r"$ #box[$a + b$] <numerator> / #box[$c - d$] <denom> $"
-)
-eq.select("numerator").set_color(RED)
-eq.select("denom").set_color(BLUE)
-```
-
-Alternatively, an even more ergonomic approach that hides the `box` boilerplate
-and uses the `{{ ... : label }}` notation:
-
-```python
-eq = TypstMath("{{ a + b : numerator }} / {{ c - d : denom }}")
-eq.select("numerator").set_color(RED)
-```
-
-Here the pre-processor recognizes `{{ content : label }}` and emits
-`#box[$content$] <label>` in the Typst source.
-
-### 3. The `.select()` Method
-
-```python
-def select(self, key: str | int) -> VGroup:
- """Select a labeled sub-expression.
-
- Parameters
- ----------
- key
- Either a label name (string) matching a ``data-typst-label``
- in the SVG, or an integer index into the auto-numbered
- ``{{ ... }}`` groups.
-
- Returns
- -------
- VGroup
- The sub-mobjects corresponding to the selected group.
-
- Raises
- ------
- KeyError
- If no group with the given label/index exists.
- """
-```
-
-This returns a `VGroup` containing exactly the submobjects (paths) that
-were rendered inside the corresponding `<g data-typst-label="...">` in the SVG.
-
-## Implementation Plan
-
-### Step 1: Extend `SVGMobject.get_mobjects_from()` to Track Labels
-
-In `manim/mobject/svg/svg_mobject.py`, the group-walking loop already checks
-for `id` attributes. Add a parallel check for `data-typst-label`:
-
-```python
-try:
- group_name = str(element.values["id"])
-except Exception:
- # Fall back to data-typst-label if available
- label = element.values.get("data-typst-label")
- if label:
- group_name = f"typst-label:{label}"
- else:
- group_name = f"numbered_group_{group_id_number}"
- group_id_number += 1
-```
-
-This automatically populates `id_to_vgroup_dict` with label-keyed entries.
-
-### Step 2: Pre-Processing `{{ ... }}` in Typst Source
-
-Add a `_split_and_label_groups()` method that:
-
-1. Scans the input for `{{ ... }}` or `{{ ... : label }}` patterns
- (using the same whitespace-guard rules as `MathTex._split_double_braces`).
-2. Replaces each group with `#box[$content$] <label>` (math mode) or
- `#box[content] <label>` (text mode).
-3. Records the mapping from label → original source string for later lookup.
-
-### Step 3: `Typst.select()` / Index Access
-
-- Store the ordered list of group labels and their source strings.
-- `select(label_or_index)` looks up the corresponding `VGroup` from
- `id_to_vgroup_dict` (using the `typst-label:...` key).
-- `__getitem__(int)` returns the *n*-th group's `VGroup`.
-
-### Step 4: Compatibility with `TransformMatchingTex` (future)
-
-`TransformMatchingTex` (and its successor `TransformMatchingShapes`) works by
-matching submobjects between two `MathTex` instances by their TeX string keys.
-The same approach extends to `Typst` if each `{{ ... }}` group carries its
-original source string as metadata. A `TransformMatchingTypst` animation could
-match groups by label name or by source string equality.
-
-## Open Design Questions
-
-### Q1: Context-Aware Wrapping — Math vs. Text Mode
-
-The `box` + `label` mechanism works identically in math and text mode, but the
-**wrapping** of group content must match the surrounding context:
-
-- **In text mode:** `{{ Hello : greeting }}` → `#box[Hello] <greeting>`
-- **In math mode:** `{{ y^2 : second }}` → `#box[$y^2$] <second>`
-
-Getting this wrong is not a silent error — it produces visually broken output.
-Wrapping math content with `#box[y^2]` (no `$...$`) renders `y^2` as literal
-text in the body font instead of as a math superscript.
-
-This is a real problem for `Typst()`, where a single source string can mix text
-and math freely:
-
-```python
-Typst("hello world, here is a formula: $x^2 + {{ y^2 : second }} = z^2$")
-```
-
-Here `{{ y^2 : second }}` is inside a `$ ... $` block, so it needs the
-math-mode wrapper, but the pre-processor has no way to know this unless it
-tracks `$` delimiters.
-
-### The `#` prefix problem and math calls
-
-A natural idea is to translate `{{ content }}` into a Typst function call like
-`grp("lbl", content)`. However, this has a subtle but critical context
-sensitivity: Typst has two different call conventions depending on context:
-
-- **Math call** (no `#` prefix): `$ grp("lbl", a^2 + b) $` — arguments are
- parsed **in math mode**. The content `a^2 + b` is math. ✓
-- **Code call** (`#` prefix): `$ #grp("lbl", a^2 + b) $` — arguments are
- parsed **in code mode**. `a^2` is a syntax error in code! ✗
-
-So in math mode, the function MUST be called without `#` for args to stay in
-math mode. In text/markup mode, the function MUST be called WITH `#` (that's
-how you invoke code from markup), and content arguments need `[...]` wrapping:
-
-```typst
-// Text context: #grp("lbl", [Hello world])
-// Math context: grp("lbl", a^2 + b)
-```
-
-The function definition is the same either way:
-```typst
-#let grp(lbl, body) = [#box(body) #label(lbl)]
-```
-
-This means the function call approach has **exactly the same context problem**
-as the raw `#box` approach: the pre-processor must know whether it's in math or
-text to emit the right calling convention.
-
-### Further complication: string literals and content blocks
-
-Even inside `TypstMath` (where everything is math), the scanner must avoid
-`{{ }}` matches inside string literals or content blocks:
-
-```python
-TypstMath('x^2 + y^2 =_("Hello {{ world }}") z^2')
-```
-
-Here `{{ world }}` is inside a `"..."` string literal — it should NOT be
-processed. Similarly, content blocks `[...]` inside math switch back to text
-mode.
-
-### Options
-
-**A. `TypstMath`: math calls with simple string-aware scanning.**
-For `TypstMath`, the entire body is math, so `{{ content }}` always becomes
-`grp("_grp-N", content)` (no `#`, no `$...$`). The scanner just needs to
-skip `"..."` string literals and `[...]` content blocks — no `$` tracking
-needed. This is clean and robust.
-
-**B. `Typst`: context-aware scanning (full parser).**
-For the general `Typst` class, the scanner must additionally track `$...$`
-math blocks (toggling a mode flag on unescaped `$`) to choose between
-`grp(...)` (in math) and `#grp("lbl", [...])` (in text). It must also handle
-string literals and content blocks inside math that switch context back. This
-is doable but non-trivial — essentially a mini Typst lexer.
-
-**C. `Typst`: no `{{ }}`, manual groups only.**
-For the general `Typst` class, don't support `{{ }}` at all. Users write
-`grp(...)` / `#grp(...)` themselves (with the helper injected into the
-preamble). `{{ }}` is only available on `TypstMath`. This is simpler and
-avoids the parsing complexity, at the cost of ergonomics for mixed-mode
-documents.
-
-**Recommendation:** Start with A (TypstMath only) and C (manual for Typst).
-Upgrade to B later if demand warrants it — the function call infrastructure
-is already in place, it's only the scanner that needs upgrading.
-
-### Q2: What about "unlabeled" content between groups?
-
-Like `MathTex`, the pieces of content *between* `{{ ... }}` groups should also
-become their own submobjects (auto-labeled with sequential indices). For
-example:
-
-```python
-TypstMath("{{ a }} + {{ b }} = {{ c }}")
-# group-0: "a"
-# group-1: "+" (auto-group for inter-group content)
-# group-2: "b"
-# group-3: "=" (auto-group for inter-group content)
-# group-4: "c"
-```
-
-Each segment (group or inter-group) gets wrapped in its own labeled `box`.
-
-### Q3: What happens with `box` and baseline alignment?
-
-`box` is an inline element in Typst, and when used inside math mode it
-participates in math layout. Testing confirms that fractions, superscripts, and
-other constructs render correctly when their children are `box`-wrapped.
-However, `box` creates a "hard frame" boundary which may subtly affect spacing
-in edge cases (e.g., math operator spacing around a boxed expression). This
-needs further testing; if issues arise, we could explore `block(breakable: false)`
-or invisible `rect` wrappers as alternatives.
-
-### Q4: Can we avoid the `#grp(...)` / `#box[...] <label>` verbosity?
-
-Yes — the `{{ ... }}` double-brace notation is purely syntactic sugar that gets
-pre-processed by Manim before the source reaches the Typst compiler. Users never
-need to write raw `#box` or `#label()` calls unless they want finer control.
-
-### Q5: String-based selection without explicit groups?
-
-A future enhancement could support:
-
-```python
-eq = TypstMath(r"a + b = c")
-eq.select("a") # finds submobjects corresponding to the glyph "a"
-```
-
-This is hard to do reliably because:
-- Typst SVGs embed glyphs as `<use xlink:href="#gXXX">` references; there's no
- text content in the SVG itself.
-- A single variable in Typst may span multiple glyphs (e.g., `"alpha"` → one
- glyph) or identical glyphs may appear multiple times.
-
-A possible approach: at pre-processing time, wrap every "token" in the Typst
-math source in its own labeled `box`. This would require a Typst math tokenizer
-and is better suited for a v2 implementation.
-
-## Summary: What Typst Gives Us
-
-| Mechanism | How it works | SVG output |
-|---|---|---|
-| `#box(body) <label>` | Creates a hard-frame `GroupItem` with a `Label` | `<g data-typst-label="label">...</g>` |
-| `#metadata(val) <label>` | Invisible; queryable via `typst query` CLI | No visual output (useful for CLI queries, not SVG) |
-| Show rules on labels | `#show <label>: ...` | Transforms visual output but no automatic SVG grouping |
-| `context query(<label>)` | Document introspection (positions, counters) | In-document only; not available from Python |
-
-The `box` + `label` mechanism is the **only** one that produces identifiable
-groups in the SVG output, making it the correct tool for sub-expression
-selection in Manim.
diff --git a/docs/source/guides/using_text.rst b/docs/source/guides/using_text.rst
index 933670383..cdfb78983 100644
--- a/docs/source/guides/using_text.rst
+++ b/docs/source/guides/using_text.rst
@@ -17,7 +17,7 @@ LaTeX rendering is available via :class:`~.Tex` and
information.
Typst support is available via :class:`~.Typst` and
-:class:`~.TypstMath`. It offers both general markup and mathematical
+:class:`~.MathTypst`. It offers both general markup and mathematical
typesetting through the Typst compiler without requiring a TeX
distribution. See :ref:`typst-mobjects` for more information.
@@ -304,7 +304,7 @@ Text With Typst
***************
Manim also supports rendering text and formulas with Typst via
-:class:`~.Typst` and :class:`~.TypstMath`.
+:class:`~.Typst` and :class:`~.MathTypst`.
.. important::
@@ -324,23 +324,23 @@ expressions.
text = Typst(r"*Hello* from _Typst!_", font_size=96)
self.add(text)
-For mathematical expressions, use :class:`~.TypstMath`:
+For mathematical expressions, use :class:`~.MathTypst`:
-.. manim:: HelloTypstMath
+.. manim:: HelloMathTypst
:save_last_frame:
- :ref_classes: TypstMath
+ :ref_classes: MathTypst
- class HelloTypstMath(Scene):
+ class HelloMathTypst(Scene):
def construct(self):
- equation = TypstMath(r"sum_(k=1)^n k = (n(n + 1)) / 2", font_size=72)
+ equation = MathTypst(r"sum_(k=1)^n k = (n(n + 1)) / 2", font_size=72)
self.add(equation)
Typst also supports selecting subexpressions via labels in the Typst source,
-or via Manim's ``{{ ... }}`` shorthand in :class:`~.TypstMath`:
+or via Manim's ``{{ ... }}`` shorthand in :class:`~.MathTypst`:
.. code-block:: python
- eq = TypstMath("{{ a + b : lhs }} = {{ c }}")
+ eq = MathTypst("{{ a + b : lhs }} = {{ c }}")
eq.select("lhs").set_color(BLUE)
eq.select(0).set_color(YELLOW)
diff --git a/manim/mobject/geometry/labeled.py b/manim/mobject/geometry/labeled.py
index 5fe75ae4d..d9ca2afcb 100644
--- a/manim/mobject/geometry/labeled.py
+++ b/manim/mobject/geometry/labeled.py
@@ -102,7 +102,7 @@ class Label(VGroup):
self.rendered_label = label
else:
raise TypeError(
- "Unsupported label type. Must be MathTex, Tex, Text, Typst, or TypstMath."
+ "Unsupported label type. Must be MathTex, Tex, Text, Typst, or MathTypst."
)
# Add a background box
diff --git a/manim/mobject/graphing/number_line.py b/manim/mobject/graphing/number_line.py
index 3274c71c1..43aca3073 100644
--- a/manim/mobject/graphing/number_line.py
+++ b/manim/mobject/graphing/number_line.py
@@ -25,7 +25,7 @@ from manim.mobject.geometry.line import Line
from manim.mobject.graphing.scale import LinearBase, _ScaleBase
from manim.mobject.text.numbers import DecimalNumber
from manim.mobject.text.tex_mobject import MathTex, SingleStringMathTex, Tex
-from manim.mobject.text.typst_mobject import Typst, TypstMath
+from manim.mobject.text.typst_mobject import MathTypst, Typst
from manim.mobject.types.vectorized_mobject import VGroup, VMobject
from manim.utils.bezier import interpolate
from manim.utils.config_ops import merge_dicts_recursively
@@ -613,7 +613,7 @@ class NumberLine(Line):
if isinstance(label, str):
if label_constructor is MathTex:
label = Tex(label)
- elif label_constructor is TypstMath:
+ elif label_constructor is MathTypst:
label = Typst(label)
else:
label = self._create_label_tex(label, label_constructor)
diff --git a/manim/mobject/text/typst_mobject.py b/manim/mobject/text/typst_mobject.py
index e239bdf58..b2e5aeb79 100644
--- a/manim/mobject/text/typst_mobject.py
+++ b/manim/mobject/text/typst_mobject.py
@@ -10,7 +10,7 @@
Typst mobjects compile Typst markup directly to SVG using the ``typst``
Python package and then import the result through :class:`~.SVGMobject`.
-Use :class:`~.Typst` for general Typst markup and :class:`~.TypstMath`
+Use :class:`~.Typst` for general Typst markup and :class:`~.MathTypst`
for display-style math.
Examples
@@ -32,13 +32,13 @@ Basic text and math
)
self.add(text)
-.. manim:: TypstMathReferenceExample
+.. manim:: MathTypstReferenceExample
:save_last_frame:
- :ref_classes: TypstMath
+ :ref_classes: MathTypst
- class TypstMathReferenceExample(Scene):
+ class MathTypstReferenceExample(Scene):
def construct(self):
- equation = TypstMath(
+ equation = MathTypst(
r"sum_(k=1)^n k = frac(n(n + 1), 2)",
font_size=72,
)
@@ -51,12 +51,12 @@ Typst mobjects expose label-based selection via :meth:`~.Typst.select`.
There are two common ways to create selectable groups:
- use ordinary Typst labels in :class:`~.Typst`
-- use Manim's ``{{ ... }}`` shorthand in :class:`~.TypstMath`
+- use Manim's ``{{ ... }}`` shorthand in :class:`~.MathTypst`
.. note::
The ``{{ ... }}`` shorthand is currently only supported by
- :class:`~.TypstMath`. For :class:`~.Typst`, create labels directly in the
+ :class:`~.MathTypst`. For :class:`~.Typst`, create labels directly in the
Typst source, for example with ``#box[body] <label>``.
.. manim:: TypstLabelSelectionExample
@@ -81,14 +81,14 @@ There are two common ways to create selectable groups:
text.select("picked").set_color(YELLOW)
self.add(text)
-.. manim:: TypstMathSelectionExample
+.. manim:: MathTypstSelectionExample
:save_last_frame:
- :ref_classes: TypstMath
+ :ref_classes: MathTypst
:ref_methods: Typst.select
- class TypstMathSelectionExample(Scene):
+ class MathTypstSelectionExample(Scene):
def construct(self):
- equation = TypstMath(
+ equation = MathTypst(
"{{ a^2 + b^2 : lhs }} = {{ c^2 }}",
font_size=72,
)
@@ -109,7 +109,7 @@ query either :attr:`~.Typst.baseline_frames` for all tracked leaf elements or
text = Typst("Ggf", track_baselines=True)
orig, right, up = text.baseline_frames[0]
- eq = TypstMath("{{ a^2 + b^2 : lhs }} = c^2", track_baselines=True)
+ eq = MathTypst("{{ a^2 + b^2 : lhs }} = c^2", track_baselines=True)
for part in eq.select("lhs"):
orig, right, up = eq.get_baseline_frame(part)
print(orig, right, up)
@@ -119,7 +119,7 @@ from __future__ import annotations
__all__ = [
"Typst",
- "TypstMath",
+ "MathTypst",
]
import re
@@ -539,7 +539,7 @@ class Typst(SVGMobject):
Labels are created in the Typst source either manually via the
``manimgrp`` helper or automatically through the ``{{ }}``
- double-brace notation in :class:`TypstMath`.
+ double-brace notation in :class:`MathTypst`.
Parameters
----------
@@ -564,12 +564,12 @@ class Typst(SVGMobject):
--------
.. manim:: TypstSelectExample
:save_last_frame:
- :ref_classes: TypstMath
+ :ref_classes: MathTypst
:ref_methods: Typst.select
class TypstSelectExample(Scene):
def construct(self):
- eq = TypstMath(
+ eq = MathTypst(
"{{ a + b : num }} / {{ c : den }} = {{ lambda }} {{ x }}"
)
eq.select("num").set_color(RED) # "a + b"
@@ -618,7 +618,7 @@ class Typst(SVGMobject):
return self
-class TypstMath(Typst):
+class MathTypst(Typst):
r"""Convenience wrapper: wraps the input in Typst math delimiters.
The expression is rendered as a display-level equation
@@ -645,21 +645,21 @@ class TypstMath(Typst):
--------
.. manim:: DisplayMath
:save_last_frame:
- :ref_classes: TypstMath
+ :ref_classes: MathTypst
class DisplayMath(Scene):
def construct(self):
- eq = TypstMath(r"sum_(k=0)^n k = (n(n+1)) / 2")
+ eq = MathTypst(r"sum_(k=0)^n k = (n(n+1)) / 2")
self.add(eq)
.. manim:: GroupedMath
:save_last_frame:
- :ref_classes: TypstMath
+ :ref_classes: MathTypst
:ref_methods: Typst.select
class GroupedMath(Scene):
def construct(self):
- eq = TypstMath("{{ a^2 + b^2 : lhs }} = {{ c^2 }}")
+ eq = MathTypst("{{ a^2 + b^2 : lhs }} = {{ c^2 }}")
eq.select("lhs").set_color(RED) # "a^2 + b^2"
eq.select(0).set_color(BLUE) # "c^2" (auto-numbered: "grp-0")
self.add(eq)
diff --git a/manim/typing.py b/manim/typing.py
index 41087e489..fad8793ba 100644
--- a/manim/typing.py
+++ b/manim/typing.py
@@ -946,7 +946,7 @@ ManimTextLabel: TypeAlias = "Text | MathTex | Typst"
"""Text-like label mobjects commonly used across Manim.
This includes :class:`~.Text`, :class:`~.MathTex`, and :class:`~.Typst`.
-Subtype-specific variants like :class:`~.Tex` and :class:`~.TypstMath` are
+Subtype-specific variants like :class:`~.Tex` and :class:`~.MathTypst` are
covered implicitly through inheritance.
"""
diff --git a/tests/module/mobject/text/test_typst_mobject.py b/tests/module/mobject/text/test_typst_mobject.py
index 998d3d61c..1ac379df7 100644
--- a/tests/module/mobject/text/test_typst_mobject.py
+++ b/tests/module/mobject/text/test_typst_mobject.py
@@ -7,10 +7,10 @@ from manim import (
RIGHT,
Label,
MathTex,
+ MathTypst,
NumberLine,
Tex,
Typst,
- TypstMath,
Vector,
VectorScene,
)
@@ -24,9 +24,9 @@ def test_Typst(config):
assert len(m.submobjects) > 0
-def test_TypstMath(config):
- """TypstMath wraps the expression in math delimiters."""
- m = TypstMath(r"alpha + beta")
+def test_MathTypst(config):
+ """MathTypst wraps the expression in math delimiters."""
+ m = MathTypst(r"alpha + beta")
assert m.typst_code == "$ alpha + beta $"
assert m.height > 0
@@ -54,7 +54,7 @@ def test_typst_font_size_property_setter(config):
def test_typst_font_size_scaling_also_scales_svg_strokes(config):
"""Typst-authored stroke widths scale together with font_size."""
- m = TypstMath("frac(a,b)", font_size=48, use_svg_cache=False)
+ m = MathTypst("frac(a,b)", font_size=48, use_svg_cache=False)
original_stroke_width = max(submobject.stroke_width for submobject in m.submobjects)
m.font_size = 96
@@ -92,8 +92,8 @@ def test_typst_repr(config):
m = Typst("hello")
assert repr(m) == "Typst('hello')"
- m2 = TypstMath("x")
- assert repr(m2) == "TypstMath('$ x $')"
+ m2 = MathTypst("x")
+ assert repr(m2) == "MathTypst('$ x $')"
def test_typst_text_rendering(config):
@@ -138,12 +138,12 @@ def test_typst_text_font_size_matches_tex_closely(config):
assert np.isclose(typst.width, tex.width, rtol=0.02)
-def test_typstmath_font_size_matches_mathtex_closely(config):
+def test_mathtypst_font_size_matches_mathtex_closely(config):
"""Typst math is calibrated close to MathTex for the same font_size."""
mathtex = MathTex(r"\frac{a}{b}", font_size=48)
- typstmath = TypstMath("frac(a,b)", font_size=48, use_svg_cache=False)
- assert np.isclose(typstmath.height, mathtex.height, rtol=0.02)
- assert np.isclose(typstmath.width, mathtex.width, rtol=0.02)
+ mathtypst = MathTypst("frac(a,b)", font_size=48, use_svg_cache=False)
+ assert np.isclose(mathtypst.height, mathtex.height, rtol=0.02)
+ assert np.isclose(mathtypst.width, mathtex.width, rtol=0.02)
# -- data-typst-label → id mapping tests ------------------------------------
@@ -257,56 +257,56 @@ def test_typst_select_keyerror_lists_labels_starting_with_g(config):
# -- {{ }} double-brace preprocessor tests ----------------------------------
-def test_typstmath_double_brace_auto_numbered(config):
+def test_mathtypst_double_brace_auto_numbered(config):
"""{{ }} groups are auto-numbered and selectable by index."""
- eq = TypstMath("{{ a + b }} / {{ c - d }} = {{ x }}", use_svg_cache=False)
+ eq = MathTypst("{{ a + b }} / {{ c - d }} = {{ x }}", use_svg_cache=False)
assert eq._group_labels == ["_grp-0", "_grp-1", "_grp-2"]
assert len(eq.select(0)) == 3 # a, +, b
assert len(eq.select(1)) == 3 # c, -, d
assert len(eq.select(2)) == 1 # x
-def test_typstmath_double_brace_named(config):
+def test_mathtypst_double_brace_named(config):
"""{{ content : label }} assigns an explicit label."""
- eq = TypstMath("{{ a + b : numerator }} / {{ c - d : denom }}", use_svg_cache=False)
+ eq = MathTypst("{{ a + b : numerator }} / {{ c - d : denom }}", use_svg_cache=False)
assert "numerator" in eq._group_labels
assert "denom" in eq._group_labels
assert len(eq.select("numerator")) == 3
assert len(eq.select("denom")) == 3
-def test_typstmath_double_brace_mixed_named_auto(config):
+def test_mathtypst_double_brace_mixed_named_auto(config):
"""Named and auto-numbered groups can coexist."""
- eq = TypstMath("{{ a : lhs }} = {{ b }}", use_svg_cache=False)
+ eq = MathTypst("{{ a : lhs }} = {{ b }}", use_svg_cache=False)
assert eq._group_labels == ["lhs", "_grp-0"]
assert len(eq.select("lhs")) == 1
assert len(eq.select(0)) == 1
-def test_typstmath_no_braces_no_preamble(config):
+def test_mathtypst_no_braces_no_preamble(config):
"""Without {{ }}, the manimgrp preamble is not injected."""
- eq = TypstMath("a + b", use_svg_cache=False)
+ eq = MathTypst("a + b", use_svg_cache=False)
assert eq._group_labels == []
assert "manimgrp" not in eq.typst_preamble
-def test_typstmath_select_index_error(config):
+def test_mathtypst_select_index_error(config):
"""select(int) raises IndexError for out-of-range index."""
- eq = TypstMath("{{ a }}", use_svg_cache=False)
+ eq = MathTypst("{{ a }}", use_svg_cache=False)
with pytest.raises(IndexError, match="out of range"):
eq.select(1)
-def test_typstmath_preprocessor_skips_strings():
+def test_mathtypst_preprocessor_skips_strings():
"""{{ }} inside string literals are not processed."""
- processed, labels = TypstMath._preprocess_groups('x =_("{{ not a group }}") z')
+ processed, labels = MathTypst._preprocess_groups('x =_("{{ not a group }}") z')
assert labels == []
assert "manimgrp" not in processed
-def test_typstmath_preprocessor_skips_content_blocks():
+def test_mathtypst_preprocessor_skips_content_blocks():
"""{{ }} inside [...] content blocks are not processed."""
- processed, labels = TypstMath._preprocess_groups("[text {{ here }}] {{ real }}")
+ processed, labels = MathTypst._preprocess_groups("[text {{ here }}] {{ real }}")
assert labels == ["_grp-0"]
assert processed.count("manimgrp") == 1
@@ -321,13 +321,13 @@ def test_label_accepts_typst(config):
assert label.rendered_label is rendered
-def test_numberline_add_labels_with_typstmath_constructor_uses_typst(config):
- """String labels use Typst text mode when label_constructor is TypstMath."""
+def test_numberline_add_labels_with_mathtypst_constructor_uses_typst(config):
+ """String labels use Typst text mode when label_constructor is MathTypst."""
number_line = NumberLine(x_range=[-1, 1])
- number_line.add_labels({0: "origin"}, label_constructor=TypstMath)
+ number_line.add_labels({0: "origin"}, label_constructor=MathTypst)
assert len(number_line.labels) == 1
assert isinstance(number_line.labels[0], Typst)
- assert not isinstance(number_line.labels[0], TypstMath)
+ assert not isinstance(number_line.labels[0], MathTypst)
def test_vector_scene_get_vector_label_accepts_typst(config):