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

fix(native-formula): reserve structural inline math height

hugohe309404779f6a6
diff --git a/skills/ppt-master/references/executor-base.md b/skills/ppt-master/references/executor-base.md
index 88607081..2b2e373d 100644
--- a/skills/ppt-master/references/executor-base.md
+++ b/skills/ppt-master/references/executor-base.md
@@ -120,7 +120,7 @@ Apply the content-vs-expression contract above within the selected reading mode.
- **Prepared decorative lettering**: When the approved plan selects stable artistic lettering as part of the visual, place its prepared AI/slice file as an image asset and keep the ordinary editable title/subtitle in separate native text frames. Do not recreate the asset with layered glyph copies or native WordArt; when the plan keeps that wording as native text and prepares no lettering asset, use ordinary `<text>` without inventing a missing image.
- **Outside-band recovery**: for structural text, reflow geometry and use the declared role band locally. For a sparse display occurrence, keep the unitless value and verify that its deck-wide count remains at most two. Never flatten a justified distinction or add a role merely to silence the checker. Mirror pages preserve exact source typography as inherited input.
- Images MUST reference files listed under `images`; no invented filenames
-- For math, load [`native-formula.md`](./native-formula.md): simple notation stays text; one-line structural prose uses inline; matrices, multiline derivations, or standalone high structure use block. Keep exact LaTeX plus preview; never use an image.
+- For math, load [`native-formula.md`](./native-formula.md): simple notation stays text; one-line structural prose uses inline only when its native-height envelope fits the reserved row/module space; matrices, multiline derivations, standalone high structure, or vertically expanding math without that clearance use block. Keep exact LaTeX plus preview; never use an image.
Return upstream before any derived/accent identity becomes recurring or structural, or when an undeclared display size reaches its third occurrence, then update the retained context under §2.1. Local garnish, same-role `±2`px adjustments, and at most two sparse display-size occurrences need no lock row. Never expand the lock to silence a comparison. New icon acquisition, images, structural fonts, role anchors, and resources keep their preparation/role rules.
diff --git a/skills/ppt-master/references/native-formula.md b/skills/ppt-master/references/native-formula.md
index 55bc33bf..1771c4d1 100644
--- a/skills/ppt-master/references/native-formula.md
+++ b/skills/ppt-master/references/native-formula.md
@@ -19,8 +19,8 @@ construction, accent, or complex script.
| Content form | Authoring choice |
|---|---|
| Short variables, percentages, simple assignments, or notation such as `O(n log n)` | Ordinary editable SVG text |
-| One-line structural math embedded in prose | Inline native marker |
-| Matrix, `cases`, `aligned`, multiline derivation, or standalone high-structure expression | Block native marker |
+| One-line structural math embedded in prose whose native-height envelope fits the reserved row/module space | Inline native marker |
+| Matrix, `cases`, `aligned`, multiline derivation, standalone high-structure expression, or vertically expanding math that cannot fit its prose row | Block native marker |
The Strategist's `Mathematical content` field does not pre-decide this choice.
Formula handling is not a user-confirmed policy, image resource, manifest, or
@@ -57,6 +57,14 @@ preserved `txBody`, geometry transport subtree, another inline marker, or any
`data-pptx-replace-with` subtree. Export keeps the surrounding text runs in the
same `a:p` and replaces only the marker run with `a14:m > m:oMath`.
+**Hard rule — reserve native height**: Treat the parsed formula structure, not
+its flat SVG preview, as vertical layout truth. Keep adjacent content outside
+the native ascent/descent required by fractions, radicals, nested scripts,
+n-ary limits, accents, and other stacked structures. The exporter and SVG
+checker use the same structural envelope. If the prose row or root module
+cannot reserve that space without overlap, isolate the formula line or use the
+block marker.
+
### 2.2 Block formula
```xml
@@ -154,5 +162,7 @@ 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.
+**Validation**: The first-page/final SVG checker validates every marker,
+compiles its LaTeX, and applies the shared native-height envelope to page/module
+text bounds before release; native export repeats validation and uses that
+envelope for the generated text frame.
diff --git a/skills/ppt-master/references/shared-standards-core.md b/skills/ppt-master/references/shared-standards-core.md
index d3190c2f..97572cb3 100644
--- a/skills/ppt-master/references/shared-standards-core.md
+++ b/skills/ppt-master/references/shared-standards-core.md
@@ -626,7 +626,7 @@ These forms are needed only when the stated PPT behavior matters:
### 4.3 Element Grouping (Mandatory)
-**Hard rule — root groups protect body-text layout**: Every visible direct root `<g>` declares positive root-coordinate `data-pptx-bounds="x y width height"`. Keep it when frame/native coordinates size one PowerPoint object; placeholder bounds also supply the slot frame. On flat pages, make each module zone as generous as the canvas and sibling layout allow without overlapping another module zone. Checker validates this subcanvas against the root `viewBox`, then recursively validates only estimable `<text>` descendants against it using the shared SVG-to-PPTX per-run width estimate and DrawingML wrapping headroom. It validates every estimable visible text carrier directly against the root `viewBox` with the same per-run estimate before that headroom. Nested groups and all shapes, images, paths, `<use>` instances, effects, and object frames are not module-boundary inputs. Per side, Checker ignores overflow through `1px`; module-boundary overflow warns through `5%` and fails above `5%`, while any larger root-`viewBox` text overflow fails. Bounds do not clip or reflow; unestimable visible text receives an advisory warning. The only page-boundary exception is a wholly off-canvas direct-root Morph endpoint marked `data-pptx-morph-staging="true"`; its own module bounds still apply, retained Morph uses an explicit pair, and the marker never excuses partial page overflow.
+**Hard rule — root groups protect body-text layout**: Every visible direct root `<g>` declares positive root-coordinate `data-pptx-bounds="x y width height"`. Keep it when frame/native coordinates size one PowerPoint object; placeholder bounds also supply the slot frame. On flat pages, make each module zone as generous as the canvas and sibling layout allow without overlapping another module zone. Checker validates this subcanvas against the root `viewBox`, then recursively validates only estimable `<text>` descendants against it using the shared SVG-to-PPTX per-run width estimate, inline-formula native-height envelope, and DrawingML wrapping headroom. It validates every estimable visible text carrier directly against the root `viewBox` with the same per-run estimate before that headroom. Nested groups and all shapes, images, paths, `<use>` instances, effects, and object frames are not module-boundary inputs. Per side, Checker ignores overflow through `1px`; module-boundary overflow warns through `5%` and fails above `5%`, while any larger root-`viewBox` text overflow fails. Bounds do not clip or reflow; unestimable visible text receives an advisory warning. The only page-boundary exception is a wholly off-canvas direct-root Morph endpoint marked `data-pptx-morph-staging="true"`; its own module bounds still apply, retained Morph uses an explicit pair, and the marker never excuses partial page overflow.
Wrap each logical Slide-local body unit in one descriptive top-level `<g id>`; group count follows the page's semantic units, and each group becomes one stable animation target when animation is enabled. Generic deck-wide animation gives that target one step; an explicit animation sidecar may assign it several ordered effects. Nested implementation groups may remain anonymous and need no bounds; any nested bounds are ignored. Flat pages use ordinary groups; structured slots already qualify, while titles, direct atomic Master/Layout elements, and canvas-level static framing—including background images and full-canvas scrim/decoration rectangles—may remain root primitives. On flat pages, give such static framing a stable `id` plus `data-pptx-role="background"` / `"decoration"`; never add a `<g>` solely to silence an ungrouped-element advisory.
diff --git a/skills/ppt-master/scripts/svg_quality/checker.py b/skills/ppt-master/scripts/svg_quality/checker.py
index 9c2e9f3f..e0ded183 100644
--- a/skills/ppt-master/scripts/svg_quality/checker.py
+++ b/skills/ppt-master/scripts/svg_quality/checker.py
@@ -219,6 +219,7 @@ except ImportError:
try:
from svg_to_pptx.native_objects import (
INLINE_FORMULA_ATTR as _INLINE_FORMULA_ATTR,
+ estimate_inline_formula_vertical_extent as _estimate_inline_formula_vertical_extent,
native_fallback_kind as _native_fallback_kind,
inline_formula_marker_errors as _inline_formula_marker_errors,
native_marker_legacy_warnings as _native_marker_legacy_warnings,
@@ -227,6 +228,7 @@ try:
)
except ImportError:
_INLINE_FORMULA_ATTR = 'data-pptx-inline-formula'
+ _estimate_inline_formula_vertical_extent = None
_native_fallback_kind = None
_inline_formula_marker_errors = None
_native_marker_legacy_warnings = None
@@ -1946,6 +1948,7 @@ class SVGQualityChecker:
parent_by_id,
) or '1',
'opacity_chain': tuple(reversed(opacity_chain)),
+ 'inline_formula': owner.get(_INLINE_FORMULA_ATTR),
})
return cls._coalesce_checker_text_runs(resolved)
@@ -1978,6 +1981,10 @@ class SVGQualityChecker:
merged: List[Dict] = []
previous_signature: Tuple | None = None
for run in runs:
+ if run.get('inline_formula') is not None:
+ merged.append(run)
+ previous_signature = None
+ continue
current_signature = signature(run)
if merged and current_signature == previous_signature:
candidate = {
@@ -1996,6 +2003,29 @@ class SVGQualityChecker:
previous_signature = current_signature
return merged
+ @staticmethod
+ def _text_line_vertical_extent(
+ runs: List[Dict],
+ font_size: float,
+ ) -> Tuple[float, float]:
+ """Return native-math-aware ascent/descent for checker bounds."""
+ ascent = font_size * 0.85
+ descent = font_size * 0.35
+ if _estimate_inline_formula_vertical_extent is None:
+ return ascent, descent
+ for run in runs:
+ latex = run.get('inline_formula')
+ if latex is None:
+ continue
+ try:
+ run_font_size = float(run.get('font_size', font_size))
+ extent = _estimate_inline_formula_vertical_extent(str(latex))
+ except (TypeError, ValueError):
+ continue
+ ascent = max(ascent, run_font_size * extent.ascent_em)
+ descent = max(descent, run_font_size * extent.descent_em)
+ return ascent, descent
+
def _check_text_output_geometry(
self,
root: ET.Element,
@@ -2191,8 +2221,9 @@ class SVGQualityChecker:
right = x + width
else:
return None
- top = y - font_size * 0.85
- bottom = y + font_size * 0.35
+ ascent, descent = cls._text_line_vertical_extent(runs, font_size)
+ top = y - ascent
+ bottom = y + descent
return cls._transformed_rect_bounds(
line_el,
diff --git a/skills/ppt-master/scripts/svg_to_pptx/drawingml/elements.py b/skills/ppt-master/scripts/svg_to_pptx/drawingml/elements.py
index 13ac4a1a..a24bd2ef 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/drawingml/elements.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/drawingml/elements.py
@@ -1969,6 +1969,39 @@ _INLINE_FORMULA_ATTR = 'data-pptx-inline-formula'
_INLINE_FORMULA_KEY = '_inline_formula_latex'
+def _text_line_vertical_extent(
+ runs: list[dict[str, Any]],
+ font_size: float,
+) -> tuple[float, float, bool]:
+ """Return native-math-aware ascent/descent for one authored text line."""
+ ascent = font_size * 0.85
+ descent = font_size * 0.35
+ has_inline_formula = False
+ from ..native_objects.formula_compiler import (
+ estimate_inline_formula_vertical_extent,
+ )
+
+ for run in runs:
+ latex = run.get(_INLINE_FORMULA_KEY)
+ if latex is None:
+ continue
+ has_inline_formula = True
+ run_font_size = float(run.get('font_size', font_size))
+ extent = estimate_inline_formula_vertical_extent(str(latex))
+ ascent = max(ascent, run_font_size * extent.ascent_em)
+ descent = max(descent, run_font_size * extent.descent_em)
+ return ascent, descent, has_inline_formula
+
+
+def _native_text_line_frame_height(
+ ascent: float,
+ descent: float,
+ font_size: float,
+) -> float:
+ """Add the ordinary text-frame headroom to one visible line extent."""
+ return ascent + descent + font_size * 0.30
+
+
def _normalize_text_run_whitespace(
runs: list[dict[str, Any]],
) -> list[dict[str, Any]]:
@@ -2888,6 +2921,7 @@ def convert_text(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None:
# of how many merge into one <a:p>; used to size the textbox so PowerPoint
# has room to wrap text to the SVG's original line widths.
visual_line_widths: list[float] = []
+ visual_line_runs: list[list[dict[str, Any]]] = []
if line_height_px is not None and line_height_px > 0:
xml_space = resolve_project_xml_space(elem)
paragraph_runs = []
@@ -2903,6 +2937,7 @@ def convert_text(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None:
line_runs = _normalize_text_run_whitespace(line_runs)
if not line_runs:
continue
+ visual_line_runs.append(line_runs)
visual_line_widths.append(
_estimate_bullet_line_width(line_runs, fonts, ctx)
)
@@ -2944,6 +2979,7 @@ def convert_text(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None:
paragraph_runs = None
paragraph_space_before = []
visual_line_widths = []
+ visual_line_runs = []
else:
stripped_paragraphs: list[list[dict[str, Any]]] = []
for line_runs in paragraph_runs:
@@ -2975,24 +3011,61 @@ def convert_text(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None:
paragraph_space_before = []
paragraph_bullets = []
visual_line_widths = []
+ visual_line_runs = []
single_bullet = None
# Estimate text dimensions
if paragraph_runs is not None:
# Use the widest authored visual line, not a reflow-joined paragraph.
text_width = max(visual_line_widths) if visual_line_widths else 0.0
- # Keep the authored visual-line count as the source height contract.
- text_height = (
- line_height_px * (len(visual_line_widths) - 1)
- + sum(paragraph_space_before)
- + font_size * 1.5
- )
+ line_extents = [
+ _text_line_vertical_extent(line, font_size)
+ for line in visual_line_runs
+ ]
+ text_height = sum(paragraph_space_before)
+ for ascent, descent, has_formula in line_extents[:-1]:
+ line_advance = line_height_px
+ if has_formula:
+ line_advance = max(
+ line_advance,
+ _native_text_line_frame_height(
+ ascent,
+ descent,
+ font_size,
+ ),
+ )
+ text_height += line_advance
+ first_line_ascent = line_extents[0][0]
+ last_ascent, last_descent, last_has_formula = line_extents[-1]
+ last_line_height = font_size * 1.5
+ if last_has_formula:
+ last_line_height = max(
+ last_line_height,
+ _native_text_line_frame_height(
+ last_ascent,
+ last_descent,
+ font_size,
+ ),
+ )
+ text_height += last_line_height
else:
text_width = _estimate_text_runs_width(runs)
if single_bullet:
fs_px = float(runs[0].get('font_size', font_size)) if runs else font_size
text_width += _bullet_margin_px(single_bullet, fs_px)
+ first_line_ascent, line_descent, has_formula = (
+ _text_line_vertical_extent(runs, font_size)
+ )
text_height = font_size * 1.5
+ if has_formula:
+ text_height = max(
+ text_height,
+ _native_text_line_frame_height(
+ first_line_ascent,
+ line_descent,
+ font_size,
+ ),
+ )
padding = _textbox_padding(font_size)
# Adjust position based on text-anchor. This first box follows the visible
@@ -3005,7 +3078,7 @@ def convert_text(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None:
else:
box_x = x - padding
- box_y = y - font_size * 0.85
+ box_y = y - first_line_ascent
box_w = text_width + padding * 2
box_h = text_height + padding
if reflect_y:
diff --git a/skills/ppt-master/scripts/svg_to_pptx/native_objects/__init__.py b/skills/ppt-master/scripts/svg_to_pptx/native_objects/__init__.py
index bae05579..8e4ca084 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/native_objects/__init__.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/native_objects/__init__.py
@@ -35,6 +35,7 @@ from .fallback_hash import (
stamp_native_fallback_baseline,
)
from .formula import FormulaSpec, build_native_formula, validate_formula_payload
+from .formula_compiler import estimate_inline_formula_vertical_extent
from .inline_formula import (
INLINE_FORMULA_ATTR,
inline_formula_marker_errors,
@@ -79,6 +80,7 @@ from .workbook import (
__all__ = [
"convert_native_object",
+ "estimate_inline_formula_vertical_extent",
"INLINE_FORMULA_ATTR",
"NativeMarkerAttributeError",
"native_fallback_kind",
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
index 863773a5..1d6c9fa1 100644
--- 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
@@ -168,6 +168,19 @@ class BorderBox:
kind: str
+@dataclass(frozen=True)
+class FormulaVerticalExtent:
+ """Conservative formula bounds relative to the surrounding baseline."""
+
+ ascent_em: float
+ descent_em: float
+
+ @property
+ def height_em(self) -> float:
+ """Return total vertical extent in units of the owning font size."""
+ return self.ascent_em + self.descent_em
+
+
Node = (
Text
| Sequence
@@ -192,6 +205,227 @@ Node = (
)
+_BASE_VERTICAL_EXTENT = FormulaVerticalExtent(0.85, 0.35)
+# These ratios model Office Math topology rather than any one installed font.
+# The ordinary-text floor matches the exporter/checker baseline contract.
+_SCRIPT_SCALE = 0.62
+_FRACTION_SCALE = 0.68
+
+
+def _max_vertical_extent(
+ *extents: FormulaVerticalExtent,
+) -> FormulaVerticalExtent:
+ if not extents:
+ return FormulaVerticalExtent(0.0, 0.0)
+ return FormulaVerticalExtent(
+ max(extent.ascent_em for extent in extents),
+ max(extent.descent_em for extent in extents),
+ )
+
+
+def _scaled_vertical_extent(
+ extent: FormulaVerticalExtent,
+ scale: float,
+) -> FormulaVerticalExtent:
+ return FormulaVerticalExtent(
+ extent.ascent_em * scale,
+ extent.descent_em * scale,
+ )
+
+
+def _script_vertical_extent(
+ base: FormulaVerticalExtent,
+ subscript: Sequence | None,
+ superscript: Sequence | None,
+) -> FormulaVerticalExtent:
+ ascent = base.ascent_em
+ descent = base.descent_em
+ if superscript is not None:
+ upper = _scaled_vertical_extent(
+ _node_vertical_extent(superscript),
+ _SCRIPT_SCALE,
+ )
+ baseline_shift = 0.55
+ ascent = max(ascent, baseline_shift + upper.ascent_em)
+ descent = max(descent, upper.descent_em - baseline_shift)
+ if subscript is not None:
+ lower = _scaled_vertical_extent(
+ _node_vertical_extent(subscript),
+ _SCRIPT_SCALE,
+ )
+ baseline_shift = 0.30
+ ascent = max(ascent, lower.ascent_em - baseline_shift)
+ descent = max(descent, baseline_shift + lower.descent_em)
+ return FormulaVerticalExtent(ascent, descent)
+
+
+def _limit_vertical_extent(
+ base: FormulaVerticalExtent,
+ lower: Sequence | None,
+ upper: Sequence | None,
+) -> FormulaVerticalExtent:
+ ascent = base.ascent_em
+ descent = base.descent_em
+ if upper is not None:
+ upper_extent = _node_vertical_extent(upper)
+ ascent += 0.14 + _SCRIPT_SCALE * upper_extent.height_em
+ if lower is not None:
+ lower_extent = _node_vertical_extent(lower)
+ descent += 0.14 + _SCRIPT_SCALE * lower_extent.height_em
+ return FormulaVerticalExtent(ascent, descent)
+
+
+def _rows_vertical_extent(
+ rows: tuple[tuple[Sequence, ...], ...] | tuple[Sequence, ...],
+) -> FormulaVerticalExtent:
+ row_heights: list[float] = []
+ for row in rows:
+ cells = row if isinstance(row, tuple) else (row,)
+ row_extent = _max_vertical_extent(
+ *(_node_vertical_extent(cell) for cell in cells)
+ )
+ row_heights.append(
+ max(_BASE_VERTICAL_EXTENT.height_em, row_extent.height_em)
+ )
+ if not row_heights:
+ return _BASE_VERTICAL_EXTENT
+ total_height = sum(row_heights) + 0.18 * (len(row_heights) - 1)
+ return FormulaVerticalExtent(
+ max(_BASE_VERTICAL_EXTENT.ascent_em, total_height * 0.55),
+ max(_BASE_VERTICAL_EXTENT.descent_em, total_height * 0.45),
+ )
+
+
+def _node_vertical_extent(node: Node) -> FormulaVerticalExtent:
+ if isinstance(node, Text):
+ return _BASE_VERTICAL_EXTENT
+ if isinstance(node, AlignmentPoint):
+ return FormulaVerticalExtent(0.0, 0.0)
+ if isinstance(node, Sequence):
+ return _max_vertical_extent(
+ *(_node_vertical_extent(child) for child in node.children)
+ )
+ if isinstance(node, Styled):
+ return _node_vertical_extent(node.body)
+ if isinstance(node, Fraction):
+ numerator = _node_vertical_extent(node.numerator)
+ denominator = _node_vertical_extent(node.denominator)
+ return FormulaVerticalExtent(
+ max(
+ _BASE_VERTICAL_EXTENT.ascent_em,
+ 0.28 + _FRACTION_SCALE * numerator.height_em,
+ ),
+ max(
+ _BASE_VERTICAL_EXTENT.descent_em,
+ 0.06 + _FRACTION_SCALE * denominator.height_em,
+ ),
+ )
+ if isinstance(node, Radical):
+ body = _node_vertical_extent(node.body)
+ ascent = body.ascent_em + 0.20
+ if node.degree is not None:
+ degree = _scaled_vertical_extent(
+ _node_vertical_extent(node.degree),
+ 0.50,
+ )
+ ascent = max(ascent, 0.55 + degree.ascent_em)
+ return FormulaVerticalExtent(ascent, max(body.descent_em, 0.40))
+ if isinstance(node, (Script, Prescript)):
+ return _script_vertical_extent(
+ _node_vertical_extent(node.base),
+ node.subscript,
+ node.superscript,
+ )
+ if isinstance(node, Nary):
+ base = _max_vertical_extent(
+ FormulaVerticalExtent(1.05, 0.45),
+ _node_vertical_extent(node.body)
+ if node.body is not None else FormulaVerticalExtent(0.0, 0.0),
+ )
+ if node.limit_modifier == "limits":
+ return _limit_vertical_extent(
+ base,
+ node.subscript,
+ node.superscript,
+ )
+ return _script_vertical_extent(
+ base,
+ node.subscript,
+ node.superscript,
+ )
+ if isinstance(node, Delimiter):
+ body = _max_vertical_extent(
+ *(_node_vertical_extent(segment) for segment in node.segments)
+ )
+ return FormulaVerticalExtent(
+ max(_BASE_VERTICAL_EXTENT.ascent_em, body.ascent_em + 0.05),
+ max(_BASE_VERTICAL_EXTENT.descent_em, body.descent_em + 0.05),
+ )
+ if isinstance(node, Matrix):
+ return _rows_vertical_extent(node.rows)
+ if isinstance(node, EquationArray):
+ return _rows_vertical_extent(node.rows)
+ if isinstance(node, Accent):
+ body = _node_vertical_extent(node.body)
+ return FormulaVerticalExtent(body.ascent_em + 0.24, body.descent_em)
+ if isinstance(node, Bar):
+ body = _node_vertical_extent(node.body)
+ if node.position in {"bot", "bottom"}:
+ return FormulaVerticalExtent(body.ascent_em, body.descent_em + 0.16)
+ return FormulaVerticalExtent(body.ascent_em + 0.16, body.descent_em)
+ if isinstance(node, GroupChar):
+ body = _node_vertical_extent(node.body)
+ if node.position in {"bot", "bottom"}:
+ return FormulaVerticalExtent(body.ascent_em, body.descent_em + 0.30)
+ return FormulaVerticalExtent(body.ascent_em + 0.30, body.descent_em)
+ if isinstance(node, Limit):
+ return _limit_vertical_extent(
+ _node_vertical_extent(node.base),
+ node.lower,
+ node.upper,
+ )
+ if isinstance(node, Function):
+ name = _node_vertical_extent(node.name)
+ if node.subscript is not None or node.superscript is not None:
+ if node.limit_modifier == "limits":
+ name = _limit_vertical_extent(
+ name,
+ node.subscript,
+ node.superscript,
+ )
+ else:
+ name = _script_vertical_extent(
+ name,
+ node.subscript,
+ node.superscript,
+ )
+ if node.body is None:
+ return name
+ return _max_vertical_extent(name, _node_vertical_extent(node.body))
+ if isinstance(node, OperatorEmulator):
+ return _node_vertical_extent(node.body)
+ if isinstance(node, Phantom):
+ if node.kind == "hphantom":
+ return FormulaVerticalExtent(0.0, 0.0)
+ return _node_vertical_extent(node.body)
+ if isinstance(node, BorderBox):
+ body = _node_vertical_extent(node.body)
+ return FormulaVerticalExtent(
+ body.ascent_em + 0.08,
+ body.descent_em + 0.08,
+ )
+ return _BASE_VERTICAL_EXTENT
+
+
+def formula_vertical_extent(root: Node) -> FormulaVerticalExtent:
+ """Estimate native math ascent/descent from the parsed formula structure."""
+ extent = _node_vertical_extent(root)
+ return FormulaVerticalExtent(
+ max(_BASE_VERTICAL_EXTENT.ascent_em, extent.ascent_em),
+ max(_BASE_VERTICAL_EXTENT.descent_em, extent.descent_em),
+ )
+
+
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:
@@ -334,6 +568,7 @@ __all__ = [
"Delimiter",
"EquationArray",
"Fraction",
+ "FormulaVerticalExtent",
"Function",
"GroupChar",
"Limit",
@@ -351,6 +586,7 @@ __all__ = [
"Text",
"append_child",
"formula_node_count",
+ "formula_vertical_extent",
"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 100ac250..fa4bdaa7 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
@@ -20,7 +20,12 @@ Dependencies:
from __future__ import annotations
-from .formula_ast import formula_node_count
+from .formula_ast import (
+ FormulaVerticalExtent,
+ Sequence,
+ formula_node_count,
+ formula_vertical_extent,
+)
from .formula_omml import emit_omml, validate_omml_fragment
from .formula_parser import FormulaCompileError, parse_latex_formula
@@ -29,7 +34,7 @@ _MAX_LATEX_LENGTH = 65_536
_MAX_AST_NODES = 100_000
-def _compile(latex: str, *, display: bool) -> str:
+def _parse_checked_formula(latex: str, *, display: bool) -> Sequence:
if not isinstance(latex, str):
raise FormulaCompileError("LaTeX formula must be a string")
if len(latex) > _MAX_LATEX_LENGTH:
@@ -42,6 +47,16 @@ def _compile(latex: str, *, display: bool) -> str:
formula_node_count(expression, maximum=_MAX_AST_NODES)
except ValueError as exc:
raise FormulaCompileError(str(exc)) from exc
+ return expression
+ except RecursionError as exc:
+ raise FormulaCompileError(
+ "Formula nesting exceeds the supported limit"
+ ) from exc
+
+
+def _compile(latex: str, *, display: bool) -> str:
+ expression = _parse_checked_formula(latex, display=display)
+ try:
return emit_omml(expression, display=display)
except RecursionError as exc:
raise FormulaCompileError(
@@ -59,9 +74,23 @@ def compile_latex_to_inline_omml(latex: str) -> str:
return _compile(latex, display=False)
+def estimate_inline_formula_vertical_extent(
+ latex: str,
+) -> FormulaVerticalExtent:
+ """Estimate inline native-math bounds relative to its text baseline."""
+ expression = _parse_checked_formula(latex, display=False)
+ try:
+ return formula_vertical_extent(expression)
+ except RecursionError as exc:
+ raise FormulaCompileError(
+ "Formula nesting exceeds the supported limit"
+ ) from exc
+
+
__all__ = [
"FormulaCompileError",
"compile_latex_to_inline_omml",
"compile_latex_to_omml",
+ "estimate_inline_formula_vertical_extent",
"validate_omml_fragment",
]