vibe-sketcherDocumentation
Source code for vibesketcher.render.mathtext
"""Math in figure text: a bounded TeX-like subset drawn as SVG text (#247).
A figure string is plain text with math between ``$`` signs, as in
``"$E_{\\mathrm{coh}}$ per cell, $N_c = N_1 N_2$"``. Inside math the
subset is:
- subscripts and superscripts: ``x_1``, ``x^2``, ``x_{ij}^{(n)}``, nested to
:data:`MAX_DEPTH` levels; a doubled script on one base is refused, as in TeX;
- Greek letters and a few operators from :data:`SYMBOLS` (``\\alpha``,
``\\Gamma``, ``\\times``, ``\\leq``, ``\\infty``, ...);
- ``\\frac{a}{b}``, a stacked fraction with a bar;
- ``\\overline{x}`` (also ``\\bar{x}``), a bar over the group, for example a
negative Miller index ``$[\\overline{1}10]$``;
- ``\\mathrm{...}`` and ``\\text{...}`` (text is upright anyway), the spaces
``\\,`` ``\\;`` ``\\quad`` ``\\ `` and ``~``, and the escapes ``\\{ \\} \\_
\\^ \\$ \\% \\# \\&``.
A hyphen in math is the minus sign U+2212. Spaces in math are kept as typed,
also after a command (TeX would drop them and space operators itself).
Letters stay upright: the publication font is one upright face, and no
italic is synthesised.
Nothing else is guessed: an unknown command, an unbalanced brace or ``$``, a
script without its argument and a character the publication font
(:mod:`vibesketcher.render.fonts`) has no glyph for are refused with
:class:`MathRefused`. Scripts are smaller runs lifted or lowered by explicit
baseline positions, never Unicode super- or subscript characters, and bars are
drawn lines, never combining characters, so the font needs only the base
glyphs. Each run is placed at an absolute position computed from the font's
advance widths, so SVG, PDF and PNG agree. The proportions (script size 0.7,
superscript rise 0.36 em, subscript drop 0.22 em, fraction bar on the math
axis at 0.25 em) follow the conventions of D. E. Knuth, *The TeXbook*
(Addison-Wesley, 1984), Appendix G, rounded to a sans-serif face.
"""
from __future__ import annotations
import html
from dataclasses import dataclass, field
from typing import Literal
from vibesketcher.render import RenderRefused
__all__ = [
"MAX_DEPTH",
"MAX_LENGTH",
"SYMBOLS",
"MathRefused",
"math_svg",
"measure",
"plain_text",
"svg_text",
"validate",
]
#: The longest figure string accepted, in characters.
MAX_LENGTH = 500
#: How deeply scripts and fractions may nest.
MAX_DEPTH = 3
#: Every symbol command and the character it draws. Each one has a glyph in
#: the publication font (a test checks this); commands whose glyph the font
#: lacks, such as ``\\to``, ``\\equiv`` or ``\\hbar``, are refused.
SYMBOLS: dict[str, str] = {
"alpha": "α",
"beta": "β",
"gamma": "γ",
"delta": "δ",
"epsilon": "ε",
"varepsilon": "ε",
"zeta": "ζ",
"eta": "η",
"theta": "θ",
"vartheta": "ϑ",
"iota": "ι",
"kappa": "κ",
"lambda": "λ",
"mu": "μ",
"nu": "ν",
"xi": "ξ",
"pi": "π",
"rho": "ρ",
"sigma": "σ",
"tau": "τ",
"upsilon": "υ",
"phi": "φ",
"varphi": "φ",
"chi": "χ",
"psi": "ψ",
"omega": "ω",
"Gamma": "Γ",
"Delta": "Δ",
"Theta": "Θ",
"Lambda": "Λ",
"Xi": "Ξ",
"Pi": "Π",
"Sigma": "Σ",
"Upsilon": "Υ",
"Phi": "Φ",
"Psi": "Ψ",
"Omega": "Ω",
"times": "×",
"cdot": "·",
"pm": "±",
"leq": "≤",
"le": "≤",
"geq": "≥",
"ge": "≥",
"neq": "≠",
"ne": "≠",
"approx": "≈",
"infty": "∞",
"partial": "∂",
"sum": "∑",
"prod": "∏",
"int": "∫",
"AA": "Å",
"circ": "°",
"prime": "′",
"ldots": "…",
"dots": "…",
"minus": "−",
}
_SPACES = {",": 0.167, ";": 0.278, " ": 0.25, "quad": 1.0}
_ESCAPES = set("{}_^$%#&")
_GROUPS = {"mathrm", "text"}
_SCRIPT = 0.7
_SUP_RISE, _SUB_DROP = 0.36, 0.22
_AXIS = 0.25
_ASCENT, _DESCENT = 0.72, 0.21
[docs]
class MathRefused(RenderRefused):
"""A figure string uses math outside the supported subset."""
# ── Parsing ─────────────────────────────────────────────────────────────
@dataclass
class _Text:
text: str
@dataclass
class _Space:
em: float
@dataclass
class _Group:
items: list[_Node] = field(default_factory=list)
@dataclass
class _Scripted:
base: _Node
sup: _Node | None = None
sub: _Node | None = None
@dataclass
class _Frac:
numerator: _Node
denominator: _Node
@dataclass
class _Over:
body: _Node
_Node = _Text | _Space | _Group | _Scripted | _Frac | _Over
class _Parser:
def __init__(self, text: str, source: str) -> None:
self.text, self.at, self.source = text, 0, source
def fail(self, why: str) -> MathRefused:
return MathRefused(f"math {self.source!r}: {why}")
def items(self, depth: int, closing: str | None) -> list[_Node]:
out: list[_Node] = []
while self.at < len(self.text):
char = self.text[self.at]
if char == "}":
if closing != "}":
raise self.fail("unbalanced '}'")
return out
if char in "^_":
self.at += 1
base = out.pop() if out and not isinstance(out[-1], _Space) else _Text("")
scripted = base if isinstance(base, _Scripted) else _Scripted(base)
if depth + 1 > MAX_DEPTH:
raise self.fail(f"scripts nest more than {MAX_DEPTH} levels")
argument = self.argument(depth + 1, "a script")
slot = "sup" if char == "^" else "sub"
if getattr(scripted, slot) is not None:
kind = "superscript" if char == "^" else "subscript"
raise self.fail(f"double {kind}; group it in braces")
setattr(scripted, slot, argument)
out.append(scripted)
continue
out.append(self.atom(depth))
if closing is not None:
raise self.fail("unbalanced '{'")
return out
def argument(self, depth: int, what: str) -> _Node:
while self.at < len(self.text) and self.text[self.at] == " ":
self.at += 1
if self.at >= len(self.text) or self.text[self.at] in "}^_":
raise self.fail(f"{what} needs an argument")
return self.atom(depth)
def atom(self, depth: int) -> _Node:
char = self.text[self.at]
if char == "{":
self.at += 1
group = _Group(self.items(depth, "}"))
self.at += 1
return group
if char == "\\":
return self.command(depth)
self.at += 1
if char == "~":
return _Space(_SPACES[" "])
return _Text("−" if char == "-" else char)
def command(self, depth: int) -> _Node:
start = self.at + 1
if start >= len(self.text):
raise self.fail("a lone backslash")
end = start
while end < len(self.text) and self.text[end].isascii() and self.text[end].isalpha():
end += 1
name = self.text[start:end] if end > start else self.text[start]
self.at = end if end > start else start + 1
if name in _ESCAPES:
return _Text(name)
if name in _SPACES:
return _Space(_SPACES[name])
if name in SYMBOLS:
return _Text(SYMBOLS[name])
if name in _GROUPS:
return self.braced(depth, f"\\{name}")
if name in ("overline", "bar"):
return _Over(self.braced(depth, f"\\{name}"))
if name == "frac":
if depth + 1 > MAX_DEPTH:
raise self.fail(f"fractions nest more than {MAX_DEPTH} levels")
return _Frac(self.braced(depth + 1, "\\frac"), self.braced(depth + 1, "\\frac"))
raise self.fail(f"unsupported command \\{name}")
def braced(self, depth: int, what: str) -> _Group:
while self.at < len(self.text) and self.text[self.at] == " ":
self.at += 1
if self.at >= len(self.text) or self.text[self.at] != "{":
raise self.fail(f"{what} takes a braced argument")
self.at += 1
group = _Group(self.items(depth, "}"))
self.at += 1
return group
def _segments(text: str) -> list[tuple[bool, str]]:
"""Split a figure string into (is_math, text) parts at unescaped ``$``."""
if not isinstance(text, str):
raise MathRefused("figure text must be a string")
if len(text) > MAX_LENGTH:
raise MathRefused(f"figure text is longer than {MAX_LENGTH} characters")
if any(ch in text for ch in "\n\r\t"):
raise MathRefused("figure text is one line; it may not hold line breaks or tabs")
parts: list[tuple[bool, str]] = []
current, math, i = "", False, 0
while i < len(text):
char = text[i]
if char == "\\" and i + 1 < len(text) and text[i + 1] == "$":
current += "\\$" if math else "$"
i += 2
continue
if char == "$":
if current:
parts.append((math, current))
current, math = "", not math
i += 1
continue
current += char
i += 1
if math:
raise MathRefused(f"math {text!r}: unbalanced '$'")
if current:
parts.append((False, current))
return parts
def _parse(text: str) -> list[_Node]:
nodes: list[_Node] = []
for is_math, part in _segments(text):
if is_math:
nodes.append(_Group(_Parser(part, part).items(0, None)))
else:
nodes.append(_Text(part))
return nodes
# ── Layout ──────────────────────────────────────────────────────────────
@dataclass
class _Box:
width: float
ascent: float
descent: float
#: (x, baseline rise, size, text) runs and (x0, x1, rise, thickness) rules.
runs: list[tuple[float, float, float, str]] = field(default_factory=list)
rules: list[tuple[float, float, float, float]] = field(default_factory=list)
def place(self, other: _Box, dx: float, rise: float) -> None:
self.runs.extend((x + dx, r + rise, s, t) for x, r, s, t in other.runs)
self.rules.extend((a + dx, b + dx, r + rise, w) for a, b, r, w in other.rules)
def _check_glyphs(text: str) -> None:
from vibesketcher.render.fonts import _font
glyphs = _font()[1]
missing = sorted({ord(c) for c in text if c != " " and ord(c) not in glyphs})
if missing:
names = ", ".join(f"U+{code:04X}" for code in missing[:8])
raise MathRefused(f"the publication font has no glyph for {names}")
def _layout(node: _Node, size: float) -> _Box:
from vibesketcher.render.fonts import advance
if isinstance(node, _Text):
_check_glyphs(node.text)
box = _Box(advance(node.text) * size, _ASCENT * size, _DESCENT * size)
x = 0.0
for word in node.text.split(" "):
if word:
box.runs.append((x, 0.0, size, word))
x += (advance(word) + advance(" ")) * size
return box
if isinstance(node, _Space):
return _Box(node.em * size, 0.0, 0.0)
if isinstance(node, _Group):
box = _Box(0.0, _ASCENT * size, _DESCENT * size)
merged: list[_Node] = []
for item in node.items: # one run per stretch of text, so the font's spacing holds
if isinstance(item, _Text) and merged and isinstance(merged[-1], _Text):
merged[-1] = _Text(merged[-1].text + item.text)
else:
merged.append(item)
for item in merged:
part = _layout(item, size)
box.place(part, box.width, 0.0)
box.width += part.width
box.ascent, box.descent = max(box.ascent, part.ascent), max(box.descent, part.descent)
return box
if isinstance(node, _Scripted):
base = _layout(node.base, size)
box = _Box(base.width, base.ascent, base.descent)
box.place(base, 0.0, 0.0)
extra = 0.0
if node.sup is not None:
sup = _layout(node.sup, size * _SCRIPT)
rise = max(_SUP_RISE * size, base.ascent - 0.75 * sup.ascent)
box.place(sup, base.width, rise)
box.ascent = max(box.ascent, rise + sup.ascent)
extra = sup.width
if node.sub is not None:
sub = _layout(node.sub, size * _SCRIPT)
drop = max(_SUB_DROP * size, sub.ascent - 0.8 * _ASCENT * size)
box.place(sub, base.width, -drop)
box.descent = max(box.descent, drop + sub.descent)
extra = max(extra, sub.width)
box.width += extra
return box
if isinstance(node, _Frac):
num = _layout(node.numerator, size * _SCRIPT)
den = _layout(node.denominator, size * _SCRIPT)
pad = 0.1 * size
width = max(num.width, den.width) + 2 * pad
axis, gap, bar = _AXIS * size, 0.12 * size, 0.05 * size
box = _Box(width, axis + gap + num.descent + num.ascent, 0.0)
box.place(num, (width - num.width) / 2, axis + gap + num.descent)
den_rise = axis - gap - den.ascent
box.place(den, (width - den.width) / 2, den_rise)
box.descent = max(0.0, -(den_rise - den.descent))
box.rules.append((pad / 2, width - pad / 2, axis, bar))
return box
body = _layout(node.body, size)
box = _Box(body.width, body.ascent + 0.14 * size, body.descent)
box.place(body, 0.0, 0.0)
box.rules.append(
(0.04 * size, body.width - 0.04 * size, body.ascent + 0.08 * size, 0.05 * size)
)
return box
def _box(text: str, size: float) -> _Box:
if not (0 < size <= 1000):
raise MathRefused("text size must be positive and at most 1000")
return _layout(_Group(_parse(text)), size)
[docs]
def validate(text: str) -> None:
"""Refuse ``text`` (:class:`MathRefused`) unless it is in the supported subset."""
_box(text, 10.0)
[docs]
def measure(text: str, size: float) -> tuple[float, float, float]:
"""Width, ascent and descent of ``text`` at ``size``, in the figure's units."""
box = _box(text, size)
return box.width, box.ascent, box.descent
def _n(value: float) -> str:
text = f"{value:.3f}".rstrip("0").rstrip(".")
return "0" if text in ("-0", "") else text
Anchor = Literal["start", "middle", "end"]
[docs]
def svg_text(
text: str,
x: float,
y: float,
size: float,
*,
anchor: Anchor = "start",
fill: str = "#000",
weight: Literal["normal", "bold"] = "normal",
) -> str:
"""``text`` as an SVG fragment whose baseline starts (or centres, or ends) at (x, y).
The fragment is a ``<g>`` holding one ``<text>`` with absolutely placed
``<tspan>`` runs and a ``<line>`` per fraction bar or overline. Anchoring
is done here, from the measured width, so every run keeps its place.
"""
box = _box(text, size)
left = x - {"start": 0.0, "middle": box.width / 2, "end": box.width}[anchor]
spans = "".join(
f'<tspan x="{_n(left + rx)}" y="{_n(y - rise)}"'
+ (f' font-size="{_n(rsize)}"' if abs(rsize - size) > 1e-9 else "")
+ f">{html.escape(run)}</tspan>"
for rx, rise, rsize, run in box.runs
)
bold = ' font-weight="bold"' if weight == "bold" else ""
parts = [
f'<g class="vibe-math"><text font-size="{_n(size)}" fill="{fill}"{bold}>{spans}</text>'
]
for x0, x1, rise, thickness in box.rules:
parts.append(
f'<line x1="{_n(left + x0)}" y1="{_n(y - rise)}" x2="{_n(left + x1)}" '
f'y2="{_n(y - rise)}" stroke="{fill}" stroke-width="{_n(thickness)}"/>'
)
parts.append("</g>")
return "".join(parts)
[docs]
def plain_text(text: str) -> str:
"""A one-line plain reading of ``text`` for titles and alt text (scripts as _ and ^)."""
def walk(node: _Node) -> str:
if isinstance(node, _Text):
return node.text
if isinstance(node, _Space):
return " "
if isinstance(node, _Group):
return "".join(walk(item) for item in node.items)
if isinstance(node, _Scripted):
out = walk(node.base)
for mark, part in (("_", node.sub), ("^", node.sup)):
if part is not None:
inner = walk(part)
out += mark + (inner if len(inner) == 1 else "{" + inner + "}")
return out
if isinstance(node, _Frac):
return f"({walk(node.numerator)})/({walk(node.denominator)})"
return walk(node.body) + "̅" * 0 # the bar is visual only
validate(text)
return "".join(walk(node) for node in _parse(text))
[docs]
def math_svg(text: str, size: float = 12.0, *, fill: str = "#000") -> bytes:
"""A standalone SVG of one figure string, tight around its ink, for annotations."""
box = _box(text, size)
pad = 0.15 * size
width, height = box.width + 2 * pad, box.ascent + box.descent + 2 * pad
body = svg_text(text, pad, pad + box.ascent, size, fill=fill)
svg = (
'<?xml version="1.0" encoding="UTF-8"?>\n'
f'<svg xmlns="http://www.w3.org/2000/svg" width="{_n(width)}pt" height="{_n(height)}pt" '
f'viewBox="0 0 {_n(width)} {_n(height)}" font-family="Roboto, Arial, sans-serif">'
f"<title>{html.escape(plain_text(text))}</title>{body}</svg>"
)
return svg.encode("utf-8")