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(svg-to-pptx): close text whitespace semantics
hugohe3b3aea946762e
diff --git a/docs/powerpoint-svg-mapping.md b/docs/powerpoint-svg-mapping.mdindex 4fd0fc39..6d4692f1 100644--- a/docs/powerpoint-svg-mapping.md+++ b/docs/powerpoint-svg-mapping.md@@ -113,6 +113,7 @@ preset selection and authoring behavior are documented in| Text box | `<text>` | Editable `p:sp` with `p:txBody` | Reconstructed as `<text>` and, when needed, `<tspan>` | Text must be well-formed XML and use registered attributes || Mixed formatting within a line | Non-positioned `<tspan>` runs | DrawingML runs in one text frame | `Native-normalized`; registered run formatting remains editable | Positioning that changes frame geometry may split the result || Multiple paragraphs | Mergeable text/tspan structure | Multiple `a:p` paragraphs in one text frame | `Native-normalized` | Strict independently positioned lines may remain separate text boxes |+| Significant text whitespace | Exact `xml:space="default"` or `xml:space="preserve"` on `<text>`/`<tspan>` | Normalized or preserved U+0020 text in editable DrawingML runs | `Native-normalized`; inline run ownership is retained | Uses the project Chromium/SVG2 contract: LF/TAB become spaces, `default` collapses across runs, `preserve` retains them, and Unicode spacing characters remain literal; CSS `white-space` and legacy SVG 1.1 newline deletion are outside the mapping || Font family | Canonical `font-family` resolved against the project lock | Direct typeface or registered theme font | `Native-stable` within installed/font-substitution limits | Unlocked or unavailable fonts are reported by validation || Font size | Finite unitless SVG pixels, for example `font-size="24"` | DrawingML hundredths of a point; `1 px = 0.75 pt` | `Native-stable` after unit conversion | Generated authoring uses only unitless px; registered legacy units are compatible input and warn, while unknown units error; DrawingML minimum is 1 pt || Font weight | Registered `font-weight` on `<text>`/`<tspan>` | DrawingML regular/bold run switch | `Native-normalized`; numeric weights collapse to the DrawingML boolean boundary | The exact value grammar and aliases belong to [`shared-standards.md` §6.7](../skills/ppt-master/references/shared-standards.md#67-advanced-text-treatments) |diff --git a/docs/zh/powerpoint-svg-mapping.md b/docs/zh/powerpoint-svg-mapping.mdindex 51a2617c..2997fafd 100644--- a/docs/zh/powerpoint-svg-mapping.md+++ b/docs/zh/powerpoint-svg-mapping.md@@ -108,6 +108,7 @@ PowerPoint 意图| 文本框 | `<text>` | 带 `p:txBody` 的可编辑 `p:sp` | 重建为 `<text>`,需要时含 `<tspan>` | 文本必须是良构 XML,且仅使用已登记属性 || 行内混合格式 | 不带定位的 `<tspan>` run | 同一文本框内的 DrawingML run | `Native-normalized`;已登记 run 格式仍可编辑 | 改变文本框几何的定位可能会拆分结果 || 多段落 | 可合并的 text/tspan 结构 | 同一文本框内的多个 `a:p` 段落 | `Native-normalized` | 严格独立定位的行可保持为独立文本框 |+| 有意义的文本空白 | `<text>`/`<tspan>` 上精确的 `xml:space="default"` 或 `xml:space="preserve"` | 可编辑 DrawingML run 中归一化或保留的 U+0020 文本 | `Native-normalized`;保留行内 run 所有权 | 使用项目 Chromium/SVG2 合同:LF/TAB 转为空格,`default` 跨 run 折叠,`preserve` 全部保留,Unicode 间隔字符保持字面值;CSS `white-space` 与 SVG 1.1 遗留换行删除不在映射内 || 字体 | 根据项目 lock 解析的规范 `font-family` | 直接 typeface 或已登记 theme font | 在安装字体/替换边界内为 `Native-stable` | 校验会报告未锁定或不可用字体 || 字号 | 有限、无单位的 SVG px,例如 `font-size="24"` | DrawingML 百分之一磅;`1 px = 0.75 pt` | 单位转换后为 `Native-stable` | 生成创作只使用无单位 px;已登记历史单位是会产生 warning 的兼容输入,未知单位为 error;DrawingML 下限为 1 pt || 字重 | `<text>`/`<tspan>` 上已登记的 `font-weight` | DrawingML 常规/粗体 run 开关 | `Native-normalized`;数值字重会折叠到 DrawingML 布尔边界 | 精确取值语法与别名属于 [`shared-standards.md` §6.7](../../skills/ppt-master/references/shared-standards.md#67-advanced-text-treatments) |diff --git a/skills/ppt-master/references/shared-standards.md b/skills/ppt-master/references/shared-standards.mdindex 65b18a92..2f05e6a5 100644--- a/skills/ppt-master/references/shared-standards.md+++ b/skills/ppt-master/references/shared-standards.md@@ -992,6 +992,26 @@ runs or a text frame from the SVG estimate.- Any other unregistered `font-*` or `text-*` property is also an error; theclosed grammar must not grow through an ignored CSS spelling.+**Hard rule — project text whitespace**:++- `xml:space` is the project's closed authoring control for significant text+ whitespace. It is valid only as an exact direct attribute on `<text>` or+ `<tspan>`, accepts only the case-sensitive values `default` and `preserve`,+ inherits through the text tree, and may be reset on a child `<tspan>`.+- The project maps this control to the visible Chromium/SVG2 behavior used by+ Live Preview; it does not claim the legacy SVG 1.1 newline-deletion model.+ XML line endings and tabs become U+0020 SPACE. In `default` mode, contiguous+ U+0020 characters collapse across inline run boundaries and leading or+ trailing default-mode spaces in the resulting text chunk are removed. In+ `preserve` mode, every resulting U+0020 character remains significant.+- Only XML whitespace is normalized. NBSP, ideographic space, and other+ Unicode spacing characters remain literal text and must not be rewritten by+ a generic Unicode-whitespace regular expression.+- Source line breaks do not create PowerPoint paragraphs. Use the registered+ positioned-`tspan`/paragraph structure for visual lines, and preserve DOM+ text/tail order plus original style inheritance when normalizing that+ structure.+These allowlists are additive to the global structural blacklist and thepaint, font-size, opacity, filter, and transform value contracts owned by theirrespective sections; they do not weaken those contracts.diff --git a/skills/ppt-master/scripts/pptx_to_svg/txbody_to_svg.py b/skills/ppt-master/scripts/pptx_to_svg/txbody_to_svg.pyindex 16530e16..e613911e 100644--- a/skills/ppt-master/scripts/pptx_to_svg/txbody_to_svg.py+++ b/skills/ppt-master/scripts/pptx_to_svg/txbody_to_svg.py@@ -231,11 +231,7 @@ def convert_vertical_txbody(glyphs: list[tuple[str, TextRun]] = []for run in runs:for char in run.text:- if char in "\r\n":- continue- if char == " ":- continue- glyphs.append((char, run))+ glyphs.append((" " if char in "\t\r\n" else char, run))if not glyphs:return TextResult()diff --git a/skills/ppt-master/scripts/svg_finalize/flatten_tspan.py b/skills/ppt-master/scripts/svg_finalize/flatten_tspan.pyindex bfad80b4..29d68361 100644--- a/skills/ppt-master/scripts/svg_finalize/flatten_tspan.py+++ b/skills/ppt-master/scripts/svg_finalize/flatten_tspan.py@@ -160,6 +160,11 @@ def collect_text_content(el: ET.Element) -> str:return "".join(parts)+def _has_non_xml_whitespace(text: str | None) -> bool:+ """Return whether text contains content beyond XML layout whitespace."""+ return bool(text and text.strip(" \t\r\n"))++def copy_text_attrs(src_el: ET.Element,dst_el: ET.Element,@@ -423,24 +428,29 @@ def _emit_mergeable_paragraph(# Normalize authoring variants before the downstream converter reads the# paragraph: a line-break tspan may be followed by direct-child inline- # formatting tspans. Move those inline runs under the line-break tspan so- # every direct child of <text> is one logical visual line.+ # formatting tspans. Wrap those original siblings in one unstyled line+ # container so every direct child of <text> is one logical visual line.+ # Keeping the authored runs as siblings is important: nesting later runs+ # under the positioned first run would incorrectly inherit its typography,+ # and moving them independently would lose the first run's tail whitespace.normalized_lines: list[ET.Element] = []for group in line_groups:line = group[0]- for inline_tspan in group[1:]:- try:- text_el.remove(inline_tspan)- except ValueError:- pass- if inline_tspan.tail and not inline_tspan.tail.strip():- inline_tspan.tail = None- line.append(inline_tspan)- normalized_lines.append(line)+ if len(group) == 1:+ normalized_lines.append(line)+ continue++ container = ET.Element(f"{{{SVG_NS}}}tspan")+ for k in ("x", "y", "dy"):+ line.attrib.pop(k, None)+ for run in group:+ container.append(run)+ normalized_lines.append(container)for child in list(text_el):- if child not in normalized_lines:- text_el.remove(child)+ text_el.remove(child)+ for line in normalized_lines:+ text_el.append(line)extras_iter = iter(extras)soft_iter = iter(soft_breaks)@@ -552,13 +562,8 @@ def flatten_text_with_tspans(# Collect tspan elements belonging to the same linecurrent_line_tspans = []- current_line_lead_text = None+ current_line_lead_text = text_el.text or None- # Leading text directly under <text>- lead_text = (text_el.text or "").strip()- if lead_text:- current_line_lead_text = lead_text-for idx, child in enumerate(list(text_el)):if not is_svg_tag(child, "tspan"):continue@@ -568,7 +573,9 @@ def flatten_text_with_tspans(# Check whether this tspan starts a new lineif is_new_line_tspan(child):# Save previously accumulated same-line tspans first- if current_line_tspans or current_line_lead_text:+ if current_line_tspans or _has_non_xml_whitespace(+ current_line_lead_text+ ):ne = _create_text_element_from_line(text_el, current_line_lead_text, current_line_tspans, cur_x, cur_y)@@ -580,12 +587,16 @@ def flatten_text_with_tspans(nx, ny = compute_line_positions(text_el, child, cur_x, cur_y)cur_x, cur_y = nx, ny- # If content is not empty, add to the current line- if content.strip():+ # Keep raw XML whitespace and tails until the shared downstream+ # text normalizer sees the whole line. A whitespace-only run can+ # still be the visible boundary between two formatted runs.+ if content or child.tail:current_line_tspans.append(child)# Process the last line- if current_line_tspans or current_line_lead_text:+ if current_line_tspans or _has_non_xml_whitespace(+ current_line_lead_text+ ):ne = _create_text_element_from_line(text_el, current_line_lead_text, current_line_tspans, cur_x, cur_y)@@ -662,11 +673,23 @@ def _create_text_element_from_line(if p_tf:ne.set("transform", p_tf)- # Compact path: a single tspan with no nested inline runs collapses to <text>text</text>- if not lead_text and len(tspans) == 1 and not _has_tspan_children(tspans[0]):+ # Compact path: a single tspan with no nested inline runs or parent-owned+ # tail collapses to <text>text</text>. A tail must remain outside the tspan+ # so its parent typography and xml:space semantics remain intact.+ if (+ not lead_text+ and len(tspans) == 1+ and not _has_tspan_children(tspans[0])+ and not tspans[0].tail+ ):tspan = tspans[0]content = collect_text_content(tspan)+ xml_space_attr = "{http://www.w3.org/XML/1998/namespace}space"+ xml_space = tspan.get(xml_space_attr)+ if xml_space is not None:+ ne.set(xml_space_attr, xml_space)+# Merge stylemerged_style = merge_styles(text_el.get("style"), tspan.get("style"))if merged_style:diff --git a/skills/ppt-master/scripts/svg_quality_checker.py b/skills/ppt-master/scripts/svg_quality_checker.pyindex 7e30b475..7a7339f0 100644--- a/skills/ppt-master/scripts/svg_quality_checker.py+++ b/skills/ppt-master/scripts/svg_quality_checker.py@@ -198,16 +198,20 @@ except ImportError:try:from svg_to_pptx.drawingml.text_properties import (+ normalize_project_text_segments as _normalize_project_text_segments,parse_project_font_weight as _parse_project_font_weight,parse_project_text_anchor as _parse_project_text_anchor,project_text_property_diagnostics as _project_text_property_diagnostics,+ resolve_project_xml_space as _resolve_project_xml_space,resolve_project_font_sizes as _resolve_project_font_sizes,resolve_project_letter_spacings as _resolve_project_letter_spacings,)except ImportError:+ _normalize_project_text_segments = None_parse_project_font_weight = None_parse_project_text_anchor = None_project_text_property_diagnostics = None+ _resolve_project_xml_space = None_resolve_project_font_sizes = None_resolve_project_letter_spacings = None@@ -2453,22 +2457,27 @@ class SVGQualityChecker:text_el: ET.Element,) -> List[Tuple[ET.Element, str]] | None:"""Return normalized inline runs, or ``None`` for positioned text."""- runs: List[Tuple[ET.Element, str]] = []-- def preserves_space(elem: ET.Element) -> bool:- return (- elem.get('{http://www.w3.org/XML/1998/namespace}space')- or elem.get('xml:space')- ) == 'preserve'+ if (+ _normalize_project_text_segments is None+ or _resolve_project_xml_space is None+ ):+ return None+ raw_runs: List[Tuple[ET.Element, str, str]] = []- def append_run(owner: ET.Element, raw: str, preserve: bool) -> None:- normalized = raw if preserve else re.sub(r'\s+', ' ', raw)- if normalized:- runs.append((owner, normalized))+ def append_run(owner: ET.Element, raw: str, xml_space: str) -> None:+ if raw:+ raw_runs.append((owner, xml_space, raw))- def collect(container: ET.Element, preserve: bool) -> bool:+ def collect(container: ET.Element, inherited_xml_space: str) -> bool:+ try:+ xml_space = _resolve_project_xml_space(+ container,+ inherited_xml_space,+ )+ except ValueError:+ return Falseif container.text:- append_run(container, container.text, preserve)+ append_run(container, container.text, xml_space)for child in list(container):if not cls._is_tspan(child):return False@@ -2479,24 +2488,22 @@ class SVGQualityChecker:for name in child.attrib):return False- child_preserve = preserve or preserves_space(child)- if not collect(child, child_preserve):+ if not collect(child, xml_space):return Falseif child.tail:- append_run(container, child.tail, preserve)+ append_run(container, child.tail, xml_space)return True- preserve = preserves_space(text_el)- if not collect(text_el, preserve):- return None- if any('\n' in text or '\r' in text for _owner, text in runs):+ if not collect(text_el, 'default'):return None- if runs and not preserve:- owner, text = runs[0]- runs[0] = (owner, text.lstrip(' '))- owner, text = runs[-1]- runs[-1] = (owner, text.rstrip(' '))- return [(owner, text) for owner, text in runs if text]+ normalized = _normalize_project_text_segments([+ (xml_space, raw)+ for _owner, xml_space, raw in raw_runs+ ])+ return [+ (raw_runs[index][0], text)+ for index, text in normalized+ ]@staticmethoddef _unchanged_txbody_group_ids(diff --git a/skills/ppt-master/scripts/svg_to_pptx/drawingml/elements.py b/skills/ppt-master/scripts/svg_to_pptx/drawingml/elements.pyindex 188c3993..ef4ed36c 100644--- a/skills/ppt-master/scripts/svg_to_pptx/drawingml/elements.py+++ b/skills/ppt-master/scripts/svg_to_pptx/drawingml/elements.py@@ -31,11 +31,13 @@ from .theme_colors import color_node_xmlfrom .theme_fonts import theme_font_tokensfrom .text_properties import (drawingml_letter_spacing,+ normalize_project_text_segments,parse_project_font_style,parse_project_font_weight,parse_project_letter_spacing,parse_project_text_anchor,parse_project_text_decoration,+ resolve_project_xml_space,)from .utils import (SVG_NS, XLINK_NS, ANGLE_UNIT, FONT_PX_TO_HUNDREDTHS_PT,@@ -1971,28 +1973,20 @@ _TEXT_BULLET_RE = re.compile()-def _normalize_text(text: str, *, preserve_space: bool = False) -> str:- """Collapse runs of whitespace into a single space; do NOT strip the ends.-- Stripping at this layer would silently delete the inline boundary- spaces in nested-tspan structures like- ``<tspan>foo <tspan>bar</tspan> baz</tspan>``: the parent's text- ("foo ") and the child's tail (" baz") would each lose the only space- that separated them from the inner run, producing "foobarbaz".-- The paragraph's overall leading / trailing whitespace is removed once- in ``_build_text_runs`` after all inline runs have been concatenated.- """- if not text:- return ''- if preserve_space:- return text- return re.sub(r'\s+', ' ', text)---def _preserves_space(elem: ET.Element) -> bool:- xml_space = elem.get('{http://www.w3.org/XML/1998/namespace}space') or elem.get('xml:space')- return xml_space == 'preserve'+def _normalize_text_run_whitespace(+ runs: list[dict[str, Any]],+) -> list[dict[str, Any]]:+ """Apply the shared whitespace contract without losing run ownership."""+ normalized: list[dict[str, Any]] = []+ segments = [+ (str(run.get('_xml_space', 'default')), str(run.get('text', '')))+ for run in runs+ ]+ for index, text in normalize_project_text_segments(segments):+ run = {**runs[index], 'text': text}+ run.pop('_xml_space', None)+ normalized.append(run)+ return normalizeddef _letter_spacing_to_drawingml_spc(letter_spacing_px: float) -> str:@@ -2384,7 +2378,7 @@ def _collect_tspan_runs(tspan: ET.Element,inherited_attrs: dict[str, Any],ctx: ConvertContext,- preserve_space: bool = False,+ inherited_xml_space: str = 'default',) -> list[dict[str, Any]]:"""Recursively turn a tspan subtree into runs, propagating styling through nested tspans.@@ -2392,23 +2386,27 @@ def _collect_tspan_runs("""runs: list[dict[str, Any]] = []own_attrs = _override_run_attrs(inherited_attrs, tspan, ctx)- child_preserve_space = preserve_space or _preserves_space(tspan)+ own_xml_space = resolve_project_xml_space(tspan, inherited_xml_space)if tspan.text:- t = _normalize_text(tspan.text, preserve_space=child_preserve_space)- if t:- runs.append({**own_attrs, 'text': t})+ runs.append({+ **own_attrs,+ 'text': tspan.text,+ '_xml_space': own_xml_space,+ })for child in tspan:child_tag = child.tag.replace(f'{{{SVG_NS}}}', '')if child_tag == 'tspan':runs.extend(- _collect_tspan_runs(child, own_attrs, ctx, child_preserve_space)+ _collect_tspan_runs(child, own_attrs, ctx, own_xml_space))if child.tail:- t = _normalize_text(child.tail, preserve_space=child_preserve_space)- if t:- runs.append({**own_attrs, 'text': t})+ runs.append({+ **own_attrs,+ 'text': child.tail,+ '_xml_space': own_xml_space,+ })return runs@@ -2425,32 +2423,29 @@ def _build_text_runs(recursively so inline format changes inside a tspan still produce distinct runs."""runs: list[dict[str, Any]] = []- preserve_space = _preserves_space(elem)+ xml_space = resolve_project_xml_space(elem)if elem.text:- t = _normalize_text(elem.text, preserve_space=preserve_space)- if t:- runs.append({**parent_attrs, 'text': t})+ runs.append({+ **parent_attrs,+ 'text': elem.text,+ '_xml_space': xml_space,+ })for child in elem:child_tag = child.tag.replace(f'{{{SVG_NS}}}', '')if child_tag == 'tspan':runs.extend(- _collect_tspan_runs(child, parent_attrs, ctx, preserve_space)+ _collect_tspan_runs(child, parent_attrs, ctx, xml_space))if child.tail:- t = _normalize_text(child.tail, preserve_space=preserve_space)- if t:- runs.append({**parent_attrs, 'text': t})+ runs.append({+ **parent_attrs,+ 'text': child.tail,+ '_xml_space': xml_space,+ })- # Strip the paragraph's overall leading / trailing whitespace once unless- # xml:space="preserve" asks us to keep source indentation.- if runs and not preserve_space:- runs[0]['text'] = runs[0]['text'].lstrip(' ')- runs[-1]['text'] = runs[-1]['text'].rstrip(' ')- runs = [r for r in runs if r['text']]-- return runs+ return _normalize_text_run_whitespace(runs)def _build_text_fill_xml(@@ -2712,7 +2707,7 @@ def convert_text(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None:# has room to wrap text to the SVG's original line widths.visual_line_widths: list[float] = []if line_height_px is not None and line_height_px > 0:- preserve_space = _preserves_space(elem)+ xml_space = resolve_project_xml_space(elem)paragraph_runs = []for child in elem:if child.tag != f'{{{SVG_NS}}}tspan':@@ -2721,12 +2716,9 @@ def convert_text(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None:child,parent_attrs,ctx,- preserve_space,+ xml_space,)- if line_runs and not preserve_space:- line_runs[0]['text'] = line_runs[0]['text'].lstrip(' ')- line_runs[-1]['text'] = line_runs[-1]['text'].rstrip(' ')- line_runs = [r for r in line_runs if r['text']]+ line_runs = _normalize_text_run_whitespace(line_runs)if not line_runs:continuevisual_line_widths.append(diff --git a/skills/ppt-master/scripts/svg_to_pptx/drawingml/text_properties.py b/skills/ppt-master/scripts/svg_to_pptx/drawingml/text_properties.pyindex ffb7bfe7..317be3e3 100644--- a/skills/ppt-master/scripts/svg_to_pptx/drawingml/text_properties.py+++ b/skills/ppt-master/scripts/svg_to_pptx/drawingml/text_properties.py@@ -132,6 +132,8 @@ _COMPATIBLE_LETTER_SPACING_RE = re.compile(re.IGNORECASE,)_XML_NAMESPACE = 'http://www.w3.org/XML/1998/namespace'+_XML_SPACE_ATTRIBUTE = f'{{{_XML_NAMESPACE}}}space'+_PROJECT_XML_SPACE_VALUES = frozenset({'default', 'preserve'})_DRAWINGML_TEXT_SPACING_MIN = -400_000_DRAWINGML_TEXT_SPACING_MAX = 400_000@@ -175,6 +177,74 @@ def _attribute_name(raw_name: str) -> str:return _local_name(raw_name)+def resolve_project_xml_space(+ elem: ET.Element,+ inherited: str = 'default',+) -> str:+ """Resolve the exact project ``xml:space`` value for one text element."""+ if inherited not in _PROJECT_XML_SPACE_VALUES:+ raise ValueError(f'invalid inherited xml:space value {inherited!r}')+ raw = elem.get(_XML_SPACE_ATTRIBUTE)+ if raw is None:+ raw = elem.get('xml:space')+ if raw is None:+ return inherited+ if raw not in _PROJECT_XML_SPACE_VALUES:+ raise ValueError("xml:space must be exactly 'default' or 'preserve'")+ return raw+++def normalize_project_text_segments(+ segments: list[tuple[str, str]],+) -> list[tuple[int, str]]:+ """Normalize text whitespace while retaining the source segment owner.++ Each input tuple is ``(effective_xml_space, raw_text)``. The returned+ tuples are ``(input_index, normalized_text)`` so callers can retain run+ formatting. Project whitespace follows rendered SVG behavior: tabs and+ line endings become ordinary spaces; ``default`` runs collapse across+ element boundaries and lose only overall leading/trailing spaces;+ ``preserve`` runs retain every resulting ordinary space. Unicode spacing+ characters such as NBSP are text, not XML whitespace, and remain intact.+ """+ output: list[tuple[int, str]] = []+ pending_default_space: int | None = None++ def append(index: int, text: str) -> None:+ if not text:+ return+ if output and output[-1][0] == index:+ owner, existing = output[-1]+ output[-1] = (owner, existing + text)+ else:+ output.append((index, text))++ def flush_pending() -> None:+ nonlocal pending_default_space+ if pending_default_space is not None and output:+ append(pending_default_space, ' ')+ pending_default_space = None++ for index, (xml_space, raw_text) in enumerate(segments):+ if xml_space not in _PROJECT_XML_SPACE_VALUES:+ raise ValueError(+ f'xml:space must be exactly default or preserve; got '+ f'{xml_space!r}'+ )+ text = re.sub(r'[\t\r\n]', ' ', raw_text)+ for char in text:+ if xml_space == 'default' and char == ' ':+ if pending_default_space is None:+ pending_default_space = index+ continue+ flush_pending()+ append(index, char)++ # A pending default-mode space is the overall trailing space and is+ # intentionally discarded. Preserved trailing spaces were emitted inline.+ return output++def _is_unregistered_prefixed_text_property(name: str) -> bool:lowered = name.lower()return (@@ -539,6 +609,20 @@ def _diagnose_text_declaration() -> tuple[bool, TextPropertyDiagnostic | None]:"""Return whether a declaration belongs to the text contract and its issue."""label = _element_label(elem)+ if name == 'xml:space':+ if source != 'attribute' or tag not in {'text', 'tspan'}:+ return True, TextPropertyDiagnostic(+ 'error', label, source, name, raw,+ f'{label} can use xml:space only as a direct attribute on '+ '<text> or <tspan>',+ )+ if raw not in _PROJECT_XML_SPACE_VALUES:+ return True, TextPropertyDiagnostic(+ 'error', label, source, name, raw,+ f'{label} attribute xml:space={raw!r}: expected exactly '+ "'default' or 'preserve'",+ )+ return True, Noneif _is_unregistered_prefixed_text_property(name):return True, TextPropertyDiagnostic('error', label, source, name, raw,diff --git a/skills/ppt-master/scripts/test_svg_quality_checker.py b/skills/ppt-master/scripts/test_svg_quality_checker.pyindex 772c27cb..14b19eca 100644--- a/skills/ppt-master/scripts/test_svg_quality_checker.py+++ b/skills/ppt-master/scripts/test_svg_quality_checker.py@@ -28,6 +28,8 @@ from pptx_to_svg.preset_authoring import (render_preset_shape_fragment,validate_authored_preset_tree,)+from pptx_to_svg.emu_units import Xfrm+from pptx_to_svg.txbody_to_svg import convert_vertical_txbodyfrom svg_to_pptx.drawingml.converter import (SvgNativeConversionError,convert_svg_to_slide_shapes,@@ -2729,6 +2731,180 @@ class SVGQualityCheckerCompatibilityTests(unittest.TestCase):self.assertEqual(slide_xml.count(' spc="150"'), 2)self.assertIn('algn="r"', slide_xml)+ def test_text_whitespace_contract_matches_rendered_run_boundaries(self):+ source = '''<svg xmlns="http://www.w3.org/2000/svg"+ viewBox="0 0 640 360" font-family="Arial" font-size="20">+ <text x="20" y="50">A <tspan fill="#FF0000"> B </tspan> C</text>+ <text x="20" y="100"><tspan xml:space="preserve"> D </tspan></text>+ <text x="20" y="150" xml:space="preserve"><tspan+ xml:space="default"> E </tspan></text>+ <text x="20" y="200">F G H</text>+ <text x="20" y="250" xml:space="preserve">H+ I</text>+</svg>'''+ result = self._check(source)+ self.assertTrue(result['passed'])+ self.assertEqual(result['errors'], [])++ with tempfile.TemporaryDirectory() as tmp_dir:+ svg_path = Path(tmp_dir) / 'text-whitespace.svg'+ svg_path.write_text(source, encoding='utf-8')+ slide_xml = convert_svg_to_slide_shapes(svg_path)[0]++ texts = re.findall(r'<a:t(?: [^>]*)?>(.*?)</a:t>', slide_xml, re.S)+ self.assertEqual(+ texts,+ ['A ', 'B ', 'C', ' D ', 'E', 'F G H', 'H I'],+ )+ self.assertNotIn('<a:t>H\n', slide_xml)+ self.assertEqual(slide_xml.count(' xml:space="preserve"'), 4)++ def test_paragraph_runs_use_the_same_xml_space_inheritance(self):+ source = '''<svg xmlns="http://www.w3.org/2000/svg"+ viewBox="0 0 640 360" font-family="Arial" font-size="20">+ <text x="20" y="50" data-paragraph-line-height="24">+ <tspan x="20" xml:space="preserve"> First </tspan>+ <tspan x="20" dy="24" xml:space="default"> Second </tspan>+ </text>+</svg>'''+ result = self._check(source)+ self.assertTrue(result['passed'])+ with tempfile.TemporaryDirectory() as tmp_dir:+ svg_path = Path(tmp_dir) / 'paragraph-whitespace.svg'+ svg_path.write_text(source, encoding='utf-8')+ slide_xml = convert_svg_to_slide_shapes(svg_path)[0]+ self.assertEqual(slide_xml.count('<a:p>'), 1)+ self.assertIn(+ '<a:t xml:space="preserve"> First Second</a:t>',+ slide_xml,+ )++ def test_paragraph_merge_preserves_inline_sibling_space_and_inheritance(self):+ source = '''<svg xmlns="http://www.w3.org/2000/svg"+ viewBox="0 0 640 360">+ <text x="40" y="80" font-family="Arial" font-size="24">+ <tspan x="40" dy="0" font-family="Arial Black"+ font-weight="bold">· Stable:</tspan>+ <tspan fill="#FF0000">distributed ownership</tspan>+ <tspan x="40" dy="40" font-family="Arial Black"+ font-weight="bold">· Future:</tspan>+ <tspan fill="#FF0000">long-term incentives</tspan>+ </text>+</svg>'''+ result = self._check(source)+ self.assertTrue(result['passed'])+ with tempfile.TemporaryDirectory() as tmp_dir:+ svg_path = Path(tmp_dir) / 'paragraph-inline-siblings.svg'+ svg_path.write_text(source, encoding='utf-8')+ slide_xml = convert_svg_to_slide_shapes(svg_path)[0]++ texts = re.findall(r'<a:t(?: [^>]*)?>(.*?)</a:t>', slide_xml, re.S)+ self.assertEqual(+ ''.join(texts),+ 'Stable: distributed ownership'+ 'Future: long-term incentives',+ )+ self.assertEqual(slide_xml.count('<a:buChar char="•"/>'), 2)+ visible_runs = [+ run+ for run in re.findall(r'<a:r>(.*?)</a:r>', slide_xml, re.S)+ if re.search(r'<a:t(?: [^>]*)?>[^ <]', run)+ ]+ self.assertEqual(len(visible_runs), 4)+ self.assertIn('typeface="Arial Black"', visible_runs[0])+ self.assertIn(' b="1"', visible_runs[0])+ self.assertIn('typeface="Arial"', visible_runs[1])+ self.assertNotIn(' b="1"', visible_runs[1])+ self.assertIn('typeface="Arial Black"', visible_runs[2])+ self.assertIn(' b="1"', visible_runs[2])+ self.assertIn('typeface="Arial"', visible_runs[3])+ self.assertNotIn(' b="1"', visible_runs[3])++ def test_flattened_lines_keep_tail_and_xml_space_overrides(self):+ cases = {+ 'tail': (+ '<text x="10" y="20" font-size="20">'+ '<tspan x="10" dy="20">A</tspan> B</text>',+ ['A B'],+ ),+ 'child_preserve': (+ '<text x="10" y="20" font-size="20">'+ '<tspan x="10" dy="20" xml:space="preserve">'+ ' A </tspan></text>',+ [' A '],+ ),+ 'child_default_reset': (+ '<text x="10" y="20" font-size="20" '+ 'xml:space="preserve"><tspan x="10" dy="20" '+ 'xml:space="default"> A </tspan></text>',+ ['A'],+ ),+ 'preserved_leading_text': (+ '<text x="10" y="20" font-size="20" '+ 'xml:space="preserve"> A '+ '<tspan x="10" dy="20">B</tspan></text>',+ [' A ', 'B'],+ ),+ }+ for name, (body, expected) in cases.items():+ source = (+ '<svg xmlns="http://www.w3.org/2000/svg" '+ f'viewBox="0 0 640 360">{body}</svg>'+ )+ with self.subTest(name=name), tempfile.TemporaryDirectory() as tmp_dir:+ svg_path = Path(tmp_dir) / f'{name}.svg'+ svg_path.write_text(source, encoding='utf-8')+ slide_xml = convert_svg_to_slide_shapes(+ svg_path,+ merge_paragraphs=False,+ )[0]+ texts = re.findall(+ r'<a:t(?: [^>]*)?>(.*?)</a:t>',+ slide_xml,+ re.S,+ )+ self.assertEqual(texts, expected)++ def test_explicit_default_xml_space_matches_the_omitted_default(self):+ source = (+ '<svg xmlns="http://www.w3.org/2000/svg" '+ 'viewBox="0 0 640 360"><text x="40" y="100" '+ 'font-size="24"> A B </text></svg>'+ )+ explicit = source.replace(+ 'font-size="24"',+ 'font-size="24" xml:space="default"',+ )+ with tempfile.TemporaryDirectory() as tmp_dir:+ svg_path = Path(tmp_dir) / 'default-space.svg'+ svg_path.write_text(source, encoding='utf-8')+ omitted_xml = convert_svg_to_slide_shapes(svg_path)[0]+ svg_path.write_text(explicit, encoding='utf-8')+ explicit_xml = convert_svg_to_slide_shapes(svg_path)[0]+ self.assertEqual(omitted_xml, explicit_xml)+ self.assertIn('<a:t>A B</a:t>', explicit_xml)++ def test_vertical_text_import_keeps_literal_space_advances(self):+ tx_body = ET.fromstring('''+<p:txBody xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main"+ xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main">+ <a:bodyPr vert="eaVert"/><a:lstStyle/><a:p><a:r>+ <a:rPr sz="1800"/><a:t xml:space="preserve">甲 乙</a:t>+ </a:r></a:p>+</p:txBody>''')+ result = convert_vertical_txbody(+ tx_body,+ Xfrm(x=0, y=0, w=100, h=400),+ None,+ )+ self.assertEqual(result.svg.count('<tspan'), 4)+ root = ET.fromstring(+ '<svg xmlns="http://www.w3.org/2000/svg">'+ f'{result.svg}</svg>'+ )+ text = next(root.iter('{http://www.w3.org/2000/svg}text'))+ self.assertEqual(''.join(text.itertext()), '甲 乙')+def test_text_property_compatibility_aliases_warn_and_normalize(self):compatible = '''<svg xmlns="http://www.w3.org/2000/svg"viewBox="0 0 640 360">@@ -2787,6 +2963,7 @@ class SVGQualityCheckerCompatibilityTests(unittest.TestCase):'baseline': ('style="dominant-baseline:middle"', 'dominant-baseline'),'unknown_attribute': ('textLength="120"', 'textLength'),'inline_filter': ('style="filter:url(#shadow)"', 'filter'),+ 'xml_space': ('xml:space="Preserve"', 'xml:space'),}for name, (declaration, expected) in cases.items():content = (@@ -2802,6 +2979,28 @@ class SVGQualityCheckerCompatibilityTests(unittest.TestCase):'invalid project text property',)+ def test_xml_space_is_scoped_to_text_and_tspan(self):+ invalid_sources = {+ 'root': (+ '<svg xmlns="http://www.w3.org/2000/svg" '+ 'viewBox="0 0 640 360" xml:space="preserve">'+ '<text x="40" y="100" font-size="24">Text</text></svg>'+ ),+ 'group': (+ '<svg xmlns="http://www.w3.org/2000/svg" '+ 'viewBox="0 0 640 360"><g xml:space="preserve">'+ '<text x="40" y="100" font-size="24">Text</text>'+ '</g></svg>'+ ),+ }+ for name, source in invalid_sources.items():+ with self.subTest(name=name):+ self._assert_checker_and_exporter_reject(+ source,+ 'xml:space only as a direct attribute on <text> or <tspan>',+ 'invalid project text property',+ )+def test_compatible_letter_spacing_units_match_unitless_px(self):cases = (('2px', '2', '150'),