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): compile inline LaTeX into editable PowerPoint math

hugohe33cdb3264f7dd
diff --git a/skills/ppt-master/scripts/svg_finalize/flatten_tspan.py b/skills/ppt-master/scripts/svg_finalize/flatten_tspan.py
index b5e5d917..232f5914 100644
--- a/skills/ppt-master/scripts/svg_finalize/flatten_tspan.py
+++ b/skills/ppt-master/scripts/svg_finalize/flatten_tspan.py
@@ -189,6 +189,7 @@ PARAGRAPH_SOFT_BREAK_ATTR = "data-paragraph-soft-break"
# Marks an authored visual line boundary that remains a hard DrawingML break
# in the default single-frame preserve mode.
PARAGRAPH_LINE_BREAK_ATTR = "data-paragraph-line-break"
+INLINE_FORMULA_ATTR = "data-pptx-inline-formula"
# Tolerance for detecting "base line-height" vs "paragraph gap": dy values
# within ±DY_TOLERANCE_PX of each other are considered the same line-height.
@@ -741,6 +742,7 @@ def _create_text_element_from_line(
and len(tspans) == 1
and not _has_tspan_children(tspans[0])
and not tspans[0].tail
+ and tspans[0].get(INLINE_FORMULA_ATTR) is None
):
tspan = tspans[0]
content = collect_text_content(tspan)
diff --git a/skills/ppt-master/scripts/svg_quality/checker.py b/skills/ppt-master/scripts/svg_quality/checker.py
index 8496bda5..e95fa1d7 100644
--- a/skills/ppt-master/scripts/svg_quality/checker.py
+++ b/skills/ppt-master/scripts/svg_quality/checker.py
@@ -209,13 +209,17 @@ except ImportError:
try:
from svg_to_pptx.native_objects import (
+ INLINE_FORMULA_ATTR as _INLINE_FORMULA_ATTR,
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,
native_replacement_kind as _native_replacement_kind,
native_replacement_status as _native_replacement_status,
)
except ImportError:
+ _INLINE_FORMULA_ATTR = 'data-pptx-inline-formula'
_native_fallback_kind = None
+ _inline_formula_marker_errors = None
_native_marker_legacy_warnings = None
_native_replacement_kind = None
_native_replacement_status = None
@@ -3727,6 +3731,19 @@ class SVGQualityChecker:
def _check_native_object_markers(self, root: ET.Element, result: Dict) -> None:
"""Validate explicit native replacement markers before PPTX export."""
+ inline_formula_markers = [
+ elem for elem in root.iter()
+ if elem.get(_INLINE_FORMULA_ATTR) is not None
+ ]
+ if inline_formula_markers and _inline_formula_marker_errors is None:
+ result['errors'].append(
+ "Unable to import inline-formula validator; cannot verify "
+ f"{_INLINE_FORMULA_ATTR} markers"
+ )
+ elif _inline_formula_marker_errors is not None:
+ for error in _inline_formula_marker_errors(root):
+ result['errors'].append(f"Invalid inline formula marker: {error}")
+
invalid_status_elements: set[ET.Element] = set()
for elem in root.iter():
marker_id = elem.get('id') or elem.get('data-name') or '<unnamed>'
diff --git a/skills/ppt-master/scripts/svg_to_pptx/drawingml/converter.py b/skills/ppt-master/scripts/svg_to_pptx/drawingml/converter.py
index fcf9925e..f140645d 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/drawingml/converter.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/drawingml/converter.py
@@ -92,8 +92,10 @@ from ..canvas_contract import (
parse_project_viewbox,
)
from ..native_objects import (
+ INLINE_FORMULA_ATTR,
NativeMarkerAttributeError,
convert_native_object,
+ inline_formula_marker_errors,
native_metadata_payload_matches,
native_replacement_kind,
native_marker_transform,
@@ -152,6 +154,22 @@ def _require_native_marker_attributes(
)
+def _require_inline_formula_markers(
+ root: ET.Element,
+ svg_path: Path | str,
+) -> None:
+ """Reject malformed inline formula runs before text lowering."""
+ errors = inline_formula_marker_errors(root)
+ if not errors:
+ return
+ preview = '; '.join(errors[:8])
+ suffix = '' if len(errors) <= 8 else f'; +{len(errors) - 8} more'
+ raise SvgNativeConversionError(
+ f'{Path(svg_path).name}: invalid {INLINE_FORMULA_ATTR} marker(s): '
+ f'{preview}{suffix}'
+ )
+
+
def _native_replacement_enabled(elem: ET.Element, ctx: ConvertContext) -> bool:
"""Return whether this marker is active under the current export policy."""
kind = native_replacement_kind(elem)
@@ -1205,6 +1223,16 @@ def _geometry_trace_metadata(elem: ET.Element, result: ShapeResult) -> dict[str,
if xml.startswith('<p:graphicFrame>'):
return {'output_geometry': 'native-object', 'fidelity': 'native-normalized'}
if xml.startswith('<mc:AlternateContent'):
+ if elem.tag.replace(f'{{{SVG_NS}}}', '') == 'text':
+ inline_formula_count = sum(
+ 1 for child in elem.iter()
+ if child.get(INLINE_FORMULA_ATTR) is not None
+ )
+ return {
+ 'output_geometry': 'text',
+ 'inline_formula_count': inline_formula_count,
+ 'fidelity': 'native-normalized',
+ }
return {'output_geometry': 'native-formula', 'fidelity': 'exact'}
preset_match = re.search(r'<a:prstGeom prst="([^"]+)"', xml)
@@ -1475,6 +1503,7 @@ def convert_svg_to_slide_shapes(
except CanvasContractError as exc:
raise SvgNativeConversionError(str(exc)) from exc
_require_native_marker_attributes(root, svg_path)
+ _require_inline_formula_markers(root, svg_path)
_require_project_nested_svg_crops(root, svg_path)
_require_project_clip_paths(root, svg_path)
authored_errors = validate_authored_preset_tree(root)
@@ -1616,6 +1645,8 @@ def convert_svg_to_slide_shapes(
if verbose:
print(f' Expanded {expanded_local} local <use href="#..."/> instance(s)')
+ _require_inline_formula_markers(root, svg_path)
+
# Recheck compiler-injected icon/use wrappers and cloned definition trees.
_require_project_nested_svg_crops(root, svg_path)
_require_project_images(root, svg_path)
@@ -1640,6 +1671,11 @@ def convert_svg_to_slide_shapes(
f'{svg_path.name}: text-metric materialization failed: {exc}'
) from exc
+ inline_formula_count_before_text_lowering = sum(
+ 1 for elem in root.iter()
+ if elem.get(INLINE_FORMULA_ATTR) is not None
+ )
+
# Flatten positional <tspan> (those with x/y/non-zero dy) into independent
# <text> elements. DrawingML runs cannot reposition mid-paragraph, so a
# dy-stacked block of tspans would otherwise collapse onto one baseline,
@@ -1665,6 +1701,21 @@ def convert_svg_to_slide_shapes(
if verbose:
print(f' Lowered positional <tspan> using {text_flow} text flow')
+ inline_formula_count_after_text_lowering = sum(
+ 1 for elem in root.iter()
+ if elem.get(INLINE_FORMULA_ATTR) is not None
+ )
+ if (
+ inline_formula_count_after_text_lowering
+ != inline_formula_count_before_text_lowering
+ ):
+ raise SvgNativeConversionError(
+ f'{svg_path.name}: positional text lowering changed inline formula '
+ f'marker count from {inline_formula_count_before_text_lowering} '
+ f'to {inline_formula_count_after_text_lowering}'
+ )
+ _require_inline_formula_markers(root, svg_path)
+
_require_project_text_properties(root, svg_path)
try:
text_font_sizes = resolve_project_font_sizes(root)
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 7f540b35..1c155129 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/drawingml/elements.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/drawingml/elements.py
@@ -1957,6 +1957,8 @@ _TEXT_BULLET_MARKERS = {
_TEXT_BULLET_RE = re.compile(
r'^(?P<prefix>\s*)(?P<marker>[·•●▪■◆◇◦‣])(?P<space>\s*)'
)
+_INLINE_FORMULA_ATTR = 'data-pptx-inline-formula'
+_INLINE_FORMULA_KEY = '_inline_formula_latex'
def _normalize_text_run_whitespace(
@@ -2172,6 +2174,9 @@ def _extract_text_bullet(
runs: list[dict[str, Any]],
) -> tuple[list[dict[str, Any]], dict[str, Any] | None]:
"""Convert a leading text bullet marker into paragraph metadata."""
+ first_nonspace = _first_nonspace_run(runs)
+ if first_nonspace and first_nonspace.get(_INLINE_FORMULA_KEY) is not None:
+ return runs, None
full_text = ''.join(str(run.get('text', '')) for run in runs)
match = _TEXT_BULLET_RE.match(full_text)
if not match:
@@ -2394,11 +2399,15 @@ def _collect_tspan_runs(
own_xml_space = resolve_project_xml_space(tspan, inherited_xml_space)
if tspan.text:
- runs.append({
+ run = {
**own_attrs,
'text': tspan.text,
'_xml_space': own_xml_space,
- })
+ }
+ inline_formula = tspan.get(_INLINE_FORMULA_ATTR)
+ if inline_formula is not None:
+ run[_INLINE_FORMULA_KEY] = inline_formula
+ runs.append(run)
for child in tspan:
child_tag = child.tag.replace(f'{{{SVG_NS}}}', '')
@@ -2540,6 +2549,7 @@ def _build_run_properties_xml(
default_fonts: dict[str, str],
ctx: ConvertContext | None = None,
effect_xml: str = '',
+ fixed_font_family: str | None = None,
) -> str:
"""Build the final ``a:rPr`` used to compare and emit one text run."""
text = str(run['text'])
@@ -2569,14 +2579,22 @@ def _build_run_properties_xml(
spc_attr = _letter_spacing_to_drawingml_spc(letter_spacing_px)
fonts = parse_font_family(ff) if ff else default_fonts
- run_fonts = theme_font_tokens(
- fonts,
- ctx.theme_font_spec if ctx is not None else None,
- ) or resolve_text_run_fonts(text, fonts)
- lang = detect_text_lang(
+ run_fonts = (
+ {
+ 'latin': fixed_font_family,
+ 'ea': fixed_font_family,
+ 'cs': fixed_font_family,
+ }
+ if fixed_font_family is not None
+ else theme_font_tokens(
+ fonts,
+ ctx.theme_font_spec if ctx is not None else None,
+ ) or resolve_text_run_fonts(text, fonts)
+ )
+ lang = str(run.get('_language_override') or detect_text_lang(
text,
ctx.primary_language if ctx is not None else None,
- )
+ ))
rtl_xml = (
'\n<a:rtl val="1"/>'
if text_has_rtl_characters(text)
@@ -2612,8 +2630,16 @@ def _coalesce_text_runs(
text = str(run.get('text', ''))
if not text:
continue
+ if run.get(_INLINE_FORMULA_KEY) is not None:
+ merged.append({**run, 'text': text})
+ previous_properties = None
+ continue
properties = _build_run_properties_xml(run, default_fonts, ctx)
- if merged and properties == previous_properties:
+ if (
+ merged
+ and merged[-1].get(_INLINE_FORMULA_KEY) is None
+ and properties == previous_properties
+ ):
candidate = {
**merged[-1],
'text': str(merged[-1].get('text', '')) + text,
@@ -2652,6 +2678,37 @@ def _build_run_xml(
if run.get('_line_break'):
return '<a:br/>'
text = str(run['text'])
+ inline_formula = run.get(_INLINE_FORMULA_KEY)
+ if inline_formula is not None:
+ fill_raw = str(run.get('fill_raw') or f"#{run.get('fill', '000000')}")
+ fill_color, fill_alpha = parse_svg_color(fill_raw)
+ if fill_color is None or fill_alpha <= 0:
+ raise ValueError(
+ 'inline formula text requires one visible solid fill color'
+ )
+ math_run = {
+ **run,
+ 'font_family': 'Cambria Math',
+ 'font_weight': '400',
+ 'font_style': 'normal',
+ 'text_decoration': 'none',
+ 'letter_spacing': 0.0,
+ 'stroke_raw': '',
+ 'stroke_opacity': None,
+ '_language_override': (
+ ctx.primary_language
+ if ctx is not None and ctx.primary_language is not None
+ else 'en-US'
+ ),
+ }
+ properties_xml = _build_run_properties_xml(
+ math_run,
+ default_fonts,
+ ctx,
+ fixed_font_family='Cambria Math',
+ )
+ from ..native_objects.inline_formula import build_inline_formula_xml
+ return build_inline_formula_xml(str(inline_formula), properties_xml)
properties_xml = _build_run_properties_xml(
run,
default_fonts,
@@ -2802,11 +2859,13 @@ def convert_text(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None:
if prev and not prev_text.endswith(' ') \
and not next_text.startswith(' ') \
and not boundary_is_cjk:
- prev.append({
+ joining_space = {
**prev[-1],
'text': ' ',
'letter_spacing': 0.0,
- })
+ }
+ joining_space.pop(_INLINE_FORMULA_KEY, None)
+ prev.append(joining_space)
prev.extend(line_runs)
else:
paragraph_runs.append(line_runs)
@@ -3036,6 +3095,11 @@ def convert_text(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None:
(run for run in line if not run.get('_line_break')),
None,
)
+ effective_line_spacing = (
+ ''
+ if any(run.get(_INLINE_FORMULA_KEY) is not None for run in line)
+ else ln_spc_xml
+ )
p_pr_xml = _paragraph_pr_xml(
algn=algn,
font_size=(
@@ -3043,7 +3107,7 @@ def convert_text(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None:
if first_text_run is not None
else font_size
),
- body_xml=f'{ln_spc_xml}{spc_bef_xml}',
+ body_xml=f'{effective_line_spacing}{spc_bef_xml}',
bullet=bullet,
ctx=ctx,
rtl=text_uses_rtl(
@@ -3128,7 +3192,7 @@ def convert_text(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None:
'anchor="t" anchorCtr="0">\n<a:spAutoFit/>\n</a:bodyPr>'
)
- return ShapeResult(xml=f'''<p:sp>
+ shape_xml = f'''<p:sp>
<p:nvSpPr>
<p:cNvPr id="{shape_id}" name="TextBox {shape_id}"/>
<p:cNvSpPr txBox="1"/><p:nvPr/>
@@ -3146,7 +3210,14 @@ def convert_text(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None:
<a:lstStyle/>
{paragraphs_xml}
</p:txBody>
-</p:sp>''', bounds_emu=(off_x, off_y, off_x + ext_cx, off_y + ext_cy))
+</p:sp>'''
+ if any(run.get(_INLINE_FORMULA_KEY) is not None for run in runs):
+ from ..native_objects.inline_formula import wrap_inline_formula_shape
+ shape_xml = wrap_inline_formula_shape(shape_xml)
+ return ShapeResult(
+ xml=shape_xml,
+ bounds_emu=(off_x, off_y, off_x + ext_cx, off_y + ext_cy),
+ )
# ---------------------------------------------------------------------------
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 58bbd5c9..1a0b91e0 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
@@ -34,6 +34,10 @@ from .fallback_hash import (
stamp_native_fallback_baseline,
)
from .formula import FormulaSpec, build_native_formula, validate_formula_payload
+from .inline_formula import (
+ INLINE_FORMULA_ATTR,
+ inline_formula_marker_errors,
+)
from .marker_common import (
CHART_CONTENT_TYPE,
CHARTEX_CONTENT_TYPE,
@@ -74,6 +78,7 @@ from .workbook import (
__all__ = [
"convert_native_object",
+ "INLINE_FORMULA_ATTR",
"NativeMarkerAttributeError",
"native_fallback_kind",
"native_import_source",
@@ -83,6 +88,7 @@ __all__ = [
"native_replacement_kind",
"native_replacement_status",
"native_marker_transform",
+ "inline_formula_marker_errors",
"snapshot_native_fallback_freshness",
"stamp_native_fallback_baseline",
"validate_native_object_marker",
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 921b7b77..d2a0589c 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,10 +2,11 @@
r"""
PPT Master - Native Formula Compiler
-Compile a strict, block-only LaTeX subset into editable Office Math XML.
+Compile a strict LaTeX subset into editable block or inline Office Math XML.
Usage:
- Import compile_latex_to_omml() from the SVG-to-PPTX native-object pipeline.
+ Import compile_latex_to_omml() or compile_latex_to_inline_omml() from the
+ SVG-to-PPTX native-object pipeline.
Examples:
compile_latex_to_omml(r"\frac{-b \pm \sqrt{b^2-4ac}}{2a}")
@@ -1294,6 +1295,33 @@ def validate_omml_fragment(xml: str) -> str:
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)
+
+
+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:
@@ -1310,20 +1338,12 @@ def compile_latex_to_omml(latex: str) -> str:
expression = _LatexParser(source).parse()
_formula_node_count(expression)
-
- 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 expression
__all__ = [
"FormulaCompileError",
+ "compile_latex_to_inline_omml",
"compile_latex_to_omml",
"validate_omml_fragment",
]
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
new file mode 100644
index 00000000..60618452
--- /dev/null
+++ b/skills/ppt-master/scripts/svg_to_pptx/native_objects/inline_formula.py
@@ -0,0 +1,297 @@
+#!/usr/bin/env python3
+"""
+PPT Master - Native Inline Formula Contract
+
+Validate SVG inline-formula markers and build editable PowerPoint math runs.
+
+Usage:
+ Imported by the SVG quality checker and SVG-to-PPTX text converter.
+
+Examples:
+ <tspan data-pptx-inline-formula="x_i^2">xᵢ²</tspan>
+
+Dependencies:
+ None (only uses standard library and local PPT Master modules)
+"""
+
+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
+from .formula_compiler import (
+ FormulaCompileError,
+ compile_latex_to_inline_omml,
+)
+
+
+SVG_NS = "http://www.w3.org/2000/svg"
+DML_NS = "http://schemas.openxmlformats.org/drawingml/2006/main"
+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"
+INLINE_FORMULA_ATTR = "data-pptx-inline-formula"
+_SVG_TEXT = f"{{{SVG_NS}}}text"
+_SVG_TSPAN = f"{{{SVG_NS}}}tspan"
+_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 = (
+ "data-paragraph-line-height",
+ "data-paragraph-line-break",
+ "data-paragraph-soft-break",
+ "data-paragraph-space-before",
+)
+_NON_OUTPUT_ANCESTORS = frozenset({
+ "clipPath",
+ "desc",
+ "defs",
+ "filter",
+ "linearGradient",
+ "marker",
+ "mask",
+ "metadata",
+ "pattern",
+ "radialGradient",
+ "style",
+ "symbol",
+ "title",
+})
+
+for _prefix, _uri in (("a", DML_NS), ("m", MATH_NS)):
+ try:
+ ET.register_namespace(_prefix, _uri)
+ except (ValueError, AttributeError):
+ pass
+
+
+def _marker_label(elem: ET.Element) -> str:
+ elem_id = (elem.get("id") or "").strip()
+ return f"<tspan id={elem_id!r}>" if elem_id else "<tspan>"
+
+
+def inline_formula_marker_errors(root: ET.Element) -> list[str]:
+ """Return strict authoring errors for every inline-formula marker."""
+ errors: list[str] = []
+ parent_map = {child: parent for parent in root.iter() for child in parent}
+ markers = [
+ elem for elem in root.iter()
+ if elem.get(INLINE_FORMULA_ATTR) is not None
+ ]
+
+ for marker in markers:
+ label = _marker_label(marker)
+ if marker.tag != _SVG_TSPAN:
+ tag = marker.tag.rsplit("}", 1)[-1]
+ errors.append(
+ f"{INLINE_FORMULA_ATTR} is only valid on <tspan>, found <{tag}>"
+ )
+ continue
+
+ if marker.get("data-pptx-replace-with") is not None:
+ errors.append(
+ f"{label} cannot also declare data-pptx-replace-with"
+ )
+
+ source = marker.get(INLINE_FORMULA_ATTR) or ""
+ if not source.strip():
+ errors.append(f"{label} requires non-empty {INLINE_FORMULA_ATTR}")
+ else:
+ try:
+ compile_latex_to_inline_omml(source)
+ except FormulaCompileError as exc:
+ errors.append(f"{label} has unsupported inline LaTeX: {exc}")
+
+ if list(marker):
+ errors.append(
+ f"{label} must contain preview text directly and cannot nest elements"
+ )
+ if not (marker.text or "").strip():
+ errors.append(f"{label} requires non-empty visible SVG preview text")
+ elif marker.text != marker.text.strip():
+ errors.append(
+ f"{label} preview cannot contain leading or trailing whitespace; "
+ "place spacing in the surrounding text"
+ )
+
+ positioned = [name for name in _POSITION_ATTRIBUTES if marker.get(name) is not None]
+ if positioned:
+ errors.append(
+ f"{label} is an inline run and cannot set " + ", ".join(positioned)
+ )
+ paragraph_attrs = [
+ name for name in _PARAGRAPH_ATTRIBUTES
+ if marker.get(name) is not None
+ ]
+ if paragraph_attrs:
+ errors.append(
+ f"{label} cannot own paragraph layout metadata: "
+ + ", ".join(paragraph_attrs)
+ )
+
+ effective_fill: str | None = None
+ style_owner: ET.Element | None = marker
+ while style_owner is not None:
+ inline_style = parse_inline_style(style_owner.get("style"))
+ effective_fill = inline_style.get("fill")
+ if effective_fill is None:
+ effective_fill = style_owner.get("fill")
+ if effective_fill is not None:
+ break
+ style_owner = parent_map.get(style_owner)
+ color, alpha = parse_svg_color(effective_fill or "#000000")
+ if color is None or alpha <= 0:
+ errors.append(
+ f"{label} requires one visible solid fill color inherited "
+ "from itself or its text ancestors"
+ )
+
+ parent = parent_map.get(marker)
+ text_owner: ET.Element | None = None
+ nested_marker = False
+ inside_block_formula = False
+ inside_native_replacement = False
+ inside_preserved_text = False
+ inside_placeholder = False
+ inside_skipped_transport = False
+ invalid_inline_container: str | None = None
+ non_output_ancestor: str | None = None
+ fixed_structure_layer: str | None = None
+ while parent is not None:
+ parent_tag = parent.tag.rsplit("}", 1)[-1]
+ if text_owner is None and parent.tag == _SVG_TEXT:
+ text_owner = parent
+ elif (
+ text_owner is None
+ and parent.tag != _SVG_TSPAN
+ and invalid_inline_container is None
+ ):
+ invalid_inline_container = parent_tag
+ if parent_tag in _NON_OUTPUT_ANCESTORS:
+ non_output_ancestor = parent_tag
+ if parent.get(INLINE_FORMULA_ATTR) is not None:
+ nested_marker = True
+ replacement = (
+ parent.get("data-pptx-replace-with") or ""
+ ).strip().lower()
+ if replacement:
+ inside_native_replacement = True
+ inside_block_formula = (
+ inside_block_formula or replacement == "formula"
+ )
+ if (parent.get("data-pptx-part") or "").strip() in {
+ "geometry-detail",
+ "geometry-preview",
+ }:
+ inside_skipped_transport = True
+ if parent.get("data-pptx-placeholder") is not None:
+ inside_placeholder = True
+ layer = (parent.get("data-pptx-layer") or "").strip().lower()
+ if layer in {"master", "layout"}:
+ fixed_structure_layer = layer
+ if any(
+ child.tag.rsplit("}", 1)[-1] == "metadata"
+ and child.get("data-pptx-part") == "txbody"
+ for child in parent
+ ):
+ inside_preserved_text = True
+ parent = parent_map.get(parent)
+ if text_owner is None:
+ errors.append(f"{label} must be inside an SVG <text> element")
+ elif invalid_inline_container is not None:
+ errors.append(
+ f"{label} can only be nested through <tspan> elements before "
+ f"its owning <text>, found <{invalid_inline_container}>"
+ )
+ if non_output_ancestor is not None:
+ errors.append(
+ f"{label} cannot be placed inside non-output "
+ f"<{non_output_ancestor}> content"
+ )
+ if nested_marker:
+ errors.append(f"{label} cannot be nested inside another inline formula marker")
+ if inside_block_formula:
+ errors.append(
+ f"{label} cannot be placed inside a block formula preview"
+ )
+ elif inside_native_replacement:
+ errors.append(
+ f"{label} cannot be placed inside a native replacement subtree"
+ )
+ if inside_skipped_transport:
+ errors.append(
+ f"{label} cannot be placed inside non-output geometry transport"
+ )
+ if inside_preserved_text:
+ errors.append(
+ f"{label} cannot be placed inside an imported preserved txBody group"
+ )
+ if inside_placeholder:
+ errors.append(
+ f"{label} cannot be used inside a structured Layout placeholder"
+ )
+ if fixed_structure_layer is not None:
+ errors.append(
+ f"{label} cannot be used on the {fixed_structure_layer} layer; "
+ "inline formulas are slide-local text"
+ )
+
+ return errors
+
+
+def _apply_run_properties(omml: str, run_properties_xml: str) -> str:
+ """Replace DrawingML properties on every Office Math leaf run."""
+ try:
+ root = ET.fromstring(omml)
+ wrapper = ET.fromstring(
+ f'<root xmlns:a="{DML_NS}">{run_properties_xml}</root>'
+ )
+ except (ET.ParseError, RecursionError) as exc:
+ raise RuntimeError(f"Invalid inline formula XML: {exc}") from exc
+ if len(wrapper) != 1:
+ raise RuntimeError("Inline formula styling must contain one a:rPr root")
+ run_properties = wrapper[0]
+ if root.tag != f"{{{MATH_NS}}}oMath":
+ raise RuntimeError("Inline formula compiler must return one m:oMath root")
+ if run_properties.tag != _DML_RUN_PROPERTIES:
+ 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))
+
+ return ET.tostring(root, encoding="unicode", short_empty_elements=True)
+
+
+def build_inline_formula_xml(latex: str, run_properties_xml: str) -> str:
+ """Build one ``a14:m`` inline math zone for insertion inside ``a:p``."""
+ try:
+ omml = compile_latex_to_inline_omml(latex)
+ except FormulaCompileError as exc:
+ raise RuntimeError(f"Unsupported inline formula LaTeX: {exc}") from exc
+ styled = _apply_run_properties(omml, run_properties_xml)
+ return f"<a14:m>{styled}</a14:m>"
+
+
+def wrap_inline_formula_shape(shape_xml: str) -> str:
+ """Wrap a text shape containing ``a14:m`` in its required MCE Choice."""
+ return (
+ f'<mc:AlternateContent xmlns:mc="{MC_NS}">'
+ f'<mc:Choice xmlns:a14="{A14_NS}" Requires="a14">'
+ f"{shape_xml}"
+ "</mc:Choice>"
+ "</mc:AlternateContent>"
+ )
+
+
+__all__ = [
+ "INLINE_FORMULA_ATTR",
+ "build_inline_formula_xml",
+ "inline_formula_marker_errors",
+ "wrap_inline_formula_shape",
+]