Coverage for src/manimgx/mobjects/text.py: 97%
725 statements
« prev ^ index » next coverage.py v7.16.1, created at 2026-10-26 05:52 +0000
« prev ^ index » next coverage.py v7.16.1, created at 2026-10-26 05:52 +0000
1"""Typeset mobjects from Typst, literal Unicode, and LaTeX source.
3Typst documents as mobjects: every glyph and shape of the layout becomes a part (a glyph its
4outline, shared per font and glyph, placed where Typst put it). After CE 0.21 (MIT).
6CE's Pango text classes, typeset by Typst: one submobject per non-space glyph, in reading
7order, sized so a font-size-48 capital has CE's height.
9The text is set literally, as Typst strings. Slant and weight (`t2s`, `t2w`) change the layout,
10so they are set as runs; color does not: every glyph knows the characters it draws,
11so `gradient`, `t2g` and `t2c` color it by character, and a glyph whose characters differ in
12color is cut at its carets. A key is a slice "[a:b]" or each occurrence of a string; a key that
13occurs nowhere picks nothing.
15CE's LaTeX classes, typeset by Typst: LaTeX converted by mitex, so `MathTex("a", "=", "b")[i]`
16is part i. A MathTex's strings are one formula, a Tex's one text: joined, and typeset once.
18"""
20from __future__ import annotations
22from warnings import deprecated
24__all__ = [
25 "BulletedList",
26 "MathTex",
27 "MathTexPart",
28 "MathTypst",
29 "Paragraph",
30 "SingleStringMathTex",
31 "Tex",
32 "Text",
33 "Title",
34 "Typst",
35]
37import bisect
38import re
39import unicodedata
40from collections.abc import Callable, Collection, Iterable, Mapping, Sequence
41from pathlib import Path
42from typing import Literal, Self, Unpack
44import numpy as np
46from manimgx import _engine
47from manimgx.caches import Memo
48from manimgx.constants import (
49 DEFAULT_FONT_SIZE,
50 MED_LARGE_BUFF,
51 MED_SMALL_BUFF,
52 NORMAL,
53 SCALE_FACTOR_PER_FONT_POINT,
54 SMALL_BUFF,
55)
56from manimgx.drawing.geometry import (
57 EMPTY,
58 Blend,
59 Shape,
60 _pathops,
61 _to_path,
62 extent,
63 interpolate,
64 placed_box,
65)
66from manimgx.drawing.paint import (
67 WHITE,
68 Colors,
69 Look,
70 ManimColor,
71 ParsableManimColor,
72 Repaint,
73 _Look,
74 color_gradient,
75)
76from manimgx.drawing.typesetting import (
77 ADVANCE,
78 DRAWN,
79 FILL,
80 GLYPH,
81 KEY,
82 KIND,
83 NODE,
84 PLACEMENT,
85 STROKE,
86 WIDTH,
87 Layout,
88 TypstError,
89 typeset,
90 typst_string,
91)
92from manimgx.mobject import Mobject, Pivot, VGroup, VMobject, _append_path, prototype
93from manimgx.typing import Vector3DLike
95_HEX: Memo[tuple[float, ...], str] = Memo(1 << 12)
98def _ink(rgba: np.ndarray, color: str) -> str:
99 """A paint Typst gave: its default ink (black) is `color`."""
100 return color if not rgba[:3].any() else _hex(rgba)
103def _hex(rgba: np.ndarray) -> str:
104 key = tuple(rgba[:3])
105 color = _HEX.get(key)
106 if color is None:
107 r, g, b = (round(c * 255) for c in key)
108 color = _HEX.keep(key, f"#{r:02x}{g:02x}{b:02x}")
109 return color
112class _TypstOptions(_Look, Repaint, total=False):
113 """TypstOptions's keys, open, for the keywords that add to them."""
115 font_size: float
116 """The size of the text: an em is `font_size / 96` scene units, 0.5 at the default,
117 48 (a [Text][manimgx.Text] is sized by its capitals instead: 0.449 units tall at
118 48)."""
119 typst_preamble: str
120 """Typst code set before the document: `#set` and `#show` rules, `#let`
121 definitions, imports (default "")."""
122 font_paths: list[str | Path] | None
123 """Directories of font files (.ttf, .otf, .ttc, .otc), searched with their
124 subdirectories before the fonts manimgx ships; a path to a file adds nothing
125 (default None)."""
126 should_center: bool
127 """Whether the mobject is centered on the origin (default True)."""
128 height: float | None
129 """The height to scale the mobject to, in scene units, instead of sizing it by
130 `font_size` (default None)."""
131 width: float | None
132 """The width to scale the mobject to, in scene units, instead of sizing it by
133 `font_size`; with a `height` too, the width is set last (default None)."""
134 package_path: str | Path | None
135 """The directory Typst packages are imported from, which holds them as
136 `namespace/name/version` directories: `#import "@preview/name:1.0.0"` reads
137 `preview/name/1.0.0` (default None: none but mitex, which manimgx's engine holds).
138 Nothing is downloaded."""
141class TypstOptions(_TypstOptions, total=False, closed=True):
142 """[Typst][manimgx.Typst]'s keywords, for the classes that pass them on: text and
143 LaTeX.
145 Beyond these, they take the [look keywords][manimgx.drawing.paint.Look], and the
146 [paint keywords][manimgx.drawing.paint.Repaint], which paint over the colors the
147 typesetting gives the parts.
148 """
151class TypstGlyph(VMobject):
152 """One glyph as Typst set it, a part of a typeset mobject: its outline, placed, and
153 which characters of the source it draws.
155 `node` is where the glyph's source node starts in the Typst code (-1 if it isn't
156 from the code), `drawn` the bytes of that node's text it draws, `key` its outline,
157 `x_advance` its width in font units.
158 """
160 # Immutable float64 bytes, shared by copies; absent for ordinary glyphs.
161 _carets: bytes = b""
163 node: int
164 """Where the source node the glyph came from starts in the Typst code, in bytes. A
165 glyph a package's code drew (a radical a package's function sets) came from the
166 innermost element of the code around it (its equation); -1 if none is."""
167 drawn: tuple[int, int]
168 """The bytes of that node's text the glyph's cluster draws, from and to: of a string
169 literal, the bytes of its value; -1, -1 if the node is an element around it."""
170 key: int
171 """The provenance key of its outline and font carets, the same in every process.
172 Assigning a key does not change the live glyph's outline or carets."""
173 x_advance: float
174 """Its advance, the width it takes in the line, in font units: a ligature's carets
175 divide it."""
178class Typst(VMobject):
179 r"""A Typst document, typeset in the engine: every glyph and shape of its layout is
180 a part, white unless styled.
182 The code is Typst markup, a document's body on a page as large as what it holds:
183 `*strong*`, `_emphasis_`, math between `$` signs, `#set` and `#show` rules, and the
184 rest of Typst. The parts are what Typst lays out, in document order, spaces
185 excluded: glyphs ([TypstGlyph][manimgx.mobjects.text.TypstGlyph]) and
186 shapes (a rule, a fraction's bar, a box). A labelled box, `#box[…] <name>`, is a
187 group: [select][manimgx.Typst.select] gives it. Packages are imported from
188 `package_path` (and mitex, `@preview/mitex:0.2.7`, from ManimGX's engine), never
189 downloaded; code Typst can't typeset raises a
190 [TypstError][manimgx.drawing.typesetting.TypstError].
192 Text is set in Libertinus Serif and math in New Computer Modern Math, Typst's
193 defaults, unless the code sets another font. The fonts are those ManimGX ships, so a
194 document looks the same on every machine: Typst's own (these two, New Computer
195 Modern and DejaVu Sans Mono), Noto Sans, and Noto faces for the scripts those lack,
196 from Arabic, Hebrew and Devanagari to Chinese, Japanese and Korean, with symbols and
197 emoji; a character a font lacks is set in one that has it. Fonts in `font_paths`
198 come first, and a system font is read only for a family the code names that none of
199 these has. A paragraph's direction and the forms of Han characters follow the code's
200 `lang` and `dir` (`#set text(lang: "ja")`, `#set text(dir: rtl)`); a
201 [Text][manimgx.Text] sets them from its characters.
203 What Typst paints in its default ink, black, takes `color`, and the colors the code
204 sets are kept, unless paint keywords (`fill_color` and the rest) paint over every
205 part. A document is typeset once: the same code is read back from a cache on disk,
206 in any process.
208 Args:
209 typst_code: The document: Typst markup.
210 font_size: The size of the text: an em is `font_size / 96` scene units (0.5 at
211 48).
212 typst_preamble: Typst code set before the document: rules, definitions,
213 imports.
214 font_paths: Directories of font files, searched, with their subdirectories,
215 before the fonts ManimGX ships.
216 should_center: Whether the mobject is centered on the origin.
217 height: The height to scale the mobject to, in scene units; None to size it by
218 `font_size`.
219 width: The width to scale it to, in scene units, after `height`; None to size
220 it by `font_size`.
221 package_path: The directory Typst packages are imported from (as
222 `namespace/name/version` directories), besides mitex, which ManimGX's
223 engine holds; None for none but mitex.
224 font_scale: How much larger than `font_size` the text is set: the layout is
225 scaled by `font_size * font_scale`, while
226 [font_size][manimgx.Typst.font_size] reads `font_size`. A
227 [Text][manimgx.Text] sets it to its font's own scale, which makes a capital
228 as tall in every font.
229 color: The color of Typst's default ink, black; None for white.
230 fill_color: A fill color for every part; None keeps the typeset ones.
231 fill_opacity: A fill opacity for every part, from 0 to 1; None keeps the
232 typeset ones.
233 stroke_color: A stroke color for every part; None keeps the typeset ones.
234 stroke_opacity: A stroke opacity for every part, from 0 to 1; None keeps the
235 typeset ones.
236 stroke_width: A stroke width for every part, in hundredths of a scene unit;
237 None keeps the typeset ones, which scale with the mobject.
238 opacity: The opacity of every part's fill and stroke, from 0 to 1, where
239 `fill_opacity` or `stroke_opacity` doesn't give one; None keeps the
240 typeset ones.
242 Examples:
243 ```python
244 import manimgx as m
247 class TypstExample(m.Scene):
248 def construct(self) -> None:
249 document = m.Typst(
250 "*Typst* markup, _typeset_ in the engine:\n\n"
251 "$ sum_(k=1)^n k = (n(n+1))/2 $\n\n"
252 "with #text(fill: orange)[colors of its own]",
253 font_size=64,
254 )
255 self.play(m.Write(document))
256 ```
257 """
259 @prototype
260 def __init__(
261 self,
262 typst_code: str,
263 *,
264 font_size: float = DEFAULT_FONT_SIZE,
265 typst_preamble: str = "",
266 font_paths: list[str | Path] | None = None,
267 should_center: bool = True,
268 height: float | None = None,
269 width: float | None = None,
270 package_path: str | Path | None = None,
271 font_scale: float = 1.0,
272 color: Colors | None = None,
273 fill_color: Colors | None = None,
274 fill_opacity: float | Sequence[float] | None = None,
275 stroke_color: Colors | None = None,
276 stroke_opacity: float | Sequence[float] | None = None,
277 stroke_width: float | None = None,
278 opacity: float | None = None,
279 **kwargs: Unpack[Look],
280 ):
281 super().__init__(stroke_color=None, fill_color=None, **kwargs)
282 self.set_color(WHITE if color is None else color)
283 # how much larger than font_size the text is set (a font's calibration: see Text)
284 self._font_scale = font_scale
285 self.typst_code = typst_code
286 """The Typst code the mobject was typeset from."""
287 self.typst_preamble = typst_preamble
288 """The Typst code set before it."""
289 # unless a stroke width is given, a stroke keeps its share of its part's size as
290 # typeset: (part, its size and its stroke width as typeset)
291 self._strokes_scale = stroke_width is None
292 self._strokes: list[tuple[VMobject, float, float]] = []
293 # A height overrides font sizing; width is fitted afterward in either case.
294 placed = should_center and height is None
295 self.initial_height = self._build(
296 typeset(
297 typst_code,
298 typst_preamble,
299 font_paths=font_paths,
300 package_path=package_path,
301 ),
302 font_size * font_scale * SCALE_FACTOR_PER_FONT_POINT if placed else None,
303 )
304 if opacity is not None: # both, where one isn't given its own
305 fill_opacity = opacity if fill_opacity is None else fill_opacity
306 stroke_opacity = opacity if stroke_opacity is None else stroke_opacity
307 self.set_style(
308 fill_color=fill_color,
309 fill_opacity=fill_opacity,
310 stroke_color=stroke_color,
311 stroke_opacity=stroke_opacity,
312 stroke_width=stroke_width,
313 )
314 if should_center and not placed:
315 self.center()
316 if height is not None:
317 self.set(height=height)
318 elif not placed:
319 self.font_size = font_size
320 if width is not None:
321 self.set(width=width)
323 def _build(self, layout: Layout, scale: float | None) -> float:
324 """Every glyph and shape of the layout, in document order, Typst's black ink painted this
325 mobject's color, and the labelled groups. With `scale`, parts are built in place (the ink
326 centered and scaled). Returns the ink's height as typeset."""
327 rows = layout.rows
328 # each part's placement (a glyph) or points (a shape), and the ink box around them all:
329 # the one box, its curves' tight box
330 places: list[np.ndarray] = []
331 low, high = np.full(2, np.inf), np.full(2, -np.inf)
332 for row in rows:
333 if row[KIND] == GLYPH:
334 _, outline, _ = layout.glyphs[int(row[KEY])]
335 assert outline is not None
336 a, b, c, d, e, f = row[PLACEMENT]
337 place = np.array([[a, c, 0.0, e], [b, d, 0.0, f], [0.0, 0.0, 1.0, 0.0]])
338 ink = placed_box(place, outline, True)[:, :2]
339 else:
340 place = layout.shapes[int(row[KEY])]
341 ink = extent(place, True)[:, :2]
342 places.append(place)
343 if len(ink):
344 low, high = (
345 np.minimum(low, ink.min(axis=0)),
346 np.maximum(high, ink.max(axis=0)),
347 )
348 height = float(high[1] - low[1]) if high[1] >= low[1] else 0.0
349 if scale is not None and height > 0:
350 shift = np.array([*((low + high) / 2), 0.0])
351 for k, place in enumerate(places):
352 if place.shape == (3, 4): # a glyph's placement
353 place = place * scale
354 place[:, 3] -= shift * scale
355 else: # a shape's points
356 place = (place - shift) * scale
357 places[k] = place
358 else:
359 scale = None
360 ink_color = self.color.to_hex()
361 parts: list[VMobject] = []
362 for row, place in zip(rows, places):
363 fill, stroke = row[FILL], row[STROKE]
364 if row[KIND] == GLYPH:
365 key = int(row[KEY])
366 _, outline, carets = layout.glyphs[key]
367 assert outline is not None
368 # its color is its ink: both brushes, as `color=` means
369 glyph = TypstGlyph(
370 color=_ink(fill, ink_color),
371 fill_opacity=float(fill[3]),
372 stroke_width=0,
373 )
374 glyph._geometry = Blend(((place, outline),), len(outline.array))
375 node, drawn = row[NODE], row[DRAWN]
376 glyph.node = int(node[0]) - layout.body if node[0] >= 0 else -1
377 glyph.drawn = (int(drawn[0]), int(drawn[1]))
378 glyph.key, glyph.x_advance = key, float(row[ADVANCE])
379 if carets:
380 glyph._carets = carets
381 part: VMobject = glyph
382 else:
383 part = VMobject(
384 color=_ink(fill, ink_color) if fill[0] >= 0 else ink_color,
385 fill_opacity=float(fill[3]) if fill[0] >= 0 else 0.0,
386 stroke_width=0,
387 )
388 part.points = place
389 if stroke[0] >= 0 and row[WIDTH] > 0:
390 size = max(part.width, part.height)
391 width = float(row[WIDTH])
392 part.set_stroke(
393 _ink(stroke, ink_color),
394 opacity=float(stroke[3]),
395 width=None if scale is None else width * scale * 100,
396 )
397 if self._strokes_scale and size > 0:
398 self._strokes.append((part, size / (scale or 1.0), width))
399 parts.append(part)
400 self.add(*parts)
401 self.labels: dict[str, VGroup] = {} # the parts inside each `<label>`
402 for label, members in layout.labels:
403 group = self.labels.setdefault(label, VGroup())
404 group.add(*(parts[i] for i in members))
405 return height
407 def select(self, key: str | int) -> VGroup:
408 """Find the parts of a labelled group: of every group with that label, as one.
410 A label names a box in the code, `#box[…] <name>`; a
411 [MathTypst][manimgx.MathTypst] makes a group of `{{ … }}` too, named by
412 `{{ … : name }}` or numbered in order. An unknown label raises KeyError, a
413 number out of range IndexError.
415 Args:
416 key: The label; or the number of a MathTypst's unnamed `{{ … }}` group, from
417 0.
419 Returns:
420 A new group of the parts themselves (not copies), in order.
422 Examples:
423 ```python
424 import manimgx as m
427 class TypstSelectExample(m.Scene):
428 def construct(self) -> None:
429 text = m.Typst(
430 "Label a #box[box] <noun> to #box[select] <verb> it",
431 font_size=96,
432 )
433 text.select("noun").set_color(m.YELLOW)
434 text.select("verb").set_color(m.BLUE)
435 self.add(text)
436 ```
437 """
438 label = f"_grp-{key}" if isinstance(key, int) else key
439 if label not in self.labels:
440 error = IndexError if isinstance(key, int) else KeyError
441 raise error(f"no group {key!r}; labels: {list(self.labels)}")
442 return self.labels[label]
444 @property
445 def font_size(self) -> float:
446 """The mobject's effective font size, including scaling. Explicit width or height
447 determines this size when given at construction. Set it to a positive size to
448 scale the mobject to it."""
449 return (
450 self.height
451 / self.initial_height
452 / SCALE_FACTOR_PER_FONT_POINT
453 / self._font_scale
454 )
456 @font_size.setter
457 def font_size(self, val: float) -> None:
458 if val <= 0:
459 raise ValueError("font_size must be greater than 0.")
460 if self.height > 0:
461 self.scale(val / self.font_size)
463 def scale(
464 self,
465 scale_factor: float | Vector3DLike,
466 scale_stroke: bool = False,
467 **kwargs: Unpack[Pivot],
468 ) -> Self:
469 """Scale the mobject and its whole family about a point, as
470 [Mobject.scale][manimgx.Mobject.scale] does; the strokes the typesetting drew (a
471 rule, a box's outline) keep their share of their part's size, unless the mobject
472 was made with a `stroke_width`.
474 Args:
475 scale_factor: The factor: 2 doubles the mobject's size, 0.5 halves it; or
476 its factors along x, y and z.
477 scale_stroke: Whether the other strokes' widths scale too, by the factor.
478 **kwargs: [Pivot keywords][manimgx.mobject.Pivot].
479 """
480 result = super().scale(scale_factor, scale_stroke=scale_stroke, **kwargs)
481 self._scale_strokes()
482 return result
484 def _scale_strokes(self) -> None:
485 """Each typeset stroke's width, its share of its part's size again."""
486 if not self._strokes_scale:
487 return
488 for part, typeset_size, typeset_width in self._strokes:
489 if typeset_size > 0:
490 width = typeset_width * max(part.width, part.height) / typeset_size
491 part.set_stroke(width=width * 100, family=False) # in 1/100 units
493 def init_colors(self, propagate_colors: bool = True) -> Self:
494 # Its parts are painted from the layout's ink; constructor style is not reused.
495 self.__dict__.pop("style", None)
496 return self
499_MANIMGRP = "#let manimgrp(lbl, body) = [#box(body) #label(lbl)]"
500# a string, `{{`, `}}`, a bracket, or a run of anything else: strings and content blocks hold no groups
501_TOKEN = re.compile(r'"(?:\\[\s\S]|[^"\\])*"?|\{\{|\}\}|[\[\]]|[^"\[\]{}]+|[{}]')
502_LABELLED = re.compile(r"^(.*)\s*:\s*([a-zA-Z_][a-zA-Z0-9_-]*)\s*$", re.DOTALL)
505def _groups(expression: str) -> tuple[str, list[str]]:
506 """The expression with each `{{ body }}` or `{{ body : label }}` as `manimgrp(label, body)`
507 (unlabelled groups numbered `_grp-0`, `_grp-1`…), and the labels in order. A group runs to
508 its matching `}}`; one never closed stays as written, with all that follows it."""
509 tokens = _TOKEN.findall(expression)
510 out: list[str] = []
511 labels: list[str] = []
512 i = brackets = auto = 0
513 while i < len(tokens):
514 token = tokens[i]
515 i += 1
516 if token == "[":
517 brackets += 1
518 elif token == "]" and brackets:
519 brackets -= 1
520 elif token == "{{" and not brackets:
521 depth, inner, j = 1, 0, i
522 while j < len(tokens) and depth:
523 t, j = tokens[j], j + 1
524 if t == "[":
525 inner += 1
526 elif t == "]" and inner:
527 inner -= 1
528 elif t in ("{{", "}}") and not inner:
529 depth += 1 if t == "{{" else -1
530 if depth:
531 out.append("{{" + "".join(tokens[i:]))
532 break
533 content, i = "".join(tokens[i : j - 1]), j
534 if match := _LABELLED.match(content):
535 body, label = match.group(1).strip(), match.group(2)
536 else:
537 body, label, auto = content.strip(), f"_grp-{auto}", auto + 1
538 labels.append(label)
539 out.append(f'manimgrp("{label}", {body})')
540 continue
541 out.append(token)
542 return "".join(out), labels
545class MathTypst(Typst):
546 """A formula in Typst's math syntax, typeset in display style: its parts are its
547 glyphs and shapes, white unless styled.
549 `MathTypst("x^2 + y^2")` typesets `$ x^2 + y^2 $`, in New Computer Modern Math.
550 Double braces make groups, which [select][manimgx.Typst.select] gives: `{{ x^2 }}`
551 is numbered, 0 the first, and `{{ x^2 : square }}` is named "square"; the braces are
552 not typeset.
554 Args:
555 math_expression: The formula, in Typst math.
557 Examples:
558 ```python
559 import manimgx as m
562 class MathTypstExample(m.Scene):
563 def construct(self) -> None:
564 formula = m.MathTypst(
565 "{{ a^2 : a }} + {{ b^2 : b }} = {{ c^2 : c }}", font_size=144
566 )
567 formula.select("a").set_color(m.BLUE)
568 formula.select("b").set_color(m.GREEN)
569 formula.select("c").set_color(m.YELLOW)
570 self.play(m.Write(formula))
571 ```
572 """
574 @prototype
575 def __init__(self, math_expression: str, **kwargs: Unpack[TypstOptions]):
576 processed, labels = _groups(math_expression)
577 preamble = kwargs.get("typst_preamble", "")
578 if labels and _MANIMGRP not in preamble:
579 kwargs["typst_preamble"] = (
580 f"{_MANIMGRP}\n{preamble}" if preamble else _MANIMGRP
581 )
582 super().__init__(f"$ {processed} $", **kwargs)
585DEFAULT_FONT = ( # embedded in Typst: identical text on every machine
586 "New Computer Modern"
587)
588_SANS = ("Noto Sans", "Noto Sans Hebrew") # Typst's own fallback sets Hebrew in a serif
589# CSS's and Pango's generic families, as faces ManimGX ships (lowercase keys)
590_GENERIC: dict[str, tuple[str, ...]] = {
591 "serif": (DEFAULT_FONT,),
592 "sans-serif": _SANS,
593 "sans": _SANS,
594 "monospace": ("DejaVu Sans Mono",),
595 "mono": ("DejaVu Sans Mono",),
596}
597# the scripts that decide a CJK text's language (its Han characters' regional forms)
598_KANA = re.compile("[\u3040-\u30ff\u31f0-\u31ff]")
599_HANGUL = re.compile("[\u1100-\u11ff\u3130-\u318f\uac00-\ud7af]")
600_HAN = re.compile("[\u3400-\u9fff\uf900-\ufaff\U00020000-\U0003ffff]")
601_CE_CAP_HEIGHT_PER_POINT = 0.8979 / 96 # CE Text("A", font_size=96).height, measured
602# The space between lines, in ems, for a line_spacing of -1: CE's default (its baselines are
603# meant to be font_size * (1 + 0.3) apart)
604_LINE_SPACING = 0.3
605_WEIGHTS = {
606 "THIN": 100,
607 "ULTRALIGHT": 200,
608 "LIGHT": 300,
609 "SEMILIGHT": 350,
610 "BOOK": 380,
611 "NORMAL": 400,
612 "MEDIUM": 500,
613 "SEMIBOLD": 600,
614 "BOLD": 700,
615 "ULTRABOLD": 800,
616 "HEAVY": 900,
617 "ULTRAHEAVY": 950,
618}
619# CE's slants (any other is upright)
620_SLANTS = {"ITALIC": "italic", "OBLIQUE": "oblique"}
621_SLICE = re.compile(r"\[(-?\d*):(-?\d*)\]") # CE's slice keys, "[a:b]"
622_FAR = 1e6 # a cut's outer edges, in font units: past any glyph's ink
624type Style = tuple[str, str]
625"""A run's CE weight and CE slant."""
628def _arguments(style: Style) -> str:
629 """Typst's text arguments for a style."""
630 weight, slant = style
631 return (
632 f"weight: {_WEIGHTS.get(weight.upper(), 400)},"
633 f' style: "{_SLANTS.get(slant.upper(), "normal")}"'
634 )
637def _fonts(font: str) -> str:
638 """Typst's font list for a CE font name: a generic family's faces, or the family named
639 and then ManimGX's default face (for a family no font has, or a character it lacks).
640 Typst falls back among ManimGX's fonts after them."""
641 families = _GENERIC.get(font.lower(), (font, DEFAULT_FONT))
642 return f"({''.join(f'{typst_string(f)}, ' for f in dict.fromkeys(families))})"
645def _rules(text: str) -> str:
646 """The Typst rules a text's characters call for: a right-to-left paragraph when its first
647 strong character is (Unicode's rule, UAX #9 P2-P3; Typst takes a paragraph's direction
648 from its language), and a CJK text's language, which picks its Han characters' regional
649 forms: Japanese with kana, Korean with hangul, else Chinese (Simplified)."""
650 rules = ""
651 for ch in text:
652 kind = unicodedata.bidirectional(ch)
653 if kind in ("R", "AL"):
654 rules += "#set text(dir: rtl)\n"
655 if kind in ("L", "R", "AL"):
656 break
657 if _KANA.search(text):
658 rules += '#set text(lang: "ja")\n'
659 elif _HANGUL.search(text):
660 rules += '#set text(lang: "ko")\n'
661 elif _HAN.search(text):
662 rules += '#set text(lang: "zh")\n'
663 return rules
666def _find(text: str, key: str) -> list[range]:
667 """The characters of `text` a key picks, as CE defines them: "[a:b]" is a slice of the text
668 as written; any other key, each occurrence of it (not overlapping)."""
669 match = _SLICE.fullmatch(key)
670 if match is not None:
671 start, stop = (int(g) if g else None for g in match.groups())
672 return [range(*slice(start, stop).indices(len(text)))]
673 spans = []
674 at = text.find(key) if key else -1
675 while at != -1:
676 spans.append(range(at, at + len(key)))
677 at = text.find(key, at + len(key))
678 return spans
681def _literal(
682 text: str,
683 tab_width: int,
684 out: list[str],
685 runs: dict[int, list[int]],
686 at: int,
687 first: int,
688) -> int:
689 """Append `text` as a Typst string (set literally; tabs as `tab_width` spaces) and record,
690 for each byte of its value, the character it came from. Return where the string ends.
691 """
692 value: list[str] = []
693 chars: list[int] = []
694 for k, ch in enumerate(text):
695 piece = " " * tab_width if ch == "\t" else ch
696 value.append(piece)
697 chars.extend([first + k] * len(piece.encode()))
698 literal = "#" + typst_string("".join(value))
699 runs[at + 1] = chars # the string's node starts after the "#"
700 out.append(literal)
701 return at + len(literal.encode())
704def _lines(line_spacing: float) -> str:
705 """The Typst rules that set lines on a baseline grid: baselines (1 + line_spacing) em
706 apart, whatever the glyphs on them (-1: CE's default, 0.3). A line's box is its baseline,
707 so the leading is the whole pitch."""
708 gap = _LINE_SPACING if line_spacing == -1 else line_spacing
709 return (
710 '#set text(top-edge: "baseline", bottom-edge: "baseline")\n'
711 f"#set par(leading: {1 + gap}em)\n"
712 )
715def _calibration(font: str, kwargs: TypstOptions) -> float:
716 """A capital's exact measured scale, reusing Typst's cached construction."""
717 options: TypstOptions = {"font_size": DEFAULT_FONT_SIZE}
718 if "font_paths" in kwargs:
719 options["font_paths"] = kwargs["font_paths"]
720 probe = Typst(f"#text(font: {_fonts(font)})[H]", **options)
721 target = _CE_CAP_HEIGHT_PER_POINT * DEFAULT_FONT_SIZE
722 return target / probe.height if probe.height > 0 else 1.0
725class TextOptions(_TypstOptions, total=False, closed=True):
726 """[Text][manimgx.Text]'s keywords, for the classes that pass them on:
727 [Paragraph][manimgx.Paragraph].
729 Beyond these, they take the
730 [Typst keywords][manimgx.mobjects.text.TypstOptions].
731 """
733 line_spacing: float
734 """The space between lines, in ems: a text's baselines are `1 + line_spacing` ems
735 apart, whatever the glyphs on them (default -1: 0.3)."""
736 font: str
737 """The font family: one manimgx ships (New Computer Modern, Libertinus Serif,
738 DejaVu Sans Mono, Noto Sans, …), "serif", "sans-serif" or "monospace", one in
739 `font_paths`, or else one of the system's; a family found nowhere falls back to New
740 Computer Modern (default "": New Computer Modern)."""
741 slant: str
742 """The slant: `NORMAL`, `ITALIC` or `OBLIQUE` (default `NORMAL`)."""
743 weight: str
744 """The weight, by name, from `THIN` through `NORMAL` and `BOLD` to `ULTRAHEAVY`
745 (default `NORMAL`); the font's nearest weight is used."""
746 t2c: Mapping[str, ParsableManimColor] | None
747 """A color for each key: a slice `"[a:b]"` of the text as written, spaces included,
748 or a string, each occurrence of it (default None)."""
749 t2g: Mapping[str, Sequence[ParsableManimColor]] | None
750 """A gradient for each key: its colors spread along the characters the key picks, as
751 `t2c` picks them (default None)."""
752 t2s: Mapping[str, str] | None
753 """A slant for each key, picking characters as `t2c` does (default None)."""
754 t2w: Mapping[str, str] | None
755 """A weight for each key, picking characters as `t2c` does (default None)."""
756 gradient: Sequence[ParsableManimColor] | None
757 """Colors spread along the whole text, character by character, spaces included
758 (default None)."""
759 tab_width: int
760 """How many spaces a tab is set as (default 4)."""
761 disable_ligatures: bool
762 """Whether every character is a glyph of its own, with no ligatures (default False:
763 "fi" may be one glyph)."""
766class Text(Typst):
767 """Text in a font, typeset by Typst as it is written: white unless styled.
769 Spaces stay, a newline breaks the line, a tab is `tab_width` spaces, and nothing is
770 markup ("= Title" is no heading). The lines are set on a grid: their baselines are
771 `1 + line_spacing` ems apart, whatever the glyphs on them. The parts are the glyphs,
772 in reading order, spaces excluded: `Text("Hello")[0]` is the "H", a
773 [TypstGlyph][manimgx.mobjects.text.TypstGlyph]. A ligature is one glyph
774 (the "ffi" of "office", in the default font) unless `disable_ligatures`.
776 A text is set in one font, from the fonts ManimGX ships, so it looks the same on
777 every machine: New Computer Modern unless `font` names another. "serif",
778 "sans-serif" (or "sans") and "monospace" (or "mono") are New Computer Modern, Noto
779 Sans and DejaVu Sans Mono. Fonts in `font_paths` come first; a family neither they
780 nor ManimGX have is read from the system's fonts, and one found nowhere falls back
781 to New Computer Modern. A character the font lacks is set in another font that has
782 it: ManimGX ships Noto faces for Arabic, Hebrew, the Indic scripts, Thai, Chinese,
783 Japanese, Korean and more, with symbols and emoji. In any font, a capital is 0.449
784 scene units tall at the default size, 48, and in proportion at others: each font is
785 scaled to that, and `font_size` still reads the size asked for.
787 A text whose first letter is from a right-to-left script (Arabic, Hebrew) is set as
788 a right-to-left paragraph, its lines lined up on the right. A Chinese, Japanese or
789 Korean text takes its language from its characters (Japanese with kana, Korean with
790 hangul, else Chinese), which gives its Han characters their regional forms.
792 Keys pick characters: a slice `"[a:b]"` of the text as written, spaces included, or
793 a string, each occurrence of it (a key that occurs nowhere picks nothing). `t2s` and
794 `t2w` set what they pick in another slant or weight; `gradient`, then `t2g`, then
795 `t2c` color it, each over the one before. Color never changes the layout: the text
796 is laid out once, and each glyph takes the color of the characters it draws — a
797 ligature that a color boundary crosses is cut there, each piece in its characters'
798 color. A custom glyph's path-building methods also construct its color pieces.
800 Args:
801 text: The text, as written.
802 line_spacing: The space between lines, in ems: the baselines are
803 `1 + line_spacing` ems apart; -1 for 0.3.
804 font: The font family, or "serif", "sans-serif" or "monospace"; "" for New
805 Computer Modern.
806 slant: `NORMAL`, `ITALIC` or `OBLIQUE`.
807 weight: A weight by name, from `THIN` through `NORMAL` and `BOLD` to
808 `ULTRAHEAVY`; the font's nearest weight is used.
809 t2c: A color for each key.
810 t2g: A gradient for each key: its colors spread along what the key picks.
811 t2s: A slant for each key.
812 t2w: A weight for each key.
813 gradient: Colors spread along the whole text, character by character, spaces
814 included.
815 tab_width: How many spaces a tab is set as.
816 disable_ligatures: Whether every character is a glyph of its own.
817 **kwargs: [Typst keywords][manimgx.mobjects.text.TypstOptions]:
818 `font_size` (48 unless given), `color`, `width` or `height`, and the rest.
820 Examples:
821 ```python
822 import manimgx as m
825 class TextExample(m.Scene):
826 def construct(self) -> None:
827 texts = m.VGroup(
828 m.Text("New Computer Modern"),
829 m.Text("sans-serif: Noto Sans", font="sans-serif"),
830 m.Text("monospace: DejaVu Sans Mono", font="monospace"),
831 m.Text("Libertinus Serif", font="Libertinus Serif"),
832 m.Text("bold and italic", weight=m.BOLD, slant=m.ITALIC),
833 )
834 self.add(texts.arrange(m.DOWN, buff=0.5).scale(1.3))
835 ```
837 ```python
838 import manimgx as m
841 class TextScriptsExample(m.Scene):
842 def construct(self) -> None:
843 texts = m.VGroup(
844 m.Text("Ελληνικά, кириллица"),
845 m.Text("مرحبا بالعالم"),
846 m.Text("สวัสดีชาวโลก"),
847 m.Text("你好,世界"),
848 m.Text("こんにちは、世界"),
849 m.Text("안녕하세요, 세계"),
850 )
851 self.add(texts.arrange(m.DOWN, buff=0.4).scale(1.2))
852 ```
854 ```python
855 import manimgx as m
858 class TextColoringExample(m.Scene):
859 def construct(self) -> None:
860 words = {"red": m.RED, "green": m.GREEN, "blue": m.BLUE}
861 word = {"gradient": (m.RED, m.YELLOW)}
862 texts = m.VGroup(
863 m.Text("red, green and blue", t2c=words),
864 m.Text("a slice of the text", t2c={"[2:7]": m.YELLOW}),
865 m.Text("a gradient along it all", gradient=(m.BLUE, m.GREEN)),
866 m.Text("a gradient in one word", t2g=word),
867 )
868 self.add(texts.arrange(m.DOWN, buff=0.5).scale(1.3))
869 ```
870 """
872 @prototype
873 def __init__(
874 self,
875 text: str,
876 line_spacing: float = -1,
877 font: str = "",
878 slant: str = NORMAL,
879 weight: str = NORMAL,
880 t2c: Mapping[str, ParsableManimColor] | None = None,
881 t2g: Mapping[str, Sequence[ParsableManimColor]] | None = None,
882 t2s: Mapping[str, str] | None = None,
883 t2w: Mapping[str, str] | None = None,
884 gradient: Sequence[ParsableManimColor] | None = None,
885 tab_width: int = 4,
886 disable_ligatures: bool = False,
887 **kwargs: Unpack[TypstOptions],
888 ) -> None:
889 if kwargs.get("fill_opacity") is None and kwargs.get("opacity") is None:
890 kwargs["fill_opacity"] = 1.0 # filled, unless an opacity is given
891 self.text = text
892 """The text, as it was written."""
893 self.original_text = text
894 self.font = font
895 self.slant, self.weight = slant, weight
896 chars = text # the text as written, as characters
897 family = font or DEFAULT_FONT
898 base: Style = (weight, slant)
899 styles: list[Style] | None = None
900 if t2w or t2s:
901 styles = [base] * len(chars)
902 for field, mapping in enumerate((t2w, t2s)):
903 for key, value in (mapping or {}).items():
904 for span in _find(chars, key):
905 for i in span:
906 style = list(styles[i])
907 style[field] = value
908 styles[i] = (style[0], style[1])
909 ligatures = ", ligatures: false" if disable_ligatures else ""
910 head = f"#text(font: {_fonts(family)}, {_arguments(base)}{ligatures})["
911 body, runs = self._source(text, tab_width, len(head.encode()), base, styles)
912 rules = _rules(text) + (_lines(line_spacing) if "\n" in text else "")
913 if rules:
914 kwargs["typst_preamble"] = rules + kwargs.get("typst_preamble", "")
915 # set larger by its font's calibration, so font_size stays the size asked for
916 super().__init__(
917 f"{head}{body}]", font_scale=_calibration(family, kwargs), **kwargs
918 )
919 self._chars = chars
920 self._clusters = self._characters(runs)
921 colors: dict[int, ManimColor] = {}
922 if gradient:
923 colors |= dict(enumerate(color_gradient(list(gradient), len(chars))))
924 for key, stops in (t2g or {}).items():
925 for span in _find(chars, key):
926 if span:
927 colors |= dict(zip(span, color_gradient(list(stops), len(span))))
928 for key, color in (t2c or {}).items():
929 for span in _find(chars, key):
930 colors |= dict.fromkeys(span, ManimColor(color))
931 if colors:
932 self._paint(colors)
934 def _source(
935 self,
936 text: str,
937 tab_width: int,
938 at: int,
939 base: Style,
940 styles: list[Style] | None,
941 ) -> tuple[str, dict[int, list[int]]]:
942 """The Typst code setting the text (from byte `at`): a string per run of one style, and for
943 each string where it starts and the character each byte of its value came from.
944 """
945 out: list[str] = []
946 runs: dict[int, list[int]] = {}
947 if styles is None or not text:
948 _literal(text, tab_width, out, runs, at, 0)
949 return "".join(out), runs
950 start = 0
951 for end in range(1, len(text) + 1):
952 if end < len(text) and styles[end] == styles[start]:
953 continue
954 opener = (
955 "" if styles[start] == base else f"#text({_arguments(styles[start])})["
956 )
957 out.append(opener)
958 at += len(opener.encode())
959 at = _literal(text[start:end], tab_width, out, runs, at, start)
960 if opener:
961 out.append("]")
962 at += 1
963 start = end
964 return "".join(out), runs
966 def _characters(self, runs: dict[int, list[int]]) -> list[range]:
967 """Each part's characters: those its glyph's cluster draws, through the string it came
968 from (none for a part not from the text: a list's marker, an underline)."""
969 clusters = []
970 for part in self.submobjects:
971 drawn: list[int] = []
972 if isinstance(part, TypstGlyph) and part.node in runs:
973 drawn = runs[part.node][part.drawn[0] : part.drawn[1]]
974 clusters.append(range(drawn[0], drawn[-1] + 1) if drawn else range(0))
975 return clusters
977 def _paint(self, colors: Mapping[int, ManimColor]) -> None:
978 """Each glyph takes its characters' colors (a grapheme's color: its first character's);
979 a glyph of several colors is cut at its carets."""
980 graphemes = _engine.graphemes(self._chars)
981 for part, chars in zip(self.submobjects, self._clusters):
982 if not chars:
983 continue
984 heads = graphemes[
985 bisect.bisect_left(graphemes, chars.start) : bisect.bisect_left(
986 graphemes, chars.stop
987 )
988 ]
989 if not heads or heads[0] != chars.start:
990 heads.insert(0, chars.start)
991 paints = [colors.get(i) for i in heads]
992 if len(set(paints)) == 1:
993 if paints[0] is not None:
994 part.set_color(paints[0])
995 elif isinstance(part, TypstGlyph):
996 rtl = unicodedata.bidirectional(self._chars[chars.start]) in ("R", "AL")
997 _cut(part, paints[::-1] if rtl else paints)
1000def _cut(glyph: TypstGlyph, paints: list[ManimColor | None]) -> None:
1001 """Cut a glyph at its carets (the font's, else equal parts) into pieces of one color each; the
1002 glyph becomes their group."""
1003 n = len(paints)
1004 carets: np.ndarray | tuple[float, ...] = np.frombuffer(glyph._carets, dtype="<f8")
1005 if len(carets) != n - 1:
1006 carets = tuple(glyph.x_advance * k / n for k in range(1, n))
1007 edges = [-_FAR, *carets, _FAR]
1008 runs: list[tuple[float, float, ManimColor | None]] = []
1009 for k, paint in enumerate(paints):
1010 if runs and runs[-1][2] == paint:
1011 runs[-1] = (runs[-1][0], edges[k + 1], paint)
1012 else:
1013 runs.append((edges[k], edges[k + 1], paint))
1014 ((placement, outline),) = glyph._geometry.terms
1015 tolerance = VMobject.tolerance_for_point_equality
1016 whole = _to_path(Blend.of(outline.array).points(), tolerance)
1017 pieces = []
1018 for x0, x1, paint in runs:
1019 corners = np.array(
1020 [
1021 [x0, -_FAR, 0],
1022 [x1, -_FAR, 0],
1023 [x1, _FAR, 0],
1024 [x0, _FAR, 0],
1025 [x0, -_FAR, 0],
1026 ]
1027 )
1028 strip = np.empty((16, 3))
1029 for i, alpha in enumerate(np.linspace(0, 1, 4)):
1030 strip[i::4] = interpolate(corners[:-1], corners[1:], alpha)
1031 result = _pathops().op(
1032 whole,
1033 _to_path(Blend.of(strip).points(), tolerance),
1034 _pathops().PathOp.INTERSECTION,
1035 )
1036 piece = glyph.copy()
1037 piece._geometry = EMPTY
1038 _append_path(piece, result)
1039 local = piece.points
1040 piece._geometry = Blend(((placement, Shape(np.array(local))),), len(local))
1041 if paint is not None:
1042 piece.set_color(paint)
1043 pieces.append(piece)
1044 glyph._geometry = EMPTY
1045 glyph.add(*pieces)
1048class Paragraph(VGroup):
1049 """Lines of text set as one paragraph: on one grid of baselines, each line at the
1050 paragraph's start or where `alignment` puts it.
1052 The lines are one [Text][manimgx.Text] (`lines_text`), joined by newlines, so they
1053 share its grid: their baselines are `1 + line_spacing` ems apart (1.3 unless
1054 `line_spacing` is given). The paragraph's parts are its lines, from the top, each
1055 the group of its glyphs.
1057 Args:
1058 *text: The lines: each string is one, or several, split at its newlines.
1059 alignment: "left", "center" or "right" to line the lines up on that side or
1060 center them; None to start each at the paragraph's start (the left, for
1061 left-to-right text).
1063 Examples:
1064 ```python
1065 import manimgx as m
1068 class ParagraphExample(m.Scene):
1069 def construct(self) -> None:
1070 lines = ("Twinkle, twinkle,", "little star,", "how I wonder")
1071 paragraphs = m.VGroup(
1072 m.Paragraph(*lines),
1073 m.Paragraph(*lines, alignment="center", line_spacing=1),
1074 m.Paragraph(*lines, alignment="right"),
1075 )
1076 self.add(paragraphs.arrange(buff=0.8).scale(0.85))
1077 ```
1078 """
1080 def __init__(
1081 self,
1082 *text: str,
1083 alignment: Literal["left", "center", "right"] | None = None,
1084 **kwargs: Unpack[TextOptions],
1085 ) -> None:
1086 joined = "\n".join(text)
1087 if alignment is not None: # Typst's alignments of these names
1088 kwargs["typst_preamble"] = f"#set align({alignment})\n" + kwargs.get(
1089 "typst_preamble", ""
1090 )
1091 self.lines_text = whole = Text(joined, **kwargs)
1092 """The lines as one [Text][manimgx.Text], joined by newlines: the paragraph's
1093 lines group its glyphs."""
1094 # the parts are the lines, each the group of its glyphs (CE's structure)
1095 starts = [0, *(i + 1 for i, ch in enumerate(joined) if ch == "\n")]
1096 lines: list[list[Mobject]] = [[] for _ in starts]
1097 for part, chars in zip(whole.submobjects, whole._clusters):
1098 lines[bisect.bisect_right(starts, chars.start) - 1].append(part)
1099 super().__init__(*(VGroup(*line) for line in lines))
1100 self.alignment = alignment
1103# LaTeX is converted to Typst by mitex, compiled into the engine; the package gives its scope.
1104# LaTeX sets its text in Computer Modern, as its math (Typst's default text face is Libertinus)
1105_IMPORT = (
1106 '#import "@preview/mitex:0.2.7": mitex-scope\n'
1107 '#set text(font: "New Computer Modern")\n'
1108)
1111def _standalone(tex: str) -> str:
1112 """CE's `_modify_special_strings`: make a lone fragment of a formula typeset on its own.
1113 Its mends are math's (a trailing `dot` is `\\dot`'s); text is converted as written."""
1114 tex = tex.strip()
1115 if tex in ("\\over", "\\overline", "\\sqrt", "\\sqrt{") or tex.endswith(
1116 ("_", "^", "dot")
1117 ):
1118 tex += "{\\quad}"
1119 if tex in ("\\substack", ""):
1120 tex = "\\quad"
1121 if tex.startswith("\\\\"):
1122 tex = tex.replace("\\\\", "\\quad\\\\")
1123 lefts, rights = (
1124 len([s for s in tex.split(k)[1:] if s and s[0] in "(){}[]|.\\"])
1125 for k in ("\\left", "\\right")
1126 )
1127 if lefts != rights:
1128 tex = tex.replace("\\left", "\\big").replace("\\right", "\\big")
1129 opens = tex.count("{") - tex.count("\\{") + tex.count("\\\\{")
1130 closes = tex.count("}") - tex.count("\\}") + tex.count("\\\\}")
1131 return "{" * max(0, closes - opens) + tex + "}" * max(0, opens - closes)
1134_HOLE = 0xE000 # private-use characters: mitex passes them through as they are
1137_TOKENS = re.compile(r"\\([a-zA-Z]+)|\\.|([{}])")
1138_DEPTH = {"{": 1, "}": -1, "begin": 1, "end": -1, "left": 1, "right": -1}
1141def _split_braces(tex: str) -> list[str]:
1142 """The string split at its `{{…}}`: what is outside them and what each holds, in turn,
1143 starting outside. A group ends at the first `}}` where its own braces are closed, so it
1144 may hold braces of its own: `{{\\tfrac{1}{3}}}` holds `\\tfrac{1}{3}`. An escaped brace
1145 is no brace, and a `{{` never closed is as written."""
1146 pieces: list[str] = []
1147 at = depth = 0
1148 for token in _TOKENS.finditer(tex):
1149 inside = len(pieces) % 2 == 1 # the pieces alternate, starting outside
1150 if token.start() < at:
1151 continue # the second brace of a pair
1152 if depth == 0 and tex.startswith("}}" if inside else "{{", token.start()):
1153 pieces.append(tex[at : token.start()])
1154 at = token.start() + 2
1155 elif inside:
1156 depth += _DEPTH.get(token[2], 0)
1157 if len(pieces) % 2: # a `{{` never closed
1158 return [*pieces[:-1], pieces[-1] + tex[at - 2 :]]
1159 return [*pieces, tex[at:]]
1162def _isolate_braces(strings: list[str], math: bool) -> list[str]:
1163 """CE's double braces: `{{…}}` sets what it holds apart as a part of its own. In math,
1164 where spaces mean nothing, once they split anything every part is stripped; text keeps
1165 its spaces, so its strings still join into the text as written."""
1166 pieces = [p for s in strings for p in _split_braces(s)]
1167 if math and len(pieces) > len(strings):
1168 pieces = [p.strip() for p in pieces]
1169 return [p for p in pieces if p]
1172def _balanced(tex: str) -> bool:
1173 """Does the LaTeX stand on its own: every group, environment and delimiter it opens closed
1174 in it, and none closed that it did not open? (mitex closes what is left open, so a
1175 piece converting on its own does not tell.)"""
1176 depth = 0
1177 for command, brace in _TOKENS.findall(tex):
1178 depth += _DEPTH.get(command or brace, 0)
1179 if depth < 0:
1180 return False
1181 return depth == 0
1184def _one_formula(
1185 pieces: list[str], separator: str, convert: Callable[[str], str]
1186) -> tuple[str, str, dict[int, str]]:
1187 """The pieces as one formula, or one text: the Typst code of their joined LaTeX
1188 (`convert`: mitex's conversion of LaTeX math, or of LaTeX text); its skeleton, the same
1189 code with each piece that stands on its own (a `hole`) a private-use character; and each
1190 hole's code. The holes are converted on their own, in the joined LaTeX's skeleton, and the
1191 skeleton with their code in place is checked to be what the whole converts to: telling
1192 the pieces apart never changes the code."""
1193 whole = convert(separator.join(pieces))
1194 holes: dict[int, str] = {}
1195 for i, piece in enumerate(pieces):
1196 if not _balanced(piece) or piece.lstrip()[:1] in ("^", "_", "'", ""):
1197 continue # a fragment, or an attachment to what comes before
1198 try:
1199 holes[i] = convert(piece)
1200 except TypstError:
1201 continue
1202 apart = ValueError(f"cannot tell these parts apart: {pieces}")
1203 try:
1204 skeleton = convert(
1205 separator.join(
1206 chr(_HOLE + i) if i in holes else p for i, p in enumerate(pieces)
1207 )
1208 )
1209 except TypstError as error: # a hole within what converts only whole (math in text)
1210 raise apart from error
1211 found = [ord(c) - _HOLE for c in skeleton if _HOLE <= ord(c) < _HOLE + len(pieces)]
1212 plain = _fill(skeleton, holes)
1213 if found != sorted(holes) or "".join(plain.split()) != "".join(whole.split()):
1214 raise apart
1215 return whole, skeleton, holes
1218def _fill(skeleton: str, holes: Mapping[int, str]) -> str:
1219 """The skeleton with each hole's code (or what stands for it) in its place."""
1220 for i, code in holes.items():
1221 skeleton = skeleton.replace(chr(_HOLE + i), code)
1222 return skeleton
1225def _in_place(skeleton: str, holes: Mapping[int, str]) -> dict[int, str]:
1226 """Each hole's markup as it reads in the whole. Typst reads a line's first characters
1227 apart (`- `, `+ `, `= ` and `/ ` begin a list's item, an enumeration's, a heading, a
1228 term), so a hole that goes on with a line is read after an empty expression, which
1229 keeps it on the line."""
1230 read = {}
1231 for i, code in holes.items():
1232 before = _fill(skeleton[: skeleton.index(chr(_HOLE + i))], holes)
1233 read[i] = f"#none;{code}" if before.rsplit("\n", 1)[-1].strip() else code
1234 return read
1237_MITEX = 'mode: "math", scope: mitex-scope'
1238_MARKUP = 'mode: "markup", scope: mitex-scope'
1241def _math(latex: str) -> str:
1242 converted = typst_string(_engine.mitex_math(latex))
1243 return f"eval({converted}, {_MITEX})"
1246def _text(latex: str) -> str:
1247 return _markup(_engine.mitex_text(latex))
1250def _markup(code: str, scope: str = "") -> str:
1251 """Typst markup (mitex's conversion of LaTeX text) as an expression of its content, in
1252 mitex's scope and, after it, the bindings `scope` lists ("name: value, ")."""
1253 within = f"mitex-scope + ({scope})" if scope else "mitex-scope"
1254 return f'eval({typst_string(code)}, mode: "markup", scope: {within})'
1257def _bindings(codes: Mapping[int, str]) -> tuple[str, dict[int, int]]:
1258 """Typst code binding each string's content (its markup, evaluated) to its name, `p{i}`;
1259 and where in that code each string's markup starts, in bytes, which every glyph the
1260 markup draws comes from."""
1261 out, starts, at = [], {}, 0
1262 for i, code in codes.items():
1263 head = f"#let p{i} = eval("
1264 starts[at + len(head.encode())] = i
1265 binding = f"{head}{typst_string(code)}, {_MARKUP});"
1266 out.append(binding)
1267 at += len(binding.encode())
1268 return "".join(out), starts
1271def _same(a: Layout, b: Layout) -> bool:
1272 """Whether two layouts draw the same: the same items, placed and painted alike, wherever
1273 in the code they came from."""
1274 return (
1275 np.array_equal(a.rows[:, : NODE.start], b.rows[:, : NODE.start])
1276 and len(a.shapes) == len(b.shapes)
1277 and all(np.array_equal(p, q) for p, q in zip(a.shapes, b.shapes))
1278 )
1281@deprecated("use MathTex", category=None)
1282class SingleStringMathTex(Typst):
1283 r"""One LaTeX formula, typeset in the engine, whose parts are its glyphs: white
1284 unless styled.
1286 The LaTeX is converted to Typst as a [MathTex][manimgx.MathTex]'s is, and set in
1287 display style; the parts are not grouped by strings, so `formula[i]` is its i-th
1288 glyph (or shape, such as a fraction's bar), in the order Typst sets them.
1290 Args:
1291 tex_string: The formula, in LaTeX.
1292 organize_left_to_right: Whether to order the parts by their centers, from left
1293 to right, rather than as Typst sets them.
1294 tex_environment: Any environment (the default, "align*") sets the string as
1295 math; None as LaTeX text, math between `$` signs.
1297 Examples:
1298 ```python
1299 import manimgx as m
1302 class SingleStringMathTexExample(m.Scene):
1303 def construct(self) -> None:
1304 formula = m.SingleStringMathTex(r"e^{i\pi} + 1 = 0", font_size=144)
1305 formula[1:3].set_color(m.YELLOW)
1306 self.add(formula, m.index_labels(formula, label_height=0.3))
1307 ```
1308 """
1310 @prototype
1311 def __init__(
1312 self,
1313 tex_string: str,
1314 organize_left_to_right: bool = False,
1315 tex_environment: str | None = "align*",
1316 **kwargs: Unpack[TypstOptions],
1317 ) -> None:
1318 self.tex_string = tex_string
1319 """The LaTeX the formula was typeset from."""
1320 self.tex_environment = tex_environment
1321 body = (
1322 f"$ #{_math(tex_string)} $" if tex_environment else f"#{_text(tex_string)}"
1323 )
1324 kwargs["typst_preamble"] = _IMPORT + kwargs.get("typst_preamble", "")
1325 super().__init__(body, **kwargs)
1326 if organize_left_to_right:
1327 self.submobjects.sort(key=lambda m: m.get_x())
1330class MathTexPart(VGroup):
1331 """One of a [MathTex][manimgx.MathTex]'s parts: the glyphs one of its strings adds
1332 to the formula, as a group that knows the string.
1334 Args:
1335 tex_string: The LaTeX it was typeset from.
1336 *members: Its glyphs.
1337 """
1339 def __init__(self, tex_string: str, *members: Mobject) -> None:
1340 super().__init__(*members)
1341 self.tex_string = tex_string
1342 """The LaTeX the part was typeset from."""
1345class MathTexOptions(_TypstOptions, total=False, closed=True):
1346 """[MathTex][manimgx.MathTex]'s keywords, for the classes that pass them on:
1347 [Tex][manimgx.Tex], [BulletedList][manimgx.BulletedList], [Title][manimgx.Title] and
1348 labels.
1350 Beyond these, they take the
1351 [Typst keywords][manimgx.mobjects.text.TypstOptions].
1352 """
1354 arg_separator: str
1355 """What joins the strings into `tex_string`, the formula a MathTex is typeset as,
1356 or the text a Tex is (default " "; "" for a Tex)."""
1357 substrings_to_isolate: Iterable[str] | None
1358 """Substrings to make parts of their own: each string is split around every
1359 occurrence of each (default None)."""
1360 tex_to_color_map: Mapping[str, ParsableManimColor] | None
1361 """A color for each substring, which is made a part of its own, as
1362 `substrings_to_isolate` makes it, and colored (default None)."""
1363 tex_environment: str | None
1364 """How the strings are read: with a name containing "align" ("align*", a MathTex's
1365 default), as math; with any other ("center", a Tex's default, which also centers the
1366 lines), or None, as LaTeX text, math between `$` signs."""
1369class MathTex(Typst):
1370 r"""LaTeX math, typeset in the engine, a part per string: `MathTex("a^2", "+",
1371 "b^2")[2]` is the $b^2$, to color, move or match with another formula.
1373 There is no LaTeX installation: the LaTeX is converted to Typst (by mitex, part of
1374 the engine) and typeset in display style, in New Computer Modern Math, white unless
1375 styled. Most of LaTeX's math converts: fractions, roots, sums and integrals,
1376 matrices (`pmatrix`, `bmatrix`, `array`), `cases` and `aligned`, accents, `\mathbb`
1377 and the other alphabets, `\text`, `\left` and `\right`, `\color`, `\newcommand`.
1378 Packages don't — `\usepackage` and their commands, such as `\ce` or `\SI` — nor does
1379 `\def`: a command mitex doesn't know raises a
1380 [TypstError][manimgx.drawing.typesetting.TypstError].
1382 The strings are one formula, joined by `arg_separator` and typeset whole, so parting
1383 a formula moves none of its glyphs. Each string is a part, a
1384 [MathTexPart][manimgx.MathTexPart] of the glyphs it adds, and double braces set a
1385 part apart within a string, wherever they are:
1386 `MathTex("{{a^2}} + {{b^2}} = {{c^2}}")` has the five parts of the first example
1387 below. A part ends at the `}}` that closes its own braces, so it may hold braces of
1388 its own (`{{\tfrac{1}{3}}}`); an escaped brace (`\{`) is no brace, and a `{{` never
1389 closed is as written. A string that stands on its own (its braces, environments and
1390 `\left`…`\right` closed within it) holds exactly its glyphs. The rest, such as a
1391 fraction's bar or the glyphs of a fragment like `"^2"`, go to the first fragment
1392 between the standing strings around them: in
1393 `MathTex(r"\frac{", "a", "}{", "b", "}")` the bar is the closing `"}"`'s, where TeX
1394 draws it, and in `MathTex(r"e^{i", r"\pi}")`, split inside a term, every glyph is
1395 the first part's. A formula whose parts can't be told apart raises ValueError.
1397 `substrings_to_isolate` and `tex_to_color_map` split the strings further;
1398 [set_color_by_tex][manimgx.MathTex.set_color_by_tex] and
1399 [get_part_by_tex][manimgx.MathTex.get_part_by_tex] find parts by their LaTeX, and
1400 [TransformMatchingTex][manimgx.TransformMatchingTex] moves each part to the part
1401 written the same way in another formula. Read as text (see [Tex][manimgx.Tex]), the
1402 strings are one text in the same way, spaces and all.
1404 Args:
1405 *tex_strings: The formula, in LaTeX: a string per part (a number is written as
1406 a string), and a part per `{{…}}` within one.
1407 arg_separator: What joins the strings into `tex_string`, the formula (or text)
1408 they are typeset as.
1409 substrings_to_isolate: Substrings to make parts of their own: each string is
1410 split around every occurrence of each.
1411 tex_to_color_map: A color for each substring, which is made a part of its own
1412 and colored.
1413 tex_environment: How the strings are read: with a name containing "align" (the
1414 default, "align*"), as math; with any other, or None, as LaTeX text, math
1415 between `$` signs.
1417 Examples:
1418 ```python
1419 import manimgx as m
1422 class MathTexExample(m.Scene):
1423 def construct(self) -> None:
1424 formula = m.MathTex("a^2", "+", "b^2", "=", "c^2", font_size=144)
1425 formula[0].set_color(m.BLUE)
1426 formula[2].set_color(m.GREEN)
1427 formula[4].set_color(m.YELLOW)
1428 self.play(m.Write(formula))
1429 ```
1431 ```python
1432 import manimgx as m
1435 class MathTexLatexExample(m.Scene):
1436 def construct(self) -> None:
1437 limit = r"\lim_{n \to \infty} \left(1 + \frac{1}{n}\right)^n = e"
1438 formulas = m.VGroup(
1439 m.MathTex(r"\int_0^1 x^2 \, dx = \frac{1}{3}"),
1440 m.MathTex(r"\begin{pmatrix} a & b \\ c & d \end{pmatrix}"),
1441 m.MathTex(limit),
1442 m.MathTex(r"\sum_{n=1}^\infty \frac{1}{n^2} = \frac{\pi^2}{6}"),
1443 )
1444 self.add(formulas.arrange_in_grid(rows=2, buff=1).scale(1.3))
1445 ```
1446 """
1448 @prototype
1449 def __init__(
1450 self,
1451 *tex_strings: str | float,
1452 arg_separator: str = " ",
1453 substrings_to_isolate: Iterable[str] | None = None,
1454 tex_to_color_map: Mapping[str, ParsableManimColor] | None = None,
1455 tex_environment: str | None = "align*",
1456 **kwargs: Unpack[TypstOptions],
1457 ) -> None:
1458 self.tex_to_color_map = dict(tex_to_color_map or {})
1459 isolate = list(substrings_to_isolate or []) + list(self.tex_to_color_map)
1460 math = bool(tex_environment and "align" in tex_environment)
1461 strings = _isolate_braces([str(s) for s in tex_strings], math)
1462 self.tex_strings = (
1463 [p for s in strings for p in _split(s, isolate, math)]
1464 if isolate
1465 else strings
1466 )
1467 """The strings, a part's each: the arguments, split at `{{…}}` and around the
1468 isolated substrings."""
1469 self.arg_separator = arg_separator
1470 self.tex_string = arg_separator.join(self.tex_strings)
1471 """The LaTeX of the whole formula, or text: the strings, joined by
1472 `arg_separator`."""
1473 self.tex_environment = tex_environment
1474 preamble = f"{_IMPORT}{_MANIMGRP}\n" if math else _IMPORT
1475 kwargs["typst_preamble"] = preamble + kwargs.get("typst_preamble", "")
1477 def layout(source: str) -> Layout:
1478 return typeset(
1479 source,
1480 kwargs["typst_preamble"],
1481 font_paths=kwargs.get("font_paths"),
1482 package_path=kwargs.get("package_path"),
1483 )
1485 if not math:
1486 body, starts, whole = self._compose(self.tex_strings, arg_separator)
1487 owners: dict[int, int] = {}
1488 if len(self.tex_strings) > 1 and starts: # which string drew each item
1489 apart = ValueError(f"cannot tell these parts apart: {self.tex_strings}")
1490 reference = None if whole is None else layout(whole)
1491 try:
1492 drawn = layout(body)
1493 except TypstError as error: # the text is fine, its parting is not
1494 if reference is None:
1495 raise
1496 raise apart from error
1497 if reference is not None and not _same(drawn, reference):
1498 raise apart
1499 owners = self._owners(drawn, starts)
1500 super().__init__(body, **kwargs)
1501 self._regroup(owners, set(starts.values()))
1502 elif len(self.tex_strings) > 1: # one formula, its parts told apart
1503 _, skeleton, holes = _one_formula(
1504 self.tex_strings, arg_separator, _engine.mitex_math
1505 )
1506 plain = typst_string(_fill(skeleton, holes))
1507 super().__init__(f"$ #eval({plain}, {_MITEX}) $", **kwargs)
1508 boxed = _fill(
1509 skeleton,
1510 {i: f'#manimgrp("p{i}", ${code}$)' for i, code in holes.items()},
1511 )
1512 self._regroup_by_twin(
1513 layout(
1514 f"$ #eval({typst_string(boxed)}, {_MITEX} + (manimgrp: manimgrp)) $"
1515 ),
1516 set(holes),
1517 )
1518 else: # a part's box would drop to text style; keep display style
1519 parts = " ".join(
1520 f'#manimgrp("p{i}", $display(#{_math(_standalone(s))})$)'
1521 for i, s in enumerate(self.tex_strings)
1522 )
1523 super().__init__(f"$ {parts} $", **kwargs)
1524 self._regroup_by_labels()
1525 for tex, c in self.tex_to_color_map.items():
1526 self.set_color_by_tex(tex, c)
1528 def _compose(
1529 self, strings: list[str], separator: str
1530 ) -> tuple[str, dict[int, int], str | None]:
1531 """The strings as one text, joined by `separator`, set as the document sets it (see
1532 `_set`): the document's body; where in it the code of each string that stands on its
1533 own (a hole, see `_one_formula`) starts, and the string's index; and the whole as one
1534 text, which the body must draw exactly (None if no string is told apart).
1536 Each hole's code is evaluated on its own and bound to a name, which the code of the
1537 joined text calls in the hole's place, so every glyph comes from the code of the
1538 string that drew it, and Typst shapes the text across them as it shapes the whole.
1539 """
1540 if len(strings) < 2: # nothing to tell apart
1541 return self._set(_text(separator.join(strings))), {}, None
1542 whole, skeleton, holes = _one_formula(strings, separator, _engine.mitex_text)
1543 if not holes:
1544 return self._set(_markup(whole)), {}, None
1545 bindings, starts = _bindings(_in_place(skeleton, holes))
1546 called = _fill(skeleton, {i: f"#p{i};" for i in holes})
1547 text = _markup(called, "".join(f"p{i}: p{i}, " for i in holes))
1548 return bindings + self._set(text), starts, self._set(_markup(whole))
1550 def _set(self, text: str) -> str:
1551 """The text (a Typst expression of its content) as the document sets it: centered
1552 in the "center" environment."""
1553 if self.tex_environment == "center":
1554 return f"#align(center)[#{text}]"
1555 return f"#{text}"
1557 def _owners(self, layout: Layout, starts: Mapping[int, int]) -> dict[int, int]:
1558 """The string each item of the layout came from, if it came from a string's code
1559 (where it starts in the body, `starts`): a glyph or shape the code drew, or one
1560 drawn within an element of it (a radical within an equation)."""
1561 nodes = (layout.rows[:, NODE.start].astype(np.int64) - layout.body).tolist()
1562 return {k: starts[node] for k, node in enumerate(nodes) if node in starts}
1564 def _regroup(self, owners: Mapping[int, int], holes: Collection[int]) -> None:
1565 """The parts: each string's own items (`owners`, the item's index to the string's),
1566 and every other item to the first string that is not a hole between the strings
1567 whose items are around it; else to the one before (the first, before any)."""
1568 count, leaves = len(self.tex_strings), list(self.submobjects)
1569 if not count:
1570 return
1571 groups: list[list[Mobject]] = [[] for _ in range(count)]
1572 start, before = 0, -1
1573 for k in range(len(leaves) + 1):
1574 owner = count if k == len(leaves) else owners.get(k)
1575 if owner is None:
1576 continue
1577 if start < k: # this run lies between the same two strings' items
1578 fragment = next(
1579 (i for i in range(before + 1, owner) if i not in holes),
1580 max(before, 0),
1581 )
1582 groups[fragment].extend(leaves[start:k])
1583 if k < len(leaves):
1584 groups[owner].append(leaves[k])
1585 start, before = k + 1, owner
1586 self.submobjects = [
1587 MathTexPart(s, *members)
1588 for s, members in zip(self.tex_strings, groups, strict=True)
1589 ]
1591 def _regroup_by_labels(self) -> None:
1592 groups: list[Mobject] = []
1593 for i, s in enumerate(self.tex_strings):
1594 members = self.labels.get(f"p{i}", VGroup())
1595 groups.append(MathTexPart(s, *members))
1596 if any(len(g) for g in groups):
1597 self.submobjects = groups
1599 def _regroup_by_twin(self, twin: Layout, holes: set[int]) -> None:
1600 """Parts from the formula's boxed twin, which draws what the formula draws in the same
1601 order: a hole's glyphs and shapes are labelled; the rest belong to the piece between
1602 the holes around them (the first, if several are)."""
1603 rows, leaves = twin.rows, self.submobjects
1604 if len(rows) != len(leaves) or any(
1605 (row[KIND] == GLYPH) != isinstance(leaf, TypstGlyph)
1606 for row, leaf in zip(rows, leaves, strict=True)
1607 ):
1608 raise ValueError(f"cannot tell these parts apart: {self.tex_strings}")
1609 labelled = {
1610 row: int(label[1:])
1611 for label, members in twin.labels
1612 if label.startswith("p") and label[1:].isdigit()
1613 for row in members
1614 }
1615 self._regroup(labelled, holes)
1617 def get_parts_by_tex(
1618 self, tex: str, substring: bool = True, case_sensitive: bool = True
1619 ) -> VGroup:
1620 """Find the parts whose LaTeX contains `tex`, or is it.
1622 Args:
1623 tex: The LaTeX to look for.
1624 substring: Whether a part whose LaTeX contains `tex` matches; if not, only
1625 one whose LaTeX is `tex`.
1626 case_sensitive: Whether upper and lower case differ.
1628 Returns:
1629 A new group of the parts themselves, in order.
1630 """
1632 def match(s: str) -> bool:
1633 a, b = (tex, s) if case_sensitive else (tex.lower(), s.lower())
1634 return a in b if substring else a == b
1636 return VGroup(
1637 *(
1638 m
1639 for m in self.submobjects
1640 if isinstance(m, MathTexPart) and match(m.tex_string)
1641 )
1642 )
1644 def get_part_by_tex(
1645 self, tex: str, substring: bool = True, case_sensitive: bool = True
1646 ) -> Mobject | None:
1647 r"""Find the first part whose LaTeX contains `tex`, or is it.
1649 Args:
1650 tex: The LaTeX to look for.
1651 substring: Whether a part whose LaTeX contains `tex` matches; if not, only
1652 one whose LaTeX is `tex`.
1653 case_sensitive: Whether upper and lower case differ.
1655 Returns:
1656 The part itself, or None if none matches.
1658 Examples:
1659 ```python
1660 import manimgx as m
1663 class MathTexGetPartByTexExample(m.Scene):
1664 def construct(self) -> None:
1665 formula = m.MathTex(
1666 r"\sin^2\theta", "+", r"\cos^2\theta", "=", "1", font_size=120
1667 )
1668 self.add(formula)
1669 self.play(m.Indicate(formula.get_part_by_tex(r"\cos")))
1670 ```
1671 """
1672 parts = self.get_parts_by_tex(tex, substring, case_sensitive)
1673 return parts[0] if len(parts) else None
1675 def index_of_part(self, part: Mobject) -> int:
1676 """Find where a part is among the formula's parts; a mobject that is not one
1677 raises ValueError.
1679 Args:
1680 part: One of the parts.
1682 Returns:
1683 Its index, from 0.
1684 """
1685 return self.submobjects.index(part)
1687 def set_color_by_tex(
1688 self,
1689 tex: str,
1690 color: ParsableManimColor,
1691 substring: bool = True,
1692 case_sensitive: bool = True,
1693 ) -> Self:
1694 """Color the parts whose LaTeX contains `tex`, or is it.
1696 Args:
1697 tex: The LaTeX to look for.
1698 color: Their color.
1699 substring: Whether a part whose LaTeX contains `tex` matches; if not, only
1700 one whose LaTeX is `tex`.
1701 case_sensitive: Whether upper and lower case differ.
1703 Examples:
1704 ```python
1705 import manimgx as m
1708 class MathTexSetColorByTexExample(m.Scene):
1709 def construct(self) -> None:
1710 formula = m.MathTex(
1711 "x + y = y + x", substrings_to_isolate=["x", "y"], font_size=144
1712 )
1713 formula.set_color_by_tex("x", m.YELLOW)
1714 formula.set_color_by_tex("y", m.BLUE)
1715 self.add(formula)
1716 ```
1717 """
1718 for part in self.get_parts_by_tex(tex, substring, case_sensitive):
1719 part.set_color(color)
1720 return self
1722 def set_color_by_tex_to_color_map(
1723 self,
1724 texs_to_color_map: Mapping[str, ParsableManimColor],
1725 substring: bool = True,
1726 case_sensitive: bool = True,
1727 ) -> Self:
1728 """Color parts by their LaTeX: for each entry, the parts whose LaTeX contains
1729 it, or is it.
1731 Args:
1732 texs_to_color_map: A color for each piece of LaTeX, applied in order.
1733 substring: Whether a part whose LaTeX contains a piece matches; if not, only
1734 one whose LaTeX is the piece.
1735 case_sensitive: Whether upper and lower case differ.
1736 """
1737 for tex, color in texs_to_color_map.items():
1738 self.set_color_by_tex(tex, color, substring, case_sensitive)
1739 return self
1742def _split(s: str, isolate: list[str], math: bool) -> list[str]:
1743 """The string split around each isolated substring; in math, where spaces mean
1744 nothing, without the parts that are only spaces."""
1745 parts = [s]
1746 for sub in sorted(isolate, key=len, reverse=True):
1747 out: list[str] = []
1748 for p in parts:
1749 if p in isolate:
1750 out.append(p)
1751 continue
1752 pieces = p.split(sub)
1753 for k, piece in enumerate(pieces):
1754 if piece:
1755 out.append(piece)
1756 if k < len(pieces) - 1:
1757 out.append(sub)
1758 parts = out
1759 return [p for p in parts if (p.strip() if math else p)]
1762class Tex(MathTex):
1763 r"""LaTeX text, typeset in the engine and centered, a part per string: math goes
1764 between `$` signs.
1766 It is a [MathTex][manimgx.MathTex] that reads its strings as LaTeX text: bold
1767 (`\textbf`), italics (`\emph`, `\textit`), line breaks (`\\`) and inline math
1768 convert. The text is set in New Computer Modern, as LaTeX sets it, the math in New
1769 Computer Modern Math; white unless styled. The strings are one text, joined by
1770 `arg_separator` (nothing, by default) and typeset whole, as a MathTex's are one
1771 formula: `Tex("Fade", "In")` reads "FadeIn", and parting a text moves none of its
1772 glyphs. Its parts are told apart as a formula's are; a ligature two strings share is
1773 the first's.
1775 Args:
1776 *tex_strings: The text, in LaTeX: a string per part.
1777 **kwargs: [MathTex keywords][manimgx.MathTex]:
1778 the strings are joined by "" and read in a "center" environment unless
1779 `arg_separator` and `tex_environment` say otherwise.
1781 Examples:
1782 ```python
1783 import manimgx as m
1786 class TexExample(m.Scene):
1787 def construct(self) -> None:
1788 text = m.Tex(
1789 r"\textbf{Bold}, \emph{emphasized},\\ and math: $e^{i\pi} = -1$",
1790 font_size=96,
1791 )
1792 self.play(m.Write(text))
1793 ```
1794 """
1796 def __init__(
1797 self, *tex_strings: str | float, **kwargs: Unpack[MathTexOptions]
1798 ) -> None:
1799 kwargs.setdefault("arg_separator", "")
1800 kwargs.setdefault("tex_environment", "center")
1801 super().__init__(*tex_strings, **kwargs)
1804_BULLET = "bullet"
1807class BulletedList(Tex):
1808 r"""A bulleted list: an item per line, each after a bullet, lined up on the left.
1810 Typst sets the items as a list: each bullet is a centered dot (LaTeX's `\cdot` at
1811 twice its size), `SMALL_BUFF` from its item, and the items are `buff` apart, in
1812 scene units at the list's font size. Each item is LaTeX text (math between `$`
1813 signs) and a part of its own, its bullet first: `items[1]` is the second item.
1814 `height` and `width` scale the list as set.
1816 Args:
1817 *items: The items, in LaTeX.
1818 buff: The space between items, in scene units.
1820 Examples:
1821 ```python
1822 import manimgx as m
1825 class BulletedListExample(m.Scene):
1826 def construct(self) -> None:
1827 items = m.BulletedList(
1828 "Typeset in the engine",
1829 "No LaTeX installation",
1830 r"Math too: $a^2 + b^2 = c^2$",
1831 font_size=72,
1832 )
1833 self.add(items)
1834 self.play(items.animate.fade_all_but(1))
1835 ```
1836 """
1838 # the list's lengths are a set rule of the preamble, so part of what a construction
1839 # is keyed by; the bullet is CE's (dot_scale_factor 2), and so is the structure
1841 def __init__(
1842 self,
1843 *items: str,
1844 buff: float = MED_LARGE_BUFF,
1845 **kwargs: Unpack[MathTexOptions],
1846 ) -> None:
1847 self.buff = buff
1848 pt = 1 / (
1849 kwargs.get("font_size", DEFAULT_FONT_SIZE) * SCALE_FACTOR_PER_FONT_POINT
1850 )
1851 kwargs["typst_preamble"] = (
1852 f"#set list(marker: [#box(scale(200%, $dot.c$))<{_BULLET}>], indent: 0pt,"
1853 f" body-indent: {SMALL_BUFF * pt}pt, spacing: {buff * pt}pt)\n"
1854 + kwargs.get("typst_preamble", "")
1855 )
1856 kwargs.setdefault("tex_environment", None)
1857 super().__init__(*items, **kwargs)
1859 def _compose(
1860 self, strings: list[str], separator: str
1861 ) -> tuple[str, dict[int, int], str | None]:
1862 """The items as a Typst list, each item's code bound to its name, as a Tex binds a
1863 string's (see `MathTex._compose`): every glyph comes from its item's code."""
1864 codes = {i: _engine.mitex_text(s) for i, s in enumerate(strings)}
1865 bindings, starts = _bindings(codes)
1866 items = ", ".join(f"p{i}" for i in codes)
1867 return f"{bindings}#list({items})", starts, None
1869 def _owners(self, layout: Layout, starts: Mapping[int, int]) -> dict[int, int]:
1870 """Each item's glyphs, and its bullet: one glyph, in its own labelled box, the
1871 items' bullets in their order."""
1872 owners = super()._owners(layout, starts)
1873 bullets = (rows for label, rows in layout.labels if label == _BULLET)
1874 for item, rows in enumerate(bullets):
1875 owners |= dict.fromkeys(rows, item)
1876 return owners
1878 def fade_all_but(self, index: int, opacity: float = 0.5) -> Self:
1879 """Fade every item but one: the others' fill to `opacity`, the one's to 1.
1881 Args:
1882 index: The item's index, from 0.
1883 opacity: The other items' fill opacity, from 0 to 1.
1884 """
1885 part = self.submobjects[index]
1886 for other in self.submobjects:
1887 other.set_fill(opacity=1 if other is part else opacity)
1888 return self
1891class Title(Tex):
1892 """A title: LaTeX text at the top of the frame, over a line across it.
1894 The line is the last part, and the title's `underline`; a `color` colors it with
1895 the text, as [set_color][manimgx.Mobject.set_color] would.
1897 Args:
1898 *text_parts: The title, in LaTeX: a string per part.
1899 include_underline: Whether a line is drawn under the title.
1900 match_underline_width_to_text: Whether the line is as wide as the title; if
1901 not, it spans the frame but 1 unit at each side.
1902 underline_buff: The gap between the title and the line, in scene units.
1904 Examples:
1905 ```python
1906 import manimgx as m
1909 class TitleExample(m.Scene):
1910 def construct(self) -> None:
1911 title = m.Title(r"The Pythagorean theorem: $a^2 + b^2 = c^2$")
1912 self.play(m.Write(title))
1913 ```
1914 """
1916 def __init__(
1917 self,
1918 *text_parts: str,
1919 include_underline: bool = True,
1920 match_underline_width_to_text: bool = False,
1921 underline_buff: float = MED_SMALL_BUFF,
1922 **kwargs: Unpack[MathTexOptions],
1923 ) -> None:
1924 from manimgx.constants import DOWN, LEFT, RIGHT, UP
1925 from manimgx.mobjects.shapes import Line
1926 from manimgx.settings import config
1928 super().__init__(*text_parts, **kwargs)
1929 self.to_edge(UP)
1930 if include_underline:
1931 underline = Line(LEFT, RIGHT).next_to(self, DOWN, buff=underline_buff)
1932 underline.width = (
1933 self.width if match_underline_width_to_text else config.frame_width - 2
1934 )
1935 color = kwargs.get("color")
1936 if color is not None: # color= colors the whole title, as set_color does
1937 underline.set_color(color)
1938 self.add(underline)
1939 self.underline = underline
1940 """The line under the title, its last part (a title made without one has
1941 none)."""