Skip to content

AI turns documents or topics into real, native PowerPoint decks—with native shapes, transitions and animations, data-backed charts and tables on demand, audio narration from speaker notes, and support for your own .pptx templates. · by Hugo He

feat(native-formula): cover the documented Microsoft 365 LaTeX profile

hugohe3136d5abd66fc
diff --git a/skills/ppt-master/references/native-formula.md b/skills/ppt-master/references/native-formula.md
index 97f1853f..46e37689 100644
--- a/skills/ppt-master/references/native-formula.md
+++ b/skills/ppt-master/references/native-formula.md
@@ -11,7 +11,7 @@ construction, accent, or complex script.
| Layer | Ownership |
|---|---|
-| Default Strategist | Record exact mathematical content as a delimiter-free LaTeX expression body; do not classify its implementation |
+| Default Strategist | Record exact mathematical content as a canonical delimiter-free LaTeX expression body; do not classify its implementation |
| Default Executor | Decide ordinary text versus inline native math versus block native math, then author the selected marker and SVG preview |
| Active Quick context | Perform both content and authoring responsibilities directly |
| SVG-to-PPTX exporter | Compile marker LaTeX to editable Office Math and replace only the registered preview |
@@ -38,12 +38,18 @@ Formula handling is not a user-confirmed policy, image resource, manifest, or
</text>
```
-**Hard rule — one leaf run**: Put non-empty, delimiter-free LaTeX directly in
-`data-pptx-inline-formula` on a leaf `<tspan>`. Give that `<tspan>` one non-empty
+**Hard rule — one leaf run**: Put non-empty LaTeX directly in
+`data-pptx-inline-formula` on a leaf `<tspan>`. Canonical authoring omits outer
+`$...$`, `$$...$$`, `\(...\)`, and `\[...\]` delimiters, though the compiler
+accepts and removes one complete outer pair. Give that `<tspan>` one non-empty
direct preview string with no leading/trailing whitespace, no child element,
and no `x`, `y`, `dx`, `dy`, or paragraph-layout metadata; spacing belongs to
the surrounding text. The marker inherits its computed size and visible solid
-fill; exported math uses the project text language and Cambria Math.
+fill; exported math uses the project text language and Cambria Math. Local
+`\color` / `\textcolor` scopes override the marker fill on both selectable
+formula runs and non-selectable structural controls. `\boldsymbol` / `\bm`
+also applies its bold-italic style to structural control glyphs. Neither form
+changes unrelated marker defaults.
**Hard rule — Slide-local ordinary text only**: Do not place an inline marker
inside a structured Layout placeholder, a Master/Layout layer, imported
@@ -68,11 +74,12 @@ same `a:p` and replaces only the marker run with `a14:m > m:oMath`.
```
**Hard rule — block metadata is truth**: Write one direct
-`<metadata type="application/json">` child with non-empty delimiter-free
-`latex`, `display: block`, `font_size` in `(0, 400]`, a visible `color`, and
-`align: left|center|right`. Give the group finite `data-pptx-x/y`, positive
-`data-pptx-width/height`, and matching root-coordinate `data-pptx-bounds`.
-Export replaces the complete group with `a14:m > m:oMathPara > m:oMath`.
+`<metadata type="application/json">` child with non-empty `latex`, `display:
+block`, `font_size` in `(0, 400]`, a visible `color`, and `align:
+left|center|right`. Use the same canonical delimiter-free form described above.
+Give the group finite `data-pptx-x/y`, positive `data-pptx-width/height`, and
+matching root-coordinate `data-pptx-bounds`. Export replaces the complete group
+with `a14:m > m:oMathPara > m:oMath`.
**Hard rule — preview is SVG, never fallback**: Make every marker preview
semantically equivalent with ordinary SVG text/shapes/lines/paths. Do not use
@@ -83,20 +90,54 @@ The exporter discards the registered preview and emits no picture branch.
## 3. Source, Failure, and Validation
-**Supported subset**: basic text, numbers, operators, Greek/symbol commands,
-fractions, radicals, scripts, `\sum` / `\prod` / `\int` with limits, `\left` /
-`\right` delimiters, matrix variants, `cases`, `aligned`, text/math styles,
-accents, and spacing. Unknown commands or environments fail closed.
+**Forward input profile**: The compiler implements every explicitly named
+LaTeX-to-OMML input and behavior in Microsoft's documented
+[Microsoft 365 LaTeX profile](https://learn.microsoft.com/en-us/office/math/latex)
+(Windows 2606 / Mac 16.110) and
+[mhchem profile](https://learn.microsoft.com/en-us/office/math/latex.mhchem)
+(Windows 2605 / Mac 16.109). This includes outer delimiters, all listed symbols
+and relations, fractions and binomials, roots, right and left scripts,
+delimiters and `\middle`, accents, bars and group characters, limits, all 21
+listed n-ary operators, standard/custom functions, matrices and equation-array
+environments, CD diagrams, fonts and local colors, boxes and phantoms, spacing,
+global 0–9 argument macros, and the documented `\ce` chemistry grammar. The
+closed command tables in `scripts/svg_to_pptx/native_objects/formula_profile.py`
+are the executable vocabulary; the public compiler facade and OMML structure
+gate live in `scripts/svg_to_pptx/native_objects/formula_compiler.py` and
+`scripts/svg_to_pptx/native_objects/formula_omml.py`. Microsoft's open-ended
+“etc.” wording for additional relation aliases does not define undisclosed
+names; only explicitly named commands and retained project aliases are
+contractual.
+
+**Native normalization**: `\dfrac` / `\tfrac`, `\dbinom` / `\tbinom`, and
+continued-fraction alignment normalize to the corresponding OMML structure;
+explicit big-delimiter grades become auto-sizing delimiters; `\mathscr`
+normalizes to `\mathcal`; `smallmatrix` normalizes to `matrix`; PowerPoint array
+columns become centered; style/size commands and equation tags are accepted but
+not stored. Color is stored in generated formula runs and structural control
+properties. No reverse OMML-to-LaTeX build-down is implemented by PPT Master.
+
+**Fail-closed boundary**: Input containing unknown commands or environments,
+Microsoft's explicitly unsupported commands, unsupported mhchem arrows,
+unescaped `%` comments, invalid macros, or any resource-limit overflow blocks
+conversion. This is stricter than Microsoft 365's literal-text passthrough and
+macro-limit behavior: PPT Master never leaks unresolved LaTeX into a released
+slide.
**Hard rule — repair LaTeX upstream**: Unsupported source or an invalid marker
-blocks the page. Rewrite within the supported subset without changing the
+blocks the page. Rewrite within the documented profile without changing the
planned mathematics; otherwise return it to the content owner. Never substitute
a PNG, flatten structural math into ordinary text, hand-write OMML, or leave raw
LaTeX visible.
-**Compatibility boundary**: Both forms target Microsoft PowerPoint 2010+ Office
-Math. WPS, Keynote, LibreOffice, and other clients receive no embedded formula
-fallback and are outside the rendering/editability contract.
+**Compatibility boundary**: The generated package uses standard editable Office
+Math and retains the PowerPoint 2010+ package target. The executable profile is
+pinned to the Microsoft documentation versions above. Repository verification
+covers compilation, OMML structure, and PPTX packaging; it is not a complete
+Microsoft 365 UI rendering/editability certification. Earlier PowerPoint
+versions are not the source-profile baseline. WPS, Keynote, LibreOffice, and
+other clients receive no embedded formula fallback and are outside the
+rendering/editability contract.
**Validation**: The first-page/final SVG checker validates every marker and
compiles its LaTeX before release; native export repeats validation.
diff --git a/skills/ppt-master/references/strategist.md b/skills/ppt-master/references/strategist.md
index 552f62f8..80d8d7c2 100644
--- a/skills/ppt-master/references/strategist.md
+++ b/skills/ppt-master/references/strategist.md
@@ -256,13 +256,13 @@ Scan §IX before locking. Declare every recurring role, including `lead`, `footn
Preserve every source-backed equation and its mathematical meaning. In each
applicable §IX page block, record the exact expression under `Mathematical
-content` as a LaTeX body without `$...$`, `$$...$$`, `\(...\)`, or `\[...\]`
-source delimiters. This field may cover any mathematics that needs exact
+content` in the canonical form: a LaTeX body without `$...$`, `$$...$$`,
+`\(...\)`, or `\[...\]` source delimiters. This field may cover any mathematics that needs exact
preservation; do not classify it as inline or structural or choose its
implementation. Never invent an equation for decoration or create a formula
policy, manifest, PNG, §VIII row, or `spec_lock.md images` entry. Executor owns
-the text-versus-native-formula decision and its authoring; if the supported
-LaTeX subset cannot preserve the planned content, return here for a
+the text-versus-native-formula decision and its authoring; if the documented
+Microsoft 365 input profile cannot preserve the planned content, return here for a
content-level correction.
#### Hyperlink Content Planning
diff --git a/skills/ppt-master/scripts/prompt_audit_manifest.json b/skills/ppt-master/scripts/prompt_audit_manifest.json
index 74605c27..ee7ad8c5 100644
--- a/skills/ppt-master/scripts/prompt_audit_manifest.json
+++ b/skills/ppt-master/scripts/prompt_audit_manifest.json
@@ -13,7 +13,7 @@
"skills/ppt-master/templates/schemas/*.json"
],
"exclude": [],
- "max_tokens": 500000
+ "max_tokens": 555000
},
"file_budgets": {
"AGENTS.md": 2750,
@@ -1052,7 +1052,7 @@
"files": [
"skills/ppt-master/references/native-formula.md"
],
- "max_tokens": 1250
+ "max_tokens": 2000
},
"stage.generate.executor.hyperlink": {
"description": "Conditional direct authoring contract for PowerPoint-native external and same-deck click hyperlinks.",
diff --git a/skills/ppt-master/scripts/svg_to_pptx/native_objects/formula.py b/skills/ppt-master/scripts/svg_to_pptx/native_objects/formula.py
index b28d3f92..13b6b0dd 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/native_objects/formula.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/native_objects/formula.py
@@ -4,6 +4,8 @@ PPT Master - Native Formula Shape Builder
Build editable PowerPoint formula shapes from explicit LaTeX markers.
+See references/native-formula.md for the owning block-formula contract.
+
Usage:
Imported by the SVG-to-PPTX native-object converter.
@@ -25,6 +27,11 @@ from xml.etree import ElementTree as ET
from ..drawingml.context import ConvertContext, ShapeResult
from ..drawingml.utils import _xml_escape, font_px_to_hpt
from .formula_compiler import FormulaCompileError, compile_latex_to_omml
+from .formula_run_properties import (
+ merge_formula_control_properties,
+ merge_formula_run_properties,
+ serialize_styled_formula_omml,
+)
from .marker_common import _bounds, _hex_or_none
@@ -33,7 +40,6 @@ MATH_NS = "http://schemas.openxmlformats.org/officeDocument/2006/math"
A14_NS = "http://schemas.microsoft.com/office/drawing/2010/main"
MC_NS = "http://schemas.openxmlformats.org/markup-compatibility/2006"
_MATH_RUN = f"{{{MATH_NS}}}r"
-_MATH_RUN_PROPERTIES = f"{{{MATH_NS}}}rPr"
_DML_RUN_PROPERTIES = f"{{{DML_NS}}}rPr"
_LANGUAGE_RE = re.compile(r"^[A-Za-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$")
_ALIGNMENTS = {
@@ -162,38 +168,32 @@ def _styled_omml(spec: FormulaSpec) -> str:
)
justification.set(f"{{{MATH_NS}}}val", spec.math_alignment)
- for run in root.iter(_MATH_RUN):
- for existing in list(run):
- if existing.tag == _DML_RUN_PROPERTIES:
- run.remove(existing)
-
- run_properties = ET.Element(
- _DML_RUN_PROPERTIES,
- {
- "lang": spec.language,
- "sz": str(spec.font_size_hpt),
- "dirty": "0",
- },
- )
- solid_fill = ET.SubElement(run_properties, f"{{{DML_NS}}}solidFill")
+ run_properties = ET.Element(
+ _DML_RUN_PROPERTIES,
+ {
+ "lang": spec.language,
+ "sz": str(spec.font_size_hpt),
+ "dirty": "0",
+ },
+ )
+ solid_fill = ET.SubElement(run_properties, f"{{{DML_NS}}}solidFill")
+ ET.SubElement(
+ solid_fill,
+ f"{{{DML_NS}}}srgbClr",
+ {"val": spec.color},
+ )
+ for tag in ("latin", "ea", "cs"):
ET.SubElement(
- solid_fill,
- f"{{{DML_NS}}}srgbClr",
- {"val": spec.color},
+ run_properties,
+ f"{{{DML_NS}}}{tag}",
+ {"typeface": "Cambria Math"},
)
- for tag in ("latin", "ea", "cs"):
- ET.SubElement(
- run_properties,
- f"{{{DML_NS}}}{tag}",
- {"typeface": "Cambria Math"},
- )
- insert_at = 0
- if len(run) and run[0].tag == _MATH_RUN_PROPERTIES:
- insert_at = 1
- run.insert(insert_at, run_properties)
+ for run in root.iter(_MATH_RUN):
+ merge_formula_run_properties(run, run_properties)
+ merge_formula_control_properties(root, run_properties)
- return ET.tostring(root, encoding="unicode", short_empty_elements=True)
+ return serialize_styled_formula_omml(root)
def build_native_formula(
diff --git a/skills/ppt-master/scripts/svg_to_pptx/native_objects/formula_ast.py b/skills/ppt-master/scripts/svg_to_pptx/native_objects/formula_ast.py
new file mode 100644
index 00000000..863773a5
--- /dev/null
+++ b/skills/ppt-master/scripts/svg_to_pptx/native_objects/formula_ast.py
@@ -0,0 +1,356 @@
+#!/usr/bin/env python3
+"""
+PPT Master - Native Formula Abstract Syntax Tree
+
+Define the internal math nodes shared by the Microsoft 365 LaTeX parser,
+chemistry parser, and OMML emitter.
+
+See references/native-formula.md for the owning authoring contract.
+
+Usage:
+ Imported by native formula compiler modules.
+
+Examples:
+ expression = Sequence((Text("x"),))
+
+Dependencies:
+ None (only uses standard library)
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+
+
+@dataclass(frozen=True)
+class RunStyle:
+ style: str | None = None
+ normal: bool | None = None
+ script: str | None = None
+ color: str | None = None
+ bold: bool | None = None
+ italic: bool | None = None
+ typeface: str | None = None
+ is_default: bool = False
+
+
+@dataclass(frozen=True)
+class Text:
+ value: str
+ style: RunStyle | None = None
+ literal: bool = False
+
+
+@dataclass(frozen=True)
+class Sequence:
+ children: tuple[Node, ...]
+
+
+@dataclass(frozen=True)
+class Styled:
+ body: Sequence
+ style: RunStyle
+
+
+@dataclass(frozen=True)
+class Fraction:
+ numerator: Sequence
+ denominator: Sequence
+ kind: str = "bar"
+
+
+@dataclass(frozen=True)
+class Radical:
+ body: Sequence
+ degree: Sequence | None = None
+
+
+@dataclass(frozen=True)
+class Script:
+ base: Node
+ subscript: Sequence | None = None
+ superscript: Sequence | None = None
+
+
+@dataclass(frozen=True)
+class Prescript:
+ base: Node
+ subscript: Sequence | None = None
+ superscript: Sequence | None = None
+
+
+@dataclass(frozen=True)
+class Nary:
+ symbol: str
+ category: str
+ subscript: Sequence | None = None
+ superscript: Sequence | None = None
+ body: Sequence | None = None
+ limit_modifier: str | None = None
+
+
+@dataclass(frozen=True)
+class Delimiter:
+ left: str
+ right: str
+ segments: tuple[Sequence, ...]
+ separator: str = ""
+
+
+@dataclass(frozen=True)
+class Matrix:
+ environment: str
+ rows: tuple[tuple[Sequence, ...], ...]
+ column_alignments: tuple[str, ...] = ()
+
+
+@dataclass(frozen=True)
+class AlignmentPoint:
+ pass
+
+
+@dataclass(frozen=True)
+class EquationArray:
+ rows: tuple[Sequence, ...]
+
+
+@dataclass(frozen=True)
+class Accent:
+ character: str
+ body: Sequence
+
+
+@dataclass(frozen=True)
+class Bar:
+ position: str
+ body: Sequence
+
+
+@dataclass(frozen=True)
+class GroupChar:
+ character: str
+ position: str
+ vertical_justification: str
+ body: Sequence
+
+
+@dataclass(frozen=True)
+class Limit:
+ base: Node
+ lower: Sequence | None = None
+ upper: Sequence | None = None
+
+
+@dataclass(frozen=True)
+class Function:
+ name: Sequence
+ body: Sequence | None = None
+ subscript: Sequence | None = None
+ superscript: Sequence | None = None
+ limit_style: bool = False
+ limit_modifier: str | None = None
+
+
+@dataclass(frozen=True)
+class OperatorEmulator:
+ body: Sequence
+
+
+@dataclass(frozen=True)
+class Phantom:
+ body: Sequence
+ kind: str
+
+
+@dataclass(frozen=True)
+class BorderBox:
+ body: Sequence
+ kind: str
+
+
+Node = (
+ Text
+ | Sequence
+ | Styled
+ | Fraction
+ | Radical
+ | Script
+ | Prescript
+ | Nary
+ | Delimiter
+ | Matrix
+ | AlignmentPoint
+ | EquationArray
+ | Accent
+ | Bar
+ | GroupChar
+ | Limit
+ | Function
+ | OperatorEmulator
+ | Phantom
+ | BorderBox
+)
+
+
+def merge_run_styles(base: RunStyle | None, override: RunStyle | None) -> RunStyle | None:
+ """Merge inherited and local run style without clearing unrelated fields."""
+ if base is None:
+ return override
+ if override is None:
+ return base
+ if override.is_default:
+ return RunStyle(
+ style=base.style if base.style is not None else override.style,
+ normal=base.normal if base.normal is not None else override.normal,
+ script=base.script if base.script is not None else override.script,
+ color=base.color if base.color is not None else override.color,
+ bold=base.bold if base.bold is not None else override.bold,
+ italic=base.italic if base.italic is not None else override.italic,
+ typeface=(
+ base.typeface
+ if base.typeface is not None
+ else override.typeface
+ ),
+ is_default=base.is_default,
+ )
+ return RunStyle(
+ style=override.style if override.style is not None else base.style,
+ normal=override.normal if override.normal is not None else base.normal,
+ script=override.script if override.script is not None else base.script,
+ color=override.color if override.color is not None else base.color,
+ bold=override.bold if override.bold is not None else base.bold,
+ italic=override.italic if override.italic is not None else base.italic,
+ typeface=(
+ override.typeface
+ if override.typeface is not None
+ else base.typeface
+ ),
+ is_default=override.is_default,
+ )
+
+
+def append_child(children: list[Node], node: Node) -> None:
+ """Append one node while coalescing adjacent text with equal style."""
+ if isinstance(node, Sequence) and not node.children:
+ return
+ if (
+ isinstance(node, Text)
+ and children
+ and isinstance(children[-1], Text)
+ and children[-1].style == node.style
+ and children[-1].literal == node.literal
+ ):
+ previous = children[-1]
+ children[-1] = Text(
+ previous.value + node.value,
+ node.style,
+ literal=node.literal,
+ )
+ return
+ children.append(node)
+
+
+def is_empty(node: Node) -> bool:
+ """Return whether a node contains no visible or structural content."""
+ if isinstance(node, Text):
+ return not node.value
+ if isinstance(node, Sequence):
+ return not node.children or all(is_empty(child) for child in node.children)
+ if isinstance(node, Styled):
+ return is_empty(node.body)
+ return False
+
+
+def formula_node_count(root: Node, *, maximum: int) -> int:
+ """Return iterative AST size and reject formulas above the supplied limit."""
+ pending: list[Node] = [root]
+ count = 0
+ while pending:
+ node = pending.pop()
+ count += 1
+ if count > maximum:
+ raise ValueError(f"Formula exceeds the {maximum}-node complexity limit")
+ if isinstance(node, Sequence):
+ pending.extend(reversed(node.children))
+ elif isinstance(node, Styled):
+ pending.append(node.body)
+ elif isinstance(node, Fraction):
+ pending.extend((node.denominator, node.numerator))
+ elif isinstance(node, Radical):
+ pending.append(node.body)
+ if node.degree is not None:
+ pending.append(node.degree)
+ elif isinstance(node, (Script, Prescript)):
+ pending.append(node.base)
+ if node.subscript is not None:
+ pending.append(node.subscript)
+ if node.superscript is not None:
+ pending.append(node.superscript)
+ elif isinstance(node, Nary):
+ if node.subscript is not None:
+ pending.append(node.subscript)
+ if node.superscript is not None:
+ pending.append(node.superscript)
+ if node.body is not None:
+ pending.append(node.body)
+ elif isinstance(node, Delimiter):
+ pending.extend(reversed(node.segments))
+ elif isinstance(node, Matrix):
+ for row in reversed(node.rows):
+ pending.extend(reversed(row))
+ elif isinstance(node, EquationArray):
+ pending.extend(reversed(node.rows))
+ elif isinstance(node, (
+ Accent,
+ Bar,
+ GroupChar,
+ OperatorEmulator,
+ Phantom,
+ BorderBox,
+ )):
+ pending.append(node.body)
+ elif isinstance(node, Limit):
+ pending.append(node.base)
+ if node.lower is not None:
+ pending.append(node.lower)
+ if node.upper is not None:
+ pending.append(node.upper)
+ elif isinstance(node, Function):
+ pending.append(node.name)
+ if node.body is not None:
+ pending.append(node.body)
+ if node.subscript is not None:
+ pending.append(node.subscript)
+ if node.superscript is not None:
+ pending.append(node.superscript)
+ return count
+
+
+__all__ = [
+ "Accent",
+ "AlignmentPoint",
+ "Bar",
+ "BorderBox",
+ "Delimiter",
+ "EquationArray",
+ "Fraction",
+ "Function",
+ "GroupChar",
+ "Limit",
+ "Matrix",
+ "Nary",
+ "Node",
+ "OperatorEmulator",
+ "Phantom",
+ "Prescript",
+ "Radical",
+ "RunStyle",
+ "Script",
+ "Sequence",
+ "Styled",
+ "Text",
+ "append_child",
+ "formula_node_count",
+ "is_empty",
+ "merge_run_styles",
+]
diff --git a/skills/ppt-master/scripts/svg_to_pptx/native_objects/formula_compiler.py b/skills/ppt-master/scripts/svg_to_pptx/native_objects/formula_compiler.py
index d2a0589c..100ac250 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/native_objects/formula_compiler.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/native_objects/formula_compiler.py
@@ -2,7 +2,10 @@
r"""
PPT Master - Native Formula Compiler
-Compile a strict LaTeX subset into editable block or inline Office Math XML.
+Compile the documented Microsoft 365 LaTeX input profile into editable block
+or inline Office Math XML.
+
+See references/native-formula.md for the owning authoring contract.
Usage:
Import compile_latex_to_omml() or compile_latex_to_inline_omml() from the
@@ -12,1333 +15,48 @@ Examples:
compile_latex_to_omml(r"\frac{-b \pm \sqrt{b^2-4ac}}{2a}")
Dependencies:
- None (only uses standard library)
+ None (only uses standard library and local PPT Master modules)
"""
from __future__ import annotations
-import re
-from dataclasses import dataclass
-from xml.etree import ElementTree as ET
-
+from .formula_ast import formula_node_count
+from .formula_omml import emit_omml, validate_omml_fragment
+from .formula_parser import FormulaCompileError, parse_latex_formula
-MATH_NS = "http://schemas.openxmlformats.org/officeDocument/2006/math"
-DRAWING_NS = "http://schemas.openxmlformats.org/drawingml/2006/main"
-XML_NS = "http://www.w3.org/XML/1998/namespace"
_MAX_LATEX_LENGTH = 65_536
-_MAX_OMML_LENGTH = 1_048_576
-_MAX_PARSE_DEPTH = 128
-_MAX_OMML_DEPTH = 256
_MAX_AST_NODES = 100_000
-_FORBIDDEN_XML_RE = re.compile(r"<!\s*(?:DOCTYPE|ENTITY)\b", re.IGNORECASE)
-_LATEX_COMMAND_RE = re.compile(r"\\[A-Za-z]+")
-_ENVIRONMENT_NAME_RE = re.compile(r"[A-Za-z]+")
-_MATH_ELEMENTS = frozenset({
- "acc",
- "accPr",
- "baseJc",
- "begChr",
- "chr",
- "count",
- "d",
- "deg",
- "degHide",
- "den",
- "dPr",
- "e",
- "endChr",
- "f",
- "fPr",
- "grow",
- "jc",
- "limLoc",
- "m",
- "mc",
- "mcJc",
- "mcPr",
- "mcs",
- "mPr",
- "mr",
- "nary",
- "naryPr",
- "nor",
- "num",
- "oMath",
- "oMathPara",
- "oMathParaPr",
- "plcHide",
- "r",
- "rad",
- "radPr",
- "rPr",
- "scr",
- "sepChr",
- "sSub",
- "sSubSup",
- "sSup",
- "sty",
- "sub",
- "subHide",
- "sup",
- "supHide",
- "t",
- "type",
-})
-_DRAWING_ELEMENTS = frozenset({"cs", "ea", "latin", "rPr", "solidFill", "srgbClr"})
-_MATH_VALUE_ATTRIBUTES = frozenset({"val"})
-_DRAWING_ATTRIBUTES = frozenset({"dirty", "lang", "sz", "typeface", "val"})
-
-_GREEK_SYMBOLS = {
- "alpha": "α",
- "beta": "β",
- "gamma": "γ",
- "delta": "δ",
- "epsilon": "ε",
- "varepsilon": "ϵ",
- "zeta": "ζ",
- "eta": "η",
- "theta": "θ",
- "vartheta": "ϑ",
- "iota": "ι",
- "kappa": "κ",
- "lambda": "λ",
- "mu": "μ",
- "nu": "ν",
- "xi": "ξ",
- "omicron": "ο",
- "pi": "π",
- "varpi": "ϖ",
- "rho": "ρ",
- "varrho": "ϱ",
- "sigma": "σ",
- "varsigma": "ς",
- "tau": "τ",
- "upsilon": "υ",
- "phi": "φ",
- "varphi": "ϕ",
- "chi": "χ",
- "psi": "ψ",
- "omega": "ω",
- "Gamma": "Γ",
- "Delta": "Δ",
- "Theta": "Θ",
- "Lambda": "Λ",
- "Xi": "Ξ",
- "Pi": "Π",
- "Sigma": "Σ",
- "Upsilon": "Υ",
- "Phi": "Φ",
- "Psi": "Ψ",
- "Omega": "Ω",
-}
-
-_UPRIGHT_SYMBOLS = {
- "times": "×",
- "cdot": "·",
- "div": "÷",
- "pm": "±",
- "mp": "∓",
- "le": "≤",
- "leq": "≤",
- "ge": "≥",
- "geq": "≥",
- "ne": "≠",
- "neq": "≠",
- "ll": "≪",
- "gg": "≫",
- "approx": "≈",
- "equiv": "≡",
- "sim": "∼",
- "simeq": "≃",
- "propto": "∝",
- "in": "∈",
- "notin": "∉",
- "ni": "∋",
- "subset": "⊂",
- "supset": "⊃",
- "subseteq": "⊆",
- "supseteq": "⊇",
- "cup": "∪",
- "cap": "∩",
- "setminus": "∖",
- "emptyset": "∅",
- "to": "→",
- "rightarrow": "→",
- "leftarrow": "←",
- "leftrightarrow": "↔",
- "Rightarrow": "⇒",
- "Leftarrow": "⇐",
- "Leftrightarrow": "⇔",
- "infty": "∞",
- "partial": "∂",
- "nabla": "∇",
- "ell": "ℓ",
- "ldots": "…",
- "cdots": "⋯",
- "forall": "∀",
- "exists": "∃",
- "land": "∧",
- "lor": "∨",
- "neg": "¬",
- "angle": "∠",
- "perp": "⊥",
- "parallel": "∥",
- "degree": "°",
-}
-
-_NAMED_OPERATORS = frozenset({
- "arccos",
- "arcsin",
- "arctan",
- "cos",
- "cosh",
- "cot",
- "coth",
- "csc",
- "det",
- "exp",
- "gcd",
- "inf",
- "lim",
- "ln",
- "log",
- "max",
- "min",
- "sec",
- "sin",
- "sinh",
- "sup",
- "tan",
- "tanh",
-})
-
-_NARY_SYMBOLS = {
- "sum": ("∑", "undOvr"),
- "prod": ("∏", "undOvr"),
- "int": ("∫", "subSup"),
-}
-
-_NARY_BODY_STOP_COMMANDS = frozenset({
- "Rightarrow",
- "Leftarrow",
- "Leftrightarrow",
- "approx",
- "cap",
- "cdot",
- "cup",
- "div",
- "equiv",
- "ge",
- "geq",
- "gg",
- "in",
- "land",
- "le",
- "leq",
- "leftarrow",
- "leftrightarrow",
- "ll",
- "lor",
- "mp",
- "ne",
- "neq",
- "ni",
- "notin",
- "parallel",
- "perp",
- "pm",
- "propto",
- "rightarrow",
- "setminus",
- "sim",
- "simeq",
- "subset",
- "subseteq",
- "supset",
- "supseteq",
- "times",
- "to",
-})
-
-_DELIMITER_COMMANDS = {
- "lbrace": "{",
- "rbrace": "}",
- "langle": "⟨",
- "rangle": "⟩",
- "lfloor": "⌊",
- "rfloor": "⌋",
- "lceil": "⌈",
- "rceil": "⌉",
- "vert": "|",
- "Vert": "‖",
-}
-
-_ENVIRONMENT_DELIMITERS = {
- "matrix": None,
- "pmatrix": ("(", ")"),
- "bmatrix": ("[", "]"),
- "vmatrix": ("|", "|"),
- "Vmatrix": ("‖", "‖"),
- "cases": ("{", ""),
- "aligned": None,
-}
-
-_ACCENT_COMMANDS = {
- "bar": "‾",
- "hat": "̂",
- "overline": "‾",
- "vec": "⃗",
-}
-
-
-class FormulaCompileError(ValueError):
- """Raised when formula source or OMML violates the supported contract."""
-
-
-@dataclass(frozen=True)
-class _RunStyle:
- style: str | None = None
- normal: bool = False
- script: str | None = None
-
-
-@dataclass(frozen=True)
-class _Text:
- value: str
- style: _RunStyle | None = None
-
-
-@dataclass(frozen=True)
-class _Sequence:
- children: tuple[_Node, ...]
-
-
-@dataclass(frozen=True)
-class _Styled:
- body: _Sequence
- style: _RunStyle
-
-
-@dataclass(frozen=True)
-class _Fraction:
- numerator: _Sequence
- denominator: _Sequence
-
-
-@dataclass(frozen=True)
-class _Radical:
- body: _Sequence
- degree: _Sequence | None = None
-
-
-@dataclass(frozen=True)
-class _Script:
- base: _Node
- subscript: _Sequence | None = None
- superscript: _Sequence | None = None
-
-
-@dataclass(frozen=True)
-class _Nary:
- symbol: str
- limit_location: str
- subscript: _Sequence | None = None
- superscript: _Sequence | None = None
- body: _Sequence | None = None
- limit_modifier: str | None = None
-
-
-@dataclass(frozen=True)
-class _Delimiter:
- left: str
- right: str
- body: _Sequence
-
-
-@dataclass(frozen=True)
-class _Matrix:
- environment: str
- rows: tuple[tuple[_Sequence, ...], ...]
-
-
-@dataclass(frozen=True)
-class _Accent:
- character: str
- body: _Sequence
-
-
-_Node = (
- _Text
- | _Sequence
- | _Styled
- | _Fraction
- | _Radical
- | _Script
- | _Nary
- | _Delimiter
- | _Matrix
- | _Accent
-)
-
-_ROMAN_STYLE = _RunStyle(style="p")
-_TEXT_STYLE = _RunStyle(style="p", normal=True)
-_SPACING_STYLE = _RunStyle()
-_PLAIN_OPERATOR_CHARS = frozenset("+−*/=<>±∓×÷·,;:!?")
-_SPACING_COMMANDS = {
- ",": "\u2009",
- ":": "\u2005",
- ";": "\u2004",
- "!": "\u200b",
- " ": "\u2005",
-}
-
-
-class _LatexParser:
- """Parse the intentionally small formula-source grammar."""
-
- def __init__(self, source: str) -> None:
- self.source = source
- self.position = 0
- self.depth = 0
- self.text_mode_depth = 0
-
- def parse(self) -> _Sequence:
- result = self._parse_sequence()
- if self.position != len(self.source):
- self._fail("Unexpected trailing formula source")
- if _is_empty(result):
- self._fail("Formula is empty")
- return result
-
- def _parse_sequence(
- self,
- *,
- terminator: str | None = None,
- stop_at_right: bool = False,
- stop_at_environment_boundary: bool = False,
- ) -> _Sequence:
- children: list[_Node] = []
- while self.position < len(self.source):
- if terminator is not None and self.source[self.position] == terminator:
- self.position += 1
- return _Sequence(tuple(children))
- if stop_at_right and self._at_control_word("right"):
- return _Sequence(tuple(children))
- if stop_at_environment_boundary and (
- self.source[self.position] == "&"
- or self.source.startswith("\\\\", self.position)
- or self._at_control_word("end")
- ):
- return _Sequence(tuple(children))
-
- char = self.source[self.position]
- if char == "}":
- self._fail("Unexpected closing group")
- if char in "^_":
- self._fail(f"Script marker {char!r} has no base")
- if char == "&":
- self._fail("Alignment marker '&' is only valid inside a matrix environment")
-
- atom = self._parse_complete_atom()
- _append_child(children, atom)
-
- if terminator is not None:
- self._fail(f"Unclosed group; expected {terminator!r}")
- if stop_at_right:
- self._fail("Unclosed delimiter; expected \\right")
- if stop_at_environment_boundary:
- self._fail("Unclosed matrix environment")
- return _Sequence(tuple(children))
-
- def _parse_atom(self) -> _Node:
- char = self.source[self.position]
- if char.isspace():
- while (
- self.position < len(self.source)
- and self.source[self.position].isspace()
- ):
- self.position += 1
- return (
- _Text(" ", _TEXT_STYLE)
- if self.text_mode_depth
- else _Sequence(())
- )
- if char == "{":
- return self._parse_group()
- if char == "\\":
- return self._parse_command()
- if char in "$#%":
- self._fail(f"Unsupported TeX syntax character {char!r}")
- if ord(char) < 32:
- self._fail("Unsupported control character")
-
- self.position += 1
- if char == "-":
- char = "−"
- elif char == "~":
- return _Text("\u2005", _SPACING_STYLE)
- style = _ROMAN_STYLE if char in _PLAIN_OPERATOR_CHARS else None
- return _Text(char, style)
-
- def _parse_command(self) -> _Node:
- command_start = self.position
- self.position += 1
- if self.position >= len(self.source):
- self._fail("Trailing backslash", position=command_start)
-
- char = self.source[self.position]
- if not _is_command_letter(char):
- self.position += 1
- if char == "\\":
- self._fail(
- "Row separator '\\\\' is only valid inside a matrix environment",
- position=command_start,
- )
- escaped = {
- "{": "{",
- "}": "}",
- "_": "_",
- "%": "%",
- "#": "#",
- "$": "$",
- "&": "&",
- "|": "‖",
- }
- if char in escaped:
- return _Text(escaped[char])
- if char in _SPACING_COMMANDS:
- return _Text(_SPACING_COMMANDS[char], _SPACING_STYLE)
- self._fail(f"Unsupported control symbol \\{char}", position=command_start)
-
- command = self._read_control_word_body()
- self._skip_whitespace()
-
- if command in _GREEK_SYMBOLS:
- return _Text(_GREEK_SYMBOLS[command])
- if command in _UPRIGHT_SYMBOLS:
- return _Text(_UPRIGHT_SYMBOLS[command], _ROMAN_STYLE)
- if command in _NAMED_OPERATORS:
- return _Text(command, _ROMAN_STYLE)
- if command in _DELIMITER_COMMANDS:
- return _Text(_DELIMITER_COMMANDS[command], _ROMAN_STYLE)
- if command in _NARY_SYMBOLS:
- symbol, limit_location = _NARY_SYMBOLS[command]
- return _Nary(symbol=symbol, limit_location=limit_location)
- if command == "frac":
- numerator = self._parse_required_group("fraction numerator")
- denominator = self._parse_required_group("fraction denominator")
- return _Fraction(numerator=numerator, denominator=denominator)
- if command == "sqrt":
- degree = self._parse_optional_degree()
- body = self._parse_required_group("radical body")
- return _Radical(body=body, degree=degree)
- if command == "left":
- return self._parse_delimited_expression()
- if command == "right":
- self._fail("Unexpected \\right without matching \\left", position=command_start)
- if command == "begin":
- return self._parse_environment()
- if command == "end":
- self._fail("Unexpected \\end without matching \\begin", position=command_start)
- if command in {"text", "mathrm", "mathbf", "mathit", "mathbb", "mathcal"}:
- styles = {
- "text": _TEXT_STYLE,
- "mathrm": _ROMAN_STYLE,
- "mathbf": _RunStyle(style="b"),
- "mathit": _RunStyle(style="i"),
- "mathbb": _RunStyle(style="p", script="double-struck"),
- "mathcal": _RunStyle(style="p", script="script"),
- }
- if command == "text":
- self.text_mode_depth += 1
- try:
- body = self._parse_required_group(f"\\{command} body")
- finally:
- if command == "text":
- self.text_mode_depth -= 1
- return _Styled(body=body, style=styles[command])
- if command in _ACCENT_COMMANDS:
- body = self._parse_required_group(f"\\{command} body")
- return _Accent(character=_ACCENT_COMMANDS[command], body=body)
- if command == "quad":
- return _Text("\u2001", _SPACING_STYLE)
- if command == "qquad":
- return _Text("\u2001\u2001", _SPACING_STYLE)
-
- self._fail(f"Unsupported LaTeX command \\{command}", position=command_start)
-
- def _parse_group(self) -> _Sequence:
- self.position += 1
- return self._parse_nested_sequence(terminator="}")
-
- def _parse_required_group(self, description: str) -> _Sequence:
- self._skip_whitespace()
- if self.position >= len(self.source) or self.source[self.position] != "{":
- self._fail(f"{description.capitalize()} must use a braced group")
- result = self._parse_group()
- if _is_empty(result):
- self._fail(f"{description.capitalize()} cannot be empty")
- return result
-
- def _parse_optional_degree(self) -> _Sequence | None:
- if self.position >= len(self.source) or self.source[self.position] != "[":
- return None
- self.position += 1
- result = self._parse_nested_sequence(terminator="]")
- if _is_empty(result):
- self._fail("Radical degree cannot be empty")
- return result
-
- def _parse_nested_sequence(self, **kwargs: object) -> _Sequence:
- self.depth += 1
- if self.depth > _MAX_PARSE_DEPTH:
- self._fail(f"Formula nesting exceeds {_MAX_PARSE_DEPTH} levels")
- try:
- return self._parse_sequence(**kwargs)
- finally:
- self.depth -= 1
-
- def _parse_scripts(self, base: _Node) -> _Node:
- subscript: _Sequence | None = None
- superscript: _Sequence | None = None
- while True:
- saved_position = self.position
- self._skip_whitespace()
- if (
- self.position >= len(self.source)
- or self.source[self.position] not in "^_"
- ):
- self.position = saved_position
- break
-
- marker = self.source[self.position]
- self.position += 1
- self._skip_whitespace()
- argument = self._parse_script_argument(marker)
- if marker == "_":
- if subscript is not None:
- self._fail("Duplicate subscript for one base")
- subscript = argument
- else:
- if superscript is not None:
- self._fail("Duplicate superscript for one base")
- superscript = argument
-
- if subscript is None and superscript is None:
- return base
- if isinstance(base, _Nary):
- return _Nary(
- symbol=base.symbol,
- limit_location=base.limit_location,
- subscript=subscript,
- superscript=superscript,
- body=base.body,
- limit_modifier=base.limit_modifier,
- )
- return _Script(base=base, subscript=subscript, superscript=superscript)
-
- def _parse_complete_atom(self) -> _Node:
- atom = self._parse_atom()
- if isinstance(atom, _Nary):
- atom = self._parse_nary_limit_modifier(atom)
- atom = self._parse_scripts(atom)
- if isinstance(atom, _Nary):
- atom = self._parse_nary_limit_modifier(atom)
- atom = self._parse_nary_body(atom)
- return atom
-
- def _parse_nary_limit_modifier(self, node: _Nary) -> _Nary:
- saved_position = self.position
- self._skip_whitespace()
- if self._at_control_word("limits"):
- limit_location = "undOvr"
- command = "limits"
- elif self._at_control_word("nolimits"):
- limit_location = "subSup"
- command = "nolimits"
- else:
- self.position = saved_position
- return node
-
- if node.limit_modifier is not None:
- self._fail("N-ary operator has more than one limit modifier")
- self._consume_control_word(command)
- return _Nary(
- symbol=node.symbol,
- limit_location=limit_location,
- subscript=node.subscript,
- superscript=node.superscript,
- body=node.body,
- limit_modifier=command,
- )
-
- def _parse_nary_body(self, node: _Nary) -> _Nary:
- saved_position = self.position
- spacing = self._parse_nary_spacing()
- if not self._nary_body_follows():
- self.position = saved_position
- return node
-
- if self.source[self.position] == "{":
- operand = self._parse_group()
- else:
- operand = _Sequence((self._parse_nested_atom(),))
- body = _Sequence((*spacing, *operand.children))
- if _is_empty(body):
- self._fail("N-ary operator body cannot be empty")
- return _Nary(
- symbol=node.symbol,
- limit_location=node.limit_location,
- subscript=node.subscript,
- superscript=node.superscript,
- body=body,
- limit_modifier=node.limit_modifier,
- )
-
- def _parse_nested_atom(self) -> _Node:
- """Parse one recursively owned atom under the shared depth limit."""
- self.depth += 1
- if self.depth > _MAX_PARSE_DEPTH:
- self._fail(f"Formula nesting exceeds {_MAX_PARSE_DEPTH} levels")
- try:
- return self._parse_complete_atom()
- finally:
- self.depth -= 1
-
- def _parse_nary_spacing(self) -> tuple[_Node, ...]:
- """Consume spacing before a n-ary operand without losing explicit TeX."""
- spacing: list[_Node] = []
- while True:
- self._skip_whitespace()
- if self._at_control_word("quad"):
- self._consume_control_word("quad")
- spacing.append(_Text("\u2001", _SPACING_STYLE))
- continue
- if self._at_control_word("qquad"):
- self._consume_control_word("qquad")
- spacing.append(_Text("\u2001\u2001", _SPACING_STYLE))
- continue
- if (
- self.position + 1 < len(self.source)
- and self.source[self.position] == "\\"
- and self.source[self.position + 1] in {",", ";", ":", "!", " "}
- ):
- command = self.source[self.position + 1]
- self.position += 2
- spacing.append(_Text(_SPACING_COMMANDS[command], _SPACING_STYLE))
- continue
- return tuple(spacing)
-
- def _nary_body_follows(self) -> bool:
- if self.position >= len(self.source):
- return False
- if self.source.startswith("\\\\", self.position):
- return False
- char = self.source[self.position]
- if char in "}])&^_+-=<>/,;:!?":
- return False
- if char != "\\":
- return True
- if self._at_control_word("right") or self._at_control_word("end"):
- return False
- command_position = self.position + 1
- command_end = command_position
- while (
- command_end < len(self.source)
- and _is_command_letter(self.source[command_end])
- ):
- command_end += 1
- command = self.source[command_position:command_end]
- return command not in _NARY_BODY_STOP_COMMANDS
-
- def _parse_script_argument(self, marker: str) -> _Sequence:
- if self.position >= len(self.source):
- self._fail(f"Script marker {marker!r} has no argument")
- if self.source[self.position] == "{":
- result = self._parse_group()
- else:
- result = _Sequence((self._parse_atom(),))
- if _is_empty(result):
- self._fail(f"Script marker {marker!r} has an empty argument")
- return result
-
- def _parse_delimited_expression(self) -> _Delimiter:
- left = self._parse_delimiter_token("\\left")
- body = self._parse_nested_sequence(stop_at_right=True)
- self._consume_control_word("right")
- right = self._parse_delimiter_token("\\right")
- return _Delimiter(left=left, right=right, body=body)
-
- def _parse_delimiter_token(self, owner: str) -> str:
- self._skip_whitespace()
- if self.position >= len(self.source):
- self._fail(f"{owner} requires a delimiter")
-
- char = self.source[self.position]
- if char != "\\":
- self.position += 1
- if char in "()[]|.":
- return "" if char == "." else char
- self._fail(f"Unsupported delimiter {char!r} after {owner}")
-
- command_start = self.position
- self.position += 1
- if self.position >= len(self.source):
- self._fail(f"{owner} requires a delimiter", position=command_start)
- if not _is_command_letter(self.source[self.position]):
- delimiter = self.source[self.position]
- self.position += 1
- if delimiter in "{}|":
- return "‖" if delimiter == "|" else delimiter
- self._fail(f"Unsupported delimiter command \\{delimiter}", position=command_start)
- command = self._read_control_word_body()
- self._skip_whitespace()
- if command not in _DELIMITER_COMMANDS:
- self._fail(f"Unsupported delimiter command \\{command}", position=command_start)
- return _DELIMITER_COMMANDS[command]
- def _parse_environment(self) -> _Matrix:
- environment = self._parse_environment_name("\\begin")
- if environment not in _ENVIRONMENT_DELIMITERS:
- self._fail(f"Unsupported formula environment {environment!r}")
-
- rows: list[tuple[_Sequence, ...]] = []
- row: list[_Sequence] = []
- while True:
- cell = self._parse_nested_sequence(stop_at_environment_boundary=True)
- if _is_empty(cell):
- self._fail(f"Environment {environment!r} contains an empty cell")
- row.append(cell)
-
- if self.source[self.position] == "&":
- self.position += 1
- continue
- if self.source.startswith("\\\\", self.position):
- self.position += 2
- rows.append(tuple(row))
- row = []
- self._skip_whitespace()
- if self._at_control_word("end"):
- self._consume_environment_end(environment)
- break
- continue
- if self._at_control_word("end"):
- rows.append(tuple(row))
- self._consume_environment_end(environment)
- break
- self._fail(f"Malformed environment {environment!r}")
-
- column_count = len(rows[0])
- if any(len(current_row) != column_count for current_row in rows):
- self._fail(f"Environment {environment!r} has inconsistent column counts")
- return _Matrix(environment=environment, rows=tuple(rows))
-
- def _consume_environment_end(self, expected: str) -> None:
- self._consume_control_word("end")
- actual = self._parse_environment_name("\\end")
- if actual != expected:
- self._fail(
- f"Mismatched environment ending: expected {expected!r}, got {actual!r}"
- )
-
- def _parse_environment_name(self, owner: str) -> str:
- if self.position >= len(self.source) or self.source[self.position] != "{":
- self._fail(f"{owner} requires a braced environment name")
- closing = self.source.find("}", self.position + 1)
- if closing < 0:
- self._fail(f"Unclosed environment name after {owner}")
- name = self.source[self.position + 1 : closing]
- if not _ENVIRONMENT_NAME_RE.fullmatch(name):
- self._fail(f"Invalid environment name {name!r}")
- self.position = closing + 1
- return name
-
- def _at_control_word(self, expected: str) -> bool:
- prefix = f"\\{expected}"
- if not self.source.startswith(prefix, self.position):
- return False
- following = self.position + len(prefix)
- return (
- following >= len(self.source)
- or not _is_command_letter(self.source[following])
- )
-
- def _consume_control_word(self, expected: str) -> None:
- if not self._at_control_word(expected):
- self._fail(f"Expected \\{expected}")
- self.position += len(expected) + 1
- self._skip_whitespace()
-
- def _read_control_word_body(self) -> str:
- start = self.position
- while (
- self.position < len(self.source)
- and _is_command_letter(self.source[self.position])
- ):
- self.position += 1
- return self.source[start : self.position]
-
- def _skip_whitespace(self) -> None:
- while (
- self.position < len(self.source)
- and self.source[self.position].isspace()
- ):
- self.position += 1
-
- def _fail(self, message: str, *, position: int | None = None) -> None:
- offset = self.position if position is None else position
- start = max(0, offset - 12)
- end = min(len(self.source), offset + 12)
- context = self.source[start:end].replace("\n", " ")
- raise FormulaCompileError(f"{message} at offset {offset}: {context!r}")
-
-
-def _is_command_letter(char: str) -> bool:
- return char.isascii() and char.isalpha()
-
-
-def _xml_character_allowed(char: str) -> bool:
- codepoint = ord(char)
- return (
- codepoint in {0x09, 0x0A, 0x0D}
- or 0x20 <= codepoint <= 0xD7FF
- or 0xE000 <= codepoint <= 0xFFFD
- or 0x10000 <= codepoint <= 0x10FFFF
- )
-
-
-def _append_child(children: list[_Node], node: _Node) -> None:
- if isinstance(node, _Sequence) and not node.children:
- return
- if (
- isinstance(node, _Text)
- and children
- and isinstance(children[-1], _Text)
- and children[-1].style == node.style
- ):
- previous = children[-1]
- children[-1] = _Text(previous.value + node.value, node.style)
- return
- children.append(node)
-
-
-def _is_empty(node: _Node) -> bool:
- if isinstance(node, _Text):
- return not node.value
- if isinstance(node, _Sequence):
- return not node.children or all(_is_empty(child) for child in node.children)
- if isinstance(node, _Styled):
- return _is_empty(node.body)
- return False
-
-
-def _formula_node_count(root: _Node) -> int:
- """Return iterative AST size and reject impractically complex formulas."""
- pending: list[_Node] = [root]
- count = 0
- while pending:
- node = pending.pop()
- count += 1
- if count > _MAX_AST_NODES:
- raise FormulaCompileError(
- f"Formula exceeds the {_MAX_AST_NODES}-node complexity limit"
- )
- if isinstance(node, _Sequence):
- pending.extend(reversed(node.children))
- elif isinstance(node, _Styled):
- pending.append(node.body)
- elif isinstance(node, _Fraction):
- pending.extend((node.denominator, node.numerator))
- elif isinstance(node, _Radical):
- pending.append(node.body)
- if node.degree is not None:
- pending.append(node.degree)
- elif isinstance(node, _Script):
- pending.append(node.base)
- if node.subscript is not None:
- pending.append(node.subscript)
- if node.superscript is not None:
- pending.append(node.superscript)
- elif isinstance(node, _Nary):
- if node.subscript is not None:
- pending.append(node.subscript)
- if node.superscript is not None:
- pending.append(node.superscript)
- if node.body is not None:
- pending.append(node.body)
- elif isinstance(node, _Delimiter):
- pending.append(node.body)
- elif isinstance(node, _Matrix):
- for row in reversed(node.rows):
- pending.extend(reversed(row))
- elif isinstance(node, _Accent):
- pending.append(node.body)
- return count
-
-
-def _math_tag(local_name: str) -> str:
- return f"{{{MATH_NS}}}{local_name}"
-
-
-def _math_attrs(**values: str) -> dict[str, str]:
- return {_math_tag(name): value for name, value in values.items()}
-
-
-def _math_element(
- parent: ET.Element,
- local_name: str,
- **attributes: str,
-) -> ET.Element:
- return ET.SubElement(parent, _math_tag(local_name), _math_attrs(**attributes))
-
-
-def _append_run(parent: ET.Element, value: str, style: _RunStyle | None) -> None:
- if not value:
- return
- run = _math_element(parent, "r")
- if style is not None and (style.style or style.normal or style.script):
- properties = _math_element(run, "rPr")
- if style.normal:
- _math_element(properties, "nor", val="on")
- if style.style:
- _math_element(properties, "sty", val=style.style)
- if style.script:
- _math_element(properties, "scr", val=style.script)
- text = _math_element(run, "t")
- if value != value.strip() or " " in value:
- text.set(f"{{{XML_NS}}}space", "preserve")
- text.text = value
-
-
-def _append_node(
- parent: ET.Element,
- node: _Node,
- inherited_style: _RunStyle | None = None,
-) -> None:
- if isinstance(node, _Text):
- _append_run(parent, node.value, node.style or inherited_style)
- return
- if isinstance(node, _Sequence):
- for child in node.children:
- _append_node(parent, child, inherited_style)
- return
- if isinstance(node, _Styled):
- _append_node(parent, node.body, node.style)
- return
- if isinstance(node, _Fraction):
- fraction = _math_element(parent, "f")
- properties = _math_element(fraction, "fPr")
- _math_element(properties, "type", val="bar")
- numerator = _math_element(fraction, "num")
- _append_node(numerator, node.numerator, inherited_style)
- denominator = _math_element(fraction, "den")
- _append_node(denominator, node.denominator, inherited_style)
- return
- if isinstance(node, _Radical):
- radical = _math_element(parent, "rad")
- properties = _math_element(radical, "radPr")
- _math_element(properties, "degHide", val="off" if node.degree else "on")
- degree = _math_element(radical, "deg")
- if node.degree is not None:
- _append_node(degree, node.degree, inherited_style)
- body = _math_element(radical, "e")
- _append_node(body, node.body, inherited_style)
- return
- if isinstance(node, _Script):
- _append_script(parent, node, inherited_style)
- return
- if isinstance(node, _Nary):
- _append_nary(parent, node, inherited_style)
- return
- if isinstance(node, _Delimiter):
- delimiter = _math_element(parent, "d")
- properties = _math_element(delimiter, "dPr")
- _math_element(properties, "begChr", val=node.left)
- _math_element(properties, "endChr", val=node.right)
- _math_element(properties, "sepChr", val="")
- _math_element(properties, "grow")
- body = _math_element(delimiter, "e")
- _append_node(body, node.body, inherited_style)
- return
- if isinstance(node, _Matrix):
- _append_matrix(parent, node, inherited_style)
- return
- if isinstance(node, _Accent):
- accent = _math_element(parent, "acc")
- properties = _math_element(accent, "accPr")
- _math_element(properties, "chr", val=node.character)
- body = _math_element(accent, "e")
- _append_node(body, node.body, inherited_style)
- return
- raise FormulaCompileError(f"Unsupported internal formula node: {type(node).__name__}")
-
-
-def _append_script(
- parent: ET.Element,
- node: _Script,
- inherited_style: _RunStyle | None,
-) -> None:
- if node.subscript is not None and node.superscript is not None:
- script = _math_element(parent, "sSubSup")
- elif node.subscript is not None:
- script = _math_element(parent, "sSub")
- else:
- script = _math_element(parent, "sSup")
-
- base = _math_element(script, "e")
- _append_node(base, node.base, inherited_style)
- if node.subscript is not None:
- subscript = _math_element(script, "sub")
- _append_node(subscript, node.subscript, inherited_style)
- if node.superscript is not None:
- superscript = _math_element(script, "sup")
- _append_node(superscript, node.superscript, inherited_style)
-
-
-def _append_nary(
- parent: ET.Element,
- node: _Nary,
- inherited_style: _RunStyle | None,
-) -> None:
- nary = _math_element(parent, "nary")
- properties = _math_element(nary, "naryPr")
- _math_element(properties, "chr", val=node.symbol)
- _math_element(properties, "limLoc", val=node.limit_location)
- _math_element(properties, "subHide", val="off" if node.subscript else "on")
- _math_element(properties, "supHide", val="off" if node.superscript else "on")
-
- subscript = _math_element(nary, "sub")
- if node.subscript is not None:
- _append_node(subscript, node.subscript, inherited_style)
- superscript = _math_element(nary, "sup")
- if node.superscript is not None:
- _append_node(superscript, node.superscript, inherited_style)
- body = _math_element(nary, "e")
- if node.body is not None:
- _append_node(body, node.body, inherited_style)
-
-
-def _append_matrix(
- parent: ET.Element,
- node: _Matrix,
- inherited_style: _RunStyle | None,
-) -> None:
- delimiters = _ENVIRONMENT_DELIMITERS[node.environment]
- matrix_parent = parent
- if delimiters is not None:
- delimiter = _math_element(parent, "d")
- properties = _math_element(delimiter, "dPr")
- _math_element(properties, "begChr", val=delimiters[0])
- _math_element(properties, "endChr", val=delimiters[1])
- _math_element(properties, "sepChr", val="")
- _math_element(properties, "grow")
- matrix_parent = _math_element(delimiter, "e")
-
- matrix = _math_element(matrix_parent, "m")
- properties = _math_element(matrix, "mPr")
- _math_element(properties, "baseJc", val="center")
- _math_element(properties, "plcHide", val="on")
- columns = _math_element(properties, "mcs")
- for index in range(len(node.rows[0])):
- column = _math_element(columns, "mc")
- column_properties = _math_element(column, "mcPr")
- justification = "center"
- if node.environment == "cases":
- justification = "left"
- elif node.environment == "aligned":
- justification = "right" if index % 2 == 0 else "left"
- _math_element(column_properties, "mcJc", val=justification)
- _math_element(column_properties, "count", val="1")
-
- for row_data in node.rows:
- row = _math_element(matrix, "mr")
- for cell_data in row_data:
- cell = _math_element(row, "e")
- _append_node(cell, cell_data, inherited_style)
-
-
-def _qualified_name(name: str) -> tuple[str | None, str]:
- if name.startswith("{") and "}" in name:
- namespace, local_name = name[1:].split("}", 1)
- return namespace, local_name
- return None, name
-
-
-def _validate_xml_tree(root: ET.Element) -> None:
- namespace, local_name = _qualified_name(root.tag)
- if namespace != MATH_NS or local_name not in {"oMathPara", "oMath"}:
- raise FormulaCompileError("OMML root must be m:oMathPara or m:oMath")
-
- math_roots = 0
- visible_text: list[str] = []
- pending: list[tuple[ET.Element, int]] = [(root, 1)]
- while pending:
- element, depth = pending.pop()
- if depth > _MAX_OMML_DEPTH:
- raise FormulaCompileError(
- f"OMML nesting exceeds {_MAX_OMML_DEPTH} levels"
- )
- pending.extend((child, depth + 1) for child in reversed(element))
- element_namespace, element_name = _qualified_name(element.tag)
- if (
- element_namespace == MATH_NS
- and element_name not in _MATH_ELEMENTS
- ):
- raise FormulaCompileError(
- f"OMML contains unsupported math element: {element_name!r}"
- )
- if (
- element_namespace == DRAWING_NS
- and element_name not in _DRAWING_ELEMENTS
- ):
- raise FormulaCompileError(
- f"OMML contains unsupported DrawingML element: {element_name!r}"
- )
- if element_namespace not in {MATH_NS, DRAWING_NS}:
- raise FormulaCompileError(
- f"OMML contains unsupported element namespace: {element_namespace!r}"
- )
- if element_namespace == MATH_NS and element_name in {"oMathPara", "oMath"}:
- math_roots += 1
- for attribute in element.attrib:
- attribute_namespace, attribute_name = _qualified_name(attribute)
- if (
- attribute_namespace == MATH_NS
- and attribute_name in _MATH_VALUE_ATTRIBUTES
- ):
- continue
- if (
- attribute_namespace in {None, DRAWING_NS}
- and element_namespace == DRAWING_NS
- and attribute_name in _DRAWING_ATTRIBUTES
- ):
- continue
- if (
- attribute_namespace == XML_NS
- and element_namespace == MATH_NS
- and element_name == "t"
- and attribute_name == "space"
- and element.attrib[attribute] == "preserve"
- ):
- continue
- if attribute_namespace is not None or attribute_name:
- raise FormulaCompileError(
- f"OMML contains unsupported attribute {attribute_name!r}"
- )
- if element.text:
- if element_namespace == MATH_NS and element_name == "t":
- visible_text.append(element.text)
- elif element.text.strip():
- raise FormulaCompileError(
- f"OMML text is only allowed inside m:t, found in {element_name!r}"
- )
- if element.tail and element.tail.strip():
- raise FormulaCompileError("OMML contains unexpected trailing text")
-
- expected_roots = 2 if local_name == "oMathPara" else 1
- if math_roots != expected_roots:
- raise FormulaCompileError("OMML must contain exactly one math expression")
- if _LATEX_COMMAND_RE.search("".join(visible_text)):
- raise FormulaCompileError("OMML contains an uncompiled LaTeX command")
-
- if local_name == "oMathPara":
- direct_expressions = [
- child
- for child in root
- if _qualified_name(child.tag) == (MATH_NS, "oMath")
- ]
- if len(direct_expressions) != 1:
- raise FormulaCompileError(
- "m:oMathPara must contain exactly one direct m:oMath expression"
- )
-
-
-def validate_omml_fragment(xml: str) -> str:
- """Validate the supported Office Math subset and canonicalize prefixes."""
- if not isinstance(xml, str):
- raise FormulaCompileError("OMML fragment must be a string")
- if not xml.strip():
- raise FormulaCompileError("OMML fragment is empty")
- if len(xml) > _MAX_OMML_LENGTH:
+def _compile(latex: str, *, display: bool) -> str:
+ if not isinstance(latex, str):
+ raise FormulaCompileError("LaTeX formula must be a string")
+ if len(latex) > _MAX_LATEX_LENGTH:
raise FormulaCompileError(
- f"OMML fragment exceeds the {_MAX_OMML_LENGTH}-character limit"
+ f"LaTeX formula exceeds the {_MAX_LATEX_LENGTH}-character limit"
)
- if _FORBIDDEN_XML_RE.search(xml):
- raise FormulaCompileError("DOCTYPE and ENTITY declarations are forbidden in OMML")
-
- try:
- root = ET.fromstring(xml)
- except (ET.ParseError, RecursionError) as exc:
- raise FormulaCompileError(f"Invalid OMML XML: {exc}") from exc
- _validate_xml_tree(root)
-
- ET.register_namespace("m", MATH_NS)
- ET.register_namespace("a", DRAWING_NS)
try:
- canonical = ET.tostring(
- root,
- encoding="unicode",
- short_empty_elements=True,
- )
+ expression = parse_latex_formula(latex, display=display)
+ try:
+ formula_node_count(expression, maximum=_MAX_AST_NODES)
+ except ValueError as exc:
+ raise FormulaCompileError(str(exc)) from exc
+ return emit_omml(expression, display=display)
except RecursionError as exc:
raise FormulaCompileError(
- "OMML nesting exceeds the XML serializer limit"
+ "Formula nesting exceeds the supported limit"
) from exc
- if len(canonical) > _MAX_OMML_LENGTH:
- raise FormulaCompileError(
- f"Canonical OMML exceeds the {_MAX_OMML_LENGTH}-character limit"
- )
- return canonical
def compile_latex_to_omml(latex: str) -> str:
"""Compile one standalone block formula into canonical m:oMathPara XML."""
- expression = _parse_latex_formula(latex)
-
- root = ET.Element(_math_tag("oMathPara"))
- properties = _math_element(root, "oMathParaPr")
- _math_element(properties, "jc", val="center")
- math = _math_element(root, "oMath")
- _append_node(math, expression)
-
- ET.register_namespace("m", MATH_NS)
- xml = ET.tostring(root, encoding="unicode", short_empty_elements=True)
- return validate_omml_fragment(xml)
+ return _compile(latex, display=True)
def compile_latex_to_inline_omml(latex: str) -> str:
"""Compile one inline formula into canonical m:oMath XML."""
- expression = _parse_latex_formula(latex)
-
- root = ET.Element(_math_tag("oMath"))
- _append_node(root, expression)
-
- ET.register_namespace("m", MATH_NS)
- xml = ET.tostring(root, encoding="unicode", short_empty_elements=True)
- return validate_omml_fragment(xml)
-
-
-def _parse_latex_formula(latex: str) -> _Node:
- """Validate and parse the shared formula-source contract once."""
- if not isinstance(latex, str):
- raise FormulaCompileError("LaTeX formula must be a string")
- if len(latex) > _MAX_LATEX_LENGTH:
- raise FormulaCompileError(
- f"LaTeX formula exceeds the {_MAX_LATEX_LENGTH}-character limit"
- )
- source = latex.strip()
- if not source:
- raise FormulaCompileError("LaTeX formula is empty")
- if any(not _xml_character_allowed(char) for char in source):
- raise FormulaCompileError(
- "LaTeX formula contains an invalid XML character"
- )
-
- expression = _LatexParser(source).parse()
- _formula_node_count(expression)
- return expression
+ return _compile(latex, display=False)
__all__ = [
diff --git a/skills/ppt-master/scripts/svg_to_pptx/native_objects/formula_omml.py b/skills/ppt-master/scripts/svg_to_pptx/native_objects/formula_omml.py
new file mode 100644
index 00000000..2a6fe440
--- /dev/null
+++ b/skills/ppt-master/scripts/svg_to_pptx/native_objects/formula_omml.py
@@ -0,0 +1,1049 @@
+#!/usr/bin/env python3
+"""
+PPT Master - Native Formula OMML Emitter
+
+Emit the Microsoft 365 LaTeX profile AST as editable Office Math XML and
+validate the narrow XML vocabulary produced by this module.
+
+See references/native-formula.md for the owning compatibility contract.
+
+Usage:
+ Imported by formula_compiler.py.
+
+Examples:
+ emit_omml(expression, display=True)
+
+Dependencies:
+ None (only uses standard library and local PPT Master modules)
+"""
+
+from __future__ import annotations
+
+import re
+from xml.etree import ElementTree as ET
+
+from .formula_ast import (
+ Accent,
+ AlignmentPoint,
+ Bar,
+ BorderBox,
+ Delimiter,
+ EquationArray,
+ Fraction,
+ Function,
+ GroupChar,
+ Limit,
+ Matrix,
+ Nary,
+ Node,
+ OperatorEmulator,
+ Phantom,
+ Prescript,
+ Radical,
+ RunStyle,
+ Script,
+ Sequence,
+ Styled,
+ Text,
+ merge_run_styles,
+)
+from .formula_parser import FormulaCompileError
+
+
+MATH_NS = "http://schemas.openxmlformats.org/officeDocument/2006/math"
+DRAWING_NS = "http://schemas.openxmlformats.org/drawingml/2006/main"
+XML_NS = "http://www.w3.org/XML/1998/namespace"
+
+_MAX_OMML_LENGTH = 1_048_576
+_MAX_OMML_DEPTH = 256
+_FORBIDDEN_XML_RE = re.compile(r"<!\s*(?:DOCTYPE|ENTITY)\b", re.IGNORECASE)
+
+_MATH_ELEMENTS = frozenset({
+ "acc", "accPr", "bar", "barPr", "baseJc", "begChr", "box", "boxPr",
+ "borderBox", "borderBoxPr", "chr", "count", "ctrlPr", "d", "deg", "degHide",
+ "den", "dPr", "e", "endChr", "eqArr", "eqArrPr", "f", "fName",
+ "fPr", "func", "funcPr", "groupChr", "groupChrPr", "grow", "hideBot",
+ "hideLeft", "hideRight", "hideTop", "jc", "lim", "limLoc", "limLow",
+ "limLowPr", "limUpp", "limUppPr", "lit", "m", "mc", "mcPr", "mcs",
+ "mPr", "mr", "nary", "naryPr", "nor", "num", "oMath", "oMathPara",
+ "oMathParaPr", "phant", "phantPr", "plcHide", "pos", "r", "rad",
+ "radPr", "rPr", "scr", "sepChr", "show", "sPre", "sPrePr", "opEmu",
+ "sSub", "sSubSup", "sSup", "strikeBLTR", "strikeTLBR",
+ "sty", "sub", "subHide", "sup", "supHide", "t",
+ "type", "vertJc", "zeroAsc", "zeroDesc", "zeroWid",
+})
+_DRAWING_ELEMENTS = frozenset({
+ "cs", "ea", "latin", "rPr", "solidFill", "srgbClr",
+})
+_DRAWING_ATTRIBUTES = frozenset({
+ "b", "dirty", "i", "lang", "sz", "typeface", "val",
+})
+_ARGUMENT_ELEMENTS = frozenset({
+ "acc", "bar", "borderBox", "box", "d", "eqArr", "f", "func", "groupChr",
+ "limLow", "limUpp", "m", "nary", "phant", "r", "rad", "sPre",
+ "sSub", "sSubSup", "sSup",
+})
+_ARGUMENT_CONTAINERS = frozenset({
+ "deg", "den", "e", "fName", "lim", "num", "oMath", "sub", "sup",
+})
+_ON_OFF_ELEMENTS = frozenset({
+ "degHide", "grow", "hideBot", "hideLeft", "hideRight", "hideTop", "nor",
+ "lit", "opEmu", "plcHide", "show", "strikeBLTR", "strikeTLBR", "subHide", "supHide",
+ "zeroAsc", "zeroDesc", "zeroWid",
+})
+_VALUE_ELEMENTS = frozenset({
+ "baseJc", "begChr", "chr", "count", "degHide", "endChr", "grow",
+ "hideBot", "hideLeft", "hideRight", "hideTop", "jc", "limLoc",
+ "lit", "nor", "opEmu", "plcHide", "pos", "scr", "sepChr", "show", "strikeBLTR",
+ "strikeTLBR", "sty", "subHide", "supHide", "type", "vertJc", "zeroAsc",
+ "zeroDesc", "zeroWid",
+})
+_EMPTY_PROPERTY_ELEMENTS = frozenset({
+ "funcPr", "limLowPr", "limUppPr", "sPrePr",
+})
+_PROPERTY_ORDER = {
+ "accPr": ("chr", "ctrlPr"),
+ "barPr": ("pos", "ctrlPr"),
+ "boxPr": ("opEmu", "ctrlPr"),
+ "borderBoxPr": (
+ "hideTop", "hideBot", "hideLeft", "hideRight", "strikeBLTR",
+ "strikeTLBR", "ctrlPr",
+ ),
+ "dPr": ("begChr", "sepChr", "endChr", "grow", "ctrlPr"),
+ "eqArrPr": ("baseJc",),
+ "fPr": ("type", "ctrlPr"),
+ "groupChrPr": ("chr", "pos", "vertJc", "ctrlPr"),
+ "mPr": ("baseJc", "plcHide", "mcs"),
+ "mcPr": ("count",),
+ "naryPr": (
+ "chr", "limLoc", "grow", "subHide", "supHide", "ctrlPr",
+ ),
+ "oMathParaPr": ("jc",),
+ "phantPr": ("show", "zeroWid", "zeroAsc", "zeroDesc"),
+ "radPr": ("degHide", "ctrlPr"),
+ "rPr": ("lit", "nor", "scr", "sty"),
+}
+
+
+def _math_tag(local_name: str) -> str:
+ return f"{{{MATH_NS}}}{local_name}"
+
+
+def _math_attrs(**values: str) -> dict[str, str]:
+ return {_math_tag(name): value for name, value in values.items()}
+
+
+def _math_element(
+ parent: ET.Element,
+ local_name: str,
+ **attributes: str,
+) -> ET.Element:
+ return ET.SubElement(parent, _math_tag(local_name), _math_attrs(**attributes))
+
+
+def _effective_style(
+ inherited: RunStyle | None,
+ local: RunStyle | None,
+) -> RunStyle | None:
+ return merge_run_styles(inherited, local)
+
+
+def _append_control_style(
+ properties: ET.Element,
+ style: RunStyle | None,
+) -> None:
+ """Persist local control-glyph style that cannot live on a math run."""
+ if style is None:
+ return
+ drawing_attributes: dict[str, str] = {}
+ if style.style == "bi":
+ drawing_attributes.update({"b": "1", "i": "1"})
+ if not style.color and not drawing_attributes:
+ return
+ control_properties = _math_element(properties, "ctrlPr")
+ drawing_properties = ET.SubElement(
+ control_properties,
+ f"{{{DRAWING_NS}}}rPr",
+ drawing_attributes,
+ )
+ if style.color:
+ solid_fill = ET.SubElement(
+ drawing_properties,
+ f"{{{DRAWING_NS}}}solidFill",
+ )
+ ET.SubElement(
+ solid_fill,
+ f"{{{DRAWING_NS}}}srgbClr",
+ {"val": style.color},
+ )
+
+
+def _append_run(
+ parent: ET.Element,
+ value: str,
+ style: RunStyle | None,
+ *,
+ literal: bool = False,
+) -> None:
+ if not value:
+ return
+ if style is not None and style.script == "script" and any(
+ not character.isupper() for character in value
+ ):
+ start = 0
+ uppercase = value[0].isupper()
+ for index in range(1, len(value) + 1):
+ current = value[index].isupper() if index < len(value) else not uppercase
+ if current == uppercase:
+ continue
+ segment_style = style if uppercase else RunStyle(
+ normal=style.normal,
+ color=style.color,
+ bold=style.bold,
+ italic=style.italic,
+ typeface=style.typeface,
+ )
+ _append_run(
+ parent,
+ value[start:index],
+ segment_style,
+ literal=literal,
+ )
+ start = index
+ uppercase = current
+ return
+ run = _math_element(parent, "r")
+ if literal or (
+ style is not None and (style.style or style.normal or style.script)
+ ):
+ properties = _math_element(run, "rPr")
+ if literal:
+ _math_element(properties, "lit", val="on")
+ if style is not None and style.normal is True:
+ _math_element(properties, "nor", val="on")
+ elif style is not None:
+ if style.script:
+ _math_element(properties, "scr", val=style.script)
+ if style.style:
+ _math_element(properties, "sty", val=style.style)
+ if style is not None and any(
+ value is not None
+ for value in (style.color, style.bold, style.italic, style.typeface)
+ ):
+ drawing_attributes: dict[str, str] = {}
+ if style.bold is not None:
+ drawing_attributes["b"] = "1" if style.bold else "0"
+ if style.italic is not None:
+ drawing_attributes["i"] = "1" if style.italic else "0"
+ drawing_properties = ET.SubElement(
+ run,
+ f"{{{DRAWING_NS}}}rPr",
+ drawing_attributes,
+ )
+ if style.color:
+ solid_fill = ET.SubElement(
+ drawing_properties,
+ f"{{{DRAWING_NS}}}solidFill",
+ )
+ ET.SubElement(
+ solid_fill,
+ f"{{{DRAWING_NS}}}srgbClr",
+ {"val": style.color},
+ )
+ if style.typeface:
+ for local_name in ("latin", "ea", "cs"):
+ ET.SubElement(
+ drawing_properties,
+ f"{{{DRAWING_NS}}}{local_name}",
+ {"typeface": style.typeface},
+ )
+ text = _math_element(run, "t")
+ if value != value.strip() or " " in value:
+ text.set(f"{{{XML_NS}}}space", "preserve")
+ text.text = value
+
+
+def _append_sequence(
+ parent: ET.Element,
+ sequence: Sequence,
+ inherited_style: RunStyle | None,
+ *,
+ display: bool,
+) -> None:
+ for child in sequence.children:
+ _append_node(parent, child, inherited_style, display=display)
+
+
+def _append_node(
+ parent: ET.Element,
+ node: Node,
+ inherited_style: RunStyle | None = None,
+ *,
+ display: bool,
+) -> None:
+ if isinstance(node, Text):
+ _append_run(
+ parent,
+ node.value,
+ _effective_style(inherited_style, node.style),
+ literal=node.literal,
+ )
+ return
+ if isinstance(node, Sequence):
+ _append_sequence(parent, node, inherited_style, display=display)
+ return
+ if isinstance(node, Styled):
+ _append_sequence(
+ parent,
+ node.body,
+ _effective_style(inherited_style, node.style),
+ display=display,
+ )
+ return
+ if isinstance(node, Fraction):
+ fraction = _math_element(parent, "f")
+ properties = _math_element(fraction, "fPr")
+ _math_element(properties, "type", val=node.kind)
+ _append_control_style(properties, inherited_style)
+ numerator = _math_element(fraction, "num")
+ _append_sequence(numerator, node.numerator, inherited_style, display=display)
+ denominator = _math_element(fraction, "den")
+ _append_sequence(denominator, node.denominator, inherited_style, display=display)
+ return
+ if isinstance(node, Radical):
+ radical = _math_element(parent, "rad")
+ properties = _math_element(radical, "radPr")
+ _math_element(properties, "degHide", val="off" if node.degree else "on")
+ _append_control_style(properties, inherited_style)
+ degree = _math_element(radical, "deg")
+ if node.degree is not None:
+ _append_sequence(degree, node.degree, inherited_style, display=display)
+ body = _math_element(radical, "e")
+ _append_sequence(body, node.body, inherited_style, display=display)
+ return
+ if isinstance(node, Script):
+ _append_script(parent, node, inherited_style, display=display)
+ return
+ if isinstance(node, Prescript):
+ _append_prescript(parent, node, inherited_style, display=display)
+ return
+ if isinstance(node, Nary):
+ _append_nary(parent, node, inherited_style, display=display)
+ return
+ if isinstance(node, Delimiter):
+ delimiter = _math_element(parent, "d")
+ properties = _math_element(delimiter, "dPr")
+ _math_element(properties, "begChr", val=node.left)
+ _math_element(properties, "sepChr", val=node.separator)
+ _math_element(properties, "endChr", val=node.right)
+ _math_element(properties, "grow", val="on")
+ _append_control_style(properties, inherited_style)
+ for segment in node.segments:
+ body = _math_element(delimiter, "e")
+ _append_sequence(body, segment, inherited_style, display=display)
+ return
+ if isinstance(node, Matrix):
+ _append_matrix(parent, node, inherited_style, display=display)
+ return
+ if isinstance(node, AlignmentPoint):
+ _append_run(parent, "&", inherited_style)
+ return
+ if isinstance(node, EquationArray):
+ equation_array = _math_element(parent, "eqArr")
+ properties = _math_element(equation_array, "eqArrPr")
+ _math_element(properties, "baseJc", val="center")
+ for row in node.rows:
+ body = _math_element(equation_array, "e")
+ _append_sequence(body, row, inherited_style, display=display)
+ return
+ if isinstance(node, Accent):
+ accent = _math_element(parent, "acc")
+ properties = _math_element(accent, "accPr")
+ _math_element(properties, "chr", val=node.character)
+ _append_control_style(properties, inherited_style)
+ body = _math_element(accent, "e")
+ _append_sequence(body, node.body, inherited_style, display=display)
+ return
+ if isinstance(node, Bar):
+ bar = _math_element(parent, "bar")
+ properties = _math_element(bar, "barPr")
+ _math_element(properties, "pos", val=node.position)
+ _append_control_style(properties, inherited_style)
+ body = _math_element(bar, "e")
+ _append_sequence(body, node.body, inherited_style, display=display)
+ return
+ if isinstance(node, GroupChar):
+ group = _math_element(parent, "groupChr")
+ properties = _math_element(group, "groupChrPr")
+ _math_element(properties, "chr", val=node.character)
+ _math_element(properties, "pos", val=node.position)
+ _math_element(properties, "vertJc", val=node.vertical_justification)
+ _append_control_style(properties, inherited_style)
+ body = _math_element(group, "e")
+ _append_sequence(body, node.body, inherited_style, display=display)
+ return
+ if isinstance(node, Limit):
+ _append_limit(parent, node, inherited_style, display=display)
+ return
+ if isinstance(node, Function):
+ _append_function(parent, node, inherited_style, display=display)
+ return
+ if isinstance(node, OperatorEmulator):
+ box = _math_element(parent, "box")
+ properties = _math_element(box, "boxPr")
+ _math_element(properties, "opEmu", val="on")
+ _append_control_style(properties, inherited_style)
+ body = _math_element(box, "e")
+ _append_sequence(body, node.body, inherited_style, display=display)
+ return
+ if isinstance(node, Phantom):
+ phantom = _math_element(parent, "phant")
+ properties = _math_element(phantom, "phantPr")
+ if node.kind == "phantom":
+ _math_element(properties, "show", val="off")
+ elif node.kind == "hphantom":
+ _math_element(properties, "show", val="off")
+ _math_element(properties, "zeroAsc", val="on")
+ _math_element(properties, "zeroDesc", val="on")
+ elif node.kind == "vphantom":
+ _math_element(properties, "show", val="off")
+ _math_element(properties, "zeroWid", val="on")
+ else:
+ raise FormulaCompileError(f"Unsupported phantom kind: {node.kind!r}")
+ body = _math_element(phantom, "e")
+ _append_sequence(body, node.body, inherited_style, display=display)
+ return
+ if isinstance(node, BorderBox):
+ border = _math_element(parent, "borderBox")
+ properties = _math_element(border, "borderBoxPr")
+ if node.kind in {"cancel", "bcancel", "xcancel"}:
+ for side in ("hideTop", "hideBot", "hideLeft", "hideRight"):
+ _math_element(properties, side, val="on")
+ if node.kind == "cancel":
+ _math_element(properties, "strikeBLTR", val="on")
+ elif node.kind == "bcancel":
+ _math_element(properties, "strikeTLBR", val="on")
+ elif node.kind == "xcancel":
+ _math_element(properties, "strikeBLTR", val="on")
+ _math_element(properties, "strikeTLBR", val="on")
+ elif node.kind not in {"boxed", "fbox", "framebox"}:
+ raise FormulaCompileError(f"Unsupported border-box kind: {node.kind!r}")
+ _append_control_style(properties, inherited_style)
+ body = _math_element(border, "e")
+ _append_sequence(body, node.body, inherited_style, display=display)
+ return
+ raise FormulaCompileError(f"Unsupported internal formula node: {type(node).__name__}")
+
+
+def _append_script(
+ parent: ET.Element,
+ node: Script,
+ inherited_style: RunStyle | None,
+ *,
+ display: bool,
+) -> None:
+ if node.subscript is not None and node.superscript is not None:
+ script = _math_element(parent, "sSubSup")
+ elif node.subscript is not None:
+ script = _math_element(parent, "sSub")
+ else:
+ script = _math_element(parent, "sSup")
+ base = _math_element(script, "e")
+ _append_node(base, node.base, inherited_style, display=display)
+ if node.subscript is not None:
+ subscript = _math_element(script, "sub")
+ _append_sequence(subscript, node.subscript, inherited_style, display=display)
+ if node.superscript is not None:
+ superscript = _math_element(script, "sup")
+ _append_sequence(superscript, node.superscript, inherited_style, display=display)
+
+
+def _append_prescript(
+ parent: ET.Element,
+ node: Prescript,
+ inherited_style: RunStyle | None,
+ *,
+ display: bool,
+) -> None:
+ script = _math_element(parent, "sPre")
+ _math_element(script, "sPrePr")
+ subscript = _math_element(script, "sub")
+ if node.subscript is not None:
+ _append_sequence(subscript, node.subscript, inherited_style, display=display)
+ superscript = _math_element(script, "sup")
+ if node.superscript is not None:
+ _append_sequence(superscript, node.superscript, inherited_style, display=display)
+ base = _math_element(script, "e")
+ _append_node(base, node.base, inherited_style, display=display)
+
+
+def _append_nary(
+ parent: ET.Element,
+ node: Nary,
+ inherited_style: RunStyle | None,
+ *,
+ display: bool,
+) -> None:
+ nary = _math_element(parent, "nary")
+ properties = _math_element(nary, "naryPr")
+ _math_element(properties, "chr", val=node.symbol)
+ if node.limit_modifier == "limits":
+ limit_location = "undOvr"
+ elif node.limit_modifier == "nolimits":
+ limit_location = "subSup"
+ elif node.category == "integral":
+ limit_location = "subSup"
+ else:
+ limit_location = "undOvr" if display else "subSup"
+ _math_element(properties, "limLoc", val=limit_location)
+ _math_element(properties, "grow", val="off")
+ _math_element(properties, "subHide", val="off" if node.subscript else "on")
+ _math_element(properties, "supHide", val="off" if node.superscript else "on")
+ _append_control_style(properties, inherited_style)
+ subscript = _math_element(nary, "sub")
+ if node.subscript is not None:
+ _append_sequence(subscript, node.subscript, inherited_style, display=display)
+ superscript = _math_element(nary, "sup")
+ if node.superscript is not None:
+ _append_sequence(superscript, node.superscript, inherited_style, display=display)
+ body = _math_element(nary, "e")
+ if node.body is not None:
+ _append_sequence(body, node.body, inherited_style, display=display)
+
+
+def _append_matrix(
+ parent: ET.Element,
+ node: Matrix,
+ inherited_style: RunStyle | None,
+ *,
+ display: bool,
+) -> None:
+ matrix = _math_element(parent, "m")
+ properties = _math_element(matrix, "mPr")
+ _math_element(properties, "baseJc", val="center")
+ _math_element(properties, "plcHide", val="on")
+ columns = _math_element(properties, "mcs")
+ column_count = len(node.rows[0])
+ for _ in range(column_count):
+ column = _math_element(columns, "mc")
+ column_properties = _math_element(column, "mcPr")
+ _math_element(column_properties, "count", val="1")
+ for row_data in node.rows:
+ row = _math_element(matrix, "mr")
+ for cell_data in row_data:
+ cell = _math_element(row, "e")
+ _append_sequence(cell, cell_data, inherited_style, display=display)
+
+
+def _append_limit(
+ parent: ET.Element,
+ node: Limit,
+ inherited_style: RunStyle | None,
+ *,
+ display: bool,
+) -> None:
+ base: Node = node.base
+ if node.lower is not None:
+ lower = _math_element(parent, "limLow")
+ _math_element(lower, "limLowPr")
+ expression = _math_element(lower, "e")
+ _append_node(expression, base, inherited_style, display=display)
+ limit = _math_element(lower, "lim")
+ _append_sequence(limit, node.lower, inherited_style, display=display)
+ base = Sequence(())
+ if node.upper is not None:
+ wrapper = ET.Element(_math_tag("limUpp"))
+ _math_element(wrapper, "limUppPr")
+ expression = _math_element(wrapper, "e")
+ expression.append(lower)
+ limit = _math_element(wrapper, "lim")
+ _append_sequence(limit, node.upper, inherited_style, display=display)
+ parent.remove(lower)
+ parent.append(wrapper)
+ return
+ if node.upper is not None:
+ upper = _math_element(parent, "limUpp")
+ _math_element(upper, "limUppPr")
+ expression = _math_element(upper, "e")
+ _append_node(expression, base, inherited_style, display=display)
+ limit = _math_element(upper, "lim")
+ _append_sequence(limit, node.upper, inherited_style, display=display)
+ return
+ _append_node(parent, base, inherited_style, display=display)
+
+
+def _append_function(
+ parent: ET.Element,
+ node: Function,
+ inherited_style: RunStyle | None,
+ *,
+ display: bool,
+) -> None:
+ function = _math_element(parent, "func")
+ _math_element(function, "funcPr")
+ name_parent = _math_element(function, "fName")
+ name: Node = node.name
+ if node.subscript is not None or node.superscript is not None:
+ use_limits = node.limit_modifier == "limits" or (
+ node.limit_modifier != "nolimits" and node.limit_style and display
+ )
+ if use_limits:
+ name = Limit(name, lower=node.subscript, upper=node.superscript)
+ else:
+ name = Script(name, node.subscript, node.superscript)
+ _append_node(name_parent, name, inherited_style, display=display)
+ body = _math_element(function, "e")
+ if node.body is not None:
+ _append_sequence(body, node.body, inherited_style, display=display)
+
+
+def _qualified_name(name: str) -> tuple[str | None, str]:
+ if name.startswith("{") and "}" in name:
+ namespace, local_name = name[1:].split("}", 1)
+ return namespace, local_name
+ return None, name
+
+
+def _child_names(element: ET.Element) -> list[str]:
+ return [_qualified_name(child.tag)[1] for child in element]
+
+
+def _require_children(
+ element: ET.Element,
+ expected: tuple[str, ...],
+) -> None:
+ element_name = _qualified_name(element.tag)[1]
+ actual = tuple(_child_names(element))
+ if actual != expected:
+ raise FormulaCompileError(
+ f"m:{element_name} children must be {expected!r}, found {actual!r}"
+ )
+
+
+def _require_repeated_children(
+ element: ET.Element,
+ child_name: str,
+ *,
+ minimum: int,
+ maximum: int,
+) -> None:
+ element_name = _qualified_name(element.tag)[1]
+ actual = _child_names(element)
+ if (
+ not minimum <= len(actual) <= maximum
+ or any(name != child_name for name in actual)
+ ):
+ raise FormulaCompileError(
+ f"m:{element_name} must contain {minimum}..{maximum} "
+ f"m:{child_name} children"
+ )
+
+
+def _validate_property_children(element: ET.Element, element_name: str) -> None:
+ expected_order = _PROPERTY_ORDER[element_name]
+ actual = _child_names(element)
+ if len(actual) != len(set(actual)):
+ raise FormulaCompileError(f"m:{element_name} contains duplicate properties")
+ unknown = [name for name in actual if name not in expected_order]
+ if unknown:
+ raise FormulaCompileError(
+ f"m:{element_name} contains unsupported properties: {unknown!r}"
+ )
+ order = [expected_order.index(name) for name in actual]
+ if order != sorted(order):
+ raise FormulaCompileError(f"m:{element_name} properties are out of order")
+ if element_name == "rPr" and "nor" in actual and (
+ "scr" in actual or "sty" in actual
+ ):
+ raise FormulaCompileError(
+ "m:rPr cannot combine m:nor with m:scr or m:sty"
+ )
+
+
+def _math_value(element: ET.Element) -> str:
+ value = element.get(_math_tag("val"))
+ if value is None:
+ element_name = _qualified_name(element.tag)[1]
+ raise FormulaCompileError(f"m:{element_name} requires m:val")
+ return value
+
+
+def _validate_math_value(element: ET.Element, element_name: str) -> None:
+ value = _math_value(element)
+ allowed_values = {
+ "baseJc": {"top", "center", "bot"},
+ "jc": {"left", "right", "center", "centerGroup"},
+ "limLoc": {"subSup", "undOvr"},
+ "pos": {"top", "bot"},
+ "scr": {
+ "roman", "sans-serif", "monospace", "double-struck",
+ "script", "fraktur",
+ },
+ "sty": {"p", "b", "i", "bi"},
+ "type": {"bar", "lin", "noBar", "skw"},
+ "vertJc": {"top", "bot"},
+ }
+ if element_name in _ON_OFF_ELEMENTS:
+ if value not in {"on", "off", "true", "false", "1", "0"}:
+ raise FormulaCompileError(
+ f"m:{element_name} has invalid on/off value: {value!r}"
+ )
+ return
+ if element_name == "count":
+ if not value.isascii() or not value.isdigit() or not 1 <= int(value) <= 64:
+ raise FormulaCompileError("m:count must be an integer from 1 to 64")
+ return
+ if element_name in {"begChr", "chr", "endChr", "sepChr"}:
+ if len(value) > 1:
+ raise FormulaCompileError(
+ f"m:{element_name} must contain at most one character"
+ )
+ return
+ allowed = allowed_values.get(element_name)
+ if allowed is not None and value not in allowed:
+ raise FormulaCompileError(
+ f"m:{element_name} has invalid value: {value!r}"
+ )
+
+
+def _validate_drawing_element(element: ET.Element, element_name: str) -> None:
+ attributes = {
+ _qualified_name(name)[1]: value for name, value in element.attrib.items()
+ }
+ children = _child_names(element)
+ if element_name == "rPr":
+ unknown = set(attributes) - {"b", "dirty", "i", "lang", "sz"}
+ if unknown:
+ raise FormulaCompileError(
+ f"a:rPr contains unsupported attributes: {sorted(unknown)!r}"
+ )
+ for name in ("b", "dirty", "i"):
+ if name in attributes and attributes[name] not in {
+ "on", "off", "true", "false", "1", "0",
+ }:
+ raise FormulaCompileError(
+ f"a:rPr@{name} has invalid on/off value"
+ )
+ if "sz" in attributes and (
+ not attributes["sz"].isascii()
+ or not attributes["sz"].isdigit()
+ or not 100 <= int(attributes["sz"]) <= 400_000
+ ):
+ raise FormulaCompileError("a:rPr@sz must be from 100 to 400000")
+ expected_order = ("solidFill", "latin", "ea", "cs")
+ if len(children) != len(set(children)):
+ raise FormulaCompileError("a:rPr contains duplicate child properties")
+ if any(name not in expected_order for name in children):
+ raise FormulaCompileError("a:rPr contains unsupported child properties")
+ order = [expected_order.index(name) for name in children]
+ if order != sorted(order):
+ raise FormulaCompileError("a:rPr child properties are out of order")
+ return
+ if element_name == "solidFill":
+ if attributes or children != ["srgbClr"]:
+ raise FormulaCompileError("a:solidFill must contain one a:srgbClr")
+ return
+ if element_name == "srgbClr":
+ if children or set(attributes) != {"val"} or not re.fullmatch(
+ r"[0-9A-Fa-f]{6}", attributes["val"]
+ ):
+ raise FormulaCompileError("a:srgbClr@val must be six hexadecimal digits")
+ return
+ if element_name in {"latin", "ea", "cs"}:
+ if children or set(attributes) != {"typeface"} or not attributes["typeface"]:
+ raise FormulaCompileError(
+ f"a:{element_name} must contain one non-empty typeface attribute"
+ )
+
+
+def _validate_math_structure(element: ET.Element, element_name: str) -> None:
+ if element_name in _ARGUMENT_CONTAINERS:
+ children = list(element)
+ if element_name == "oMath" and not children:
+ raise FormulaCompileError("m:oMath must contain a math expression")
+ for child in children:
+ namespace, child_name = _qualified_name(child.tag)
+ if namespace != MATH_NS or child_name not in _ARGUMENT_ELEMENTS:
+ raise FormulaCompileError(
+ f"m:{element_name} contains an invalid math argument child"
+ )
+ return
+ fixed_children = {
+ "acc": ("accPr", "e"),
+ "bar": ("barPr", "e"),
+ "borderBox": ("borderBoxPr", "e"),
+ "box": ("boxPr", "e"),
+ "f": ("fPr", "num", "den"),
+ "func": ("funcPr", "fName", "e"),
+ "groupChr": ("groupChrPr", "e"),
+ "limLow": ("limLowPr", "e", "lim"),
+ "limUpp": ("limUppPr", "e", "lim"),
+ "mc": ("mcPr",),
+ "nary": ("naryPr", "sub", "sup", "e"),
+ "phant": ("phantPr", "e"),
+ "rad": ("radPr", "deg", "e"),
+ "sPre": ("sPrePr", "sub", "sup", "e"),
+ "sSub": ("e", "sub"),
+ "sSubSup": ("e", "sub", "sup"),
+ "sSup": ("e", "sup"),
+ }
+ if element_name in fixed_children:
+ _require_children(element, fixed_children[element_name])
+ return
+ if element_name == "oMathPara":
+ children = tuple(_child_names(element))
+ if children not in {("oMath",), ("oMathParaPr", "oMath")}:
+ raise FormulaCompileError(
+ "m:oMathPara must contain optional m:oMathParaPr then one m:oMath"
+ )
+ return
+ if element_name == "d":
+ children = _child_names(element)
+ rows = children[1:] if children and children[0] == "dPr" else []
+ if not 1 <= len(rows) <= 64 or any(name != "e" for name in rows):
+ raise FormulaCompileError("m:d must contain m:dPr then 1..64 m:e children")
+ return
+ if element_name == "eqArr":
+ children = _child_names(element)
+ offset = 1 if children and children[0] == "eqArrPr" else 0
+ rows = children[offset:]
+ if not 1 <= len(rows) <= 64 or any(name != "e" for name in rows):
+ raise FormulaCompileError("m:eqArr must contain 1..64 m:e rows")
+ return
+ if element_name == "m":
+ children = _child_names(element)
+ rows = children[1:] if children and children[0] == "mPr" else []
+ if not 1 <= len(rows) <= 256 or any(name != "mr" for name in rows):
+ raise FormulaCompileError("m:m must contain m:mPr then 1..256 m:mr rows")
+ return
+ if element_name == "mr":
+ _require_repeated_children(element, "e", minimum=1, maximum=64)
+ return
+ if element_name == "mcs":
+ _require_repeated_children(element, "mc", minimum=1, maximum=64)
+ return
+ if element_name == "r":
+ children = [(_qualified_name(child.tag), child) for child in element]
+ index = 0
+ if index < len(children) and children[index][0] == (MATH_NS, "rPr"):
+ index += 1
+ if index < len(children) and children[index][0] == (DRAWING_NS, "rPr"):
+ index += 1
+ if index != len(children) - 1 or children[index][0] != (MATH_NS, "t"):
+ raise FormulaCompileError(
+ "m:r must contain optional m:rPr, optional a:rPr, then one m:t"
+ )
+ return
+ if element_name == "ctrlPr":
+ children = [(_qualified_name(child.tag), child) for child in element]
+ if len(children) > 1 or (
+ children and children[0][0] != (DRAWING_NS, "rPr")
+ ):
+ raise FormulaCompileError(
+ "m:ctrlPr may contain only one optional a:rPr"
+ )
+ return
+ if element_name in _PROPERTY_ORDER:
+ _validate_property_children(element, element_name)
+ return
+ if element_name in _EMPTY_PROPERTY_ELEMENTS:
+ if list(element):
+ raise FormulaCompileError(f"m:{element_name} must be empty")
+ return
+ if element_name in _VALUE_ELEMENTS:
+ if list(element):
+ raise FormulaCompileError(f"m:{element_name} must not contain children")
+ _validate_math_value(element, element_name)
+ return
+ if element_name == "t" and list(element):
+ raise FormulaCompileError("m:t must not contain children")
+
+
+def _validate_matrix_dimensions(root: ET.Element) -> None:
+ for matrix in root.iter(_math_tag("m")):
+ properties = matrix.find(_math_tag("mPr"))
+ columns = properties.find(_math_tag("mcs")) if properties is not None else None
+ if columns is None:
+ raise FormulaCompileError("m:mPr must contain m:mcs")
+ column_count = 0
+ for column in columns:
+ column_properties = column.find(_math_tag("mcPr"))
+ count = (
+ column_properties.find(_math_tag("count"))
+ if column_properties is not None
+ else None
+ )
+ if count is None:
+ raise FormulaCompileError("m:mcPr must contain m:count")
+ column_count += int(_math_value(count))
+ if not 1 <= column_count <= 64:
+ raise FormulaCompileError("matrix column count must be from 1 to 64")
+ for row in matrix.findall(_math_tag("mr")):
+ if len(row.findall(_math_tag("e"))) != column_count:
+ raise FormulaCompileError(
+ "every matrix row must match the declared column count"
+ )
+
+
+def _validate_xml_tree(root: ET.Element) -> None:
+ namespace, local_name = _qualified_name(root.tag)
+ if namespace != MATH_NS or local_name not in {"oMathPara", "oMath"}:
+ raise FormulaCompileError("OMML root must be m:oMathPara or m:oMath")
+
+ math_roots = 0
+ pending = [root]
+ while pending:
+ element = pending.pop()
+ pending.extend(reversed(element))
+ element_namespace, element_name = _qualified_name(element.tag)
+ if element_namespace == MATH_NS and element_name not in _MATH_ELEMENTS:
+ raise FormulaCompileError(
+ f"OMML contains unsupported math element: {element_name!r}"
+ )
+ if element_namespace == DRAWING_NS and element_name not in _DRAWING_ELEMENTS:
+ raise FormulaCompileError(
+ f"OMML contains unsupported DrawingML element: {element_name!r}"
+ )
+ if element_namespace not in {MATH_NS, DRAWING_NS}:
+ raise FormulaCompileError(
+ f"OMML contains unsupported element namespace: {element_namespace!r}"
+ )
+ if element_namespace == MATH_NS and element_name in {"oMathPara", "oMath"}:
+ math_roots += 1
+ for attribute, value in element.attrib.items():
+ attribute_namespace, attribute_name = _qualified_name(attribute)
+ if (
+ attribute_namespace == MATH_NS
+ and attribute_name == "val"
+ and element_namespace == MATH_NS
+ and element_name in _VALUE_ELEMENTS
+ ):
+ continue
+ if (
+ attribute_namespace in {None, DRAWING_NS}
+ and element_namespace == DRAWING_NS
+ and attribute_name in _DRAWING_ATTRIBUTES
+ ):
+ continue
+ if (
+ attribute_namespace == XML_NS
+ and element_namespace == MATH_NS
+ and element_name == "t"
+ and attribute_name == "space"
+ and value == "preserve"
+ ):
+ continue
+ raise FormulaCompileError(
+ f"OMML contains unsupported attribute {attribute_name!r}"
+ )
+ if element_namespace == MATH_NS:
+ _validate_math_structure(element, element_name)
+ else:
+ _validate_drawing_element(element, element_name)
+ if element.text:
+ if not (
+ element_namespace == MATH_NS and element_name == "t"
+ ) and element.text.strip():
+ raise FormulaCompileError(
+ f"OMML text is only allowed inside m:t, found in {element_name!r}"
+ )
+ if element.tail and element.tail.strip():
+ raise FormulaCompileError("OMML contains unexpected trailing text")
+
+ expected_roots = 2 if local_name == "oMathPara" else 1
+ if math_roots != expected_roots:
+ raise FormulaCompileError("OMML must contain exactly one math expression")
+ _validate_matrix_dimensions(root)
+ if local_name == "oMathPara":
+ direct_expressions = [
+ child
+ for child in root
+ if _qualified_name(child.tag) == (MATH_NS, "oMath")
+ ]
+ if len(direct_expressions) != 1:
+ raise FormulaCompileError(
+ "m:oMathPara must contain exactly one direct m:oMath expression"
+ )
+
+
+def _validate_xml_depth(root: ET.Element) -> None:
+ pending: list[tuple[ET.Element, int]] = [(root, 1)]
+ while pending:
+ element, depth = pending.pop()
+ if depth > _MAX_OMML_DEPTH:
+ raise FormulaCompileError(
+ f"OMML nesting exceeds {_MAX_OMML_DEPTH} levels"
+ )
+ pending.extend((child, depth + 1) for child in reversed(element))
+
+
+def _parse_omml_with_resource_limits(xml: str) -> ET.Element:
+ if not isinstance(xml, str):
+ raise FormulaCompileError("OMML fragment must be a string")
+ if not xml.strip():
+ raise FormulaCompileError("OMML fragment is empty")
+ if len(xml) > _MAX_OMML_LENGTH:
+ raise FormulaCompileError(
+ f"OMML fragment exceeds the {_MAX_OMML_LENGTH}-character limit"
+ )
+ if _FORBIDDEN_XML_RE.search(xml):
+ raise FormulaCompileError("DOCTYPE and ENTITY declarations are forbidden in OMML")
+ try:
+ root = ET.fromstring(xml)
+ except (ET.ParseError, RecursionError) as exc:
+ raise FormulaCompileError(f"Invalid OMML XML: {exc}") from exc
+ _validate_xml_depth(root)
+ return root
+
+
+def _serialize_omml_with_resource_limits(root: ET.Element) -> str:
+ ET.register_namespace("m", MATH_NS)
+ ET.register_namespace("a", DRAWING_NS)
+ try:
+ canonical = ET.tostring(root, encoding="unicode", short_empty_elements=True)
+ except RecursionError as exc:
+ raise FormulaCompileError("OMML nesting exceeds the XML serializer limit") from exc
+ if len(canonical) > _MAX_OMML_LENGTH:
+ raise FormulaCompileError(
+ f"Canonical OMML exceeds the {_MAX_OMML_LENGTH}-character limit"
+ )
+ return canonical
+
+
+def validate_omml_resource_limits(xml: str) -> str:
+ """Apply only the shared serialized-size and XML-depth resource limits."""
+ root = _parse_omml_with_resource_limits(xml)
+ return _serialize_omml_with_resource_limits(root)
+
+
+def validate_omml_fragment(xml: str) -> str:
+ """Validate emitted Office Math XML and canonicalize namespace prefixes."""
+ root = _parse_omml_with_resource_limits(xml)
+ _validate_xml_tree(root)
+ return _serialize_omml_with_resource_limits(root)
+
+
+def emit_omml(expression: Sequence, *, display: bool) -> str:
+ """Emit one block or inline Office Math root from the parsed AST."""
+ if display:
+ root = ET.Element(_math_tag("oMathPara"))
+ properties = _math_element(root, "oMathParaPr")
+ _math_element(properties, "jc", val="center")
+ math = _math_element(root, "oMath")
+ else:
+ root = ET.Element(_math_tag("oMath"))
+ math = root
+ _append_sequence(math, expression, None, display=display)
+ ET.register_namespace("m", MATH_NS)
+ ET.register_namespace("a", DRAWING_NS)
+ xml = ET.tostring(root, encoding="unicode", short_empty_elements=True)
+ return validate_omml_fragment(xml)
+
+
+__all__ = [
+ "DRAWING_NS",
+ "MATH_NS",
+ "emit_omml",
+ "validate_omml_fragment",
+ "validate_omml_resource_limits",
+]
diff --git a/skills/ppt-master/scripts/svg_to_pptx/native_objects/formula_parser.py b/skills/ppt-master/scripts/svg_to_pptx/native_objects/formula_parser.py
new file mode 100644
index 00000000..30c13539
--- /dev/null
+++ b/skills/ppt-master/scripts/svg_to_pptx/native_objects/formula_parser.py
@@ -0,0 +1,2181 @@
+#!/usr/bin/env python3
+r"""
+PPT Master - Microsoft 365 LaTeX Formula Parser
+
+Parse the documented Microsoft 365 LaTeX import profile into the internal
+native-formula AST. Unknown commands remain fail-closed.
+
+See references/native-formula.md for the owning authoring contract.
+
+Usage:
+ Import parse_latex_formula() from the native formula compiler facade.
+
+Examples:
+ parse_latex_formula(r"\binom{n}{k}", display=True)
+
+Dependencies:
+ None (only uses standard library and local PPT Master modules)
+"""
+
+from __future__ import annotations
+
+import re
+from dataclasses import dataclass
+
+from .formula_ast import (
+ Accent,
+ AlignmentPoint,
+ Bar,
+ BorderBox,
+ Delimiter,
+ EquationArray,
+ Fraction,
+ Function,
+ GroupChar,
+ Limit,
+ Matrix,
+ Nary,
+ Node,
+ OperatorEmulator,
+ Phantom,
+ Prescript,
+ Radical,
+ RunStyle,
+ Script,
+ Sequence,
+ Styled,
+ Text,
+ append_child,
+ is_empty,
+ merge_run_styles,
+)
+from .formula_profile import (
+ ACCENT_COMMANDS,
+ BARE_DELIMITER_COMMAND_PAIRS,
+ COLOR_NAMES,
+ DELIMITER_COMMANDS,
+ DISCARDED_ARGUMENT_COMMANDS,
+ EQUATION_ARRAY_ENVIRONMENTS,
+ GREEK_SYMBOLS,
+ LIMIT_FUNCTIONS,
+ MATRIX_ENVIRONMENTS,
+ NARY_COMMANDS,
+ NEGATED_SYMBOLS,
+ NO_OUTPUT_COMMANDS,
+ OPERATOR_BOUNDARY_COMMANDS,
+ SPACING_COMMANDS,
+ STANDARD_FUNCTIONS,
+ SYMBOL_COMMANDS,
+ UNSUPPORTED_COMMANDS,
+ VARIANT_UPPERCASE_GREEK,
+)
+
+
+_MAX_PARSE_DEPTH = 128
+_MAX_MACRO_EXPANSIONS = 500
+_MAX_EXPANDED_LENGTH = 1_048_576
+_ENVIRONMENT_NAME_RE = re.compile(r"[A-Za-z]+\*?")
+_COLOR_HEX_RE = re.compile(r"#[0-9A-Fa-f]{6}")
+_LENGTH_RE = re.compile(
+ r"([+-]?(?:\d+(?:\.\d*)?|\.\d+))\s*(mu|em|ex|pt)",
+ re.IGNORECASE,
+)
+_BIG_DELIMITER_RE = re.compile(
+ r"\\(?:big|Big|bigg|Bigg)([lrm]?)(?![A-Za-z])\s*"
+ r"(\\[A-Za-z]+|\\[{}|]|[()\[\]{}|.])"
+)
+_BIG_LEFT_COMMAND = "pptmasterbigleft"
+_BIG_RIGHT_COMMAND = "pptmasterbigright"
+_BIG_MIDDLE_COMMAND = "pptmasterbigmiddle"
+_BIG_SYMMETRIC_COMMAND = "pptmasterbigsymmetric"
+_MIDDLE_DELIMITER_COMMANDS = ("middle", _BIG_MIDDLE_COMMAND)
+_RIGHT_DELIMITER_COMMANDS = ("right", _BIG_RIGHT_COMMAND)
+_WHITE_OPEN_RE = re.compile(
+ r"(?:(?:\\left)?(?:\[|\\lbrack))\\!"
+ r"(?:(?:\\left)?(?:\[|\\lbrack))"
+)
+_WHITE_CLOSE_RE = re.compile(
+ r"(?:(?:\\right)?(?:\]|\\rbrack))\\!"
+ r"(?:(?:\\right)?(?:\]|\\rbrack))"
+)
+
+_ROMAN_STYLE = RunStyle(style="p", is_default=True)
+_TEXT_STYLE = RunStyle(normal=True)
+_MATH_MODE_RESET_STYLE = RunStyle(
+ normal=False,
+ bold=False,
+ italic=False,
+ typeface="",
+)
+_SPACING_STYLE = RunStyle()
+_PLAIN_OPERATOR_CHARS = frozenset("+−*/=<>±∓×÷⋅,;:!?")
+_INFIX_FRACTIONS = frozenset({"over", "atop", "choose", "brace", "brack"})
+
+_STYLE_WRAPPERS = {
+ "mathrm": RunStyle(style="p"),
+ "mathbf": RunStyle(style="b"),
+ "mathit": RunStyle(style="i"),
+ "mathsf": RunStyle(style="p", script="sans-serif"),
+ "mathtt": RunStyle(style="p", script="monospace"),
+ "mathbb": RunStyle(style="p", script="double-struck"),
+ "Bbb": RunStyle(style="p", script="double-struck"),
+ "mathcal": RunStyle(style="p", script="script"),
+ "mathscr": RunStyle(style="p", script="script"),
+ "mathfrak": RunStyle(style="p", script="fraktur"),
+ "boldsymbol": RunStyle(style="bi"),
+ "bm": RunStyle(style="bi"),
+ "text": _TEXT_STYLE,
+ "textrm": _TEXT_STYLE,
+ "textnormal": _TEXT_STYLE,
+ "textbf": RunStyle(normal=True, bold=True),
+ "textit": RunStyle(normal=True, italic=True),
+ "emph": RunStyle(normal=True, italic=True),
+ "textsf": RunStyle(normal=True, typeface="Arial"),
+ "texttt": RunStyle(normal=True, typeface="Courier New"),
+ "mbox": _TEXT_STYLE,
+ "hbox": _TEXT_STYLE,
+}
+
+_DECLARATION_STYLES = {
+ "rm": RunStyle(style="p"),
+ "bf": RunStyle(style="b"),
+ "it": RunStyle(style="i"),
+ "cal": RunStyle(style="p", script="script"),
+ "frak": RunStyle(style="p", script="fraktur"),
+ "sf": RunStyle(style="p", script="sans-serif"),
+ "tt": RunStyle(style="p", script="monospace"),
+}
+
+_OVER_UNDER_COMMANDS = {
+ "overbrace": ("⏞", "top", "bot"),
+ "underbrace": ("⏟", "bot", "top"),
+ "underrightarrow": ("→", "bot", "top"),
+ "underleftarrow": ("←", "bot", "top"),
+ "underleftrightarrow": ("↔", "bot", "top"),
+}
+
+_OVER_ARROW_COMMANDS = {
+ "overrightarrow": "→",
+ "overleftarrow": "←",
+ "overleftrightarrow": "↔",
+}
+
+
+class FormulaCompileError(ValueError):
+ """Raised when formula source violates the Microsoft 365 profile."""
+
+
+@dataclass(frozen=True)
+class _Macro:
+ parameter_count: int
+ body: str
+
+
+def _is_command_letter(char: str) -> bool:
+ return char.isascii() and char.isalpha()
+
+
+def _xml_character_allowed(char: str) -> bool:
+ codepoint = ord(char)
+ return (
+ codepoint in {0x09, 0x0A, 0x0D}
+ or 0x20 <= codepoint <= 0xD7FF
+ or 0xE000 <= codepoint <= 0xFFFD
+ or 0x10000 <= codepoint <= 0x10FFFF
+ )
+
+
+def _read_control_word(source: str, position: int) -> tuple[str, int]:
+ if position >= len(source) or source[position] != "\\":
+ raise FormulaCompileError("Expected a LaTeX control word")
+ position += 1
+ start = position
+ while position < len(source) and _is_command_letter(source[position]):
+ position += 1
+ if position == start:
+ raise FormulaCompileError("Expected a LaTeX control word")
+ return source[start:position], position
+
+
+def _skip_whitespace(source: str, position: int) -> int:
+ while position < len(source) and source[position].isspace():
+ position += 1
+ return position
+
+
+def _read_raw_group(source: str, position: int) -> tuple[str, int]:
+ position = _skip_whitespace(source, position)
+ if position >= len(source) or source[position] != "{":
+ raise FormulaCompileError("Expected a braced LaTeX group")
+ depth = 1
+ cursor = position + 1
+ start = cursor
+ while cursor < len(source):
+ char = source[cursor]
+ if char == "\\":
+ cursor += 2
+ continue
+ if char == "{":
+ depth += 1
+ elif char == "}":
+ depth -= 1
+ if depth == 0:
+ return source[start:cursor], cursor + 1
+ cursor += 1
+ raise FormulaCompileError("Unclosed braced LaTeX group")
+
+
+def _read_optional_integer(source: str, position: int) -> tuple[int | None, int]:
+ position = _skip_whitespace(source, position)
+ if position >= len(source) or source[position] != "[":
+ return None, position
+ closing = source.find("]", position + 1)
+ if closing < 0:
+ raise FormulaCompileError("Unclosed optional macro parameter count")
+ raw = source[position + 1:closing].strip()
+ if not raw.isdigit() or not 0 <= int(raw) <= 9:
+ raise FormulaCompileError("Macro parameter count must be between 0 and 9")
+ return int(raw), closing + 1
+
+
+def _collect_macros(source: str) -> tuple[str, dict[str, _Macro]]:
+ macros: dict[str, _Macro] = {}
+ output: list[str] = []
+ position = 0
+ while position < len(source):
+ if source[position] != "\\":
+ output.append(source[position])
+ position += 1
+ continue
+ try:
+ command, command_end = _read_control_word(source, position)
+ except FormulaCompileError:
+ output.append(source[position])
+ position += 1
+ continue
+ if command not in {"newcommand", "renewcommand", "def"}:
+ output.append(source[position:command_end])
+ position = command_end
+ continue
+
+ cursor = _skip_whitespace(source, command_end)
+ if command in {"newcommand", "renewcommand"}:
+ name_group, cursor = _read_raw_group(source, cursor)
+ name_group = name_group.strip()
+ if not re.fullmatch(r"\\[A-Za-z]+", name_group):
+ raise FormulaCompileError(
+ f"\\{command} requires one control-word macro name"
+ )
+ parameter_count, cursor = _read_optional_integer(source, cursor)
+ body, cursor = _read_raw_group(source, cursor)
+ count = parameter_count or 0
+ if re.search(r"#(?:0|[1-9][0-9])", body):
+ raise FormulaCompileError("Macro body uses an invalid parameter number")
+ macros[name_group[1:]] = _Macro(count, body)
+ else:
+ if cursor >= len(source) or source[cursor] != "\\":
+ raise FormulaCompileError("\\def requires one control-word macro name")
+ name, cursor = _read_control_word(source, cursor)
+ parameters: list[int] = []
+ cursor = _skip_whitespace(source, cursor)
+ while cursor < len(source) and source[cursor] == "#":
+ if cursor + 1 >= len(source) or source[cursor + 1] not in "123456789":
+ raise FormulaCompileError("\\def parameters must use #1 through #9")
+ parameters.append(int(source[cursor + 1]))
+ cursor = _skip_whitespace(source, cursor + 2)
+ expected = list(range(1, len(parameters) + 1))
+ if parameters != expected:
+ raise FormulaCompileError("\\def parameters must be consecutive from #1")
+ body, cursor = _read_raw_group(source, cursor)
+ macros[name] = _Macro(len(parameters), body)
+ position = cursor
+ return "".join(output), macros
+
+
+def _read_macro_argument(source: str, position: int) -> tuple[str, int]:
+ position = _skip_whitespace(source, position)
+ if position >= len(source):
+ raise FormulaCompileError("Macro invocation is missing an argument")
+ if source[position] == "{":
+ return _read_raw_group(source, position)
+ if source[position] == "\\":
+ if position + 1 >= len(source):
+ raise FormulaCompileError("Macro invocation ends with a backslash")
+ if _is_command_letter(source[position + 1]):
+ _, end = _read_control_word(source, position)
+ return source[position:end], end
+ return source[position:position + 2], position + 2
+ return source[position], position + 1
+
+
+def _expand_macros(source: str, macros: dict[str, _Macro]) -> str:
+ if not macros:
+ return source
+ expansion_count = 0
+ while True:
+ output: list[str] = []
+ position = 0
+ replaced = False
+ while position < len(source):
+ if source[position] != "\\" or position + 1 >= len(source):
+ output.append(source[position])
+ position += 1
+ continue
+ if not _is_command_letter(source[position + 1]):
+ output.append(source[position:position + 2])
+ position += 2
+ continue
+ command, cursor = _read_control_word(source, position)
+ macro = macros.get(command)
+ if macro is None:
+ output.append(source[position:cursor])
+ position = cursor
+ continue
+ arguments: list[str] = []
+ for _ in range(macro.parameter_count):
+ argument, cursor = _read_macro_argument(source, cursor)
+ arguments.append(argument)
+ body = macro.body
+ for index, argument in enumerate(arguments, start=1):
+ body = body.replace(f"#{index}", argument)
+ output.append(body)
+ position = cursor
+ expansion_count += 1
+ if expansion_count > _MAX_MACRO_EXPANSIONS:
+ raise FormulaCompileError(
+ f"Formula exceeds the {_MAX_MACRO_EXPANSIONS}-macro expansion limit"
+ )
+ replaced = True
+ source = "".join(output)
+ if len(source) > _MAX_EXPANDED_LENGTH:
+ raise FormulaCompileError(
+ f"Expanded formula exceeds the {_MAX_EXPANDED_LENGTH}-character limit"
+ )
+ if not replaced:
+ return source
+
+
+def _strip_outer_delimiters(source: str) -> str:
+ pairs = (("$$", "$$"), ("$", "$"), ("\\(", "\\)"), ("\\[", "\\]"))
+ for opener, closer in pairs:
+ if source.startswith(opener):
+ if not source.endswith(closer) or len(source) <= len(opener) + len(closer):
+ raise FormulaCompileError(f"Unclosed outer LaTeX delimiter {opener!r}")
+ return source[len(opener):-len(closer)].strip()
+ return source
+
+
+def _normalize_big_delimiters(source: str) -> str:
+ def replace(match: re.Match[str]) -> str:
+ direction = match.group(1)
+ delimiter = match.group(2)
+ if direction:
+ command = {
+ "l": _BIG_LEFT_COMMAND,
+ "r": _BIG_RIGHT_COMMAND,
+ "m": _BIG_MIDDLE_COMMAND,
+ }[direction]
+ return f"\\{command}{delimiter}"
+ openers = {
+ "(", "[", "{", ".", r"\{", r"\lbrace", r"\langle", r"\lfloor",
+ r"\lceil", r"\lvert", r"\lVert", r"\lbrack",
+ }
+ closers = {
+ ")", "]", "}", r"\}", r"\rbrace", r"\rangle", r"\rfloor",
+ r"\rceil", r"\rvert", r"\rVert", r"\rbrack",
+ }
+ symmetric = {"|", r"\|", r"\vert", r"\Vert"}
+ if delimiter in openers:
+ return f"\\{_BIG_LEFT_COMMAND}{delimiter}"
+ if delimiter in closers:
+ return f"\\{_BIG_RIGHT_COMMAND}{delimiter}"
+ if delimiter in symmetric:
+ return f"\\{_BIG_SYMMETRIC_COMMAND}{delimiter}"
+ return delimiter
+
+ return _BIG_DELIMITER_RE.sub(replace, source)
+
+
+def _normalize_white_brackets(source: str) -> str:
+ source = _WHITE_OPEN_RE.sub(r"\\left⟦", source)
+ return _WHITE_CLOSE_RE.sub(r"\\right⟧", source)
+
+
+def _prepare_source(source: str) -> str:
+ source = _strip_outer_delimiters(source.strip())
+ if "%" in source:
+ position = 0
+ while position < len(source):
+ if source[position] == "%" and (position == 0 or source[position - 1] != "\\"):
+ raise FormulaCompileError("Unescaped % comments are outside the Office profile")
+ position += 1
+ without_definitions, macros = _collect_macros(source)
+ expanded = _expand_macros(without_definitions, macros)
+ return _normalize_white_brackets(_normalize_big_delimiters(expanded)).strip()
+
+
+def _space_from_length(raw: str) -> str:
+ match = _LENGTH_RE.fullmatch(raw.strip())
+ if match is None:
+ raise FormulaCompileError(f"Unsupported math spacing length: {raw!r}")
+ amount = float(match.group(1))
+ unit = match.group(2).lower()
+ multiplier = {"mu": 1.0, "em": 18.0, "ex": 9.0, "pt": 1.8}[unit]
+ mu = min(2160.0, amount * multiplier)
+ if mu <= 0:
+ return "\u200b"
+ whole_em = int(mu // 18)
+ remainder = mu - whole_em * 18
+ output = "\u2003" * whole_em
+ if remainder >= 14:
+ output += "\u2003"
+ elif remainder >= 9:
+ output += "\u2002"
+ elif remainder >= 4.5:
+ output += "\u2004"
+ elif remainder >= 3.5:
+ output += "\u205f"
+ elif remainder >= 2:
+ output += "\u2009"
+ elif remainder > 0:
+ output += "\u200b"
+ return output or "\u200b"
+
+
+class _LatexParser:
+ """Parse one prepared formula source under the Office import profile."""
+
+ def __init__(
+ self,
+ source: str,
+ *,
+ display: bool,
+ text_mode: bool = False,
+ inherited_style: RunStyle | None = None,
+ ) -> None:
+ self.source = source
+ self.position = 0
+ self.depth = 0
+ self.display = display
+ self.text_mode_depth = 1 if text_mode else 0
+ self.current_style = inherited_style
+ self.environment_stack: list[str] = []
+
+ def parse(self) -> Sequence:
+ result = self._parse_sequence()
+ if self.position != len(self.source):
+ self._fail("Unexpected trailing formula source")
+ if is_empty(result):
+ self._fail("Formula is empty")
+ return result
+
+ def _parse_sequence(
+ self,
+ *,
+ terminator: str | None = None,
+ stop_commands: frozenset[str] = frozenset(),
+ stop_at_environment_boundary: bool = False,
+ ) -> Sequence:
+ children: list[Node] = []
+ while self.position < len(self.source):
+ if terminator is not None and self.source[self.position] == terminator:
+ self.position += 1
+ return Sequence(tuple(children))
+ if any(self._at_control_word(command) for command in stop_commands):
+ return Sequence(tuple(children))
+ if stop_at_environment_boundary and self._at_environment_boundary():
+ return Sequence(tuple(children))
+
+ char = self.source[self.position]
+ if char == "}":
+ self._fail("Unexpected closing group")
+ if char == "&":
+ self._fail("Alignment marker '&' is only valid inside an environment")
+ if char in "^_":
+ append_child(children, self._parse_prescript())
+ continue
+ infix = self._current_infix_command()
+ if infix is not None:
+ if not children:
+ self._fail(f"Infix fraction \\{infix} has no numerator")
+ self._consume_control_word(infix)
+ right = self._parse_nested_sequence(
+ terminator=terminator,
+ stop_commands=stop_commands,
+ stop_at_environment_boundary=stop_at_environment_boundary,
+ )
+ if is_empty(right):
+ self._fail(f"Infix fraction \\{infix} has no denominator")
+ left = Sequence(tuple(children))
+ fraction = Fraction(
+ numerator=left,
+ denominator=right,
+ kind="bar" if infix == "over" else "noBar",
+ )
+ if infix in {"choose", "brace", "brack"}:
+ delimiters = {
+ "choose": ("(", ")"),
+ "brace": ("{", "}"),
+ "brack": ("[", "]"),
+ }[infix]
+ return Sequence((Delimiter(*delimiters, (Sequence((fraction,)),)),))
+ return Sequence((fraction,))
+
+ atom = self._parse_complete_atom()
+ append_child(children, atom)
+
+ if terminator is not None:
+ self._fail(f"Unclosed group; expected {terminator!r}")
+ return Sequence(tuple(children))
+
+ def _parse_atom(self) -> Node:
+ char = self.source[self.position]
+ if char.isspace():
+ while self.position < len(self.source) and self.source[self.position].isspace():
+ self.position += 1
+ return self._styled_text(" ") if self.text_mode_depth else Sequence(())
+ if char == "{":
+ return self._parse_group()
+ if char == "\\":
+ return self._parse_command()
+ if char in "([|":
+ return self._parse_or_literal_character_delimiter(char)
+ if char == "$":
+ if not self.text_mode_depth:
+ self._fail("Math delimiters are only allowed around the complete marker source")
+ return self._parse_text_embedded_math("$", "$")
+ if char in "#%":
+ self._fail(f"Unsupported TeX syntax character {char!r}")
+ if ord(char) < 32:
+ self._fail("Unsupported control character")
+
+ self.position += 1
+ if self.text_mode_depth:
+ return self._styled_text(char)
+ if char == "-":
+ char = "−"
+ elif char == "~":
+ return self._styled_text("\u00a0", _SPACING_STYLE)
+ style = _ROMAN_STYLE if char in _PLAIN_OPERATOR_CHARS else None
+ return self._styled_text(char, style)
+
+ def _parse_command(self) -> Node:
+ command_start = self.position
+ self.position += 1
+ if self.position >= len(self.source):
+ self._fail("Trailing backslash", position=command_start)
+
+ char = self.source[self.position]
+ if not _is_command_letter(char):
+ self.position += 1
+ if char == "\\":
+ self._fail(
+ "Row separator '\\\\' is only valid inside an environment",
+ position=command_start,
+ )
+ if char == "|":
+ paired = self._try_symmetric_command_delimiter(command_start)
+ if paired is not None:
+ return paired
+ return self._styled_text("‖", _ROMAN_STYLE)
+ if char == "(" and self.text_mode_depth:
+ return self._parse_text_embedded_math("\\(", "\\)", opened=True)
+ if char == "{":
+ paired = self._try_escaped_brace_delimiter()
+ if paired is not None:
+ return paired
+ escaped = {
+ "{": "{",
+ "}": "}",
+ "_": "_",
+ "%": "%",
+ "#": "#",
+ "$": "$",
+ "&": "&",
+ }
+ if char in escaped:
+ return self._styled_text(
+ escaped[char],
+ literal=char == "&",
+ )
+ if char in SPACING_COMMANDS:
+ return self._styled_text(SPACING_COMMANDS[char], _SPACING_STYLE)
+ self._fail(f"Unsupported control symbol \\{char}", position=command_start)
+
+ command = self._read_control_word_body()
+ self._skip_whitespace()
+ if command in UNSUPPORTED_COMMANDS:
+ self._fail(f"Unsupported LaTeX command \\{command}", position=command_start)
+ if command in {"vert", "Vert"}:
+ paired = self._try_symmetric_named_delimiter(command)
+ if paired is not None:
+ return paired
+ if command in GREEK_SYMBOLS:
+ style = None
+ if command[:1].isupper() and command not in VARIANT_UPPERCASE_GREEK:
+ style = _ROMAN_STYLE
+ return self._styled_text(GREEK_SYMBOLS[command], style)
+ if command in SYMBOL_COMMANDS:
+ return self._styled_text(SYMBOL_COMMANDS[command], _ROMAN_STYLE)
+ if command in DELIMITER_COMMANDS:
+ paired = self._try_command_delimiter(command, command_start)
+ if paired is not None:
+ return paired
+ return self._styled_text(DELIMITER_COMMANDS[command], _ROMAN_STYLE)
+ if command in NARY_COMMANDS:
+ symbol, category = NARY_COMMANDS[command]
+ return Nary(symbol=symbol, category=category)
+ if command in STANDARD_FUNCTIONS:
+ return Function(name=self._roman_name(command))
+ if command in LIMIT_FUNCTIONS:
+ return Function(name=self._roman_name(command), limit_style=True)
+ if command == "operatorname":
+ name = self._parse_required_argument("operator name", text_mode=True)
+ return Function(name=Sequence((Styled(name, _ROMAN_STYLE),)))
+ if command in {"frac", "dfrac", "tfrac", "cfrac", "ifrac"}:
+ if (
+ command == "cfrac"
+ and self.position < len(self.source)
+ and self.source[self.position] == "["
+ ):
+ self._parse_raw_optional_group("continued-fraction alignment")
+ numerator = self._parse_required_argument("fraction numerator")
+ denominator = self._parse_required_argument("fraction denominator")
+ return Fraction(
+ numerator=numerator,
+ denominator=denominator,
+ kind="skw" if command == "ifrac" else "bar",
+ )
+ if command in {"binom", "dbinom", "tbinom"}:
+ numerator = self._parse_required_argument("binomial numerator")
+ denominator = self._parse_required_argument("binomial denominator")
+ fraction = Fraction(numerator, denominator, kind="noBar")
+ return Delimiter("(", ")", (Sequence((fraction,)),))
+ if command == "genfrac":
+ left = self._delimiter_from_raw(self._parse_raw_required_group("left delimiter"))
+ right = self._delimiter_from_raw(self._parse_raw_required_group("right delimiter"))
+ thickness = self._parse_raw_required_group("fraction thickness").strip()
+ self._parse_raw_required_group("fraction style")
+ numerator = self._parse_required_argument("fraction numerator")
+ denominator = self._parse_required_argument("fraction denominator")
+ if not thickness:
+ kind = "bar"
+ elif thickness == "0":
+ kind = "noBar"
+ else:
+ thickness_match = _LENGTH_RE.fullmatch(thickness)
+ if thickness_match is None:
+ self._fail(
+ f"Invalid generalized-fraction thickness {thickness!r}"
+ )
+ kind = (
+ "noBar"
+ if float(thickness_match.group(1)) == 0.0
+ else "bar"
+ )
+ fraction = Fraction(numerator, denominator, kind=kind)
+ if left or right:
+ return Delimiter(left, right, (Sequence((fraction,)),))
+ return fraction
+ if command == "sqrt":
+ degree = self._parse_optional_argument("radical degree")
+ body = self._parse_required_argument("radical body")
+ return Radical(body=body, degree=degree)
+ if command == "root":
+ degree = self._parse_nested_sequence(stop_commands=frozenset({"of"}))
+ if not self._at_control_word("of") or is_empty(degree):
+ self._fail("\\root requires a degree followed by \\of")
+ self._consume_control_word("of")
+ body = self._parse_required_argument("radical body")
+ return Radical(body=body, degree=degree)
+ if command in {"left", _BIG_LEFT_COMMAND}:
+ return self._parse_delimited_expression(command)
+ if command == _BIG_RIGHT_COMMAND:
+ right = self._parse_delimiter_token("explicit big right delimiter")
+ return Delimiter("", right, (Sequence(()),))
+ if command == _BIG_MIDDLE_COMMAND:
+ separator = self._parse_delimiter_token("explicit big middle delimiter")
+ return Delimiter("", "", (Sequence(()), Sequence(())), separator)
+ if command == _BIG_SYMMETRIC_COMMAND:
+ return self._parse_big_symmetric_delimiter()
+ if command in {"right", "middle"}:
+ self._fail(f"Unexpected \\{command} without matching \\left", position=command_start)
+ if command == "begin":
+ return self._parse_environment()
+ if command == "end":
+ self._fail("Unexpected \\end without matching \\begin", position=command_start)
+ if command in _STYLE_WRAPPERS:
+ text_mode = command in {
+ "text", "textrm", "textnormal", "textbf", "textit", "emph",
+ "textsf", "texttt", "mbox", "hbox",
+ }
+ body = self._parse_required_argument(f"\\{command} body", text_mode=text_mode)
+ return Styled(body=body, style=_STYLE_WRAPPERS[command])
+ if command in _DECLARATION_STYLES:
+ self.current_style = merge_run_styles(
+ self.current_style,
+ _DECLARATION_STYLES[command],
+ )
+ return Sequence(())
+ if command in ACCENT_COMMANDS:
+ body = self._parse_required_argument(f"\\{command} body")
+ return Accent(character=ACCENT_COMMANDS[command], body=body)
+ if command == "overline":
+ return Bar("top", self._parse_required_argument("overline body"))
+ if command == "underline":
+ return Bar("bot", self._parse_required_argument("underline body"))
+ if command in _OVER_UNDER_COMMANDS:
+ character, position, vertical = _OVER_UNDER_COMMANDS[command]
+ body = self._parse_required_argument(f"\\{command} body")
+ return GroupChar(character, position, vertical, body)
+ if command in _OVER_ARROW_COMMANDS:
+ body = self._parse_required_argument(f"\\{command} body")
+ return GroupChar(_OVER_ARROW_COMMANDS[command], "top", "bot", body)
+ if command in {"xrightarrow", "xleftarrow"}:
+ lower = self._parse_optional_argument("arrow lower label", allow_empty=True)
+ upper = self._parse_required_argument("arrow upper label", allow_empty=True)
+ arrow = GroupChar(
+ "→" if command == "xrightarrow" else "←",
+ "bot",
+ "top",
+ upper,
+ )
+ return Limit(arrow, lower=lower) if lower is not None else arrow
+ if command in {"overset", "stackrel"}:
+ upper = self._parse_required_argument("upper limit")
+ base = self._single_node(self._parse_required_argument("limit base"))
+ return Limit(base=base, upper=upper)
+ if command == "underset":
+ lower = self._parse_required_argument("lower limit")
+ base = self._single_node(self._parse_required_argument("limit base"))
+ return Limit(base=base, lower=lower)
+ if command == "buildrel":
+ upper = self._parse_nested_sequence(stop_commands=frozenset({"over"}))
+ if not self._at_control_word("over"):
+ self._fail("\\buildrel requires \\over")
+ if is_empty(upper):
+ self._fail("\\buildrel requires an upper value")
+ self._consume_control_word("over")
+ base = self._single_node(self._parse_required_argument("buildrel base"))
+ return Limit(base=base, upper=upper)
+ if command == "substack":
+ raw = self._parse_raw_required_group("substack body")
+ return self._parse_synthetic_environment("aligned", raw)
+ if command == "bmod":
+ return Function(name=self._roman_name("mod"))
+ if command in {"pmod", "mod"}:
+ body = self._parse_required_argument(f"\\{command} body")
+ content = Sequence((
+ Text("mod", _ROMAN_STYLE),
+ Text(" ", _SPACING_STYLE),
+ *body.children,
+ ))
+ if command == "pmod":
+ return Delimiter("(", ")", (content,))
+ return content
+ if command in _STYLE_COLOR_COMMANDS:
+ color = self._parse_color()
+ body = self._parse_required_argument(f"\\{command} body")
+ return Styled(body, RunStyle(color=color))
+ if command in {"boxed", "fbox", "framebox", "cancel", "bcancel", "xcancel"}:
+ body = self._parse_required_argument(
+ f"\\{command} body",
+ text_mode=command in {"fbox", "framebox"},
+ )
+ return BorderBox(body=body, kind=command)
+ if command in {"phantom", "hphantom", "vphantom"}:
+ return Phantom(
+ body=self._parse_required_argument(f"\\{command} body"),
+ kind=command,
+ )
+ if command == "not":
+ target = self._parse_required_argument("negated relation")
+ node = self._single_node(target)
+ if isinstance(node, Text) and len(node.value) == 1:
+ negated = NEGATED_SYMBOLS.get(node.value)
+ if negated is not None:
+ return self._styled_text(negated, _ROMAN_STYLE)
+ return Accent("̸", target)
+ if command == "eqalign":
+ raw = self._parse_raw_required_group("eqalign body")
+ return self._parse_synthetic_environment("aligned", raw.replace("\\cr", "\\\\"))
+ if command == "ce":
+ raw = self._parse_raw_required_group("chemical expression")
+ return _ChemParser(raw, display=self.display).parse()
+ if command == "bra":
+ return Delimiter("⟨", "|", (self._parse_required_argument("bra body"),))
+ if command == "ket":
+ return Delimiter("|", "⟩", (self._parse_required_argument("ket body"),))
+ if command in SPACING_COMMANDS:
+ return self._styled_text(SPACING_COMMANDS[command], _SPACING_STYLE)
+ if command in {"mkern", "mskip"}:
+ return self._styled_text(self._parse_spacing_length(command), _SPACING_STYLE)
+ if command == "hspace":
+ return self._styled_text(
+ _space_from_length(self._parse_raw_required_group("horizontal space")),
+ _SPACING_STYLE,
+ )
+ if command in NO_OUTPUT_COMMANDS:
+ return Sequence(())
+ if command in DISCARDED_ARGUMENT_COMMANDS:
+ self._parse_required_argument(f"\\{command} body", allow_empty=True)
+ return Sequence(())
+ if command == "mathrel":
+ return OperatorEmulator(
+ self._parse_required_argument("math relation body")
+ )
+ if command == "mathop":
+ return Function(
+ name=self._parse_required_argument("math operator body"),
+ limit_style=True,
+ )
+
+ self._fail(f"Unsupported LaTeX command \\{command}", position=command_start)
+
+ def _parse_group(self) -> Sequence:
+ self.position += 1
+ saved_style = self.current_style
+ try:
+ return self._parse_nested_sequence(terminator="}")
+ finally:
+ self.current_style = saved_style
+
+ def _parse_required_argument(
+ self,
+ description: str,
+ *,
+ allow_empty: bool = False,
+ text_mode: bool = False,
+ ) -> Sequence:
+ self._skip_whitespace()
+ saved_text_depth = self.text_mode_depth
+ if text_mode:
+ self.text_mode_depth += 1
+ try:
+ if self.position >= len(self.source):
+ self._fail(f"{description.capitalize()} is missing")
+ if self.source[self.position] == "{":
+ result = self._parse_group()
+ else:
+ result = Sequence((self._parse_nested_bare_atom(),))
+ finally:
+ self.text_mode_depth = saved_text_depth
+ if not allow_empty and is_empty(result):
+ self._fail(f"{description.capitalize()} cannot be empty")
+ return result
+
+ def _parse_optional_argument(
+ self,
+ description: str,
+ *,
+ allow_empty: bool = False,
+ ) -> Sequence | None:
+ self._skip_whitespace()
+ if self.position >= len(self.source) or self.source[self.position] != "[":
+ return None
+ self.position += 1
+ result = self._parse_nested_sequence(terminator="]")
+ if not allow_empty and is_empty(result):
+ self._fail(f"{description.capitalize()} cannot be empty")
+ return result
+
+ def _parse_raw_required_group(self, description: str) -> str:
+ try:
+ raw, self.position = _read_raw_group(self.source, self.position)
+ except FormulaCompileError as exc:
+ self._fail(f"{description.capitalize()} must use a braced group")
+ raise AssertionError from exc
+ return raw
+
+ def _parse_raw_optional_group(self, description: str) -> str | None:
+ self._skip_whitespace()
+ if self.position >= len(self.source) or self.source[self.position] != "[":
+ return None
+ closing = self.source.find("]", self.position + 1)
+ if closing < 0:
+ self._fail(f"Unclosed {description}")
+ raw = self.source[self.position + 1:closing]
+ self.position = closing + 1
+ self._skip_whitespace()
+ return raw
+
+ def _parse_nested_sequence(self, **kwargs: object) -> Sequence:
+ self.depth += 1
+ if self.depth > _MAX_PARSE_DEPTH:
+ self._fail(f"Formula nesting exceeds {_MAX_PARSE_DEPTH} levels")
+ try:
+ return self._parse_sequence(**kwargs)
+ finally:
+ self.depth -= 1
+
+ def _parse_nested_atom(self) -> Node:
+ self.depth += 1
+ if self.depth > _MAX_PARSE_DEPTH:
+ self._fail(f"Formula nesting exceeds {_MAX_PARSE_DEPTH} levels")
+ try:
+ return self._parse_complete_atom()
+ finally:
+ self.depth -= 1
+
+ def _parse_nested_bare_atom(self) -> Node:
+ self.depth += 1
+ if self.depth > _MAX_PARSE_DEPTH:
+ self._fail(f"Formula nesting exceeds {_MAX_PARSE_DEPTH} levels")
+ try:
+ return self._parse_atom()
+ finally:
+ self.depth -= 1
+
+ def _parse_complete_atom(self) -> Node:
+ atom = self._parse_atom()
+ if isinstance(atom, (Nary, Function)):
+ atom = self._parse_limit_modifier(atom)
+ atom = self._parse_scripts(atom)
+ if isinstance(atom, (Nary, Function)):
+ atom = self._parse_limit_modifier(atom)
+ atom = self._parse_owned_body(atom)
+ return atom
+
+ def _parse_scripts(self, base: Node) -> Node:
+ subscript: Sequence | None = None
+ superscript: Sequence | None = None
+ while True:
+ saved_position = self.position
+ self._skip_whitespace()
+ if self.position >= len(self.source) or self.source[self.position] not in "^_":
+ self.position = saved_position
+ break
+ marker = self.source[self.position]
+ self.position += 1
+ argument = self._parse_required_argument(f"script marker {marker!r}")
+ if marker == "_":
+ if subscript is not None:
+ self._fail("Duplicate subscript for one base")
+ subscript = argument
+ else:
+ if superscript is not None:
+ self._fail("Duplicate superscript for one base")
+ superscript = argument
+ if subscript is None and superscript is None:
+ return base
+ if isinstance(base, Nary):
+ return Nary(
+ base.symbol,
+ base.category,
+ subscript,
+ superscript,
+ base.body,
+ base.limit_modifier,
+ )
+ if isinstance(base, Function):
+ return Function(
+ base.name,
+ base.body,
+ subscript,
+ superscript,
+ base.limit_style,
+ base.limit_modifier,
+ )
+ if isinstance(base, GroupChar):
+ return Limit(base, lower=subscript, upper=superscript)
+ if isinstance(base, Limit):
+ return Limit(
+ base.base,
+ lower=subscript or base.lower,
+ upper=superscript or base.upper,
+ )
+ return Script(base, subscript=subscript, superscript=superscript)
+
+ def _parse_prescript(self) -> Prescript:
+ subscript: Sequence | None = None
+ superscript: Sequence | None = None
+ while self.position < len(self.source) and self.source[self.position] in "^_":
+ marker = self.source[self.position]
+ self.position += 1
+ argument = self._parse_required_argument(f"pre-script marker {marker!r}")
+ if marker == "_":
+ if subscript is not None:
+ self._fail("Duplicate pre-subscript")
+ subscript = argument
+ else:
+ if superscript is not None:
+ self._fail("Duplicate pre-superscript")
+ superscript = argument
+ self._skip_whitespace()
+ if self.position >= len(self.source):
+ self._fail("Pre-script has no base")
+ base = self._parse_nested_atom()
+ return Prescript(base, subscript=subscript, superscript=superscript)
+
+ def _parse_limit_modifier(self, node: Nary | Function) -> Nary | Function:
+ saved = self.position
+ self._skip_whitespace()
+ command: str | None = None
+ if self._at_control_word("limits"):
+ command = "limits"
+ elif self._at_control_word("nolimits"):
+ command = "nolimits"
+ if command is None:
+ self.position = saved
+ return node
+ if node.limit_modifier is not None:
+ self._fail("Operator has more than one limit modifier")
+ self._consume_control_word(command)
+ if isinstance(node, Nary):
+ return Nary(
+ node.symbol,
+ node.category,
+ node.subscript,
+ node.superscript,
+ node.body,
+ command,
+ )
+ return Function(
+ node.name,
+ node.body,
+ node.subscript,
+ node.superscript,
+ node.limit_style,
+ command,
+ )
+
+ def _parse_owned_body(self, node: Nary | Function) -> Nary | Function:
+ if node.body is not None:
+ return node
+ saved = self.position
+ self._skip_whitespace()
+ leading_spacing: list[Node] = []
+ while self._transparent_prefix_follows():
+ append_child(leading_spacing, self._parse_nested_atom())
+ self._skip_whitespace()
+ if self.position < len(self.source) and self.source[self.position] in "+-":
+ append_child(leading_spacing, self._parse_nested_atom())
+ self._skip_whitespace()
+ while self._transparent_prefix_follows():
+ append_child(leading_spacing, self._parse_nested_atom())
+ self._skip_whitespace()
+ if not self._owned_body_follows():
+ self.position = saved
+ return node
+ if self.source[self.position] == "{":
+ body = self._parse_group()
+ else:
+ body = Sequence((self._parse_nested_atom(),))
+ if leading_spacing:
+ body = Sequence((*leading_spacing, *body.children))
+ if isinstance(node, Nary):
+ children = list(body.children)
+ while True:
+ saved_tail = self.position
+ self._skip_whitespace()
+ tail_prefix: list[Node] = []
+ while self._transparent_prefix_follows():
+ append_child(tail_prefix, self._parse_nested_atom())
+ self._skip_whitespace()
+ if not self._owned_body_follows():
+ self.position = saved_tail
+ break
+ for prefix_node in tail_prefix:
+ append_child(children, prefix_node)
+ append_child(children, self._parse_nested_atom())
+ body = Sequence(tuple(children))
+ elif isinstance(node, Function):
+ children = list(body.children)
+ while self._call_delimiter_follows():
+ append_child(children, self._parse_nested_atom())
+ body = Sequence(tuple(children))
+ if isinstance(node, Nary):
+ return Nary(
+ node.symbol,
+ node.category,
+ node.subscript,
+ node.superscript,
+ body,
+ node.limit_modifier,
+ )
+ return Function(
+ node.name,
+ body,
+ node.subscript,
+ node.superscript,
+ node.limit_style,
+ node.limit_modifier,
+ )
+
+ def _transparent_prefix_follows(self) -> bool:
+ if self.position >= len(self.source):
+ return False
+ if self.source[self.position] == "~":
+ return True
+ if self.source[self.position] != "\\" or self.position + 1 >= len(self.source):
+ return False
+ following = self.source[self.position + 1]
+ if not _is_command_letter(following):
+ return following in SPACING_COMMANDS
+ command, _ = _read_control_word(self.source, self.position)
+ return (
+ command in SPACING_COMMANDS
+ or command in NO_OUTPUT_COMMANDS
+ or command in {"mkern", "mskip", "hspace"}
+ )
+
+ def _call_delimiter_follows(self) -> bool:
+ self._skip_whitespace()
+ if self.position >= len(self.source):
+ return False
+ if self.source[self.position] in "([|":
+ return True
+ if self.source.startswith((r"\|", r"\{"), self.position):
+ return True
+ if self.source[self.position] != "\\":
+ return False
+ if self.position + 1 >= len(self.source) or not _is_command_letter(
+ self.source[self.position + 1]
+ ):
+ return False
+ command, _ = _read_control_word(self.source, self.position)
+ return command in BARE_DELIMITER_COMMAND_PAIRS
+
+ def _owned_body_follows(self) -> bool:
+ if self.position >= len(self.source) or self._at_environment_boundary():
+ return False
+ if any(
+ self._at_control_word(command)
+ for command in {"right", "middle", "end"}
+ ):
+ return False
+ char = self.source[self.position]
+ if char in "}])&^_+-=<>/,;:!?":
+ return False
+ if char != "\\":
+ return True
+ if (
+ self.position + 1 < len(self.source)
+ and not _is_command_letter(self.source[self.position + 1])
+ ):
+ return self.source[self.position + 1] not in {"\\", ",", ";", ":", "!", " "}
+ command, _ = _read_control_word(self.source, self.position)
+ return command not in OPERATOR_BOUNDARY_COMMANDS
+
+ def _parse_delimited_expression(self, command: str = "left") -> Delimiter:
+ left = self._parse_delimiter_token(f"\\{command}")
+ segments: list[Sequence] = []
+ separator = ""
+ stop_commands = frozenset({
+ *_MIDDLE_DELIMITER_COMMANDS,
+ *_RIGHT_DELIMITER_COMMANDS,
+ })
+ while True:
+ segments.append(
+ self._parse_nested_sequence(stop_commands=stop_commands)
+ )
+ middle_command = next(
+ (
+ candidate
+ for candidate in _MIDDLE_DELIMITER_COMMANDS
+ if self._at_control_word(candidate)
+ ),
+ None,
+ )
+ if middle_command is not None:
+ self._consume_control_word(middle_command)
+ current = self._parse_delimiter_token(f"\\{middle_command}")
+ if separator and separator != current:
+ self._fail("One delimiter expression cannot mix middle characters")
+ separator = current
+ continue
+ right = ""
+ right_command = next(
+ (
+ candidate
+ for candidate in _RIGHT_DELIMITER_COMMANDS
+ if self._at_control_word(candidate)
+ ),
+ None,
+ )
+ if right_command is not None:
+ self._consume_control_word(right_command)
+ right = self._parse_delimiter_token(f"\\{right_command}")
+ return Delimiter(left, right, tuple(segments), separator)
+
+ def _parse_big_symmetric_delimiter(self) -> Delimiter:
+ delimiter = self._parse_delimiter_token("explicit big symmetric delimiter")
+ body_start = self.position
+ closing = self._find_matching_big_symmetric(delimiter, body_start)
+ if closing is None:
+ return Delimiter("", "", (Sequence(()), Sequence(())), delimiter)
+ closing_start, after_closing = closing
+ body = self._parse_fragment(self.source[body_start:closing_start])
+ self.position = after_closing
+ return Delimiter(delimiter, delimiter, (body,))
+
+ def _find_matching_big_symmetric(
+ self,
+ delimiter: str,
+ start: int,
+ ) -> tuple[int, int] | None:
+ group_depth = 0
+ cursor = start
+ while cursor < len(self.source):
+ char = self.source[cursor]
+ if char == "{":
+ group_depth += 1
+ cursor += 1
+ continue
+ if char == "}":
+ group_depth = max(0, group_depth - 1)
+ cursor += 1
+ continue
+ if char != "\\" or cursor + 1 >= len(self.source):
+ cursor += 1
+ continue
+ if not _is_command_letter(self.source[cursor + 1]):
+ cursor += 2
+ continue
+ command, after_command = _read_control_word(self.source, cursor)
+ if group_depth != 0 or command != _BIG_SYMMETRIC_COMMAND:
+ cursor = after_command
+ continue
+ saved_position = self.position
+ try:
+ self.position = _skip_whitespace(self.source, after_command)
+ candidate = self._parse_delimiter_token(
+ "explicit big symmetric delimiter"
+ )
+ after_delimiter = self.position
+ finally:
+ self.position = saved_position
+ if candidate == delimiter:
+ return cursor, after_delimiter
+ cursor = after_delimiter
+ return None
+
+ def _parse_delimiter_token(self, owner: str) -> str:
+ self._skip_whitespace()
+ if self.position >= len(self.source):
+ self._fail(f"{owner} requires a delimiter")
+ char = self.source[self.position]
+ if char != "\\":
+ self.position += 1
+ if char in "()[]|.⟦⟧":
+ return "" if char == "." else char
+ self._fail(f"Unsupported delimiter {char!r} after {owner}")
+ command_start = self.position
+ self.position += 1
+ if self.position >= len(self.source):
+ self._fail(f"{owner} requires a delimiter", position=command_start)
+ if not _is_command_letter(self.source[self.position]):
+ delimiter = self.source[self.position]
+ self.position += 1
+ if delimiter in "{}|":
+ return "‖" if delimiter == "|" else delimiter
+ self._fail(f"Unsupported delimiter command \\{delimiter}", position=command_start)
+ command = self._read_control_word_body()
+ self._skip_whitespace()
+ if command not in DELIMITER_COMMANDS:
+ self._fail(f"Unsupported delimiter command \\{command}", position=command_start)
+ return DELIMITER_COMMANDS[command]
+
+ def _parse_or_literal_character_delimiter(self, opener: str) -> Node:
+ closer = {"(": ")", "[": "]", "|": "|"}[opener]
+ start = self.position
+ if opener == closer:
+ closing = self._find_symmetric_character(start, opener)
+ else:
+ closing = self._find_matching_character(start, opener, closer)
+ if closing is None:
+ self.position += 1
+ return self._styled_text(opener, _ROMAN_STYLE)
+ body_source = self.source[start + 1:closing]
+ body = self._parse_fragment(body_source)
+ self.position = closing + 1
+ return Delimiter(opener, closer, (body,))
+
+ def _find_symmetric_character(self, start: int, delimiter: str) -> int | None:
+ group_depth = 0
+ cursor = start + 1
+ while cursor < len(self.source):
+ char = self.source[cursor]
+ if char == "\\":
+ cursor += 2
+ continue
+ if char == "{":
+ group_depth += 1
+ elif char == "}" and group_depth:
+ group_depth -= 1
+ elif char == delimiter and group_depth == 0:
+ return cursor
+ cursor += 1
+ return None
+
+ def _try_escaped_brace_delimiter(self) -> Node | None:
+ closing = self._find_matching_control_symbol("{", "}", self.position)
+ if closing is None:
+ return None
+ body = self._parse_fragment(self.source[self.position:closing])
+ self.position = closing + 2
+ return Delimiter("{", "}", (body,))
+
+ def _try_command_delimiter(self, command: str, command_start: int) -> Node | None:
+ pair = BARE_DELIMITER_COMMAND_PAIRS.get(command)
+ if pair is None:
+ return None
+ closing_command, left, right = pair
+ closing = self._find_matching_control_word(command, closing_command, self.position)
+ if closing is None:
+ return None
+ body = self._parse_fragment(self.source[self.position:closing])
+ _, after = _read_control_word(self.source, closing)
+ self.position = _skip_whitespace(self.source, after)
+ return Delimiter(left, right, (body,))
+
+ def _try_symmetric_command_delimiter(self, command_start: int) -> Node | None:
+ closing = self.source.find("\\|", self.position)
+ if closing < 0:
+ return None
+ body = self._parse_fragment(self.source[self.position:closing])
+ self.position = closing + 2
+ return Delimiter("‖", "‖", (body,))
+
+ def _try_symmetric_named_delimiter(self, command: str) -> Node | None:
+ closing = self._find_symmetric_control_word(command, self.position)
+ if closing is None:
+ return None
+ body = self._parse_fragment(self.source[self.position:closing])
+ _, after = _read_control_word(self.source, closing)
+ self.position = _skip_whitespace(self.source, after)
+ delimiter = "‖" if command == "Vert" else "|"
+ return Delimiter(delimiter, delimiter, (body,))
+
+ def _find_matching_character(self, start: int, opener: str, closer: str) -> int | None:
+ expected_closers = [closer]
+ group_depth = 0
+ cursor = start + 1
+ explicit_delimiter_commands = {
+ "left",
+ "right",
+ "middle",
+ _BIG_LEFT_COMMAND,
+ _BIG_RIGHT_COMMAND,
+ _BIG_MIDDLE_COMMAND,
+ _BIG_SYMMETRIC_COMMAND,
+ }
+ while cursor < len(self.source):
+ char = self.source[cursor]
+ if char == "\\":
+ if cursor + 1 >= len(self.source):
+ return None
+ if not _is_command_letter(self.source[cursor + 1]):
+ cursor += 2
+ continue
+ command, cursor = _read_control_word(self.source, cursor)
+ if group_depth == 0 and command in explicit_delimiter_commands:
+ cursor = self._skip_scanned_delimiter_token(cursor)
+ continue
+ if char == "{":
+ group_depth += 1
+ cursor += 1
+ continue
+ if char == "}":
+ if group_depth == 0:
+ return None
+ group_depth -= 1
+ cursor += 1
+ continue
+ if group_depth == 0:
+ if char in "([":
+ expected_closers.append(")" if char == "(" else "]")
+ elif char in ")]":
+ if char != expected_closers[-1]:
+ return None
+ expected_closers.pop()
+ if not expected_closers:
+ return cursor
+ cursor += 1
+ return None
+
+ def _skip_scanned_delimiter_token(self, position: int) -> int:
+ position = _skip_whitespace(self.source, position)
+ if position >= len(self.source):
+ return position
+ if self.source[position] != "\\":
+ return position + 1
+ if position + 1 >= len(self.source):
+ return len(self.source)
+ if not _is_command_letter(self.source[position + 1]):
+ return position + 2
+ _, position = _read_control_word(self.source, position)
+ return position
+
+ def _find_matching_control_symbol(
+ self,
+ opener: str,
+ closer: str,
+ start: int,
+ ) -> int | None:
+ depth = 1
+ cursor = start
+ while cursor + 1 < len(self.source):
+ if self.source[cursor] != "\\":
+ cursor += 1
+ continue
+ symbol = self.source[cursor + 1]
+ if symbol == opener:
+ depth += 1
+ elif symbol == closer:
+ depth -= 1
+ if depth == 0:
+ return cursor
+ cursor += 2
+ return None
+
+ def _find_matching_control_word(
+ self,
+ opener: str,
+ closer: str,
+ start: int,
+ ) -> int | None:
+ depth = 1
+ cursor = start
+ while cursor < len(self.source):
+ if self.source[cursor] != "\\" or cursor + 1 >= len(self.source):
+ cursor += 1
+ continue
+ if not _is_command_letter(self.source[cursor + 1]):
+ cursor += 2
+ continue
+ command, end = _read_control_word(self.source, cursor)
+ if command == opener:
+ depth += 1
+ elif command == closer:
+ depth -= 1
+ if depth == 0:
+ return cursor
+ cursor = end
+ return None
+
+ def _find_symmetric_control_word(
+ self,
+ command: str,
+ start: int,
+ ) -> int | None:
+ group_depth = 0
+ cursor = start
+ while cursor < len(self.source):
+ char = self.source[cursor]
+ if char == "{":
+ group_depth += 1
+ cursor += 1
+ continue
+ if char == "}":
+ group_depth = max(0, group_depth - 1)
+ cursor += 1
+ continue
+ if char != "\\" or cursor + 1 >= len(self.source):
+ cursor += 1
+ continue
+ if not _is_command_letter(self.source[cursor + 1]):
+ cursor += 2
+ continue
+ current, end = _read_control_word(self.source, cursor)
+ if group_depth == 0 and current == command:
+ return cursor
+ cursor = end
+ return None
+
+ def _parse_environment(self) -> Node:
+ environment = self._parse_environment_name("\\begin")
+ if (
+ environment not in MATRIX_ENVIRONMENTS
+ and environment not in EQUATION_ARRAY_ENVIRONMENTS
+ ):
+ self._fail(f"Unsupported formula environment {environment!r}")
+
+ if environment == "CD":
+ return self._parse_cd_environment()
+
+ column_alignments: tuple[str, ...] = ()
+ if environment in {"array", "subarray"}:
+ raw = self._parse_raw_required_group(f"{environment} column specification")
+ filtered = tuple(char for char in raw if char in "lcr")
+ if not filtered:
+ self._fail(f"Environment {environment!r} requires l/c/r columns")
+ column_alignments = tuple("center" for _ in filtered)
+ elif environment in {"alignat", "alignat*", "alignedat"}:
+ raw = self._parse_raw_required_group(f"{environment} column count").strip()
+ if not raw.isdigit() or int(raw) <= 0:
+ self._fail(f"Environment {environment!r} requires a positive column count")
+
+ self.environment_stack.append(environment)
+ try:
+ rows = self._parse_environment_rows(environment)
+ finally:
+ self.environment_stack.pop()
+
+ if environment in MATRIX_ENVIRONMENTS:
+ if not column_alignments and rows:
+ column_alignments = tuple("center" for _ in rows[0])
+ matrix = Matrix(environment, rows, column_alignments)
+ delimiters = MATRIX_ENVIRONMENTS[environment]
+ if delimiters is not None:
+ return Delimiter(delimiters[0], delimiters[1], (Sequence((matrix,)),))
+ return matrix
+
+ eq_rows: list[Sequence] = []
+ for row in rows:
+ children: list[Node] = []
+ for index, cell in enumerate(row):
+ if index:
+ children.append(AlignmentPoint())
+ children.extend(cell.children)
+ eq_rows.append(Sequence(tuple(children)))
+ equation_array = EquationArray(tuple(eq_rows))
+ if environment == "cases":
+ return Delimiter("{", "", (Sequence((equation_array,)),))
+ if environment == "rcases":
+ return Delimiter("", "}", (Sequence((equation_array,)),))
+ return equation_array
+
+ def _parse_cd_environment(self) -> Matrix:
+ ending = r"\end{CD}"
+ closing = self.source.find(ending, self.position)
+ if closing < 0:
+ self._fail("Unclosed formula environment 'CD'")
+ raw = self.source[self.position:closing]
+ self.position = closing + len(ending)
+ raw_rows = re.split(r"\\\\|\\cr(?![A-Za-z])", raw)
+ if raw_rows and not raw_rows[-1].strip():
+ raw_rows.pop()
+ rows: list[tuple[Sequence, ...]] = []
+ for raw_row in raw_rows:
+ row = raw_row.strip()
+ if not row:
+ self._fail("Environment 'CD' cannot contain an empty row")
+ horizontal_parts = re.split(r"@(>>>|<<<)", row)
+ if len(horizontal_parts) > 1:
+ cells: list[Sequence] = []
+ for index, part in enumerate(horizontal_parts):
+ if index % 2:
+ cells.append(Sequence((Text(
+ "→" if part == ">>>" else "←",
+ _ROMAN_STYLE,
+ ),)))
+ else:
+ if "@" in part:
+ self._fail(
+ "Environment 'CD' supports only @>>>, @<<<, @VVV, and @AAA"
+ )
+ cells.append(self._parse_fragment(part.strip()))
+ rows.append(tuple(cells))
+ continue
+ vertical_tokens = re.findall(r"@(VVV|AAA)", row)
+ vertical_remainder = re.sub(r"@(VVV|AAA)|[&\s]", "", row)
+ if vertical_tokens and not vertical_remainder:
+ cells: list[Sequence] = []
+ for index, token in enumerate(vertical_tokens):
+ if index:
+ cells.append(Sequence(()))
+ cells.append(Sequence((Text(
+ "↓" if token == "VVV" else "↑",
+ _ROMAN_STYLE,
+ ),)))
+ rows.append(tuple(cells))
+ continue
+ if "@" in row:
+ self._fail("Environment 'CD' supports only @>>>, @<<<, @VVV, and @AAA")
+ rows.append(tuple(self._parse_fragment(cell.strip()) for cell in row.split("&")))
+ if not rows:
+ self._fail("Environment 'CD' cannot be empty")
+ column_count = max(len(row) for row in rows)
+ padded_rows = tuple(
+ (*row, *(Sequence(()) for _ in range(column_count - len(row))))
+ for row in rows
+ )
+ return Matrix(
+ "CD",
+ padded_rows,
+ tuple("center" for _ in range(column_count)),
+ )
+
+ def _parse_environment_rows(
+ self,
+ environment: str,
+ ) -> tuple[tuple[Sequence, ...], ...]:
+ rows: list[tuple[Sequence, ...]] = []
+ row: list[Sequence] = []
+ while True:
+ cell = self._parse_nested_sequence(stop_at_environment_boundary=True)
+ row.append(cell)
+ if self.position < len(self.source) and self.source[self.position] == "&":
+ self.position += 1
+ continue
+ if self.source.startswith("\\\\", self.position):
+ self.position += 2
+ rows.append(tuple(row))
+ row = []
+ self._skip_whitespace()
+ if self._at_control_word("end"):
+ self._consume_environment_end(environment)
+ break
+ continue
+ if self._at_control_word("cr"):
+ self._consume_control_word("cr")
+ rows.append(tuple(row))
+ row = []
+ if self._at_control_word("end"):
+ self._consume_environment_end(environment)
+ break
+ continue
+ if self._at_control_word("end"):
+ rows.append(tuple(row))
+ self._consume_environment_end(environment)
+ break
+ self._fail(f"Malformed environment {environment!r}")
+ if not rows or not rows[0]:
+ self._fail(f"Environment {environment!r} cannot be empty")
+ if environment in MATRIX_ENVIRONMENTS:
+ column_count = len(rows[0])
+ if any(len(current) != column_count for current in rows):
+ self._fail(f"Environment {environment!r} has inconsistent column counts")
+ return tuple(rows)
+
+ def _parse_synthetic_environment(self, environment: str, raw: str) -> Node:
+ parser = _LatexParser(
+ f"\\begin{{{environment}}}{raw}\\end{{{environment}}}",
+ display=self.display,
+ inherited_style=self.current_style,
+ )
+ result = parser.parse()
+ return self._single_node(result)
+
+ def _consume_environment_end(self, expected: str) -> None:
+ self._consume_control_word("end")
+ actual = self._parse_environment_name("\\end")
+ if actual != expected:
+ self._fail(
+ f"Mismatched environment ending: expected {expected!r}, got {actual!r}"
+ )
+
+ def _parse_environment_name(self, owner: str) -> str:
+ raw = self._parse_raw_required_group(f"{owner} environment name")
+ if _ENVIRONMENT_NAME_RE.fullmatch(raw) is None:
+ self._fail(f"Invalid environment name {raw!r}")
+ return raw
+
+ def _at_environment_boundary(self) -> bool:
+ return (
+ (self.position < len(self.source) and self.source[self.position] == "&")
+ or self.source.startswith("\\\\", self.position)
+ or self._at_control_word("cr")
+ or self._at_control_word("end")
+ )
+
+ def _parse_text_embedded_math(
+ self,
+ opener: str,
+ closer: str,
+ *,
+ opened: bool = False,
+ ) -> Sequence:
+ start = self.position if opened else self.position + len(opener)
+ if not opened:
+ self.position += len(opener)
+ closing = self.source.find(closer, self.position)
+ if closing < 0:
+ self._fail(f"Unclosed embedded math delimiter {opener!r}", position=start)
+ raw = self.source[self.position:closing]
+ self.position = closing + len(closer)
+ embedded = _LatexParser(
+ raw,
+ display=False,
+ inherited_style=self.current_style,
+ ).parse()
+ return Sequence((Styled(embedded, _MATH_MODE_RESET_STYLE),))
+
+ def _parse_fragment(self, raw: str) -> Sequence:
+ if not raw:
+ return Sequence(())
+ return _LatexParser(
+ raw,
+ display=self.display,
+ text_mode=bool(self.text_mode_depth),
+ inherited_style=self.current_style,
+ ).parse()
+
+ def _parse_spacing_length(self, command: str) -> str:
+ self._skip_whitespace()
+ match = _LENGTH_RE.match(self.source, self.position)
+ if match is None:
+ self._fail(f"\\{command} requires a numeric length with mu/em/ex/pt")
+ self.position = match.end()
+ self._skip_whitespace()
+ return _space_from_length(match.group(0))
+
+ def _parse_color(self) -> str:
+ raw = self._parse_raw_required_group("formula color").strip()
+ if _COLOR_HEX_RE.fullmatch(raw):
+ return raw[1:].upper()
+ color = COLOR_NAMES.get(raw.lower())
+ if color is None:
+ self._fail(f"Unsupported formula color {raw!r}")
+ return color
+
+ def _delimiter_from_raw(self, raw: str) -> str:
+ raw = raw.strip()
+ if raw in {"", "."}:
+ return ""
+ if raw in "()[]|{}⟨⟩⌊⌋⌈⌉⟦⟧":
+ return raw
+ control_symbols = {r"\{": "{", r"\}": "}", r"\|": "‖"}
+ if raw in control_symbols:
+ return control_symbols[raw]
+ if raw.startswith("\\"):
+ command = raw[1:]
+ if command in DELIMITER_COMMANDS:
+ return DELIMITER_COMMANDS[command]
+ self._fail(f"Unsupported generalized-fraction delimiter {raw!r}")
+
+ def _roman_name(self, name: str) -> Sequence:
+ return Sequence((Text(name, _ROMAN_STYLE),))
+
+ def _single_node(self, sequence: Sequence) -> Node:
+ if len(sequence.children) == 1:
+ return sequence.children[0]
+ return sequence
+
+ def _styled_text(
+ self,
+ value: str,
+ style: RunStyle | None = None,
+ *,
+ literal: bool = False,
+ ) -> Text:
+ return Text(
+ value,
+ merge_run_styles(self.current_style, style),
+ literal=literal,
+ )
+
+ def _current_infix_command(self) -> str | None:
+ for command in _INFIX_FRACTIONS:
+ if self._at_control_word(command):
+ return command
+ return None
+
+ def _at_control_word(self, expected: str) -> bool:
+ prefix = f"\\{expected}"
+ if not self.source.startswith(prefix, self.position):
+ return False
+ following = self.position + len(prefix)
+ return following >= len(self.source) or not _is_command_letter(self.source[following])
+
+ def _consume_control_word(self, expected: str) -> None:
+ if not self._at_control_word(expected):
+ self._fail(f"Expected \\{expected}")
+ self.position += len(expected) + 1
+ self._skip_whitespace()
+
+ def _read_control_word_body(self) -> str:
+ start = self.position
+ while self.position < len(self.source) and _is_command_letter(self.source[self.position]):
+ self.position += 1
+ return self.source[start:self.position]
+
+ def _skip_whitespace(self) -> None:
+ self.position = _skip_whitespace(self.source, self.position)
+
+ def _fail(self, message: str, *, position: int | None = None) -> None:
+ offset = self.position if position is None else position
+ start = max(0, offset - 16)
+ end = min(len(self.source), offset + 16)
+ context = self.source[start:end].replace("\n", " ")
+ raise FormulaCompileError(f"{message} at offset {offset}: {context!r}")
+
+
+_STYLE_COLOR_COMMANDS = frozenset({"color", "textcolor"})
+
+
+class _ChemParser:
+ """Parse the documented Microsoft 365 mhchem subset into shared AST nodes."""
+
+ _ARROWS = {
+ "<-->": "⟷",
+ "<=>": "⇌",
+ "<->": "↔",
+ "->": "→",
+ "<-": "←",
+ }
+ _UNSUPPORTED_AT_LABEL_RE = re.compile(r"@[<>=-]+\{")
+
+ def __init__(self, source: str, *, display: bool) -> None:
+ self.source = source
+ self.position = 0
+ self.display = display
+
+ def parse(self) -> Sequence:
+ children: list[Node] = []
+ while self.position < len(self.source):
+ if self._UNSUPPORTED_AT_LABEL_RE.match(self.source, self.position):
+ raise FormulaCompileError(
+ "mhchem @{} arrow labels are unsupported; use [above][below]"
+ )
+ self._reject_unsupported_arrow()
+ arrow = self._match_arrow()
+ if arrow is not None:
+ append_child(children, arrow)
+ continue
+ char = self.source[self.position]
+ if char.isspace():
+ while self.position < len(self.source) and self.source[self.position].isspace():
+ self.position += 1
+ append_child(children, Text(" ", _TEXT_STYLE))
+ continue
+ if char == "\\":
+ parser = _LatexParser(self.source[self.position:], display=self.display)
+ node = parser._parse_complete_atom()
+ self.position += parser.position
+ append_child(children, node)
+ continue
+ if char == "{":
+ raw, self.position = _read_raw_group(self.source, self.position)
+ if raw in {"(", ")", "[", "]"}:
+ append_child(children, Text(raw, _ROMAN_STYLE))
+ continue
+ body = _ChemParser(raw, display=self.display).parse()
+ append_child(children, body)
+ continue
+ if char in "([":
+ append_child(children, self._parse_grouped_formula(char))
+ continue
+ if char.isupper():
+ append_child(children, self._parse_element())
+ continue
+ if char.isdigit():
+ append_child(children, self._parse_number(children))
+ continue
+ if char == "^" and self._standalone_marker():
+ self.position += 1
+ append_child(children, Text("↑", _ROMAN_STYLE))
+ continue
+ if char in "^_":
+ if self._has_right_script_base(children):
+ base = children.pop()
+ append_child(children, self._parse_explicit_scripts(base))
+ else:
+ append_child(children, self._parse_isotope())
+ continue
+ if char in "+-":
+ if self._is_bond_dash():
+ self.position += 1
+ append_child(children, Text("‒", _ROMAN_STYLE))
+ elif (
+ children
+ and self.position > 0
+ and not self.source[self.position - 1].isspace()
+ ):
+ self._attach_charge(children)
+ else:
+ self.position += 1
+ append_child(children, Text("+" if char == "+" else "−", _ROMAN_STYLE))
+ continue
+ if char == "*":
+ self.position += 1
+ append_child(children, Text("·", _ROMAN_STYLE))
+ continue
+ if char == "=":
+ self.position += 1
+ append_child(children, Text("=", _ROMAN_STYLE))
+ continue
+ if char == "v" and self._standalone_marker():
+ self.position += 1
+ append_child(children, Text("↓", _ROMAN_STYLE))
+ continue
+ if char.islower():
+ start = self.position
+ while self.position < len(self.source) and self.source[self.position].islower():
+ self.position += 1
+ word = self.source[start:self.position]
+ following = self.position
+ while following < len(self.source) and self.source[following].isspace():
+ following += 1
+ is_variable = (
+ len(word) == 1
+ and following < len(self.source)
+ and self.source[following].isupper()
+ )
+ style = None if is_variable else _ROMAN_STYLE
+ append_child(children, Text(word, style))
+ continue
+ self.position += 1
+ append_child(children, Text("−" if char == "-" else char, _ROMAN_STYLE))
+ return Sequence(tuple(children))
+
+ def _parse_element(self) -> Node:
+ start = self.position
+ self.position += 1
+ while self.position < len(self.source) and self.source[self.position].islower():
+ self.position += 1
+ base: Node = Text(self.source[start:self.position], _ROMAN_STYLE)
+ if self.position < len(self.source) and self.source[self.position].isdigit():
+ digits = self._read_digits()
+ base = Script(base, subscript=Sequence((Text(digits, _ROMAN_STYLE),)))
+ if self.position < len(self.source) and self.source[self.position] in "^_":
+ base = self._parse_explicit_scripts(base)
+ if (
+ self.position < len(self.source)
+ and self.source[self.position] in "+-"
+ and not self._is_bond_dash()
+ ):
+ charge = self._read_charge()
+ base = self._merge_script(
+ base,
+ superscript=Sequence((Text(charge, _ROMAN_STYLE),)),
+ )
+ return base
+
+ def _parse_number(self, children: list[Node]) -> Node:
+ start = self.position
+ numerator = self._read_digits()
+ number: Node = Text(numerator, _ROMAN_STYLE)
+ if self.position < len(self.source) and self.source[self.position] == "/":
+ saved = self.position
+ self.position += 1
+ if self.position < len(self.source) and self.source[self.position].isdigit():
+ denominator = self._read_digits()
+ number = Fraction(
+ Sequence((Text(numerator, _ROMAN_STYLE),)),
+ Sequence((Text(denominator, _ROMAN_STYLE),)),
+ )
+ else:
+ self.position = saved
+ if self._is_coefficient_position(start):
+ following = self.position
+ while following < len(self.source) and self.source[following].isspace():
+ following += 1
+ if following < len(self.source) and self.source[following].isupper():
+ self.position = following
+ return Sequence((number, Text("\u2009", _SPACING_STYLE)))
+ return number
+
+ def _parse_grouped_formula(self, opener: str) -> Node:
+ closer = ")" if opener == "(" else "]"
+ start = self.position + 1
+ depth = 1
+ cursor = start
+ while cursor < len(self.source):
+ if self.source[cursor] == opener:
+ depth += 1
+ elif self.source[cursor] == closer:
+ depth -= 1
+ if depth == 0:
+ break
+ cursor += 1
+ if cursor >= len(self.source):
+ raise FormulaCompileError(f"Unclosed chemical delimiter {opener!r}")
+ body = _ChemParser(self.source[start:cursor], display=self.display).parse()
+ self.position = cursor + 1
+ base: Node = Sequence((
+ Text(opener, _ROMAN_STYLE),
+ *body.children,
+ Text(closer, _ROMAN_STYLE),
+ ))
+ if self.position < len(self.source) and self.source[self.position].isdigit():
+ digits = self._read_digits()
+ if self.position < len(self.source) and self.source[self.position] in "+-":
+ charge = digits + self._read_charge()
+ base = Script(
+ base,
+ superscript=Sequence((Text(charge, _ROMAN_STYLE),)),
+ )
+ else:
+ base = Script(base, subscript=Sequence((Text(digits, _ROMAN_STYLE),)))
+ if self.position < len(self.source) and self.source[self.position] in "+-":
+ charge = self._read_charge()
+ base = self._merge_script(
+ base,
+ superscript=Sequence((Text(charge, _ROMAN_STYLE),)),
+ )
+ return base
+
+ def _parse_isotope(self) -> Prescript:
+ subscript: Sequence | None = None
+ superscript: Sequence | None = None
+ while self.position < len(self.source) and self.source[self.position] in "^_":
+ marker = self.source[self.position]
+ self.position += 1
+ raw = self._read_chem_script()
+ value = self._chem_script_sequence(raw)
+ if marker == "_":
+ subscript = value
+ else:
+ superscript = value
+ if self.position >= len(self.source) or not self.source[self.position].isupper():
+ raise FormulaCompileError("Chemical pre-script requires an element base")
+ base = self._parse_element()
+ return Prescript(base, subscript=subscript, superscript=superscript)
+
+ def _parse_explicit_scripts(self, base: Node) -> Script:
+ subscript: Sequence | None = None
+ superscript: Sequence | None = None
+ while self.position < len(self.source) and self.source[self.position] in "^_":
+ marker = self.source[self.position]
+ self.position += 1
+ raw = self._read_chem_script()
+ if (
+ marker == "^"
+ and self.position < len(self.source)
+ and self.source[self.position] in "+-"
+ ):
+ raw += self._read_charge()
+ value = self._chem_script_sequence(raw)
+ if marker == "_":
+ subscript = value
+ else:
+ superscript = value
+ return self._merge_script(
+ base,
+ subscript=subscript,
+ superscript=superscript,
+ )
+
+ def _read_chem_script(self) -> str:
+ if self.position >= len(self.source):
+ raise FormulaCompileError("Chemical script is missing an argument")
+ if self.source[self.position] == "{":
+ raw, self.position = _read_raw_group(self.source, self.position)
+ return raw
+ char = self.source[self.position]
+ self.position += 1
+ return char
+
+ def _attach_charge(self, children: list[Node]) -> None:
+ charge = self._read_charge()
+ base = children.pop()
+ children.append(self._merge_script(
+ base,
+ superscript=Sequence((Text(charge, _ROMAN_STYLE),)),
+ ))
+
+ def _merge_script(
+ self,
+ base: Node,
+ *,
+ subscript: Sequence | None = None,
+ superscript: Sequence | None = None,
+ ) -> Script:
+ if isinstance(base, Script):
+ return Script(
+ base.base,
+ subscript or base.subscript,
+ superscript or base.superscript,
+ )
+ return Script(base, subscript=subscript, superscript=superscript)
+
+ def _chem_script_sequence(self, raw: str) -> Sequence:
+ if "\\" in raw:
+ return _LatexParser(raw, display=self.display).parse()
+ normalized = raw.replace("-", "−")
+ style = None if len(normalized) == 1 and normalized.islower() else _ROMAN_STYLE
+ return Sequence((Text(normalized, style),))
+
+ def _has_right_script_base(self, children: list[Node]) -> bool:
+ if not children or self.position == 0:
+ return False
+ previous = self.source[self.position - 1]
+ if previous.isspace() or previous in "+-=<>*/([{,;:":
+ return False
+ return not isinstance(children[-1], Limit)
+
+ def _is_coefficient_position(self, start: int) -> bool:
+ cursor = start - 1
+ while cursor >= 0 and self.source[cursor].isspace():
+ cursor -= 1
+ return cursor < 0 or self.source[cursor] in "+<>=-"
+
+ def _is_bond_dash(self) -> bool:
+ return (
+ self.position < len(self.source)
+ and self.source[self.position] == "-"
+ and self.position + 1 < len(self.source)
+ and self.source[self.position + 1].isupper()
+ )
+
+ def _read_charge(self) -> str:
+ start = self.position
+ while self.position < len(self.source) and self.source[self.position] in "+-":
+ self.position += 1
+ return self.source[start:self.position].replace("-", "−")
+
+ def _read_digits(self) -> str:
+ start = self.position
+ while self.position < len(self.source) and self.source[self.position].isdigit():
+ self.position += 1
+ return self.source[start:self.position]
+
+ def _match_arrow(self) -> Node | None:
+ for token, symbol in self._ARROWS.items():
+ if not self.source.startswith(token, self.position):
+ continue
+ self.position += len(token)
+ upper = self._read_arrow_label()
+ lower = self._read_arrow_label()
+ return Limit(Text(symbol, _ROMAN_STYLE), lower=lower, upper=upper)
+ return None
+
+ def _reject_unsupported_arrow(self) -> None:
+ for token in ("<<=>>", "<=>>", "<<=>", "->>"):
+ if self.source.startswith(token, self.position):
+ raise FormulaCompileError(
+ f"Unsupported chemical reaction arrow {token!r}"
+ )
+
+ def _read_arrow_label(self) -> Sequence | None:
+ if self.position >= len(self.source) or self.source[self.position] != "[":
+ return None
+ start = self.position + 1
+ depth = 1
+ brace_depth = 0
+ cursor = start
+ while cursor < len(self.source):
+ char = self.source[cursor]
+ if char == "\\":
+ cursor += 2
+ continue
+ if char == "{":
+ brace_depth += 1
+ elif char == "}" and brace_depth:
+ brace_depth -= 1
+ elif brace_depth == 0 and char == "[":
+ depth += 1
+ elif brace_depth == 0 and char == "]":
+ depth -= 1
+ if depth == 0:
+ raw = self.source[start:cursor]
+ self.position = cursor + 1
+ return _ChemParser(raw, display=self.display).parse()
+ cursor += 1
+ raise FormulaCompileError("Unclosed chemical arrow label")
+
+ def _standalone_marker(self) -> bool:
+ before = self.position == 0 or self.source[self.position - 1].isspace()
+ after_index = self.position + 1
+ after = after_index >= len(self.source) or self.source[after_index].isspace()
+ return before and after
+
+
+def parse_latex_formula(latex: str, *, display: bool) -> Sequence:
+ """Validate, normalize, and parse one Microsoft 365 LaTeX expression."""
+ if not isinstance(latex, str):
+ raise FormulaCompileError("LaTeX formula must be a string")
+ source = latex.strip()
+ if not source:
+ raise FormulaCompileError("LaTeX formula is empty")
+ if any(not _xml_character_allowed(char) for char in source):
+ raise FormulaCompileError("LaTeX formula contains an invalid XML character")
+ prepared = _prepare_source(source)
+ if not prepared:
+ raise FormulaCompileError("LaTeX formula is empty after preprocessing")
+ return _LatexParser(prepared, display=display).parse()
+
+
+__all__ = ["FormulaCompileError", "parse_latex_formula"]
diff --git a/skills/ppt-master/scripts/svg_to_pptx/native_objects/formula_profile.py b/skills/ppt-master/scripts/svg_to_pptx/native_objects/formula_profile.py
new file mode 100644
index 00000000..604dcd60
--- /dev/null
+++ b/skills/ppt-master/scripts/svg_to_pptx/native_objects/formula_profile.py
@@ -0,0 +1,739 @@
+#!/usr/bin/env python3
+"""
+PPT Master - Microsoft 365 LaTeX Formula Profile
+
+Keep the documented Microsoft 365 LaTeX command vocabulary and normalization
+tables separate from the native formula parser.
+
+See references/native-formula.md for the owning input-profile contract.
+
+Usage:
+ Imported by the SVG-to-PPTX native formula compiler.
+
+Examples:
+ from svg_to_pptx.native_objects.formula_profile import SYMBOL_COMMANDS
+
+Dependencies:
+ None (only uses standard library)
+"""
+
+from __future__ import annotations
+
+
+OFFICE_LATEX_PROFILE = "Microsoft 365 Windows 2606 / Mac 16.110"
+OFFICE_LATEX_SOURCE_COMMIT = "24753a186bd9e2e4614fb57680a253c33cf0df23"
+OFFICE_MHCHEM_SOURCE_COMMIT = "9459d37ab954aabec13966ecbf4968d92f086a29"
+
+GREEK_SYMBOLS = {
+ "alpha": "α",
+ "beta": "β",
+ "gamma": "γ",
+ "delta": "δ",
+ "epsilon": "ϵ",
+ "varepsilon": "ε",
+ "zeta": "ζ",
+ "eta": "η",
+ "theta": "θ",
+ "vartheta": "ϑ",
+ "iota": "ι",
+ "kappa": "κ",
+ "varkappa": "ϰ",
+ "lambda": "λ",
+ "mu": "μ",
+ "nu": "ν",
+ "xi": "ξ",
+ "omicron": "ο",
+ "pi": "π",
+ "varpi": "ϖ",
+ "rho": "ρ",
+ "varrho": "ϱ",
+ "sigma": "σ",
+ "varsigma": "ς",
+ "tau": "τ",
+ "upsilon": "υ",
+ "phi": "ϕ",
+ "varphi": "φ",
+ "chi": "χ",
+ "psi": "ψ",
+ "omega": "ω",
+ "Gamma": "Γ",
+ "varGamma": "Γ",
+ "Delta": "Δ",
+ "varDelta": "Δ",
+ "Theta": "Θ",
+ "varTheta": "Θ",
+ "Lambda": "Λ",
+ "varLambda": "Λ",
+ "Xi": "Ξ",
+ "varXi": "Ξ",
+ "Pi": "Π",
+ "varPi": "Π",
+ "Sigma": "Σ",
+ "varSigma": "Σ",
+ "Upsilon": "Υ",
+ "varUpsilon": "Υ",
+ "Phi": "Φ",
+ "varPhi": "Φ",
+ "Psi": "Ψ",
+ "varPsi": "Ψ",
+ "Omega": "Ω",
+ "varOmega": "Ω",
+}
+
+VARIANT_UPPERCASE_GREEK = frozenset({
+ "varGamma",
+ "varDelta",
+ "varTheta",
+ "varLambda",
+ "varXi",
+ "varPi",
+ "varSigma",
+ "varUpsilon",
+ "varPhi",
+ "varPsi",
+ "varOmega",
+})
+
+BINARY_SYMBOLS = {
+ "pm": "±",
+ "mp": "∓",
+ "times": "×",
+ "div": "÷",
+ "cdot": "⋅",
+ "ast": "∗",
+ "star": "⋆",
+ "circ": "∘",
+ "bullet": "∙",
+ "diamond": "⋄",
+ "oplus": "⊕",
+ "ominus": "⊖",
+ "otimes": "⊗",
+ "oslash": "⊘",
+ "odot": "⊙",
+ "cap": "∩",
+ "cup": "∪",
+ "uplus": "⊎",
+ "sqcap": "⊓",
+ "sqcup": "⊔",
+ "vee": "∨",
+ "wedge": "∧",
+ "setminus": "∖",
+ "wr": "≀",
+ "dagger": "†",
+ "ddagger": "‡",
+ "amalg": "⨿",
+ "barwedge": "⊼",
+ "veebar": "⊻",
+ "dotplus": "∔",
+ "ltimes": "⋉",
+ "rtimes": "⋊",
+ "leftthreetimes": "⋋",
+ "rightthreetimes": "⋌",
+ "curlyvee": "⋎",
+ "curlywedge": "⋏",
+ "circledast": "⊛",
+ "circledcirc": "⊚",
+ "circleddash": "⊝",
+ "boxplus": "⊞",
+ "boxminus": "⊟",
+ "boxtimes": "⊠",
+ "boxdot": "⊡",
+ "intercal": "⊺",
+ "divideontimes": "⋇",
+ "doublebarwedge": "⩞",
+ "triangleleft": "◁",
+ "triangleright": "▷",
+}
+
+RELATION_SYMBOLS = {
+ "leq": "≤",
+ "le": "≤",
+ "geq": "≥",
+ "ge": "≥",
+ "neq": "≠",
+ "ne": "≠",
+ "equiv": "≡",
+ "sim": "∼",
+ "simeq": "≃",
+ "approx": "≈",
+ "cong": "≅",
+ "ll": "≪",
+ "gg": "≫",
+ "subset": "⊂",
+ "supset": "⊃",
+ "subseteq": "⊆",
+ "supseteq": "⊇",
+ "in": "∈",
+ "ni": "∋",
+ "notin": "∉",
+ "mid": "∣",
+ "parallel": "∥",
+ "perp": "⊥",
+ "vdash": "⊢",
+ "dashv": "⊣",
+ "prec": "≺",
+ "succ": "≻",
+ "preceq": "⪯",
+ "succeq": "⪰",
+ "propto": "∝",
+ "therefore": "∴",
+ "because": "∵",
+ "bowtie": "⋈",
+ "smile": "⌣",
+ "frown": "⌢",
+ "models": "⊨",
+ "doteq": "≐",
+ "leqq": "≦",
+ "leqslant": "⩽",
+ "eqslantless": "⪕",
+ "lesssim": "≲",
+ "lessapprox": "⪅",
+ "lll": "⋘",
+ "lessdot": "⋖",
+ "lessgtr": "≶",
+ "lesseqgtr": "⋚",
+ "geqq": "≧",
+ "geqslant": "⩾",
+ "eqslantgtr": "⪖",
+ "gtrsim": "≳",
+ "ggg": "⋙",
+ "gtrdot": "⋗",
+ "gtrless": "≷",
+ "gtreqless": "⋛",
+ "sqsubset": "⊏",
+ "sqsupset": "⊐",
+ "sqsubseteq": "⊑",
+ "sqsupseteq": "⊒",
+ "subsetneq": "⊊",
+ "supsetneq": "⊋",
+ "subsetneqq": "⫋",
+ "supsetneqq": "⫌",
+ "Subset": "⋐",
+ "Supset": "⋑",
+ "Vdash": "⊩",
+ "Vvdash": "⊪",
+ "precapprox": "⪷",
+ "succapprox": "⪸",
+ "precnapprox": "⪹",
+ "succnapprox": "⪺",
+ "precneqq": "⪵",
+ "succneqq": "⪶",
+ "precnsim": "⋨",
+ "succnsim": "⋩",
+ "precsim": "≾",
+ "succsim": "≿",
+ "trianglelefteq": "⊴",
+ "trianglerighteq": "⊵",
+ "vartriangleleft": "⊲",
+ "vartriangleright": "⊳",
+ "circeq": "≗",
+ "eqcirc": "≖",
+ "triangleq": "≜",
+ "bumpeq": "≏",
+ "Bumpeq": "≎",
+ "doteqdot": "≑",
+ "risingdotseq": "≓",
+ "fallingdotseq": "≒",
+ "backsim": "∽",
+ "backsimeq": "⋍",
+ "between": "≬",
+ "pitchfork": "⋔",
+ "ncong": "≇",
+ "nsim": "≁",
+ "nleq": "≰",
+ "ngeq": "≱",
+ "nprec": "⊀",
+ "nsucc": "⊁",
+ "nvdash": "⊬",
+ "nvDash": "⊭",
+ "nVdash": "⊮",
+ "nVDash": "⊯",
+ "ntriangleleft": "⋪",
+ "ntriangleright": "⋫",
+ "ntrianglelefteq": "⋬",
+ "ntrianglerighteq": "⋭",
+}
+
+ARROW_SYMBOLS = {
+ "leftarrow": "←",
+ "rightarrow": "→",
+ "to": "→",
+ "Leftarrow": "⇐",
+ "Rightarrow": "⇒",
+ "leftrightarrow": "↔",
+ "Leftrightarrow": "⇔",
+ "uparrow": "↑",
+ "downarrow": "↓",
+ "Uparrow": "⇑",
+ "Downarrow": "⇓",
+ "updownarrow": "↕",
+ "Updownarrow": "⇕",
+ "mapsto": "↦",
+ "longmapsto": "⟼",
+ "longleftarrow": "⟵",
+ "longrightarrow": "⟶",
+ "longleftrightarrow": "⟷",
+ "Longleftarrow": "⟸",
+ "implies": "⟹",
+ "iff": "⟺",
+ "hookrightarrow": "↪",
+ "hookleftarrow": "↩",
+ "nearrow": "↗",
+ "searrow": "↘",
+ "nwarrow": "↖",
+ "swarrow": "↙",
+ "rightharpoonup": "⇀",
+ "rightharpoondown": "⇁",
+ "leftharpoonup": "↼",
+ "leftharpoondown": "↽",
+ "rightleftharpoons": "⇌",
+ "leftrightharpoons": "⇋",
+ "rightrightarrows": "⇉",
+ "leftleftarrows": "⇇",
+ "rightleftarrows": "⇄",
+ "leftrightarrows": "⇆",
+ "Lsh": "↰",
+ "Rsh": "↱",
+ "twoheadleftarrow": "↞",
+ "twoheadrightarrow": "↠",
+ "rightsquigarrow": "⇝",
+ "leftrightsquigarrow": "↭",
+ "circlearrowleft": "↺",
+ "circlearrowright": "↻",
+ "curvearrowleft": "↶",
+ "curvearrowright": "↷",
+ "dashleftarrow": "⇠",
+ "dashrightarrow": "⇢",
+ "upuparrows": "⇈",
+ "downdownarrows": "⇊",
+ "upharpoonleft": "↿",
+ "upharpoonright": "↾",
+ "downharpoonleft": "⇃",
+ "downharpoonright": "⇂",
+ "nleftarrow": "↚",
+ "nrightarrow": "↛",
+ "nleftrightarrow": "↮",
+ "nLeftarrow": "⇍",
+ "nRightarrow": "⇏",
+ "nLeftrightarrow": "⇎",
+}
+
+DOT_SYMBOLS = {
+ "ldots": "…",
+ "dots": "…",
+ "cdots": "⋯",
+ "vdots": "⋮",
+ "ddots": "⋱",
+ "iddots": "⋰",
+ "dotsb": "⋯",
+ "dotsc": "…",
+ "dotsi": "⋯",
+ "dotsm": "⋯",
+ "dotso": "…",
+}
+
+MISC_SYMBOLS = {
+ "infty": "∞",
+ "partial": "∂",
+ "nabla": "∇",
+ "forall": "∀",
+ "exists": "∃",
+ "nexists": "∄",
+ "emptyset": "∅",
+ "aleph": "ℵ",
+ "beth": "ℶ",
+ "gimel": "ℷ",
+ "daleth": "ℸ",
+ "ell": "ℓ",
+ "wp": "℘",
+ "Re": "ℜ",
+ "Im": "ℑ",
+ "hbar": "ℏ",
+ "imath": "ı",
+ "jmath": "ȷ",
+ "prime": "′",
+ "angle": "∠",
+ "measuredangle": "∡",
+ "sphericalangle": "∢",
+ "top": "⊤",
+ "bot": "⊥",
+ "neg": "¬",
+ "complement": "∁",
+ "square": "□",
+ "blacksquare": "■",
+ "triangle": "△",
+ "triangledown": "▽",
+ "blacktriangle": "▴",
+ "blacktriangledown": "▾",
+ "lozenge": "◊",
+ "blacklozenge": "⧫",
+ "bigstar": "★",
+ "Diamond": "◇",
+ "clubsuit": "♣",
+ "diamondsuit": "♢",
+ "heartsuit": "♡",
+ "spadesuit": "♠",
+ "flat": "♭",
+ "natural": "♮",
+ "sharp": "♯",
+ "checkmark": "✓",
+ "maltese": "✠",
+ "mho": "℧",
+ "Finv": "Ⅎ",
+ "Game": "⅁",
+ "backslash": "\\",
+ "Vert": "‖",
+ "bigcirc": "◯",
+ "degree": "°",
+ "land": "∧",
+ "lor": "∨",
+}
+
+SYMBOL_COMMANDS = {
+ **GREEK_SYMBOLS,
+ **BINARY_SYMBOLS,
+ **RELATION_SYMBOLS,
+ **ARROW_SYMBOLS,
+ **DOT_SYMBOLS,
+ **MISC_SYMBOLS,
+}
+
+OPERATOR_BOUNDARY_COMMANDS = frozenset({
+ *BINARY_SYMBOLS,
+ *RELATION_SYMBOLS,
+ *ARROW_SYMBOLS,
+ "bmod",
+ "land",
+ "lor",
+ "mathrel",
+ "mod",
+ "not",
+ "pmod",
+})
+
+NARY_COMMANDS = {
+ "sum": ("∑", "operator"),
+ "prod": ("∏", "operator"),
+ "coprod": ("∐", "operator"),
+ "int": ("∫", "integral"),
+ "iint": ("∬", "integral"),
+ "iiint": ("∭", "integral"),
+ "iiiint": ("⨌", "integral"),
+ "oint": ("∮", "integral"),
+ "oiint": ("∯", "integral"),
+ "oiiint": ("∰", "integral"),
+ "pvint": ("⨍", "integral"),
+ "bigcap": ("⋂", "operator"),
+ "bigcup": ("⋃", "operator"),
+ "bigvee": ("⋁", "operator"),
+ "bigwedge": ("⋀", "operator"),
+ "bigoplus": ("⨁", "operator"),
+ "bigotimes": ("⨂", "operator"),
+ "bigodot": ("⨀", "operator"),
+ "biguplus": ("⨄", "operator"),
+ "bigsqcup": ("⨆", "operator"),
+ "bigsqcap": ("⨅", "operator"),
+}
+
+ACCENT_COMMANDS = {
+ "hat": "ˆ",
+ "widehat": "̂",
+ "check": "̌",
+ "tilde": "˜",
+ "widetilde": "̃",
+ "acute": "́",
+ "grave": "̀",
+ "dot": "̇",
+ "ddot": "̈",
+ "dddot": "⃛",
+ "ddddot": "⃜",
+ "breve": "̆",
+ "bar": "̅",
+ "vec": "⃗",
+ "mathring": "̊",
+}
+
+DELIMITER_COMMANDS = {
+ "lbrace": "{",
+ "rbrace": "}",
+ "langle": "⟨",
+ "rangle": "⟩",
+ "lfloor": "⌊",
+ "rfloor": "⌋",
+ "lceil": "⌈",
+ "rceil": "⌉",
+ "lvert": "|",
+ "rvert": "|",
+ "vert": "|",
+ "lVert": "‖",
+ "rVert": "‖",
+ "Vert": "‖",
+ "lbrack": "[",
+ "rbrack": "]",
+}
+
+BARE_DELIMITER_COMMAND_PAIRS = {
+ "langle": ("rangle", "⟨", "⟩"),
+ "lceil": ("rceil", "⌈", "⌉"),
+ "lfloor": ("rfloor", "⌊", "⌋"),
+ "lvert": ("rvert", "|", "|"),
+ "lVert": ("rVert", "‖", "‖"),
+ "lbrace": ("rbrace", "{", "}"),
+ "lbrack": ("rbrack", "[", "]"),
+}
+
+STANDARD_FUNCTIONS = frozenset({
+ "arccos",
+ "arcsin",
+ "arctan",
+ "arg",
+ "cos",
+ "cosh",
+ "cot",
+ "coth",
+ "csc",
+ "deg",
+ "det",
+ "dim",
+ "exp",
+ "gcd",
+ "hom",
+ "ker",
+ "lg",
+ "ln",
+ "log",
+ "Pr",
+ "sec",
+ "sin",
+ "sinh",
+ "tan",
+ "tanh",
+})
+
+LIMIT_FUNCTIONS = frozenset({
+ "lim",
+ "liminf",
+ "limsup",
+ "sup",
+ "inf",
+ "min",
+ "max",
+ "injlim",
+ "projlim",
+ "varinjlim",
+ "varprojlim",
+ "varliminf",
+ "varlimsup",
+})
+
+COLOR_NAMES = {
+ "black": "000000",
+ "blue": "0000FF",
+ "brown": "A52A2A",
+ "cyan": "00FFFF",
+ "darkgray": "A9A9A9",
+ "gray": "808080",
+ "green": "008000",
+ "grey": "808080",
+ "lightgray": "D3D3D3",
+ "lime": "00FF00",
+ "magenta": "FF00FF",
+ "maroon": "800000",
+ "navy": "000080",
+ "olive": "808000",
+ "orange": "FFA500",
+ "pink": "FFC0CB",
+ "purple": "800080",
+ "red": "FF0000",
+ "teal": "008080",
+ "violet": "EE82EE",
+ "white": "FFFFFF",
+ "yellow": "FFFF00",
+}
+
+MATRIX_ENVIRONMENTS = {
+ "matrix": None,
+ "pmatrix": ("(", ")"),
+ "bmatrix": ("[", "]"),
+ "Bmatrix": ("{", "}"),
+ "vmatrix": ("|", "|"),
+ "Vmatrix": ("‖", "‖"),
+ "smallmatrix": None,
+ "array": None,
+ "CD": None,
+}
+
+EQUATION_ARRAY_ENVIRONMENTS = frozenset({
+ "cases",
+ "rcases",
+ "align",
+ "align*",
+ "aligned",
+ "gathered",
+ "eqnarray",
+ "eqnarray*",
+ "equation",
+ "equation*",
+ "gather",
+ "gather*",
+ "multline",
+ "multline*",
+ "split",
+ "alignat",
+ "alignat*",
+ "alignedat",
+ "subarray",
+})
+
+NO_OUTPUT_COMMANDS = frozenset({
+ "displaystyle",
+ "textstyle",
+ "scriptstyle",
+ "scriptscriptstyle",
+ "footnotesize",
+ "tiny",
+ "scriptsize",
+ "small",
+ "normalsize",
+ "large",
+ "Large",
+ "LARGE",
+ "huge",
+ "Huge",
+ "notag",
+ "nonumber",
+})
+
+DISCARDED_ARGUMENT_COMMANDS = frozenset({"tag", "label", "ref", "eqref"})
+
+NEGATED_SYMBOLS = {
+ "<": "≮",
+ "=": "≠",
+ ">": "≯",
+ "≤": "≰",
+ "≥": "≱",
+ "∼": "≁",
+ "≃": "≄",
+ "≅": "≇",
+ "≈": "≉",
+ "≡": "≢",
+ "≺": "⊀",
+ "≻": "⊁",
+ "⊂": "⊄",
+ "⊃": "⊅",
+ "⊆": "⊈",
+ "⊇": "⊉",
+ "⊑": "⋢",
+ "⊒": "⋣",
+ "⊢": "⊬",
+ "⊨": "⊭",
+ "∣": "∤",
+ "∥": "∦",
+ "∈": "∉",
+ "∋": "∌",
+ "∃": "∄",
+ "⊴": "⋬",
+ "⊵": "⋭",
+ "←": "↚",
+ "→": "↛",
+ "↔": "↮",
+ "⇐": "⇍",
+ "⇒": "⇏",
+ "⇔": "⇎",
+}
+
+SPACING_COMMANDS = {
+ "!": "\u200b",
+ ",": "\u2009",
+ ":": "\u205f",
+ ";": "\u2004",
+ " ": " ",
+ "medspace": "\u205f",
+ "thickspace": "\u2004",
+ "enspace": "\u2002",
+ "quad": "\u2003",
+ "qquad": "\u2003\u2003",
+ "space": " ",
+}
+
+UNSUPPORTED_COMMANDS = frozenset({
+ "smash",
+ "ensuremath",
+ "mathnormal",
+ "mathord",
+ "mathbin",
+ "mathopen",
+ "mathclose",
+ "mathpunct",
+ "mathinner",
+ "strut",
+ "mathstrut",
+ "rule",
+ "raisebox",
+ "above",
+ "overwithdelims",
+ "atopwithdelims",
+ "abovewithdelims",
+ "let",
+ "providecommand",
+ "edef",
+ "DeclareMathOperator",
+ "sideset",
+ "intertext",
+ "shortintertext",
+ "shoveleft",
+ "shoveright",
+ "hdotsfor",
+ "xleftrightarrow",
+ "xhookleftarrow",
+ "xhookrightarrow",
+ "xmapsto",
+ "nobreakdash",
+ "allowdisplaybreaks",
+ "displaybreak",
+ "numberwithin",
+ "raisetag",
+ "sout",
+ "uline",
+ "uuline",
+ "underbracket",
+ "overbracket",
+ "prescript",
+ "coloneqq",
+ "eqqcolon",
+ "dv",
+ "pdv",
+ "braket",
+ "SI",
+ "tensor",
+ "bond",
+ "pu",
+})
+
+
+__all__ = [
+ "ACCENT_COMMANDS",
+ "ARROW_SYMBOLS",
+ "BARE_DELIMITER_COMMAND_PAIRS",
+ "BINARY_SYMBOLS",
+ "COLOR_NAMES",
+ "DELIMITER_COMMANDS",
+ "DISCARDED_ARGUMENT_COMMANDS",
+ "EQUATION_ARRAY_ENVIRONMENTS",
+ "GREEK_SYMBOLS",
+ "LIMIT_FUNCTIONS",
+ "MATRIX_ENVIRONMENTS",
+ "NARY_COMMANDS",
+ "NEGATED_SYMBOLS",
+ "NO_OUTPUT_COMMANDS",
+ "OFFICE_LATEX_PROFILE",
+ "OFFICE_LATEX_SOURCE_COMMIT",
+ "OFFICE_MHCHEM_SOURCE_COMMIT",
+ "OPERATOR_BOUNDARY_COMMANDS",
+ "RELATION_SYMBOLS",
+ "SPACING_COMMANDS",
+ "STANDARD_FUNCTIONS",
+ "SYMBOL_COMMANDS",
+ "UNSUPPORTED_COMMANDS",
+ "VARIANT_UPPERCASE_GREEK",
+]
diff --git a/skills/ppt-master/scripts/svg_to_pptx/native_objects/formula_run_properties.py b/skills/ppt-master/scripts/svg_to_pptx/native_objects/formula_run_properties.py
new file mode 100644
index 00000000..5f449d34
--- /dev/null
+++ b/skills/ppt-master/scripts/svg_to_pptx/native_objects/formula_run_properties.py
@@ -0,0 +1,234 @@
+#!/usr/bin/env python3
+"""
+PPT Master - Native Formula Run Property Merge
+
+Merge marker-level DrawingML defaults with compiler-owned local formula style
+without discarding either source.
+
+See references/native-formula.md for the owning formula-style contract.
+
+Usage:
+ Imported by block and inline native formula builders.
+
+Examples:
+ merge_formula_run_properties(run, marker_properties)
+
+Dependencies:
+ None (only uses standard library)
+"""
+
+from __future__ import annotations
+
+from copy import deepcopy
+from xml.etree import ElementTree as ET
+
+from .formula_omml import validate_omml_resource_limits
+from .formula_parser import FormulaCompileError
+
+
+DML_NS = "http://schemas.openxmlformats.org/drawingml/2006/main"
+MATH_NS = "http://schemas.openxmlformats.org/officeDocument/2006/math"
+
+_DML_RUN_PROPERTIES = f"{{{DML_NS}}}rPr"
+_MATH_RUN_PROPERTIES = f"{{{MATH_NS}}}rPr"
+_MATH_CONTROL_PROPERTIES = f"{{{MATH_NS}}}ctrlPr"
+_CONTROL_OWNER_TAGS = frozenset({
+ f"{{{MATH_NS}}}{name}"
+ for name in (
+ "accPr",
+ "barPr",
+ "borderBoxPr",
+ "boxPr",
+ "dPr",
+ "fPr",
+ "groupChrPr",
+ "naryPr",
+ "radPr",
+ )
+})
+_FILL_TAGS = frozenset({
+ f"{{{DML_NS}}}blipFill",
+ f"{{{DML_NS}}}gradFill",
+ f"{{{DML_NS}}}grpFill",
+ f"{{{DML_NS}}}noFill",
+ f"{{{DML_NS}}}pattFill",
+ f"{{{DML_NS}}}solidFill",
+})
+_COLOR_TAGS = frozenset({
+ f"{{{DML_NS}}}{name}"
+ for name in ("hslClr", "prstClr", "schemeClr", "scrgbClr", "srgbClr", "sysClr")
+})
+_ALPHA_TRANSFORM_TAGS = frozenset({
+ f"{{{DML_NS}}}{name}"
+ for name in ("alpha", "alphaMod", "alphaOff")
+})
+_RUN_PROPERTY_ORDER = {
+ f"{{{DML_NS}}}{name}": index
+ for index, names in enumerate((
+ ("ln",),
+ ("blipFill", "gradFill", "grpFill", "noFill", "pattFill", "solidFill"),
+ ("effectDag", "effectLst"),
+ ("highlight",),
+ ("uLnTx",),
+ ("uLn",),
+ ("uFillTx",),
+ ("uFill",),
+ ("latin",),
+ ("ea",),
+ ("cs",),
+ ("sym",),
+ ("hlinkClick",),
+ ("hlinkMouseOver",),
+ ("rtl",),
+ ("extLst",),
+ ))
+ for name in names
+}
+
+
+def _replace_child_group(
+ target: ET.Element,
+ local: ET.Element,
+ tags: frozenset[str],
+) -> None:
+ local_children = [child for child in local if child.tag in tags]
+ if not local_children:
+ return
+ positions = [index for index, child in enumerate(target) if child.tag in tags]
+ insert_at = positions[0] if positions else 0
+ for child in list(target):
+ if child.tag in tags:
+ target.remove(child)
+ for offset, child in enumerate(local_children):
+ target.insert(insert_at + offset, deepcopy(child))
+
+
+def _inherit_default_fill_alpha(
+ default_properties: ET.Element,
+ local_properties: ET.Element,
+) -> None:
+ default_fill = next(
+ (child for child in default_properties if child.tag in _FILL_TAGS),
+ None,
+ )
+ local_fill = next(
+ (child for child in local_properties if child.tag in _FILL_TAGS),
+ None,
+ )
+ if default_fill is None or local_fill is None:
+ return
+ default_color = next(
+ (child for child in default_fill if child.tag in _COLOR_TAGS),
+ None,
+ )
+ local_color = next(
+ (child for child in local_fill if child.tag in _COLOR_TAGS),
+ None,
+ )
+ if default_color is None or local_color is None:
+ return
+ if any(child.tag in _ALPHA_TRANSFORM_TAGS for child in local_color):
+ return
+ for child in default_color:
+ if child.tag in _ALPHA_TRANSFORM_TAGS:
+ local_color.append(deepcopy(child))
+
+
+def _normalize_child_order(properties: ET.Element) -> None:
+ children = list(properties)
+ ordered = sorted(
+ enumerate(children),
+ key=lambda item: (
+ _RUN_PROPERTY_ORDER.get(item[1].tag, len(_RUN_PROPERTY_ORDER)),
+ item[0],
+ ),
+ )
+ if [child for _, child in ordered] == children:
+ return
+ for child in children:
+ properties.remove(child)
+ for _, child in ordered:
+ properties.append(child)
+
+
+def _merged_properties(
+ default_properties: ET.Element,
+ local_properties: ET.Element | None,
+) -> ET.Element:
+ merged = deepcopy(default_properties)
+ if local_properties is None:
+ _normalize_child_order(merged)
+ return merged
+ local = deepcopy(local_properties)
+ _inherit_default_fill_alpha(merged, local)
+ merged.attrib.update(local.attrib)
+ _replace_child_group(merged, local, _FILL_TAGS)
+ for child in local:
+ if child.tag in _FILL_TAGS:
+ continue
+ for existing in list(merged):
+ if existing.tag == child.tag:
+ merged.remove(existing)
+ merged.append(deepcopy(child))
+ _normalize_child_order(merged)
+ return merged
+
+
+def merge_formula_run_properties(
+ run: ET.Element,
+ default_properties: ET.Element,
+) -> None:
+ """Merge one formula run's local a:rPr over marker-level defaults."""
+ if default_properties.tag != _DML_RUN_PROPERTIES:
+ raise RuntimeError("Formula run defaults must use one a:rPr root")
+ local_properties = next(
+ (child for child in run if child.tag == _DML_RUN_PROPERTIES),
+ None,
+ )
+ merged = _merged_properties(default_properties, local_properties)
+ if local_properties is not None:
+ run.remove(local_properties)
+ insert_at = 1 if len(run) and run[0].tag == _MATH_RUN_PROPERTIES else 0
+ run.insert(insert_at, merged)
+
+
+def merge_formula_control_properties(
+ root: ET.Element,
+ default_properties: ET.Element,
+) -> None:
+ """Merge marker defaults onto visible non-selectable math controls."""
+ if default_properties.tag != _DML_RUN_PROPERTIES:
+ raise RuntimeError("Formula control defaults must use one a:rPr root")
+ for owner in root.iter():
+ if owner.tag not in _CONTROL_OWNER_TAGS:
+ continue
+ control = next(
+ (child for child in owner if child.tag == _MATH_CONTROL_PROPERTIES),
+ None,
+ )
+ if control is None:
+ control = ET.SubElement(owner, _MATH_CONTROL_PROPERTIES)
+ local_properties = next(
+ (child for child in control if child.tag == _DML_RUN_PROPERTIES),
+ None,
+ )
+ merged = _merged_properties(default_properties, local_properties)
+ if local_properties is not None:
+ control.remove(local_properties)
+ control.insert(0, merged)
+
+
+def serialize_styled_formula_omml(root: ET.Element) -> str:
+ """Serialize styled OMML under the compiler's final size and depth limits."""
+ try:
+ xml = ET.tostring(root, encoding="unicode", short_empty_elements=True)
+ return validate_omml_resource_limits(xml)
+ except (FormulaCompileError, RecursionError) as exc:
+ raise RuntimeError(f"Invalid styled formula OMML: {exc}") from exc
+
+
+__all__ = [
+ "merge_formula_control_properties",
+ "merge_formula_run_properties",
+ "serialize_styled_formula_omml",
+]
diff --git a/skills/ppt-master/scripts/svg_to_pptx/native_objects/inline_formula.py b/skills/ppt-master/scripts/svg_to_pptx/native_objects/inline_formula.py
index aaa1e356..d429b951 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/native_objects/inline_formula.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/native_objects/inline_formula.py
@@ -4,6 +4,8 @@ PPT Master - Native Inline Formula Contract
Validate SVG inline-formula markers and build editable PowerPoint math runs.
+See references/native-formula.md for the owning inline-formula contract.
+
Usage:
Imported by the SVG quality checker and SVG-to-PPTX text converter.
@@ -16,7 +18,6 @@ Dependencies:
from __future__ import annotations
-from copy import deepcopy
from xml.etree import ElementTree as ET
from ..drawingml.utils import parse_inline_style, parse_svg_color
@@ -24,6 +25,11 @@ from .formula_compiler import (
FormulaCompileError,
compile_latex_to_inline_omml,
)
+from .formula_run_properties import (
+ merge_formula_control_properties,
+ merge_formula_run_properties,
+ serialize_styled_formula_omml,
+)
SVG_NS = "http://www.w3.org/2000/svg"
@@ -39,7 +45,6 @@ _SVG_TEXT = f"{{{SVG_NS}}}text"
_SVG_TSPAN = f"{{{SVG_NS}}}tspan"
_SVG_A = f"{{{SVG_NS}}}a"
_MATH_RUN = f"{{{MATH_NS}}}r"
-_MATH_RUN_PROPERTIES = f"{{{MATH_NS}}}rPr"
_DML_RUN_PROPERTIES = f"{{{DML_NS}}}rPr"
_POSITION_ATTRIBUTES = ("x", "y", "dx", "dy")
_PARAGRAPH_ATTRIBUTES = (
@@ -253,7 +258,7 @@ def inline_formula_marker_errors(root: ET.Element) -> list[str]:
def _apply_run_properties(omml: str, run_properties_xml: str) -> str:
- """Replace DrawingML properties on every Office Math leaf run."""
+ """Merge DrawingML defaults onto every Office Math leaf run."""
try:
root = ET.fromstring(omml)
wrapper = ET.fromstring(
@@ -271,13 +276,10 @@ def _apply_run_properties(omml: str, run_properties_xml: str) -> str:
raise RuntimeError("Inline formula styling must use one a:rPr root")
for run in root.iter(_MATH_RUN):
- for existing in list(run):
- if existing.tag == _DML_RUN_PROPERTIES:
- run.remove(existing)
- insert_at = 1 if len(run) and run[0].tag == _MATH_RUN_PROPERTIES else 0
- run.insert(insert_at, deepcopy(run_properties))
+ merge_formula_run_properties(run, run_properties)
+ merge_formula_control_properties(root, run_properties)
- return ET.tostring(root, encoding="unicode", short_empty_elements=True)
+ return serialize_styled_formula_omml(root)
def build_inline_formula_xml(latex: str, run_properties_xml: str) -> str: