wolfdocx 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. wolfdocx/__init__.py +25 -0
  2. wolfdocx/_cache_root.py +24 -0
  3. wolfdocx/_comment_threads.py +278 -0
  4. wolfdocx/_inspection_cache.py +374 -0
  5. wolfdocx/_version.py +3 -0
  6. wolfdocx/admission.py +163 -0
  7. wolfdocx/assembly.py +463 -0
  8. wolfdocx/authoring.py +2773 -0
  9. wolfdocx/canonical.py +267 -0
  10. wolfdocx/content.py +963 -0
  11. wolfdocx/document.py +215 -0
  12. wolfdocx/errors.py +169 -0
  13. wolfdocx/find_replace.py +1210 -0
  14. wolfdocx/formatting.py +3160 -0
  15. wolfdocx/inspect.py +3999 -0
  16. wolfdocx/model.py +1038 -0
  17. wolfdocx/numbering_authoring.py +1422 -0
  18. wolfdocx/output.py +13 -0
  19. wolfdocx/package.py +2313 -0
  20. wolfdocx/package_profile.py +128 -0
  21. wolfdocx/page_setup.py +2483 -0
  22. wolfdocx/paragraph_authoring.py +1842 -0
  23. wolfdocx/properties.py +2728 -0
  24. wolfdocx/protection.py +1909 -0
  25. wolfdocx/regions.py +1993 -0
  26. wolfdocx/render_warnings.py +106 -0
  27. wolfdocx/reporting.py +943 -0
  28. wolfdocx/review.py +2862 -0
  29. wolfdocx/run_text.py +117 -0
  30. wolfdocx/section_break.py +1810 -0
  31. wolfdocx/session_ops/__init__.py +45 -0
  32. wolfdocx/session_ops/_bridge.py +151 -0
  33. wolfdocx/session_ops/lists.py +104 -0
  34. wolfdocx/session_ops/paragraphs.py +39 -0
  35. wolfdocx/session_ops/rich_objects.py +2598 -0
  36. wolfdocx/session_ops/run_edits.py +70 -0
  37. wolfdocx/session_ops/runs.py +313 -0
  38. wolfdocx/session_ops/sections.py +109 -0
  39. wolfdocx/session_ops/styling.py +99 -0
  40. wolfdocx/session_ops/tables.py +247 -0
  41. wolfdocx/styles_authoring.py +2822 -0
  42. wolfdocx/table_cell_properties.py +1458 -0
  43. wolfdocx/table_column.py +1501 -0
  44. wolfdocx/table_delete.py +942 -0
  45. wolfdocx/table_insert.py +1114 -0
  46. wolfdocx/table_merge.py +1863 -0
  47. wolfdocx/table_properties.py +2429 -0
  48. wolfdocx/table_row_properties.py +1095 -0
  49. wolfdocx/table_structure.py +1044 -0
  50. wolfdocx/text_effects.py +1438 -0
  51. wolfdocx-0.1.0.dist-info/METADATA +127 -0
  52. wolfdocx-0.1.0.dist-info/RECORD +54 -0
  53. wolfdocx-0.1.0.dist-info/WHEEL +4 -0
  54. wolfdocx-0.1.0.dist-info/licenses/LICENSE +21 -0
wolfdocx/formatting.py ADDED
@@ -0,0 +1,3160 @@
1
+ """Source-bound native Word formatting discovery and authoring.
2
+
3
+ The authoring surface is the main document body (``word/document.xml``) and reachable
4
+ package parts. Formatting changes are atomic, source-bound, and strictly schema-valid:
5
+ run edits target bounded text offsets within paragraphs, while paragraph edits apply
6
+ to entire paragraphs.
7
+
8
+ Anything that cannot be resolved exactly is refused instead of guessed:
9
+ - Malformed requests (unknown keys, missing required fields, empty edits).
10
+ - Unknown or missing paragraph and character styles against ``word/styles.xml``.
11
+ - Unsafe revision (w:ins, w:del, etc.), comment, or SDT (content control) contexts.
12
+ - Overlapping run edits or invalid character ranges (negative, inverted, out-of-bounds).
13
+ - Text mismatch between expected_old_text and actual document text at target offsets.
14
+ - Stale structure fingerprints.
15
+ - Occupied destination paths or modified source packages.
16
+
17
+ Everything else is preserved: non-target parts are byte-identical to the source archive,
18
+ unedited paragraph and run properties are intact, and CT_RPr/CT_PPr element sequences
19
+ strictly follow OOXML schema order.
20
+
21
+ Discovery reports direct w14 text effects using the text_effects decoder, OpenType
22
+ values using their native scalar/list types, and scene_3d/props_3d as lossless XML
23
+ trees (expanded tag/attribute names, text, and ordered children). Unparsed effects
24
+ also retain that XML representation. Stored properties stay visible in legacy
25
+ compatibility modes, with ``w14_effects_active=False`` and ``compatibility_mode``
26
+ reported separately. Numeral-spacing creation and edits below compatibilityMode 14
27
+ are refused before publication; removal is allowed, and unrelated edits preserve
28
+ existing suppressed effects.
29
+ """
30
+
31
+ from __future__ import annotations
32
+
33
+ import copy
34
+ import enum
35
+ import itertools
36
+ import json
37
+ import re
38
+ import zipfile
39
+ from collections.abc import Mapping, Sequence
40
+ from dataclasses import dataclass, replace
41
+ from pathlib import Path
42
+ from typing import Any, Literal
43
+ from xml.etree import ElementTree as ET
44
+ from xml.parsers import expat
45
+
46
+ from .authoring import _MAX_TEXT_CHARACTERS
47
+ from .inspect import (
48
+ SUPPORTED_WORD_NAMESPACES,
49
+ Q,
50
+ parse_xml_with_preserved_qnames,
51
+ serialize_xml_with_preserved_qnames,
52
+ )
53
+ from .package import PackageError, PackageGraph
54
+ from .review import (
55
+ _DOCUMENT,
56
+ ReviewReport,
57
+ _clone_run,
58
+ _mask_text,
59
+ _paragraph_map,
60
+ _ParagraphMap,
61
+ _publish,
62
+ _review_parts,
63
+ _ReviewContextError,
64
+ _sha,
65
+ _sha256,
66
+ _TextRun,
67
+ _word_namespace,
68
+ )
69
+ from .table_properties import _VALID_BORDER_STYLES, BorderSpec
70
+
71
+ _STYLES = "word/styles.xml"
72
+ _REFUSED = "refused"
73
+ _PUBLISHED = "published"
74
+
75
+ _W14 = "http://schemas.microsoft.com/office/word/2010/wordml"
76
+ _MC = "http://schemas.openxmlformats.org/markup-compatibility/2006"
77
+ _RUBY_ALIGNMENTS = frozenset(
78
+ {"center", "distributeLetter", "distributeSpace", "left", "right", "rightVertical"}
79
+ )
80
+ _NUMERAL_SPACING = frozenset({"default", "proportional", "tabular"})
81
+ _LEGACY_ANIMATIONS = frozenset(
82
+ {"none", "lights", "blinkBackground", "sparkle", "antsBlack", "antsRed", "shimmer"}
83
+ )
84
+ _EMPHASIS_MARKS = frozenset({"none", "dot", "comma", "circle", "underDot"})
85
+
86
+ _HEX_COLOR_PATTERN = re.compile(r"^[0-9a-fA-F]{6}\Z")
87
+ _VALID_UNDERLINE_STYLES = frozenset(
88
+ {
89
+ "single",
90
+ "words",
91
+ "double",
92
+ "thick",
93
+ "dotted",
94
+ "dottedHeavy",
95
+ "dash",
96
+ "dashedHeavy",
97
+ "dashLong",
98
+ "dashLongHeavy",
99
+ "dotDash",
100
+ "dashDotHeavy",
101
+ "dotDotDash",
102
+ "dashDotDotHeavy",
103
+ "wave",
104
+ "wavyHeavy",
105
+ "wavyDouble",
106
+ "none",
107
+ }
108
+ )
109
+
110
+ _ST_HIGHLIGHT_COLORS: tuple[str, ...] = (
111
+ "black",
112
+ "blue",
113
+ "cyan",
114
+ "darkBlue",
115
+ "darkCyan",
116
+ "darkGray",
117
+ "darkGreen",
118
+ "darkMagenta",
119
+ "darkRed",
120
+ "darkYellow",
121
+ "green",
122
+ "lightGray",
123
+ "magenta",
124
+ "none",
125
+ "red",
126
+ "white",
127
+ "yellow",
128
+ )
129
+ _VALID_HIGHLIGHT_COLORS: frozenset[str] = frozenset(_ST_HIGHLIGHT_COLORS)
130
+ # Word UI and python-docx ``WD_COLOR_INDEX`` names resolve to their ``ST_HighlightColor``
131
+ # literal. ``ST_HighlightColor`` literals take precedence, so ``green`` stays ``green``
132
+ # (Word's "Bright Green") even though ``WD_COLOR_INDEX.GREEN`` writes ``darkGreen``.
133
+ _HIGHLIGHT_NAME_ALIASES: dict[str, str] = {
134
+ "turquoise": "cyan",
135
+ "pink": "magenta",
136
+ "teal": "darkCyan",
137
+ "violet": "darkMagenta",
138
+ "brightgreen": "green",
139
+ "bright_green": "green",
140
+ "gray50": "darkGray",
141
+ "gray_50": "darkGray",
142
+ "gray25": "lightGray",
143
+ "gray_25": "lightGray",
144
+ }
145
+ _HIGHLIGHT_CANONICAL_MAP: dict[str, str] = {
146
+ **_HIGHLIGHT_NAME_ALIASES,
147
+ **{c.lower(): c for c in _ST_HIGHLIGHT_COLORS},
148
+ }
149
+ # python-docx ``WD_COLOR_INDEX`` member names -> ``ST_HighlightColor``. Members resolve by
150
+ # name, so ``WD_COLOR_INDEX.GREEN`` writes ``darkGreen`` while ``"green"`` stays bright green.
151
+ _WD_COLOR_INDEX_HIGHLIGHTS: dict[str, str] = {
152
+ "BLACK": "black",
153
+ "BLUE": "blue",
154
+ "TURQUOISE": "cyan",
155
+ "BRIGHT_GREEN": "green",
156
+ "PINK": "magenta",
157
+ "RED": "red",
158
+ "YELLOW": "yellow",
159
+ "WHITE": "white",
160
+ "DARK_BLUE": "darkBlue",
161
+ "TEAL": "darkCyan",
162
+ "GREEN": "darkGreen",
163
+ "VIOLET": "darkMagenta",
164
+ "DARK_RED": "darkRed",
165
+ "DARK_YELLOW": "darkYellow",
166
+ "GRAY_50": "darkGray",
167
+ "GRAY_25": "lightGray",
168
+ }
169
+ # python-docx ``BabelFish`` UI names of built-in styles whose ``w:name`` Word stores in
170
+ # lowercase: ``style="Heading 1"`` names the style whose ``w:name`` is ``heading 1``.
171
+ _STYLE_UI_NAMES: dict[str, str] = {
172
+ "caption": "Caption",
173
+ "footer": "Footer",
174
+ "header": "Header",
175
+ **{f"heading {level}": f"Heading {level}" for level in range(1, 10)},
176
+ }
177
+
178
+ _PARAGRAPH_BORDER_SIDES: tuple[str, ...] = (
179
+ "top",
180
+ "left",
181
+ "bottom",
182
+ "right",
183
+ "between",
184
+ "bar",
185
+ )
186
+
187
+ # Paragraph alignments keyed by their spelling folded to lowercase without underscores,
188
+ # mapped to the ECMA-376 ST_Jc value: the ST_Jc literals and the python-docx
189
+ # WD_PARAGRAPH_ALIGNMENT (WD_ALIGN_PARAGRAPH) names, where ``JUSTIFY`` writes ``both``.
190
+ _ALIGNMENT_ALIASES: dict[str, str] = {
191
+ "left": "left",
192
+ "center": "center",
193
+ "right": "right",
194
+ "both": "both",
195
+ "justify": "both",
196
+ "distribute": "distribute",
197
+ "start": "start",
198
+ "end": "end",
199
+ "mediumkashida": "mediumKashida",
200
+ "justifymed": "mediumKashida",
201
+ "highkashida": "highKashida",
202
+ "justifyhi": "highKashida",
203
+ "lowkashida": "lowKashida",
204
+ "justifylow": "lowKashida",
205
+ "thaidistribute": "thaiDistribute",
206
+ "thaijustify": "thaiDistribute",
207
+ }
208
+ _VALID_VERTICAL_ALIGNMENTS = frozenset({"baseline", "superscript", "subscript"})
209
+ # Paragraph line rules keyed by their spelling folded to lowercase without underscores,
210
+ # mapped to the canonical ``SpacingSpec.line_rule``: the ECMA-376 ST_LineSpacingRule
211
+ # values (``atLeast``) and the python-docx WD_LINE_SPACING names that name a rule alone
212
+ # (``AT_LEAST``, ``EXACTLY``, ``MULTIPLE``).
213
+ _LINE_RULE_ALIASES: dict[str, str] = {
214
+ "auto": "auto",
215
+ "multiple": "auto",
216
+ "exact": "exact",
217
+ "exactly": "exact",
218
+ "atleast": "at_least",
219
+ }
220
+ # python-docx WD_LINE_SPACING names that fix the line height as well as the rule: each
221
+ # writes ``lineRule="auto"`` with the listed ``w:line`` in 240ths of a line.
222
+ _PRESET_LINE_HEIGHTS: dict[str, int] = {
223
+ "single": 240,
224
+ "onepointfive": 360,
225
+ "double": 480,
226
+ }
227
+ # python-docx ParagraphFormat property names accepted for the spacing keys
228
+ _SPACING_KEY_ALIASES: dict[str, str] = {
229
+ "space_before": "before",
230
+ "space_after": "after",
231
+ "line_spacing": "line",
232
+ "line_spacing_rule": "line_rule",
233
+ }
234
+ # python-docx ParagraphFormat property names accepted for the indent keys
235
+ _INDENT_KEY_ALIASES: dict[str, str] = {"first_line_indent": "first_line"}
236
+ # ECMA-376 ST_TabJc values accepted for authoring (transitional left/right spellings)
237
+ _VALID_TAB_ALIGNMENTS = frozenset({"left", "center", "right", "decimal", "bar", "clear"})
238
+ # ECMA-376 ST_TabTlc leader characters keyed by their spelling folded to lowercase without
239
+ # underscores, including the python-docx WD_TAB_LEADER names (``DOTS``, ``MIDDLE_DOT``)
240
+ _TAB_LEADER_ALIASES: dict[str, str] = {
241
+ "none": "none",
242
+ "spaces": "none",
243
+ "dot": "dot",
244
+ "dots": "dot",
245
+ "hyphen": "hyphen",
246
+ "dashes": "hyphen",
247
+ "underscore": "underscore",
248
+ "lines": "underscore",
249
+ "heavy": "heavy",
250
+ "middledot": "middleDot",
251
+ }
252
+ # python-docx TabStop property names accepted for the tab stop keys
253
+ _TAB_KEY_ALIASES: dict[str, str] = {"alignment": "val", "position": "pos"}
254
+
255
+ # ECMA-376 CT_RPr sequence order
256
+ _RPR_ORDER: tuple[str, ...] = (
257
+ "rStyle",
258
+ "rFonts",
259
+ "b",
260
+ "bCs",
261
+ "i",
262
+ "iCs",
263
+ "caps",
264
+ "smallCaps",
265
+ "strike",
266
+ "dstrike",
267
+ "outline",
268
+ "shadow",
269
+ "emboss",
270
+ "imprint",
271
+ "noProof",
272
+ "snapToGrid",
273
+ "vanish",
274
+ "color",
275
+ "spacing",
276
+ "w",
277
+ "kern",
278
+ "position",
279
+ "sz",
280
+ "szCs",
281
+ "highlight",
282
+ "u",
283
+ "effect",
284
+ "bdr",
285
+ "shd",
286
+ "fitText",
287
+ "vertAlign",
288
+ "rtl",
289
+ "cs",
290
+ "em",
291
+ "lang",
292
+ "eastAsianLayout",
293
+ "specVanish",
294
+ "oMath",
295
+ "rPrChange",
296
+ )
297
+ _RPR_RANK: dict[str, int] = {tag: i for i, tag in enumerate(_RPR_ORDER)}
298
+
299
+ # ECMA-376 CT_Fonts attribute declaration order
300
+ _RFONTS_ATTRIBUTE_ORDER: tuple[str, ...] = (
301
+ "hint",
302
+ "ascii",
303
+ "hAnsi",
304
+ "eastAsia",
305
+ "cs",
306
+ "asciiTheme",
307
+ "hAnsiTheme",
308
+ "eastAsiaTheme",
309
+ "cstheme",
310
+ )
311
+
312
+ # ECMA-376 CT_PPrBase / CT_PPr sequence order
313
+ _PPR_ORDER: tuple[str, ...] = (
314
+ "pStyle",
315
+ "keepNext",
316
+ "keepLines",
317
+ "pageBreakBefore",
318
+ "framePr",
319
+ "widowControl",
320
+ "numPr",
321
+ "suppressLineNumbers",
322
+ "pBdr",
323
+ "shd",
324
+ "tabs",
325
+ "suppressAutoHyphens",
326
+ "kinsoku",
327
+ "wordWrap",
328
+ "overflowPunct",
329
+ "topLinePunct",
330
+ "autoSpaceDE",
331
+ "autoSpaceDN",
332
+ "bidi",
333
+ "adjustRightInd",
334
+ "snapToGrid",
335
+ "spacing",
336
+ "ind",
337
+ "contextualSpacing",
338
+ "mirrorIndents",
339
+ "suppressOverlap",
340
+ "jc",
341
+ "textDirection",
342
+ "textAlignment",
343
+ "textboxTightWrap",
344
+ "outlineLvl",
345
+ "divId",
346
+ "cnfStyle",
347
+ "rPr",
348
+ "sectPr",
349
+ "pPrChange",
350
+ )
351
+ _PPR_RANK: dict[str, int] = {tag: i for i, tag in enumerate(_PPR_ORDER)}
352
+
353
+
354
+ def _local_name(tag: Any) -> str:
355
+ return tag.split("}", 1)[-1] if isinstance(tag, str) else ""
356
+
357
+
358
+ def _flag(element: ET.Element | None) -> bool | None:
359
+ if element is None:
360
+ return None
361
+ val = element.get(Q(_word_namespace_from_element(element), "val")) or element.get("val")
362
+ if val is None:
363
+ return True
364
+ return val.strip().lower() not in {"0", "false", "off"}
365
+
366
+
367
+ def _word_namespace_from_element(element: ET.Element) -> str:
368
+ if element.tag.startswith("{"):
369
+ return element.tag[1:].split("}", 1)[0]
370
+ return "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
371
+
372
+
373
+ def _fold_alias(value: str) -> str:
374
+ return value.replace("_", "").lower()
375
+
376
+
377
+ def _conflicting_alias_keys(value: Mapping[str, Any], aliases: Mapping[str, str]) -> list[str]:
378
+ """Keys that name one property twice, once canonically and once through an alias."""
379
+ by_property: dict[str, list[str]] = {}
380
+ for key in value:
381
+ by_property.setdefault(aliases.get(key, key), []).append(key)
382
+ return sorted(key for keys in by_property.values() if len(keys) > 1 for key in keys)
383
+
384
+
385
+ def _member_name(value: Any) -> Any:
386
+ """Name of an Enum member (python-docx enumerations), otherwise the value unchanged."""
387
+ return value.name if isinstance(value, enum.Enum) else value
388
+
389
+
390
+ def _canonical_highlight(value: Any, code: str) -> str:
391
+ """Resolve an ST_HighlightColor literal, Word/python-docx name, or WD_COLOR_INDEX member."""
392
+ if isinstance(value, enum.Enum):
393
+ highlight = _WD_COLOR_INDEX_HIGHLIGHTS.get(value.name)
394
+ elif isinstance(value, str):
395
+ highlight = _HIGHLIGHT_CANONICAL_MAP.get(_fold_alias(value.strip()))
396
+ else:
397
+ highlight = None
398
+ if highlight is None:
399
+ raise ValueError(code)
400
+ return highlight
401
+
402
+
403
+ def _canonical_alignment(value: Any, code: str) -> str:
404
+ """Resolve an ST_Jc literal or python-docx alignment name/member to its ST_Jc value."""
405
+ value = _member_name(value)
406
+ alignment = _ALIGNMENT_ALIASES.get(_fold_alias(value)) if isinstance(value, str) else None
407
+ if alignment is None:
408
+ raise ValueError(code)
409
+ return alignment
410
+
411
+
412
+ def _canonical_line_spacing(line: Any, line_rule: Any) -> tuple[Any, str]:
413
+ """Resolve a line rule spelling to ``(line, canonical rule)``.
414
+
415
+ WD_LINE_SPACING ``SINGLE``/``ONE_POINT_FIVE``/``DOUBLE`` resolve to ``auto`` with their
416
+ fixed line height; an explicit ``line`` that disagrees with that height refuses.
417
+ """
418
+ name = _member_name(line_rule)
419
+ folded = _fold_alias(name) if isinstance(name, str) else None
420
+ preset = _PRESET_LINE_HEIGHTS.get(folded)
421
+ if preset is not None:
422
+ if line is not None and line != preset:
423
+ raise ValueError("format_spacing_line_rule_invalid")
424
+ return preset, "auto"
425
+ rule = _LINE_RULE_ALIASES.get(folded)
426
+ if rule is None:
427
+ raise ValueError("format_spacing_line_rule_invalid")
428
+ return line, rule
429
+
430
+
431
+ @dataclass(frozen=True)
432
+ class SpacingSpec:
433
+ """Paragraph spacing specification in twips / line-rules.
434
+
435
+ ``line_rule`` accepts ECMA-376 and python-docx spellings (strings or WD_LINE_SPACING
436
+ members) and is stored as the canonical ``auto``, ``exact``, or ``at_least``;
437
+ ``single``/``one_point_five``/``double`` also set ``line`` to 240/360/480.
438
+ """
439
+
440
+ before: int | None = None
441
+ after: int | None = None
442
+ line: int | None = None
443
+ line_rule: str | None = None
444
+
445
+ def __post_init__(self) -> None:
446
+ if self.line_rule is not None:
447
+ line, line_rule = _canonical_line_spacing(self.line, self.line_rule)
448
+ object.__setattr__(self, "line", line)
449
+ object.__setattr__(self, "line_rule", line_rule)
450
+
451
+ def to_dict(self) -> dict[str, Any]:
452
+ result: dict[str, Any] = {}
453
+ if self.before is not None:
454
+ result["before"] = self.before
455
+ if self.after is not None:
456
+ result["after"] = self.after
457
+ if self.line is not None:
458
+ result["line"] = self.line
459
+ if self.line_rule is not None:
460
+ result["line_rule"] = self.line_rule
461
+ return result
462
+
463
+
464
+ @dataclass(frozen=True)
465
+ class IndentSpec:
466
+ """Paragraph indentation specification in twips.
467
+
468
+ A negative ``first_line`` is python-docx's hanging indent: it is stored as
469
+ ``hanging`` with the absolute value, and refuses alongside an explicit ``hanging``.
470
+ """
471
+
472
+ left: int | None = None
473
+ right: int | None = None
474
+ first_line: int | None = None
475
+ hanging: int | None = None
476
+ start: int | None = None
477
+ end: int | None = None
478
+
479
+ def __post_init__(self) -> None:
480
+ first_line = self.first_line
481
+ if isinstance(first_line, int) and not isinstance(first_line, bool) and first_line < 0:
482
+ if self.hanging is not None:
483
+ raise ValueError("format_indent_first_line_hanging_conflict")
484
+ object.__setattr__(self, "hanging", -first_line)
485
+ object.__setattr__(self, "first_line", None)
486
+
487
+ def to_dict(self) -> dict[str, Any]:
488
+ result: dict[str, Any] = {}
489
+ if self.left is not None:
490
+ result["left"] = self.left
491
+ if self.right is not None:
492
+ result["right"] = self.right
493
+ if self.first_line is not None:
494
+ result["first_line"] = self.first_line
495
+ if self.hanging is not None:
496
+ result["hanging"] = self.hanging
497
+ if self.start is not None:
498
+ result["start"] = self.start
499
+ if self.end is not None:
500
+ result["end"] = self.end
501
+ return result
502
+
503
+
504
+ @dataclass(frozen=True)
505
+ class ParagraphBordersSpec:
506
+ """Paragraph border specification across supported sides."""
507
+
508
+ top: BorderSpec | Mapping[str, Any] | Literal[False] | None = None
509
+ left: BorderSpec | Mapping[str, Any] | Literal[False] | None = None
510
+ bottom: BorderSpec | Mapping[str, Any] | Literal[False] | None = None
511
+ right: BorderSpec | Mapping[str, Any] | Literal[False] | None = None
512
+ between: BorderSpec | Mapping[str, Any] | Literal[False] | None = None
513
+ bar: BorderSpec | Mapping[str, Any] | Literal[False] | None = None
514
+
515
+ def to_dict(self) -> dict[str, Any]:
516
+ data: dict[str, Any] = {}
517
+ for side in _PARAGRAPH_BORDER_SIDES:
518
+ val = getattr(self, side)
519
+ if val is not None:
520
+ if isinstance(val, BorderSpec):
521
+ data[side] = val.to_dict()
522
+ elif isinstance(val, Mapping):
523
+ data[side] = dict(val)
524
+ elif val is False:
525
+ data[side] = False
526
+ return data
527
+
528
+
529
+ @dataclass(frozen=True)
530
+ class TabStopSpec:
531
+ """One custom paragraph tab stop; ``pos`` is measured in twips from the start indent.
532
+
533
+ ``val`` and ``leader`` accept python-docx WD_TAB_ALIGNMENT / WD_TAB_LEADER names and
534
+ are stored as their ECMA-376 ``w:tab`` attribute values.
535
+ """
536
+
537
+ val: str
538
+ pos: int
539
+ leader: str | None = None
540
+
541
+ def __post_init__(self) -> None:
542
+ val = self.val.lower() if isinstance(self.val, str) else None
543
+ if val not in _VALID_TAB_ALIGNMENTS:
544
+ raise ValueError("format_tabs_invalid")
545
+ if isinstance(self.pos, bool) or not isinstance(self.pos, int) or self.pos < 0:
546
+ raise ValueError("format_tabs_invalid")
547
+ leader = self.leader
548
+ if leader is not None:
549
+ leader = (
550
+ _TAB_LEADER_ALIASES.get(_fold_alias(leader)) if isinstance(leader, str) else None
551
+ )
552
+ if leader is None:
553
+ raise ValueError("format_tabs_invalid")
554
+ object.__setattr__(self, "val", val)
555
+ object.__setattr__(self, "leader", leader)
556
+
557
+ def to_dict(self) -> dict[str, Any]:
558
+ result: dict[str, Any] = {"val": self.val, "pos": self.pos}
559
+ if self.leader is not None:
560
+ result["leader"] = self.leader
561
+ return result
562
+
563
+
564
+ # ECMA-376 17.3.1.11 CT_FramePr attributes keyed by their snake_case request names.
565
+ _FRAME_ATTRIBUTES: dict[str, str] = {
566
+ "drop_cap": "dropCap",
567
+ "lines": "lines",
568
+ "w": "w",
569
+ "h": "h",
570
+ "h_space": "hSpace",
571
+ "v_space": "vSpace",
572
+ "wrap": "wrap",
573
+ "h_anchor": "hAnchor",
574
+ "v_anchor": "vAnchor",
575
+ "x": "x",
576
+ "x_align": "xAlign",
577
+ "y": "y",
578
+ "y_align": "yAlign",
579
+ "h_rule": "hRule",
580
+ "anchor_lock": "anchorLock",
581
+ }
582
+ _FRAME_INTEGER_FIELDS = frozenset({"lines", "w", "h", "h_space", "v_space", "x", "y"})
583
+ _FRAME_CHOICES: dict[str, frozenset[str]] = {
584
+ "drop_cap": frozenset({"none", "drop", "margin"}),
585
+ "wrap": frozenset({"auto", "notBeside", "around", "tight", "through", "none"}),
586
+ "h_anchor": frozenset({"text", "margin", "page"}),
587
+ "v_anchor": frozenset({"text", "margin", "page"}),
588
+ "x_align": frozenset({"left", "center", "right", "inside", "outside"}),
589
+ "y_align": frozenset({"inline", "top", "center", "bottom", "inside", "outside"}),
590
+ "h_rule": frozenset({"auto", "exact", "atLeast"}),
591
+ }
592
+ _FRAME_INT_MAX = 2**31 - 1
593
+ # ECMA-376 17.3.3.1 w:br @w:type and @w:clear values (ST_BrType, ST_BrClear)
594
+ _BREAK_TYPES = frozenset({"page", "column", "textWrapping"})
595
+ _BREAK_CLEARS = frozenset({"none", "left", "right", "all"})
596
+
597
+
598
+ @dataclass(frozen=True)
599
+ class FrameSpec:
600
+ """Paragraph frame (w:framePr, ECMA-376 17.3.1.11) in twips unless stated.
601
+
602
+ Fields keep the ECMA attribute meaning under snake_case names: ``drop_cap``
603
+ (none, drop, margin), ``lines`` (drop-cap height, 1 to 10), ``w`` and ``h``
604
+ (extent), ``h_space`` and ``v_space`` (text distance), ``wrap`` (auto, notBeside,
605
+ around, tight, through, none), ``h_anchor`` and ``v_anchor`` (text, margin, page),
606
+ ``x`` and ``y`` (signed offsets), ``x_align`` (left, center, right, inside, outside),
607
+ ``y_align`` (inline, top, center, bottom, inside, outside), ``h_rule`` (auto, exact,
608
+ atLeast) and ``anchor_lock``. None leaves an attribute unchanged on an existing
609
+ frame; at least one attribute must be set.
610
+ """
611
+
612
+ drop_cap: str | None = None
613
+ lines: int | None = None
614
+ w: int | None = None
615
+ h: int | None = None
616
+ h_space: int | None = None
617
+ v_space: int | None = None
618
+ wrap: str | None = None
619
+ h_anchor: str | None = None
620
+ v_anchor: str | None = None
621
+ x: int | None = None
622
+ x_align: str | None = None
623
+ y: int | None = None
624
+ y_align: str | None = None
625
+ h_rule: str | None = None
626
+ anchor_lock: bool | None = None
627
+
628
+ def __post_init__(self) -> None:
629
+ present = 0
630
+ for field in _FRAME_ATTRIBUTES:
631
+ value = getattr(self, field)
632
+ if value is None:
633
+ continue
634
+ present += 1
635
+ if field == "anchor_lock":
636
+ valid = isinstance(value, bool)
637
+ elif field in _FRAME_INTEGER_FIELDS:
638
+ low, high = {
639
+ "lines": (1, 10),
640
+ "x": (-_FRAME_INT_MAX - 1, _FRAME_INT_MAX),
641
+ "y": (-_FRAME_INT_MAX - 1, _FRAME_INT_MAX),
642
+ }.get(field, (0, _FRAME_INT_MAX))
643
+ valid = (
644
+ isinstance(value, int) and not isinstance(value, bool) and low <= value <= high
645
+ )
646
+ else:
647
+ valid = isinstance(value, str) and value in _FRAME_CHOICES[field]
648
+ if not valid:
649
+ raise ValueError(f"format_frame_{field}_invalid")
650
+ if not present:
651
+ raise ValueError("format_frame_empty_invalid")
652
+
653
+ def to_dict(self) -> dict[str, Any]:
654
+ return {
655
+ field: getattr(self, field)
656
+ for field in _FRAME_ATTRIBUTES
657
+ if getattr(self, field) is not None
658
+ }
659
+
660
+
661
+ def _validate_frame_spec(value: Any) -> FrameSpec | Literal[False]:
662
+ if value is False or isinstance(value, FrameSpec):
663
+ return value
664
+ if not isinstance(value, Mapping):
665
+ raise TypeError("format_frame_invalid")
666
+ unknown = set(value) - set(_FRAME_ATTRIBUTES)
667
+ if unknown:
668
+ raise ValueError(f"format_frame_unknown_keys: {sorted(unknown)}")
669
+ return FrameSpec(**value)
670
+
671
+
672
+ def _frame_value(value: bool | int | str) -> str:
673
+ if isinstance(value, bool):
674
+ return "1" if value else "0"
675
+ return str(value)
676
+
677
+
678
+ @dataclass(frozen=True)
679
+ class RubySpec:
680
+ """ECMA-376 17.3.3 phonetic guide; all sizes/raise are half-points.
681
+
682
+ ``base_text`` must equal the selected text. ``language`` authors the required
683
+ rubyPr/lid; base_font_size authors hpsBaseText, not the surrounding run size.
684
+ Guide text is an annotation, never included in the formatting character range.
685
+ """
686
+
687
+ base_text: str
688
+ guide_text: str
689
+ alignment: str = "center"
690
+ raise_: int = 0
691
+ font_size: int = 12
692
+ base_font_size: int = 24
693
+ language: str = "en-US"
694
+
695
+ def __post_init__(self) -> None:
696
+ for text in (self.base_text, self.guide_text, self.language):
697
+ if (
698
+ not isinstance(text, str)
699
+ or not text
700
+ or len(text) > _MAX_TEXT_CHARACTERS
701
+ or any(
702
+ not (
703
+ c in "\t\n\r"
704
+ or 0x20 <= ord(c) <= 0xD7FF
705
+ or 0xE000 <= ord(c) <= 0xFFFD
706
+ or 0x10000 <= ord(c) <= 0x10FFFF
707
+ )
708
+ for c in text
709
+ )
710
+ ):
711
+ raise ValueError("format_ruby_text_invalid")
712
+ if not isinstance(self.alignment, str) or self.alignment not in _RUBY_ALIGNMENTS:
713
+ raise ValueError("format_ruby_alignment_invalid")
714
+ for value, minimum in (
715
+ (self.raise_, 0),
716
+ (self.font_size, 1),
717
+ (self.base_font_size, 1),
718
+ ):
719
+ if (
720
+ isinstance(value, bool)
721
+ or not isinstance(value, int)
722
+ or not minimum <= value <= 32767
723
+ ):
724
+ raise ValueError("format_ruby_size_invalid")
725
+
726
+ def to_dict(self) -> dict[str, Any]:
727
+ return {
728
+ "base_text": self.base_text,
729
+ "guide_text": self.guide_text,
730
+ "alignment": self.alignment,
731
+ "raise": self.raise_,
732
+ "font_size": self.font_size,
733
+ "base_font_size": self.base_font_size,
734
+ "language": self.language,
735
+ }
736
+
737
+
738
+ def _ruby_spec(value: Any) -> RubySpec:
739
+ if isinstance(value, RubySpec):
740
+ return value
741
+ if not isinstance(value, Mapping) or set(value) - {
742
+ "base_text",
743
+ "guide_text",
744
+ "alignment",
745
+ "raise",
746
+ "font_size",
747
+ "base_font_size",
748
+ "language",
749
+ }:
750
+ raise ValueError("format_ruby_invalid")
751
+ if not {"base_text", "guide_text"}.issubset(value):
752
+ raise ValueError("format_ruby_invalid")
753
+ return RubySpec(
754
+ base_text=value["base_text"],
755
+ guide_text=value["guide_text"],
756
+ alignment=value.get("alignment", "center"),
757
+ raise_=value.get("raise", 0),
758
+ font_size=value.get("font_size", 12),
759
+ base_font_size=value.get("base_font_size", 24),
760
+ language=value.get("language", "en-US"),
761
+ )
762
+
763
+
764
+ @dataclass(frozen=True)
765
+ class RunFormatEdit:
766
+ """Selective formatting anchored to a source-bound base-text character range.
767
+
768
+ ``ruby`` wraps one selected run in a phonetic guide; guide sizes and raise
769
+ are half-points (ECMA-376 Part 1, 17.3.3). Existing ruby must be selected
770
+ whole; partial annotations refuse rather than splitting the guide.
771
+ ``numeral_spacing`` authors Office 2010 w14:numSpacing: ``default``,
772
+ ``proportional`` or ``tabular``. ``False`` removes the stored property, including
773
+ in compatibility modes below 14; ``None`` preserves it.
774
+ ``legacy_animation`` stores w:effect: ``none``, ``lights``, ``blinkBackground``,
775
+ ``sparkle``, ``antsBlack``, ``antsRed`` or ``shimmer``.
776
+ ``emphasis_mark`` stores w:em: ``none``, ``dot``, ``comma``, ``circle`` or ``underDot``.
777
+ These legacy properties do not enable animation or emphasis-mark painting.
778
+ None leaves a property unchanged; ``"none"`` explicitly disables it.
779
+ All these properties are returned by discover_format_targets.
780
+ ``break_type`` (``page``, ``column`` or ``textWrapping``) and ``break_clear`` (``none``,
781
+ ``left``, ``right`` or ``all``, textWrapping only) insert one w:br immediately after the
782
+ selected text. A run holding w:br or w:lastRenderedPageBreak is edited whole: a range
783
+ that covers only part of it refuses with ``format_break_partial_range_unsupported``.
784
+ discover_format_targets lists breaks and cached page breaks with their text offsets.
785
+ """
786
+
787
+ paragraph: int
788
+ start: int
789
+ end: int
790
+ expected_old_text: str
791
+ structure_fingerprint_sha256: str
792
+ part: str = _DOCUMENT
793
+ bold: bool | None = None
794
+ italic: bool | None = None
795
+ underline: str | bool | None = None
796
+ strike: bool | None = None
797
+ color: str | None = None
798
+ font_size: int | None = None
799
+ vertical_alignment: str | None = None
800
+ style: str | None = None
801
+ font_face: str | None = None
802
+ font_face_east_asia: str | None = None
803
+ highlight: str | None = None
804
+ small_caps: bool | None = None
805
+ all_caps: bool | None = None
806
+ hidden: bool | None = None
807
+ ruby: RubySpec | None = None
808
+ numeral_spacing: str | Literal[False] | None = None
809
+ legacy_animation: str | None = None
810
+ emphasis_mark: str | None = None
811
+ break_type: str | None = None
812
+ break_clear: str | None = None
813
+
814
+ def __post_init__(self) -> None:
815
+ if self.ruby is not None:
816
+ object.__setattr__(self, "ruby", _ruby_spec(self.ruby))
817
+ if (
818
+ self.numeral_spacing is not None
819
+ and self.numeral_spacing is not False
820
+ and (
821
+ not isinstance(self.numeral_spacing, str)
822
+ or self.numeral_spacing not in _NUMERAL_SPACING
823
+ )
824
+ ):
825
+ raise ValueError("format_numeral_spacing_invalid")
826
+ for name, allowed in (
827
+ ("legacy_animation", _LEGACY_ANIMATIONS),
828
+ ("emphasis_mark", _EMPHASIS_MARKS),
829
+ ):
830
+ value = getattr(self, name)
831
+ if value is not None and (not isinstance(value, str) or value not in allowed):
832
+ raise ValueError(f"format_{name}_invalid")
833
+ if self.highlight is not None:
834
+ if isinstance(self.highlight, bool) or not isinstance(self.highlight, str):
835
+ raise ValueError("format_highlight_invalid")
836
+ stripped = self.highlight.strip()
837
+ if stripped.lower() not in _HIGHLIGHT_CANONICAL_MAP:
838
+ raise ValueError("format_highlight_invalid")
839
+ object.__setattr__(self, "highlight", _HIGHLIGHT_CANONICAL_MAP[stripped.lower()])
840
+ if self.small_caps is not None and not isinstance(self.small_caps, bool):
841
+ raise ValueError("format_small_caps_invalid")
842
+ if self.all_caps is not None and not isinstance(self.all_caps, bool):
843
+ raise ValueError("format_all_caps_invalid")
844
+ if self.hidden is not None and not isinstance(self.hidden, bool):
845
+ raise ValueError("format_hidden_invalid")
846
+ if self.font_face_east_asia is not None:
847
+ _validate_font_face_east_asia(self.font_face_east_asia)
848
+ if self.break_clear is not None and self.break_type is None:
849
+ object.__setattr__(self, "break_type", "textWrapping")
850
+ if self.break_type is not None and self.break_type not in _BREAK_TYPES:
851
+ raise ValueError("format_break_type_invalid")
852
+ if self.break_clear is not None and self.break_clear not in _BREAK_CLEARS:
853
+ raise ValueError("format_break_clear_invalid")
854
+ if self.break_clear is not None and self.break_type != "textWrapping":
855
+ raise ValueError("format_break_clear_invalid")
856
+ if self.break_type is not None and self.ruby is not None:
857
+ raise ValueError("format_break_ruby_invalid")
858
+
859
+ def to_dict(self) -> dict[str, Any]:
860
+ result: dict[str, Any] = {
861
+ "part": self.part,
862
+ "paragraph": self.paragraph,
863
+ "start": self.start,
864
+ "end": self.end,
865
+ "expected_old_text": self.expected_old_text,
866
+ "structure_fingerprint_sha256": self.structure_fingerprint_sha256,
867
+ }
868
+ if self.bold is not None:
869
+ result["bold"] = self.bold
870
+ if self.italic is not None:
871
+ result["italic"] = self.italic
872
+ if self.underline is not None:
873
+ result["underline"] = self.underline
874
+ if self.strike is not None:
875
+ result["strike"] = self.strike
876
+ if self.color is not None:
877
+ result["color"] = self.color
878
+ if self.font_size is not None:
879
+ result["font_size"] = self.font_size
880
+ if self.vertical_alignment is not None:
881
+ result["vertical_alignment"] = self.vertical_alignment
882
+ if self.style is not None:
883
+ result["style"] = self.style
884
+ if self.font_face is not None:
885
+ result["font_face"] = self.font_face
886
+ if self.font_face_east_asia is not None:
887
+ result["font_face_east_asia"] = self.font_face_east_asia
888
+ if self.highlight is not None:
889
+ result["highlight"] = self.highlight
890
+ if self.small_caps is not None:
891
+ result["small_caps"] = self.small_caps
892
+ if self.all_caps is not None:
893
+ result["all_caps"] = self.all_caps
894
+ if self.hidden is not None:
895
+ result["hidden"] = self.hidden
896
+ if self.ruby is not None:
897
+ result["ruby"] = self.ruby.to_dict()
898
+ if self.numeral_spacing is not None:
899
+ result["numeral_spacing"] = self.numeral_spacing
900
+ if self.legacy_animation is not None:
901
+ result["legacy_animation"] = self.legacy_animation
902
+ if self.emphasis_mark is not None:
903
+ result["emphasis_mark"] = self.emphasis_mark
904
+ if self.break_type is not None:
905
+ result["break_type"] = self.break_type
906
+ if self.break_clear is not None:
907
+ result["break_clear"] = self.break_clear
908
+ return result
909
+
910
+
911
+ def _fold_flag_alias(canonical: Any, alias: Any, code: str) -> bool | None:
912
+ """Fold a python-docx alias flag into its canonical flag; disagreeing values refuse."""
913
+ for flag in (canonical, alias):
914
+ if flag is not None and not isinstance(flag, bool):
915
+ raise ValueError(f"{code}_invalid")
916
+ if alias is None:
917
+ return canonical
918
+ if canonical is not None and canonical is not alias:
919
+ raise ValueError(f"{code}_conflict")
920
+ return alias
921
+
922
+
923
+ @dataclass(frozen=True)
924
+ class ParagraphFormatEdit:
925
+ """Selective paragraph formatting change anchored to a source-bound paragraph.
926
+
927
+ ``keep_with_next`` and ``keep_together`` are python-docx names for ``keep_next``
928
+ (``w:keepNext``) and ``keep_lines`` (``w:keepLines``); they fold into the canonical
929
+ fields at construction and read back as ``None``. ``alignment`` accepts ST_Jc values
930
+ and python-docx WD_PARAGRAPH_ALIGNMENT names or members in any case and is stored as
931
+ the ST_Jc value (``JUSTIFY`` becomes ``both``).
932
+
933
+ ``suppress_auto_hyphens`` and ``suppress_line_numbers`` author w:suppressAutoHyphens and
934
+ w:suppressLineNumbers; ``frame`` authors w:framePr from a ``FrameSpec`` or its mapping
935
+ (unspecified attributes of an existing frame are kept) and ``False`` removes the frame.
936
+ """
937
+
938
+ paragraph: int
939
+ structure_fingerprint_sha256: str
940
+ part: str = _DOCUMENT
941
+ style: str | None = None
942
+ alignment: str | None = None
943
+ spacing: SpacingSpec | None = None
944
+ indent: IndentSpec | None = None
945
+ keep_next: bool | None = None
946
+ keep_lines: bool | None = None
947
+ outline_level: int | None = None
948
+ shading: str | Literal[False] | None = None
949
+ page_break_before: bool | None = None
950
+ borders: ParagraphBordersSpec | Mapping[str, Any] | Literal[False] | None = None
951
+ widow_control: bool | None = None
952
+ tabs: Sequence[TabStopSpec | Mapping[str, Any]] | None = None
953
+ keep_with_next: bool | None = None
954
+ keep_together: bool | None = None
955
+ suppress_auto_hyphens: bool | None = None
956
+ suppress_line_numbers: bool | None = None
957
+ frame: FrameSpec | Mapping[str, Any] | Literal[False] | None = None
958
+
959
+ def __post_init__(self) -> None:
960
+ object.__setattr__(
961
+ self,
962
+ "keep_next",
963
+ _fold_flag_alias(self.keep_next, self.keep_with_next, "format_keep_next"),
964
+ )
965
+ object.__setattr__(
966
+ self,
967
+ "keep_lines",
968
+ _fold_flag_alias(self.keep_lines, self.keep_together, "format_keep_lines"),
969
+ )
970
+ object.__setattr__(self, "keep_with_next", None)
971
+ object.__setattr__(self, "keep_together", None)
972
+ if self.alignment is not None:
973
+ object.__setattr__(
974
+ self,
975
+ "alignment",
976
+ _canonical_alignment(self.alignment, "format_alignment_invalid"),
977
+ )
978
+ if self.page_break_before is not None and not isinstance(self.page_break_before, bool):
979
+ raise ValueError("format_page_break_before_invalid")
980
+ if self.widow_control is not None and not isinstance(self.widow_control, bool):
981
+ raise ValueError("format_widow_control_invalid")
982
+ if self.tabs is not None:
983
+ object.__setattr__(self, "tabs", _validate_tabs(self.tabs))
984
+ if self.shading is not None:
985
+ if isinstance(self.shading, bool):
986
+ if self.shading is not False:
987
+ raise ValueError("format_shading_invalid")
988
+ elif isinstance(self.shading, str):
989
+ if not _HEX_COLOR_PATTERN.match(self.shading):
990
+ raise ValueError("format_shading_invalid")
991
+ else:
992
+ raise ValueError("format_shading_invalid")
993
+ if self.borders is not None:
994
+ normalized = _validate_borders_spec(self.borders)
995
+ object.__setattr__(self, "borders", normalized)
996
+ for name in ("suppress_auto_hyphens", "suppress_line_numbers"):
997
+ value = getattr(self, name)
998
+ if value is not None and not isinstance(value, bool):
999
+ raise ValueError(f"format_{name}_invalid")
1000
+ if self.frame is not None:
1001
+ object.__setattr__(self, "frame", _validate_frame_spec(self.frame))
1002
+
1003
+ def to_dict(self) -> dict[str, Any]:
1004
+ result: dict[str, Any] = {
1005
+ "part": self.part,
1006
+ "paragraph": self.paragraph,
1007
+ "structure_fingerprint_sha256": self.structure_fingerprint_sha256,
1008
+ }
1009
+ if self.style is not None:
1010
+ result["style"] = self.style
1011
+ if self.alignment is not None:
1012
+ result["alignment"] = self.alignment
1013
+ if self.spacing is not None:
1014
+ result["spacing"] = self.spacing.to_dict()
1015
+ if self.indent is not None:
1016
+ result["indent"] = self.indent.to_dict()
1017
+ if self.keep_next is not None:
1018
+ result["keep_next"] = self.keep_next
1019
+ if self.keep_lines is not None:
1020
+ result["keep_lines"] = self.keep_lines
1021
+ if self.outline_level is not None:
1022
+ result["outline_level"] = self.outline_level
1023
+ if self.shading is not None:
1024
+ result["shading"] = self.shading
1025
+ if self.borders is not None:
1026
+ result["borders"] = (
1027
+ self.borders.to_dict()
1028
+ if isinstance(self.borders, ParagraphBordersSpec)
1029
+ else self.borders
1030
+ )
1031
+ if self.page_break_before is not None:
1032
+ result["page_break_before"] = self.page_break_before
1033
+ if self.widow_control is not None:
1034
+ result["widow_control"] = self.widow_control
1035
+ if self.tabs is not None:
1036
+ result["tabs"] = [_validate_tab_stop(stop).to_dict() for stop in self.tabs]
1037
+ if self.suppress_auto_hyphens is not None:
1038
+ result["suppress_auto_hyphens"] = self.suppress_auto_hyphens
1039
+ if self.suppress_line_numbers is not None:
1040
+ result["suppress_line_numbers"] = self.suppress_line_numbers
1041
+ if self.frame is not None:
1042
+ result["frame"] = self.frame if self.frame is False else self.frame.to_dict()
1043
+ return result
1044
+
1045
+
1046
+ @dataclass(frozen=True)
1047
+ class FormatRequest:
1048
+ """Strict request for source-bound paragraph and run formatting changes."""
1049
+
1050
+ source: Path
1051
+ source_sha256: str
1052
+ destination: Path
1053
+ run_edits: tuple[RunFormatEdit, ...] = ()
1054
+ paragraph_edits: tuple[ParagraphFormatEdit, ...] = ()
1055
+
1056
+
1057
+ @dataclass(frozen=True)
1058
+ class FormatReport:
1059
+ """Content-safe public receipt for one atomic formatting authoring request."""
1060
+
1061
+ status: str
1062
+ code: str | None
1063
+ source_sha256: str
1064
+ destination_sha256: str | None
1065
+ run_edits: list[dict[str, Any]]
1066
+ paragraph_edits: list[dict[str, Any]]
1067
+ changed_targets: list[dict[str, Any]]
1068
+
1069
+ @property
1070
+ def passed(self) -> bool:
1071
+ return self.status == _PUBLISHED
1072
+
1073
+ def to_dict(self) -> dict[str, Any]:
1074
+ return {
1075
+ "schema_version": 1,
1076
+ "passed": self.passed,
1077
+ "status": self.status,
1078
+ "code": self.code,
1079
+ "source_sha256": self.source_sha256,
1080
+ "destination_sha256": self.destination_sha256,
1081
+ "run_edits": self.run_edits,
1082
+ "paragraph_edits": self.paragraph_edits,
1083
+ "changed_targets": self.changed_targets,
1084
+ }
1085
+
1086
+
1087
+ def _validate_font_face_east_asia(value: Any) -> str:
1088
+ if not isinstance(value, str) or not value or len(value) > 256:
1089
+ raise ValueError("format_font_face_east_asia_invalid")
1090
+ return value
1091
+
1092
+
1093
+ def _validate_run_edit_dict(value: Mapping[str, Any]) -> RunFormatEdit:
1094
+ allowed_keys = {
1095
+ "paragraph",
1096
+ "start",
1097
+ "end",
1098
+ "expected_old_text",
1099
+ "structure_fingerprint_sha256",
1100
+ "part",
1101
+ "bold",
1102
+ "italic",
1103
+ "underline",
1104
+ "strike",
1105
+ "color",
1106
+ "font_size",
1107
+ "vertical_alignment",
1108
+ "style",
1109
+ "font_face",
1110
+ "font_face_east_asia",
1111
+ "highlight",
1112
+ "small_caps",
1113
+ "all_caps",
1114
+ "hidden",
1115
+ "ruby",
1116
+ "numeral_spacing",
1117
+ "legacy_animation",
1118
+ "emphasis_mark",
1119
+ "break_type",
1120
+ "break_clear",
1121
+ }
1122
+ unknown_keys = set(value) - allowed_keys
1123
+ if unknown_keys:
1124
+ raise ValueError(f"format_run_edit_unknown_keys: {sorted(unknown_keys)}")
1125
+
1126
+ required_keys = {
1127
+ "paragraph",
1128
+ "start",
1129
+ "end",
1130
+ "expected_old_text",
1131
+ "structure_fingerprint_sha256",
1132
+ }
1133
+ missing = required_keys - set(value)
1134
+ if missing:
1135
+ raise ValueError(f"format_run_edit_missing_keys: {sorted(missing)}")
1136
+
1137
+ paragraph = value["paragraph"]
1138
+ if isinstance(paragraph, bool) or not isinstance(paragraph, int) or paragraph < 1:
1139
+ raise ValueError("format_paragraph_invalid")
1140
+
1141
+ start = value["start"]
1142
+ end = value["end"]
1143
+ if isinstance(start, bool) or not isinstance(start, int) or start < 0:
1144
+ raise ValueError("format_range_invalid")
1145
+ if isinstance(end, bool) or not isinstance(end, int) or end < 0 or end <= start:
1146
+ raise ValueError("format_range_invalid")
1147
+
1148
+ expected_old_text = value["expected_old_text"]
1149
+ if not isinstance(expected_old_text, str) or len(expected_old_text) > _MAX_TEXT_CHARACTERS:
1150
+ raise ValueError("format_expected_old_text_invalid")
1151
+
1152
+ structure_fingerprint = _sha(
1153
+ value["structure_fingerprint_sha256"], "format_structure_fingerprint_sha256"
1154
+ )
1155
+
1156
+ part = value.get("part", _DOCUMENT)
1157
+ if not isinstance(part, str) or not part or not part.endswith(".xml"):
1158
+ raise ValueError("format_part_invalid")
1159
+
1160
+ # Format fields
1161
+ bold = value.get("bold")
1162
+ if bold is not None and not isinstance(bold, bool):
1163
+ raise ValueError("format_bold_invalid")
1164
+
1165
+ italic = value.get("italic")
1166
+ if italic is not None and not isinstance(italic, bool):
1167
+ raise ValueError("format_italic_invalid")
1168
+
1169
+ underline = value.get("underline")
1170
+ if underline is not None and not (
1171
+ isinstance(underline, bool)
1172
+ or (isinstance(underline, str) and underline in _VALID_UNDERLINE_STYLES)
1173
+ ):
1174
+ raise ValueError("format_underline_invalid")
1175
+
1176
+ strike = value.get("strike")
1177
+ if strike is not None and not isinstance(strike, bool):
1178
+ raise ValueError("format_strike_invalid")
1179
+
1180
+ color = value.get("color")
1181
+ if color is not None and (
1182
+ not isinstance(color, str)
1183
+ or (color.lower() != "auto" and not _HEX_COLOR_PATTERN.match(color))
1184
+ ):
1185
+ raise ValueError("format_color_invalid")
1186
+
1187
+ font_size = value.get("font_size")
1188
+ if font_size is not None and (
1189
+ isinstance(font_size, bool) or not isinstance(font_size, int) or font_size <= 0
1190
+ ):
1191
+ raise ValueError("format_font_size_invalid")
1192
+
1193
+ vertical_alignment = value.get("vertical_alignment")
1194
+ if vertical_alignment is not None and (
1195
+ not isinstance(vertical_alignment, str)
1196
+ or vertical_alignment not in _VALID_VERTICAL_ALIGNMENTS
1197
+ ):
1198
+ raise ValueError("format_vertical_alignment_invalid")
1199
+ style = value.get("style")
1200
+ if style is not None and (not isinstance(style, str) or not style or len(style) > 256):
1201
+ raise ValueError("format_style_invalid")
1202
+
1203
+ font_face = value.get("font_face")
1204
+ if font_face is not None and (
1205
+ not isinstance(font_face, str) or not font_face or len(font_face) > 256
1206
+ ):
1207
+ raise ValueError("format_font_face_invalid")
1208
+ font_face_east_asia = value.get("font_face_east_asia")
1209
+ if font_face_east_asia is not None:
1210
+ _validate_font_face_east_asia(font_face_east_asia)
1211
+ highlight = value.get("highlight")
1212
+ if highlight is not None:
1213
+ if isinstance(highlight, bool) or not isinstance(highlight, str):
1214
+ raise ValueError("format_highlight_invalid")
1215
+ stripped = highlight.strip()
1216
+ if stripped.lower() not in _HIGHLIGHT_CANONICAL_MAP:
1217
+ raise ValueError("format_highlight_invalid")
1218
+ highlight = _HIGHLIGHT_CANONICAL_MAP[stripped.lower()]
1219
+
1220
+ small_caps = value.get("small_caps")
1221
+ if small_caps is not None and not isinstance(small_caps, bool):
1222
+ raise ValueError("format_small_caps_invalid")
1223
+
1224
+ all_caps = value.get("all_caps")
1225
+ if all_caps is not None and not isinstance(all_caps, bool):
1226
+ raise ValueError("format_all_caps_invalid")
1227
+
1228
+ hidden = value.get("hidden")
1229
+ if hidden is not None and not isinstance(hidden, bool):
1230
+ raise ValueError("format_hidden_invalid")
1231
+
1232
+ # Verify at least one format property is specified
1233
+ format_props = (
1234
+ bold,
1235
+ italic,
1236
+ underline,
1237
+ strike,
1238
+ color,
1239
+ font_size,
1240
+ vertical_alignment,
1241
+ style,
1242
+ font_face,
1243
+ font_face_east_asia,
1244
+ highlight,
1245
+ small_caps,
1246
+ all_caps,
1247
+ hidden,
1248
+ value.get("ruby"),
1249
+ value.get("numeral_spacing"),
1250
+ value.get("legacy_animation"),
1251
+ value.get("emphasis_mark"),
1252
+ value.get("break_type"),
1253
+ value.get("break_clear"),
1254
+ )
1255
+ if all(p is None for p in format_props):
1256
+ raise ValueError("format_run_edit_noop_invalid")
1257
+
1258
+ return RunFormatEdit(
1259
+ paragraph=paragraph,
1260
+ start=start,
1261
+ end=end,
1262
+ expected_old_text=expected_old_text,
1263
+ structure_fingerprint_sha256=structure_fingerprint,
1264
+ part=part,
1265
+ bold=bold,
1266
+ italic=italic,
1267
+ underline=underline,
1268
+ strike=strike,
1269
+ color=color,
1270
+ font_size=font_size,
1271
+ vertical_alignment=vertical_alignment,
1272
+ style=style,
1273
+ font_face=font_face,
1274
+ font_face_east_asia=font_face_east_asia,
1275
+ highlight=highlight,
1276
+ small_caps=small_caps,
1277
+ all_caps=all_caps,
1278
+ hidden=hidden,
1279
+ ruby=_ruby_spec(value["ruby"]) if value.get("ruby") is not None else None,
1280
+ numeral_spacing=value.get("numeral_spacing"),
1281
+ legacy_animation=value.get("legacy_animation"),
1282
+ emphasis_mark=value.get("emphasis_mark"),
1283
+ break_type=value.get("break_type"),
1284
+ break_clear=value.get("break_clear"),
1285
+ )
1286
+
1287
+
1288
+ def _validate_spacing_spec(value: Any) -> SpacingSpec:
1289
+ if isinstance(value, SpacingSpec):
1290
+ return value
1291
+ if not isinstance(value, Mapping):
1292
+ raise TypeError("format_spacing_invalid")
1293
+ allowed = {"before", "after", "line", "line_rule", *_SPACING_KEY_ALIASES}
1294
+ unknown = set(value) - allowed
1295
+ if unknown:
1296
+ raise ValueError(f"format_spacing_unknown_keys: {sorted(unknown)}")
1297
+ conflicts = _conflicting_alias_keys(value, _SPACING_KEY_ALIASES)
1298
+ if conflicts:
1299
+ raise ValueError(f"format_spacing_alias_conflict: {conflicts}")
1300
+ resolved = {_SPACING_KEY_ALIASES.get(key, key): item for key, item in value.items()}
1301
+ before = resolved.get("before")
1302
+ after = resolved.get("after")
1303
+ line = resolved.get("line")
1304
+ line_rule = resolved.get("line_rule")
1305
+
1306
+ for name, val in (("before", before), ("after", after), ("line", line)):
1307
+ if val is not None and (isinstance(val, bool) or not isinstance(val, int) or val < 0):
1308
+ raise ValueError(f"format_spacing_{name}_invalid")
1309
+
1310
+ if before is None and after is None and line is None and line_rule is None:
1311
+ raise ValueError("format_spacing_empty_invalid")
1312
+
1313
+ return SpacingSpec(before=before, after=after, line=line, line_rule=line_rule)
1314
+
1315
+
1316
+ def _validate_indent_spec(value: Any) -> IndentSpec:
1317
+ if isinstance(value, IndentSpec):
1318
+ return value
1319
+ if not isinstance(value, Mapping):
1320
+ raise TypeError("format_indent_invalid")
1321
+ allowed = {
1322
+ "left",
1323
+ "right",
1324
+ "first_line",
1325
+ "hanging",
1326
+ "start",
1327
+ "end",
1328
+ *_INDENT_KEY_ALIASES,
1329
+ }
1330
+ unknown = set(value) - allowed
1331
+ if unknown:
1332
+ raise ValueError(f"format_indent_unknown_keys: {sorted(unknown)}")
1333
+ conflicts = _conflicting_alias_keys(value, _INDENT_KEY_ALIASES)
1334
+ if conflicts:
1335
+ raise ValueError(f"format_indent_alias_conflict: {conflicts}")
1336
+ resolved = {_INDENT_KEY_ALIASES.get(key, key): item for key, item in value.items()}
1337
+
1338
+ left = resolved.get("left")
1339
+ right = resolved.get("right")
1340
+ first_line = resolved.get("first_line")
1341
+ hanging = resolved.get("hanging")
1342
+ start = resolved.get("start")
1343
+ end = resolved.get("end")
1344
+
1345
+ for name, val in (
1346
+ ("left", left),
1347
+ ("right", right),
1348
+ ("first_line", first_line),
1349
+ ("hanging", hanging),
1350
+ ("start", start),
1351
+ ("end", end),
1352
+ ):
1353
+ if val is None:
1354
+ continue
1355
+ # A negative first_line is a hanging indent; IndentSpec folds it into ``hanging``.
1356
+ if isinstance(val, bool) or not isinstance(val, int) or (val < 0 and name != "first_line"):
1357
+ raise ValueError(f"format_indent_{name}_invalid")
1358
+
1359
+ if all(v is None for v in (left, right, first_line, hanging, start, end)):
1360
+ raise ValueError("format_indent_empty_invalid")
1361
+
1362
+ return IndentSpec(
1363
+ left=left,
1364
+ right=right,
1365
+ first_line=first_line,
1366
+ hanging=hanging,
1367
+ start=start,
1368
+ end=end,
1369
+ )
1370
+
1371
+
1372
+ def _validate_border_side_value(val: Any) -> BorderSpec | Literal[False]:
1373
+ if val is False:
1374
+ return False
1375
+ if isinstance(val, BorderSpec):
1376
+ val_style = val.val
1377
+ if not isinstance(val_style, str) or val_style not in _VALID_BORDER_STYLES:
1378
+ raise ValueError("format_borders_invalid")
1379
+ if val.sz is not None and (
1380
+ isinstance(val.sz, bool) or not isinstance(val.sz, int) or val.sz < 0 or val.sz > 96
1381
+ ):
1382
+ raise ValueError("format_borders_invalid")
1383
+ if val.space is not None and (
1384
+ isinstance(val.space, bool)
1385
+ or not isinstance(val.space, int)
1386
+ or val.space < 0
1387
+ or val.space > 64
1388
+ ):
1389
+ raise ValueError("format_borders_invalid")
1390
+ if val.color is not None and (
1391
+ not isinstance(val.color, str)
1392
+ or (val.color != "auto" and not _HEX_COLOR_PATTERN.match(val.color))
1393
+ ):
1394
+ raise ValueError("format_borders_invalid")
1395
+ return val
1396
+ if isinstance(val, Mapping):
1397
+ allowed = {"val", "style", "sz", "size", "space", "color"}
1398
+ if set(val) - allowed:
1399
+ raise ValueError("format_borders_invalid")
1400
+ val_style = val.get("val", val.get("style", "single"))
1401
+ if not isinstance(val_style, str) or val_style not in _VALID_BORDER_STYLES:
1402
+ raise ValueError("format_borders_invalid")
1403
+ sz = val.get("sz", val.get("size", 4))
1404
+ if sz is not None and (
1405
+ isinstance(sz, bool) or not isinstance(sz, int) or sz < 0 or sz > 96
1406
+ ):
1407
+ raise ValueError("format_borders_invalid")
1408
+ space = val.get("space", 0)
1409
+ if space is not None and (
1410
+ isinstance(space, bool) or not isinstance(space, int) or space < 0 or space > 64
1411
+ ):
1412
+ raise ValueError("format_borders_invalid")
1413
+ color = val.get("color", "auto")
1414
+ if color is not None and (
1415
+ not isinstance(color, str) or (color != "auto" and not _HEX_COLOR_PATTERN.match(color))
1416
+ ):
1417
+ raise ValueError("format_borders_invalid")
1418
+ return BorderSpec(val=val_style, sz=sz, space=space, color=color)
1419
+ raise ValueError("format_borders_invalid")
1420
+
1421
+
1422
+ def _validate_borders_spec(value: Any) -> ParagraphBordersSpec | Literal[False]:
1423
+ if value is False:
1424
+ return False
1425
+ if value is True:
1426
+ raise ValueError("format_borders_invalid")
1427
+ if isinstance(value, ParagraphBordersSpec):
1428
+ sides: dict[str, BorderSpec | Literal[False] | None] = {}
1429
+ all_none = True
1430
+ for side in _PARAGRAPH_BORDER_SIDES:
1431
+ v = getattr(value, side)
1432
+ if v is not None:
1433
+ all_none = False
1434
+ sides[side] = _validate_border_side_value(v)
1435
+ else:
1436
+ sides[side] = None
1437
+ if all_none:
1438
+ raise ValueError("format_borders_invalid")
1439
+ return ParagraphBordersSpec(**sides)
1440
+ if isinstance(value, Mapping):
1441
+ if not value:
1442
+ raise ValueError("format_borders_invalid")
1443
+ unknown = set(value) - set(_PARAGRAPH_BORDER_SIDES)
1444
+ if unknown:
1445
+ raise ValueError("format_borders_invalid")
1446
+ sides = {}
1447
+ for side in _PARAGRAPH_BORDER_SIDES:
1448
+ if side in value:
1449
+ v = value[side]
1450
+ if v is None:
1451
+ sides[side] = False
1452
+ else:
1453
+ sides[side] = _validate_border_side_value(v)
1454
+ else:
1455
+ sides[side] = None
1456
+ return ParagraphBordersSpec(**sides)
1457
+ raise ValueError("format_borders_invalid")
1458
+
1459
+
1460
+ def _validate_tab_stop(value: Any) -> TabStopSpec:
1461
+ if isinstance(value, TabStopSpec):
1462
+ return value
1463
+ if not isinstance(value, Mapping):
1464
+ raise TypeError("format_tabs_invalid")
1465
+ if set(value) - {
1466
+ "val",
1467
+ "pos",
1468
+ "leader",
1469
+ *_TAB_KEY_ALIASES,
1470
+ } or _conflicting_alias_keys(value, _TAB_KEY_ALIASES):
1471
+ raise ValueError("format_tabs_invalid")
1472
+ resolved = {_TAB_KEY_ALIASES.get(key, key): item for key, item in value.items()}
1473
+ if "val" not in resolved or "pos" not in resolved:
1474
+ raise ValueError("format_tabs_invalid")
1475
+ return TabStopSpec(val=resolved["val"], pos=resolved["pos"], leader=resolved.get("leader"))
1476
+
1477
+
1478
+ def _validate_tabs(value: Any) -> tuple[TabStopSpec, ...]:
1479
+ """Normalize tab stops into ascending ``pos`` order; empty removes the paragraph's own tabs."""
1480
+ if not isinstance(value, Sequence) or isinstance(value, (str, bytes)):
1481
+ raise TypeError("format_tabs_invalid")
1482
+ stops = tuple(sorted((_validate_tab_stop(item) for item in value), key=lambda s: s.pos))
1483
+ if len({stop.pos for stop in stops}) != len(stops):
1484
+ raise ValueError("format_tabs_invalid")
1485
+ return stops
1486
+
1487
+
1488
+ def _validate_paragraph_edit_dict(value: Mapping[str, Any]) -> ParagraphFormatEdit:
1489
+ allowed_keys = {
1490
+ "paragraph",
1491
+ "structure_fingerprint_sha256",
1492
+ "part",
1493
+ "style",
1494
+ "alignment",
1495
+ "spacing",
1496
+ "indent",
1497
+ "keep_next",
1498
+ "keep_lines",
1499
+ "keep_with_next",
1500
+ "keep_together",
1501
+ "outline_level",
1502
+ "shading",
1503
+ "page_break_before",
1504
+ "borders",
1505
+ "widow_control",
1506
+ "tabs",
1507
+ "suppress_auto_hyphens",
1508
+ "suppress_line_numbers",
1509
+ "frame",
1510
+ }
1511
+ unknown_keys = set(value) - allowed_keys
1512
+ if unknown_keys:
1513
+ raise ValueError(f"format_paragraph_edit_unknown_keys: {sorted(unknown_keys)}")
1514
+
1515
+ required_keys = {"paragraph", "structure_fingerprint_sha256"}
1516
+ missing = required_keys - set(value)
1517
+ if missing:
1518
+ raise ValueError(f"format_paragraph_edit_missing_keys: {sorted(missing)}")
1519
+
1520
+ paragraph = value["paragraph"]
1521
+ if isinstance(paragraph, bool) or not isinstance(paragraph, int) or paragraph < 1:
1522
+ raise ValueError("format_paragraph_invalid")
1523
+
1524
+ structure_fingerprint = _sha(
1525
+ value["structure_fingerprint_sha256"], "format_structure_fingerprint_sha256"
1526
+ )
1527
+
1528
+ part = value.get("part", _DOCUMENT)
1529
+ if not isinstance(part, str) or not part or not part.endswith(".xml"):
1530
+ raise ValueError("format_part_invalid")
1531
+
1532
+ style = value.get("style")
1533
+ if style is not None and (not isinstance(style, str) or not style or len(style) > 256):
1534
+ raise ValueError("format_style_invalid")
1535
+
1536
+ alignment = value.get("alignment")
1537
+ if alignment is not None:
1538
+ alignment = _canonical_alignment(alignment, "format_alignment_invalid")
1539
+
1540
+ spacing = None
1541
+ if "spacing" in value and value["spacing"] is not None:
1542
+ spacing = _validate_spacing_spec(value["spacing"])
1543
+
1544
+ indent = None
1545
+ if "indent" in value and value["indent"] is not None:
1546
+ indent = _validate_indent_spec(value["indent"])
1547
+
1548
+ keep_next = _fold_flag_alias(
1549
+ value.get("keep_next"), value.get("keep_with_next"), "format_keep_next"
1550
+ )
1551
+ keep_lines = _fold_flag_alias(
1552
+ value.get("keep_lines"), value.get("keep_together"), "format_keep_lines"
1553
+ )
1554
+
1555
+ page_break_before = value.get("page_break_before")
1556
+ if page_break_before is not None and not isinstance(page_break_before, bool):
1557
+ raise ValueError("format_page_break_before_invalid")
1558
+
1559
+ outline_level = value.get("outline_level")
1560
+ if outline_level is not None and (
1561
+ isinstance(outline_level, bool)
1562
+ or not isinstance(outline_level, int)
1563
+ or not (0 <= outline_level <= 9)
1564
+ ):
1565
+ raise ValueError("format_outline_level_invalid")
1566
+
1567
+ shading = value.get("shading")
1568
+ if shading is not None:
1569
+ if isinstance(shading, bool):
1570
+ if shading is not False:
1571
+ raise ValueError("format_shading_invalid")
1572
+ elif isinstance(shading, str):
1573
+ if not _HEX_COLOR_PATTERN.match(shading):
1574
+ raise ValueError("format_shading_invalid")
1575
+ else:
1576
+ raise ValueError("format_shading_invalid")
1577
+
1578
+ borders = None
1579
+ if "borders" in value and value["borders"] is not None:
1580
+ borders = _validate_borders_spec(value["borders"])
1581
+
1582
+ widow_control = value.get("widow_control")
1583
+ if widow_control is not None and not isinstance(widow_control, bool):
1584
+ raise ValueError("format_widow_control_invalid")
1585
+
1586
+ tabs = None
1587
+ if "tabs" in value and value["tabs"] is not None:
1588
+ tabs = _validate_tabs(value["tabs"])
1589
+
1590
+ suppress_auto_hyphens = value.get("suppress_auto_hyphens")
1591
+ if suppress_auto_hyphens is not None and not isinstance(suppress_auto_hyphens, bool):
1592
+ raise ValueError("format_suppress_auto_hyphens_invalid")
1593
+
1594
+ suppress_line_numbers = value.get("suppress_line_numbers")
1595
+ if suppress_line_numbers is not None and not isinstance(suppress_line_numbers, bool):
1596
+ raise ValueError("format_suppress_line_numbers_invalid")
1597
+
1598
+ frame = None
1599
+ if "frame" in value and value["frame"] is not None:
1600
+ frame = _validate_frame_spec(value["frame"])
1601
+
1602
+ if all(
1603
+ p is None
1604
+ for p in (
1605
+ style,
1606
+ alignment,
1607
+ spacing,
1608
+ indent,
1609
+ keep_next,
1610
+ keep_lines,
1611
+ outline_level,
1612
+ shading,
1613
+ page_break_before,
1614
+ borders,
1615
+ widow_control,
1616
+ tabs,
1617
+ suppress_auto_hyphens,
1618
+ suppress_line_numbers,
1619
+ frame,
1620
+ )
1621
+ ):
1622
+ raise ValueError("format_paragraph_edit_noop_invalid")
1623
+
1624
+ return ParagraphFormatEdit(
1625
+ paragraph=paragraph,
1626
+ structure_fingerprint_sha256=structure_fingerprint,
1627
+ part=part,
1628
+ style=style,
1629
+ alignment=alignment,
1630
+ spacing=spacing,
1631
+ indent=indent,
1632
+ keep_next=keep_next,
1633
+ keep_lines=keep_lines,
1634
+ outline_level=outline_level,
1635
+ shading=shading,
1636
+ page_break_before=page_break_before,
1637
+ borders=borders,
1638
+ widow_control=widow_control,
1639
+ tabs=tabs,
1640
+ suppress_auto_hyphens=suppress_auto_hyphens,
1641
+ suppress_line_numbers=suppress_line_numbers,
1642
+ frame=frame,
1643
+ )
1644
+
1645
+
1646
+ def parse_format_request(value: Any) -> FormatRequest:
1647
+ """Parse the strict JSON request for atomic formatting authoring operations."""
1648
+ if not isinstance(value, Mapping):
1649
+ raise TypeError("format_request_invalid")
1650
+
1651
+ allowed_keys = {
1652
+ "source",
1653
+ "source_sha256",
1654
+ "destination",
1655
+ "run_edits",
1656
+ "paragraph_edits",
1657
+ }
1658
+ unknown = set(value) - allowed_keys
1659
+ if unknown:
1660
+ raise ValueError(f"format_request_unknown_keys: {sorted(unknown)}")
1661
+
1662
+ required = {"source", "source_sha256", "destination"}
1663
+ missing = required - set(value)
1664
+ if missing:
1665
+ raise ValueError(f"format_request_missing_keys: {sorted(missing)}")
1666
+
1667
+ source_raw = value["source"]
1668
+ dest_raw = value["destination"]
1669
+ if not isinstance(source_raw, str) or not source_raw:
1670
+ raise ValueError("format_source_path_invalid")
1671
+ if not isinstance(dest_raw, str) or not dest_raw:
1672
+ raise ValueError("format_destination_path_invalid")
1673
+
1674
+ source_sha256 = _sha(value["source_sha256"], "format_source_sha256")
1675
+
1676
+ raw_run_edits = value.get("run_edits", ())
1677
+ if raw_run_edits is None:
1678
+ raw_run_edits = ()
1679
+ if not isinstance(raw_run_edits, Sequence) or isinstance(raw_run_edits, (str, bytes)):
1680
+ raise TypeError("format_run_edits_invalid")
1681
+ run_edits = tuple(_validate_run_edit_dict(item) for item in raw_run_edits)
1682
+
1683
+ raw_para_edits = value.get("paragraph_edits", ())
1684
+ if raw_para_edits is None:
1685
+ raw_para_edits = ()
1686
+ if not isinstance(raw_para_edits, Sequence) or isinstance(raw_para_edits, (str, bytes)):
1687
+ raise TypeError("format_paragraph_edits_invalid")
1688
+ para_edits = tuple(_validate_paragraph_edit_dict(item) for item in raw_para_edits)
1689
+
1690
+ if not run_edits and not para_edits:
1691
+ raise ValueError("format_edits_missing")
1692
+
1693
+ return FormatRequest(
1694
+ source=Path(source_raw),
1695
+ source_sha256=source_sha256,
1696
+ destination=Path(dest_raw),
1697
+ run_edits=run_edits,
1698
+ paragraph_edits=para_edits,
1699
+ )
1700
+
1701
+
1702
+ def load_format_request(path: str | Path) -> FormatRequest:
1703
+ """Load a formatting authoring request from a UTF-8 JSON file."""
1704
+ with Path(path).open(encoding="utf-8") as stream:
1705
+ return parse_format_request(json.load(stream))
1706
+
1707
+
1708
+ def _detect_context_unsupported(paragraph: ET.Element) -> str | None:
1709
+ unsupported_revision = {
1710
+ "ins",
1711
+ "del",
1712
+ "moveFrom",
1713
+ "moveTo",
1714
+ "rPrChange",
1715
+ "pPrChange",
1716
+ "customXmlInsRangeStart",
1717
+ "customXmlInsRangeEnd",
1718
+ "customXmlDelRangeStart",
1719
+ "customXmlDelRangeEnd",
1720
+ "customXmlMoveFromRangeStart",
1721
+ "customXmlMoveFromRangeEnd",
1722
+ "customXmlMoveToRangeStart",
1723
+ "customXmlMoveToRangeEnd",
1724
+ }
1725
+ unsupported_comment = {
1726
+ "commentRangeStart",
1727
+ "commentRangeEnd",
1728
+ "commentReference",
1729
+ }
1730
+ unsupported_sdt = {
1731
+ "sdt",
1732
+ "sdtPr",
1733
+ "sdtContent",
1734
+ "sdtEndPr",
1735
+ }
1736
+ unsupported_other = {
1737
+ "customXml",
1738
+ "fldSimple",
1739
+ "fldChar",
1740
+ }
1741
+ for node in paragraph.iter():
1742
+ local = _local_name(node.tag)
1743
+ if local in unsupported_revision:
1744
+ return "format_revision_context_unsupported"
1745
+ if local in unsupported_comment:
1746
+ return "format_comment_context_unsupported"
1747
+ if local in unsupported_sdt:
1748
+ return "format_sdt_context_unsupported"
1749
+ if local in unsupported_other:
1750
+ return "format_context_unsupported"
1751
+ return None
1752
+
1753
+
1754
+ def _is_inside_sdt_or_unsupported(
1755
+ paragraph: ET.Element, parents: Mapping[int, ET.Element]
1756
+ ) -> str | None:
1757
+ current = parents.get(id(paragraph))
1758
+ while current is not None:
1759
+ local = _local_name(current.tag)
1760
+ if local in {"sdt", "sdtContent"}:
1761
+ return "format_sdt_context_unsupported"
1762
+ if local in {"ins", "del", "moveFrom", "moveTo"}:
1763
+ return "format_revision_context_unsupported"
1764
+ current = parents.get(id(current))
1765
+ return None
1766
+
1767
+
1768
+ def _catalog_package_styles(
1769
+ graph: PackageGraph, ns: str
1770
+ ) -> tuple[dict[str, str], dict[str, str], list[dict[str, Any]]]:
1771
+ """Map paragraph and character style references to the ``w:styleId`` they name.
1772
+
1773
+ A reference resolves by style ID first, so every existing ID keeps naming its own
1774
+ style, then by ``w:name``, then by python-docx UI name (``Heading 1`` for a style named
1775
+ ``heading 1``). Within one tier the first definition wins. Styles without a
1776
+ ``w:styleId`` cannot be referenced and are not mapped.
1777
+ """
1778
+ paragraph_styles: dict[str, str] = {}
1779
+ character_styles: dict[str, str] = {}
1780
+ catalog: list[dict[str, Any]] = []
1781
+
1782
+ if _STYLES not in graph.parts:
1783
+ return paragraph_styles, character_styles, catalog
1784
+
1785
+ try:
1786
+ styles_root = ET.fromstring(graph.read_part_bytes(_STYLES))
1787
+ except (ET.ParseError, PackageError):
1788
+ return paragraph_styles, character_styles, catalog
1789
+
1790
+ # (UI name, w:name, w:styleId) tiers, lowest precedence first.
1791
+ tiers: dict[str, tuple[dict[str, str], dict[str, str], dict[str, str]]] = {
1792
+ "paragraph": ({}, {}, {}),
1793
+ "character": ({}, {}, {}),
1794
+ }
1795
+ def word(local):
1796
+ return Q(ns, local)
1797
+ for style_elem in styles_root.findall(word("style")):
1798
+ stype = style_elem.get(word("type")) or "paragraph"
1799
+ sid = style_elem.get(word("styleId")) or style_elem.get("styleId")
1800
+ name_elem = style_elem.find(word("name"))
1801
+ sname = None
1802
+ if name_elem is not None:
1803
+ sname = name_elem.get(word("val")) or name_elem.get("val")
1804
+
1805
+ if not sid:
1806
+ continue
1807
+ catalog.append({"id": sid, "name": sname, "type": stype})
1808
+
1809
+ kinds = (stype,) if stype in tiers else tuple(tiers)
1810
+ for kind in kinds:
1811
+ by_ui_name, by_name, by_id = tiers[kind]
1812
+ by_id.setdefault(sid, sid)
1813
+ if sname:
1814
+ by_name.setdefault(sname, sid)
1815
+ ui_name = _STYLE_UI_NAMES.get(sname)
1816
+ if ui_name is not None:
1817
+ by_ui_name.setdefault(ui_name, sid)
1818
+
1819
+ for kind, resolved in (
1820
+ ("paragraph", paragraph_styles),
1821
+ ("character", character_styles),
1822
+ ):
1823
+ by_ui_name, by_name, by_id = tiers[kind]
1824
+ resolved.update(by_ui_name)
1825
+ resolved.update(by_name)
1826
+ resolved.update(by_id)
1827
+ return paragraph_styles, character_styles, catalog
1828
+
1829
+
1830
+ def _unrelated_parts_preserved(source: Path, staged: Path, changed_parts: frozenset[str]) -> bool:
1831
+ with zipfile.ZipFile(source) as src_zip, zipfile.ZipFile(staged) as dst_zip:
1832
+ src_names = set(src_zip.namelist())
1833
+ dst_names = set(dst_zip.namelist())
1834
+ if src_names != dst_names:
1835
+ return False
1836
+ for name in src_names:
1837
+ if name not in changed_parts and src_zip.read(name) != dst_zip.read(name):
1838
+ return False
1839
+ return True
1840
+
1841
+
1842
+ def _format_refusal(request: FormatRequest, code: str) -> FormatReport:
1843
+ return FormatReport(
1844
+ status=_REFUSED,
1845
+ code=code,
1846
+ source_sha256=request.source_sha256,
1847
+ destination_sha256=None,
1848
+ run_edits=[e.to_dict() for e in request.run_edits],
1849
+ paragraph_edits=[e.to_dict() for e in request.paragraph_edits],
1850
+ changed_targets=[e.to_dict() for e in request.run_edits]
1851
+ + [e.to_dict() for e in request.paragraph_edits],
1852
+ )
1853
+
1854
+
1855
+ def _ruby_spans(xml: bytes) -> list[tuple[int, int]]:
1856
+ """Locate namespace-qualified ruby byte spans without guessing lexical prefixes."""
1857
+ if b"ruby" not in xml:
1858
+ return []
1859
+ parser = expat.ParserCreate(namespace_separator="}")
1860
+ tags = {namespace + "}ruby" for namespace in SUPPORTED_WORD_NAMESPACES}
1861
+ starts: list[int] = []
1862
+ spans: list[tuple[int, int]] = []
1863
+
1864
+ def start(name: str, attributes: dict[str, str]) -> None:
1865
+ if name in tags:
1866
+ starts.append(parser.CurrentByteIndex)
1867
+
1868
+ def end(name: str) -> None:
1869
+ if name in tags:
1870
+ spans.append((starts.pop(), xml.index(b">", parser.CurrentByteIndex) + 1))
1871
+
1872
+ parser.StartElementHandler = start
1873
+ parser.EndElementHandler = end
1874
+ parser.Parse(xml, True)
1875
+ return sorted(spans)
1876
+
1877
+
1878
+ def _preserve_unchanged_ruby(source_xml: bytes, output_xml: bytes) -> bytes:
1879
+ """Retain the exact lexical bytes of semantically untouched phonetic guides.
1880
+
1881
+ QName-preserving serialization retains their inherited namespace bindings;
1882
+ Expat byte offsets additionally preserve Word's empty-tag spelling and attribute
1883
+ quoting within ruby. Changed or newly added guides use the normal serializer.
1884
+ """
1885
+ source_spans = _ruby_spans(source_xml)
1886
+ if not source_spans:
1887
+ return output_xml
1888
+ output_spans = _ruby_spans(output_xml)
1889
+ tags = {Q(namespace, "ruby") for namespace in SUPPORTED_WORD_NAMESPACES}
1890
+
1891
+ def keys(xml: bytes) -> list[bytes]:
1892
+ result = []
1893
+ for element in ET.fromstring(xml).iter():
1894
+ if element.tag in tags:
1895
+ element.tail = None
1896
+ result.append(ET.tostring(element, encoding="utf-8"))
1897
+ return result
1898
+
1899
+ originals: dict[bytes, list[bytes]] = {}
1900
+ for key, (start, end) in reversed(list(zip(keys(source_xml), source_spans, strict=True))):
1901
+ originals.setdefault(key, []).append(source_xml[start:end])
1902
+ pieces: list[bytes] = []
1903
+ offset = 0
1904
+ for key, (start, end) in zip(keys(output_xml), output_spans, strict=True):
1905
+ pieces.append(output_xml[offset:start])
1906
+ available = originals.get(key)
1907
+ pieces.append(available.pop() if available else output_xml[start:end])
1908
+ offset = end
1909
+ pieces.append(output_xml[offset:])
1910
+ return b"".join(pieces)
1911
+
1912
+
1913
+ def _format_paragraph_map(paragraph: ET.Element, namespace: str) -> _ParagraphMap:
1914
+ """Map ruby carriers by base text while retaining the original editable run."""
1915
+ proxies: dict[int, ET.Element] = {}
1916
+ shadow = ET.Element(paragraph.tag)
1917
+ for child in paragraph:
1918
+ ruby = child.find(Q(namespace, "ruby")) if child.tag == Q(namespace, "r") else None
1919
+ if (
1920
+ ruby is None
1921
+ and child.tag == Q(namespace, "r")
1922
+ and _is_break_run(child, namespace)
1923
+ and all(
1924
+ _local_name(node.tag) in {"rPr", "t", "br", "lastRenderedPageBreak"}
1925
+ for node in child
1926
+ )
1927
+ ):
1928
+ proxy = ET.Element(child.tag)
1929
+ ET.SubElement(proxy, Q(namespace, "t")).text = "".join(
1930
+ str(item) for kind, item in _break_children(child, namespace) if kind == "t"
1931
+ )
1932
+ shadow.append(proxy)
1933
+ proxies[id(proxy)] = child
1934
+ continue
1935
+ if ruby is None:
1936
+ shadow.append(child)
1937
+ continue
1938
+ if any(_local_name(node.tag) not in {"rPr", "ruby"} for node in child):
1939
+ raise _ReviewContextError("format_ruby_context_unsupported")
1940
+ base = ruby.find(Q(namespace, "rubyBase"))
1941
+ if base is None:
1942
+ raise _ReviewContextError("format_ruby_context_unsupported")
1943
+ proxy = ET.Element(child.tag)
1944
+ ET.SubElement(proxy, Q(namespace, "t")).text = "".join(
1945
+ node.text or "" for node in base.iter(Q(namespace, "t"))
1946
+ )
1947
+ shadow.append(proxy)
1948
+ proxies[id(proxy)] = child
1949
+ mapping = _paragraph_map(shadow, namespace)
1950
+ return replace(
1951
+ mapping,
1952
+ runs=tuple(
1953
+ _TextRun(proxies.get(id(run.element), run.element), run.text, run.start, run.end)
1954
+ for run in mapping.runs
1955
+ ),
1956
+ )
1957
+
1958
+
1959
+ def _read_ruby(run: ET.Element, namespace: str) -> dict[str, Any] | None:
1960
+ ruby = run.find(Q(namespace, "ruby"))
1961
+ if ruby is None:
1962
+ return None
1963
+ props = ruby.find(Q(namespace, "rubyPr"))
1964
+ result: dict[str, Any] = {}
1965
+ for key, local in (("base_text", "rubyBase"), ("guide_text", "rt")):
1966
+ container = ruby.find(Q(namespace, local))
1967
+ result[key] = (
1968
+ ""
1969
+ if container is None
1970
+ else "".join(node.text or "" for node in container.iter(Q(namespace, "t")))
1971
+ )
1972
+ for key, local in (
1973
+ ("alignment", "rubyAlign"),
1974
+ ("raise", "hpsRaise"),
1975
+ ("font_size", "hps"),
1976
+ ("base_font_size", "hpsBaseText"),
1977
+ ("language", "lid"),
1978
+ ):
1979
+ node = props.find(Q(namespace, local)) if props is not None else None
1980
+ value = node.get(Q(namespace, "val")) if node is not None else None
1981
+ result[key] = (
1982
+ int(value)
1983
+ if value is not None
1984
+ and key in {"raise", "font_size", "base_font_size"}
1985
+ and value.isdecimal()
1986
+ else value
1987
+ )
1988
+ return result
1989
+
1990
+
1991
+ def _apply_run_format(run: ET.Element, edit: RunFormatEdit, namespace: str) -> None:
1992
+ def word(local):
1993
+ return Q(namespace, local)
1994
+ rpr = run.find(word("rPr"))
1995
+ if rpr is None:
1996
+ rpr = ET.Element(word("rPr"))
1997
+ run.insert(0, rpr)
1998
+
1999
+ if edit.bold is not None:
2000
+ for existing in list(rpr.findall(word("b"))):
2001
+ rpr.remove(existing)
2002
+ if edit.bold:
2003
+ rpr.append(ET.Element(word("b")))
2004
+ else:
2005
+ rpr.append(ET.Element(word("b"), {word("val"): "0"}))
2006
+
2007
+ if edit.italic is not None:
2008
+ for existing in list(rpr.findall(word("i"))):
2009
+ rpr.remove(existing)
2010
+ if edit.italic:
2011
+ rpr.append(ET.Element(word("i")))
2012
+ else:
2013
+ rpr.append(ET.Element(word("i"), {word("val"): "0"}))
2014
+
2015
+ for flag, tag in ((edit.all_caps, "caps"), (edit.hidden, "vanish")):
2016
+ if flag is None:
2017
+ continue
2018
+ for existing in list(rpr.findall(word(tag))):
2019
+ rpr.remove(existing)
2020
+ rpr.append(ET.Element(word(tag)) if flag else ET.Element(word(tag), {word("val"): "0"}))
2021
+
2022
+ if edit.small_caps is not None:
2023
+ for existing in list(rpr.findall(word("smallCaps"))):
2024
+ rpr.remove(existing)
2025
+ if edit.small_caps:
2026
+ rpr.append(ET.Element(word("smallCaps")))
2027
+ else:
2028
+ rpr.append(ET.Element(word("smallCaps"), {word("val"): "0"}))
2029
+
2030
+ if edit.strike is not None:
2031
+ for existing in list(rpr.findall(word("strike"))):
2032
+ rpr.remove(existing)
2033
+ if edit.strike:
2034
+ rpr.append(ET.Element(word("strike")))
2035
+ else:
2036
+ rpr.append(ET.Element(word("strike"), {word("val"): "0"}))
2037
+
2038
+ if edit.underline is not None:
2039
+ for existing in list(rpr.findall(word("u"))):
2040
+ rpr.remove(existing)
2041
+ val = (
2042
+ "single"
2043
+ if edit.underline is True
2044
+ else ("none" if edit.underline is False else str(edit.underline))
2045
+ )
2046
+ rpr.append(ET.Element(word("u"), {word("val"): val}))
2047
+
2048
+ if edit.color is not None:
2049
+ for existing in list(rpr.findall(word("color"))):
2050
+ rpr.remove(existing)
2051
+ val = edit.color.strip()
2052
+ if val.lower() != "auto":
2053
+ val = val.upper()
2054
+ rpr.append(ET.Element(word("color"), {word("val"): val}))
2055
+
2056
+ if edit.font_size is not None:
2057
+ for existing in list(rpr.findall(word("sz"))):
2058
+ rpr.remove(existing)
2059
+ for existing in list(rpr.findall(word("szCs"))):
2060
+ rpr.remove(existing)
2061
+ val = str(edit.font_size)
2062
+ rpr.append(ET.Element(word("sz"), {word("val"): val}))
2063
+ rpr.append(ET.Element(word("szCs"), {word("val"): val}))
2064
+
2065
+ if edit.vertical_alignment is not None:
2066
+ for existing in list(rpr.findall(word("vertAlign"))):
2067
+ rpr.remove(existing)
2068
+ rpr.append(ET.Element(word("vertAlign"), {word("val"): edit.vertical_alignment}))
2069
+
2070
+ if edit.style is not None:
2071
+ for existing in list(rpr.findall(word("rStyle"))):
2072
+ rpr.remove(existing)
2073
+ rpr.append(ET.Element(word("rStyle"), {word("val"): edit.style}))
2074
+
2075
+ if edit.font_face is not None:
2076
+ for existing in list(rpr.findall(word("rFonts"))):
2077
+ rpr.remove(existing)
2078
+ rpr.append(
2079
+ ET.Element(
2080
+ word("rFonts"),
2081
+ {
2082
+ word("ascii"): edit.font_face,
2083
+ word("hAnsi"): edit.font_face,
2084
+ word("cs"): edit.font_face,
2085
+ },
2086
+ )
2087
+ )
2088
+ if edit.font_face_east_asia is not None:
2089
+ fonts = rpr.find(word("rFonts"))
2090
+ if fonts is None:
2091
+ fonts = ET.SubElement(rpr, word("rFonts"))
2092
+ # ECMA-376 17.3.2.26: w:eastAsiaTheme supersedes w:eastAsia, so drop it
2093
+ # to make the explicit face effective; every other attribute is kept.
2094
+ fonts.attrib.pop(word("eastAsiaTheme"), None)
2095
+ fonts.set(word("eastAsia"), edit.font_face_east_asia)
2096
+ ordered = {
2097
+ word(name): fonts.attrib[word(name)]
2098
+ for name in _RFONTS_ATTRIBUTE_ORDER
2099
+ if word(name) in fonts.attrib
2100
+ }
2101
+ ordered.update(fonts.attrib)
2102
+ fonts.attrib.clear()
2103
+ fonts.attrib.update(ordered)
2104
+ if edit.highlight is not None:
2105
+ for existing in list(rpr.findall(word("highlight"))):
2106
+ rpr.remove(existing)
2107
+ val = _HIGHLIGHT_CANONICAL_MAP.get(
2108
+ edit.highlight.strip().lower() if isinstance(edit.highlight, str) else "",
2109
+ edit.highlight,
2110
+ )
2111
+ rpr.append(ET.Element(word("highlight"), {word("val"): val}))
2112
+ for value, tag in ((edit.legacy_animation, "effect"), (edit.emphasis_mark, "em")):
2113
+ if value is not None:
2114
+ for existing in list(rpr.findall(word(tag))):
2115
+ rpr.remove(existing)
2116
+ ET.SubElement(rpr, word(tag), {word("val"): value})
2117
+ if edit.numeral_spacing is not None:
2118
+ for existing in list(rpr.findall(Q(_W14, "numSpacing"))):
2119
+ rpr.remove(existing)
2120
+ if edit.numeral_spacing is not False:
2121
+ ET.SubElement(rpr, Q(_W14, "numSpacing"), {Q(_W14, "val"): edit.numeral_spacing})
2122
+ if edit.ruby is not None:
2123
+ rpr[:] = sorted(rpr, key=lambda child: _RPR_RANK.get(_local_name(child.tag), 999))
2124
+ spec = edit.ruby
2125
+ for child in list(run):
2126
+ if child.tag != word("rPr"):
2127
+ run.remove(child)
2128
+ ruby = ET.SubElement(run, word("ruby"))
2129
+ props = ET.SubElement(ruby, word("rubyPr"))
2130
+ for local, value in (
2131
+ ("rubyAlign", spec.alignment),
2132
+ ("hps", spec.font_size),
2133
+ ("hpsRaise", spec.raise_),
2134
+ ("hpsBaseText", spec.base_font_size),
2135
+ ("lid", spec.language),
2136
+ ):
2137
+ ET.SubElement(props, word(local), {word("val"): str(value)})
2138
+ for local, text in (("rt", spec.guide_text), ("rubyBase", spec.base_text)):
2139
+ carrier = ET.SubElement(ET.SubElement(ruby, word(local)), word("r"))
2140
+ if local == "rubyBase":
2141
+ carrier.append(copy.deepcopy(rpr))
2142
+ else:
2143
+ guide_props = ET.SubElement(carrier, word("rPr"))
2144
+ ET.SubElement(guide_props, word("sz"), {word("val"): str(spec.font_size)})
2145
+ ET.SubElement(
2146
+ carrier,
2147
+ word("t"),
2148
+ {"{http://www.w3.org/XML/1998/namespace}space": "preserve"},
2149
+ ).text = text
2150
+
2151
+ # Sort rPr children by canonical CT_RPr schema rank
2152
+ rpr[:] = sorted(rpr, key=lambda c: _RPR_RANK.get(_local_name(c.tag), 999))
2153
+
2154
+
2155
+ def _apply_paragraph_format(
2156
+ paragraph: ET.Element, edit: ParagraphFormatEdit, namespace: str
2157
+ ) -> None:
2158
+ def word(local):
2159
+ return Q(namespace, local)
2160
+ ppr = paragraph.find(word("pPr"))
2161
+ if ppr is None:
2162
+ ppr = ET.Element(word("pPr"))
2163
+ paragraph.insert(0, ppr)
2164
+
2165
+ if edit.style is not None:
2166
+ for existing in list(ppr.findall(word("pStyle"))):
2167
+ ppr.remove(existing)
2168
+ ppr.append(ET.Element(word("pStyle"), {word("val"): edit.style}))
2169
+
2170
+ if edit.alignment is not None:
2171
+ for existing in list(ppr.findall(word("jc"))):
2172
+ ppr.remove(existing)
2173
+ ppr.append(ET.Element(word("jc"), {word("val"): edit.alignment}))
2174
+
2175
+ if edit.spacing is not None:
2176
+ for existing in list(ppr.findall(word("spacing"))):
2177
+ ppr.remove(existing)
2178
+ attrib: dict[str, str] = {}
2179
+ if edit.spacing.before is not None:
2180
+ attrib[word("before")] = str(edit.spacing.before)
2181
+ if edit.spacing.after is not None:
2182
+ attrib[word("after")] = str(edit.spacing.after)
2183
+ if edit.spacing.line is not None:
2184
+ attrib[word("line")] = str(edit.spacing.line)
2185
+ if edit.spacing.line_rule is not None:
2186
+ rule_map = {"auto": "auto", "exact": "exact", "at_least": "atLeast"}
2187
+ attrib[word("lineRule")] = rule_map.get(edit.spacing.line_rule, edit.spacing.line_rule)
2188
+ ppr.append(ET.Element(word("spacing"), attrib))
2189
+
2190
+ if edit.indent is not None:
2191
+ for existing in list(ppr.findall(word("ind"))):
2192
+ ppr.remove(existing)
2193
+ attrib = {}
2194
+ if edit.indent.left is not None:
2195
+ attrib[word("left")] = str(edit.indent.left)
2196
+ if edit.indent.right is not None:
2197
+ attrib[word("right")] = str(edit.indent.right)
2198
+ if edit.indent.first_line is not None:
2199
+ attrib[word("firstLine")] = str(edit.indent.first_line)
2200
+ if edit.indent.hanging is not None:
2201
+ attrib[word("hanging")] = str(edit.indent.hanging)
2202
+ if edit.indent.start is not None:
2203
+ attrib[word("start")] = str(edit.indent.start)
2204
+ if edit.indent.end is not None:
2205
+ attrib[word("end")] = str(edit.indent.end)
2206
+ ppr.append(ET.Element(word("ind"), attrib))
2207
+
2208
+ if edit.keep_next is not None:
2209
+ for existing in list(ppr.findall(word("keepNext"))):
2210
+ ppr.remove(existing)
2211
+ if edit.keep_next:
2212
+ ppr.append(ET.Element(word("keepNext")))
2213
+ else:
2214
+ ppr.append(ET.Element(word("keepNext"), {word("val"): "0"}))
2215
+
2216
+ if edit.keep_lines is not None:
2217
+ for existing in list(ppr.findall(word("keepLines"))):
2218
+ ppr.remove(existing)
2219
+ if edit.keep_lines:
2220
+ ppr.append(ET.Element(word("keepLines")))
2221
+ else:
2222
+ ppr.append(ET.Element(word("keepLines"), {word("val"): "0"}))
2223
+
2224
+ if edit.page_break_before is not None:
2225
+ for existing in list(ppr.findall(word("pageBreakBefore"))):
2226
+ ppr.remove(existing)
2227
+ if edit.page_break_before:
2228
+ ppr.append(ET.Element(word("pageBreakBefore")))
2229
+ else:
2230
+ ppr.append(ET.Element(word("pageBreakBefore"), {word("val"): "0"}))
2231
+
2232
+ if edit.widow_control is not None:
2233
+ for existing in list(ppr.findall(word("widowControl"))):
2234
+ ppr.remove(existing)
2235
+ if edit.widow_control:
2236
+ ppr.append(ET.Element(word("widowControl")))
2237
+ else:
2238
+ ppr.append(ET.Element(word("widowControl"), {word("val"): "0"}))
2239
+
2240
+ for flag, tag in (
2241
+ (edit.suppress_auto_hyphens, "suppressAutoHyphens"),
2242
+ (edit.suppress_line_numbers, "suppressLineNumbers"),
2243
+ ):
2244
+ if flag is None:
2245
+ continue
2246
+ for existing in list(ppr.findall(word(tag))):
2247
+ ppr.remove(existing)
2248
+ ppr.append(ET.Element(word(tag)) if flag else ET.Element(word(tag), {word("val"): "0"}))
2249
+
2250
+ if edit.frame is not None:
2251
+ frames = ppr.findall(word("framePr"))
2252
+ if edit.frame is False:
2253
+ for existing in frames:
2254
+ ppr.remove(existing)
2255
+ else:
2256
+ frame = frames[0] if frames else ET.SubElement(ppr, word("framePr"))
2257
+ for field, value in edit.frame.to_dict().items():
2258
+ frame.set(word(_FRAME_ATTRIBUTES[field]), _frame_value(value))
2259
+
2260
+ if edit.tabs is not None:
2261
+ for existing in list(ppr.findall(word("tabs"))):
2262
+ ppr.remove(existing)
2263
+ # CT_Tabs requires at least one w:tab, so an empty sequence leaves no w:tabs element.
2264
+ stops = _validate_tabs(edit.tabs)
2265
+ if stops:
2266
+ tabs_elem = ET.SubElement(ppr, word("tabs"))
2267
+ for stop in stops:
2268
+ tab_attrib = {word("val"): stop.val}
2269
+ if stop.leader is not None:
2270
+ tab_attrib[word("leader")] = stop.leader
2271
+ tab_attrib[word("pos")] = str(stop.pos)
2272
+ ET.SubElement(tabs_elem, word("tab"), tab_attrib)
2273
+
2274
+ if edit.outline_level is not None:
2275
+ for existing in list(ppr.findall(word("outlineLvl"))):
2276
+ ppr.remove(existing)
2277
+ ppr.append(ET.Element(word("outlineLvl"), {word("val"): str(edit.outline_level)}))
2278
+
2279
+ if edit.shading is not None:
2280
+ for existing in list(ppr.findall(word("shd"))):
2281
+ ppr.remove(existing)
2282
+ if edit.shading is not False:
2283
+ ppr.append(
2284
+ ET.Element(
2285
+ word("shd"),
2286
+ {
2287
+ word("val"): "clear",
2288
+ word("color"): "auto",
2289
+ word("fill"): edit.shading,
2290
+ },
2291
+ )
2292
+ )
2293
+
2294
+ if edit.borders is not None:
2295
+ existing_p_bdr = ppr.find(word("pBdr"))
2296
+ existing_sides: dict[str, ET.Element] = {}
2297
+ if existing_p_bdr is not None:
2298
+ for c in existing_p_bdr:
2299
+ existing_sides[_local_name(c.tag)] = c
2300
+ for existing in list(ppr.findall(word("pBdr"))):
2301
+ ppr.remove(existing)
2302
+
2303
+ if edit.borders is not False:
2304
+ borders_dict: dict[str, Any] = (
2305
+ edit.borders.to_dict()
2306
+ if isinstance(edit.borders, ParagraphBordersSpec)
2307
+ else dict(edit.borders)
2308
+ )
2309
+ new_p_bdr = ET.Element(word("pBdr"))
2310
+ for side in _PARAGRAPH_BORDER_SIDES:
2311
+ if side in borders_dict:
2312
+ spec = borders_dict[side]
2313
+ if spec is not False and spec is not None:
2314
+ b_elem = ET.Element(word(side))
2315
+ val = (
2316
+ spec.val if isinstance(spec, BorderSpec) else spec.get("val", "single")
2317
+ )
2318
+ b_elem.set(word("val"), str(val))
2319
+ sz = spec.sz if isinstance(spec, BorderSpec) else spec.get("sz")
2320
+ if sz is not None:
2321
+ b_elem.set(word("sz"), str(sz))
2322
+ space = spec.space if isinstance(spec, BorderSpec) else spec.get("space")
2323
+ if space is not None:
2324
+ b_elem.set(word("space"), str(space))
2325
+ color = spec.color if isinstance(spec, BorderSpec) else spec.get("color")
2326
+ if color is not None:
2327
+ b_elem.set(word("color"), str(color))
2328
+ new_p_bdr.append(b_elem)
2329
+ elif side in existing_sides:
2330
+ new_p_bdr.append(copy.deepcopy(existing_sides[side]))
2331
+ for side, elem in existing_sides.items():
2332
+ if side not in _PARAGRAPH_BORDER_SIDES:
2333
+ new_p_bdr.append(copy.deepcopy(elem))
2334
+ if len(new_p_bdr) > 0:
2335
+ ppr.append(new_p_bdr)
2336
+ # Sort pPr children by canonical CT_PPr schema rank
2337
+ ppr[:] = sorted(ppr, key=lambda c: _PPR_RANK.get(_local_name(c.tag), 999))
2338
+
2339
+ # Enforce pPr is the very first child of w:p
2340
+ if paragraph[0] is not ppr:
2341
+ paragraph.remove(ppr)
2342
+ paragraph.insert(0, ppr)
2343
+
2344
+
2345
+ def _compatibility_mode(parts: Mapping[str, bytes]) -> int | None:
2346
+ data = parts.get("word/settings.xml")
2347
+ if data is None:
2348
+ return None
2349
+ try:
2350
+ root = ET.fromstring(data)
2351
+ ns = _word_namespace(root)
2352
+ if ns is None:
2353
+ raise ValueError("format_compatibilityMode_invalid")
2354
+ settings = [
2355
+ elem
2356
+ for elem in root.findall(f"{Q(ns, 'compat')}/{Q(ns, 'compatSetting')}")
2357
+ if elem.get(Q(ns, "name")) == "compatibilityMode"
2358
+ and elem.get(Q(ns, "uri")) == "http://schemas.microsoft.com/office/word"
2359
+ ]
2360
+ if not settings:
2361
+ return None
2362
+ if len(settings) != 1:
2363
+ raise ValueError("format_compatibilityMode_invalid")
2364
+ value = settings[0].get(Q(ns, "val"), "")
2365
+ if not value.isdecimal():
2366
+ raise ValueError("format_compatibilityMode_invalid")
2367
+ return int(value)
2368
+ except ET.ParseError as error:
2369
+ raise ValueError("format_compatibilityMode_invalid") from error
2370
+
2371
+
2372
+ def _effect_xml(element: ET.Element) -> dict[str, Any]:
2373
+ return {
2374
+ "tag": element.tag,
2375
+ "attributes": dict(element.attrib),
2376
+ "text": element.text,
2377
+ "children": [_effect_xml(child) for child in element],
2378
+ }
2379
+
2380
+
2381
+ def _read_w14_properties(rpr: ET.Element) -> dict[str, Any]:
2382
+ # text_effects imports formatting helpers, so defer this import until discovery.
2383
+ from .text_effects import read_effect
2384
+
2385
+ properties: dict[str, Any] = {}
2386
+ for child in rpr:
2387
+ if not child.tag.startswith(f"{{{_W14}}}"):
2388
+ continue
2389
+ local = _local_name(child.tag)
2390
+ if local in {"glow", "shadow", "reflection", "textOutline", "textFill"}:
2391
+ parsed = read_effect(child)
2392
+ key = {"textOutline": "outline", "textFill": "fill"}.get(local, local)
2393
+ properties[key] = parsed[1].to_dict() if parsed is not None else _effect_xml(child)
2394
+ elif local in {"scene3d", "props3d"}:
2395
+ key = "scene_3d" if local == "scene3d" else "props_3d"
2396
+ properties[key] = _effect_xml(child)
2397
+ elif local in {"ligatures", "numForm", "numSpacing"}:
2398
+ key = {
2399
+ "ligatures": "ligatures",
2400
+ "numForm": "number_form",
2401
+ "numSpacing": "numeral_spacing",
2402
+ }[local]
2403
+ properties[key] = child.get(Q(_W14, "val"))
2404
+ elif local == "cntxtAlts":
2405
+ properties["contextual_alternates"] = child.get(Q(_W14, "val"), "1") not in {
2406
+ "0",
2407
+ "false",
2408
+ "off",
2409
+ }
2410
+ elif local == "stylisticSets":
2411
+ properties["stylistic_sets"] = [
2412
+ int(style.get(Q(_W14, "id")))
2413
+ for style in child.findall(Q(_W14, "styleSet"))
2414
+ if style.get(Q(_W14, "id"), "").isdecimal()
2415
+ and style.get(Q(_W14, "val"), "1") not in {"0", "false", "off"}
2416
+ ]
2417
+ return properties
2418
+
2419
+
2420
+ def _is_break_run(run: ET.Element, namespace: str) -> bool:
2421
+ """A run carrying w:br or w:lastRenderedPageBreak, which it edits only as a whole."""
2422
+ return any(
2423
+ child.tag in {Q(namespace, "br"), Q(namespace, "lastRenderedPageBreak")} for child in run
2424
+ )
2425
+
2426
+
2427
+ def _break_element(edit: RunFormatEdit, namespace: str) -> ET.Element:
2428
+ attributes = {Q(namespace, "type"): str(edit.break_type)}
2429
+ if edit.break_clear is not None:
2430
+ attributes[Q(namespace, "clear")] = edit.break_clear
2431
+ return ET.Element(Q(namespace, "br"), attributes)
2432
+
2433
+
2434
+ def _read_frame(frame: ET.Element, namespace: str) -> dict[str, Any]:
2435
+ """Report the attributes of one w:framePr under their snake_case request names."""
2436
+ result: dict[str, Any] = {}
2437
+ for field, attribute in _FRAME_ATTRIBUTES.items():
2438
+ raw = frame.get(Q(namespace, attribute)) or frame.get(attribute)
2439
+ if raw is None:
2440
+ continue
2441
+ if field == "anchor_lock":
2442
+ result[field] = raw.strip().lower() not in {"0", "false", "off"}
2443
+ elif field in _FRAME_INTEGER_FIELDS:
2444
+ result[field] = int(raw) if re.fullmatch(r"-?\d+", raw) else raw
2445
+ else:
2446
+ result[field] = raw
2447
+ return result
2448
+
2449
+
2450
+ def _break_children(run: ET.Element, namespace: str) -> list[tuple[str, ET.Element | str]]:
2451
+ """Text and break content of a run in document order (text as plain strings)."""
2452
+ content: list[tuple[str, ET.Element | str]] = []
2453
+ for child in run:
2454
+ local = _local_name(child.tag)
2455
+ if child.tag == Q(namespace, "t"):
2456
+ content.append(("t", child.text or ""))
2457
+ elif local in {"br", "lastRenderedPageBreak"}:
2458
+ content.append((local, child))
2459
+ return content
2460
+
2461
+
2462
+ def _read_breaks(mapping: _ParagraphMap, namespace: str) -> tuple[list[dict[str, Any]], list[int]]:
2463
+ """w:br and w:lastRenderedPageBreak inventory with the paragraph text offset of each."""
2464
+ breaks: list[dict[str, Any]] = []
2465
+ rendered: list[int] = []
2466
+ for run in mapping.runs:
2467
+ offset = run.start
2468
+ for kind, item in _break_children(run.element, namespace):
2469
+ if isinstance(item, str):
2470
+ offset += len(item)
2471
+ elif kind == "br":
2472
+ breaks.append(
2473
+ {
2474
+ "offset": offset,
2475
+ "type": item.get(Q(namespace, "type")) or "textWrapping",
2476
+ "clear": item.get(Q(namespace, "clear")) or "none",
2477
+ }
2478
+ )
2479
+ else:
2480
+ rendered.append(offset)
2481
+ return breaks, rendered
2482
+
2483
+
2484
+ def discover_format_targets(source: str | Path, *, part: str = _DOCUMENT) -> dict[str, Any]:
2485
+ """List source-bound paragraph targets and available styles without writing."""
2486
+ path = Path(source)
2487
+ if not path.is_file():
2488
+ return {
2489
+ "passed": False,
2490
+ "code": "format_source_package_invalid",
2491
+ "targets": [],
2492
+ "styles": [],
2493
+ }
2494
+
2495
+ try:
2496
+ graph = PackageGraph.from_file(path)
2497
+ parts = {name: graph.read_part_bytes(name) for name in graph.parts}
2498
+ except (OSError, PackageError, zipfile.BadZipFile):
2499
+ return {
2500
+ "passed": False,
2501
+ "code": "format_source_package_invalid",
2502
+ "targets": [],
2503
+ "styles": [],
2504
+ }
2505
+
2506
+ if _DOCUMENT not in parts:
2507
+ return {
2508
+ "passed": False,
2509
+ "code": "format_source_package_invalid",
2510
+ "targets": [],
2511
+ "styles": [],
2512
+ }
2513
+
2514
+ try:
2515
+ document_root = ET.fromstring(parts[_DOCUMENT])
2516
+ except ET.ParseError:
2517
+ return {
2518
+ "passed": False,
2519
+ "code": "format_source_package_invalid",
2520
+ "targets": [],
2521
+ "styles": [],
2522
+ }
2523
+
2524
+ ns = _word_namespace(document_root)
2525
+ if ns is None:
2526
+ return {
2527
+ "passed": False,
2528
+ "code": "format_namespace_unsupported",
2529
+ "targets": [],
2530
+ "styles": [],
2531
+ }
2532
+
2533
+ allowed = _review_parts(graph, document_root, ns)
2534
+ if part not in allowed:
2535
+ return {
2536
+ "passed": False,
2537
+ "code": "format_part_unsupported",
2538
+ "source_sha256": graph.file_sha256,
2539
+ "part": part,
2540
+ "targets": [],
2541
+ "styles": [],
2542
+ }
2543
+
2544
+ try:
2545
+ root = ET.fromstring(parts[part])
2546
+ except ET.ParseError:
2547
+ return {
2548
+ "passed": False,
2549
+ "code": "format_source_package_invalid",
2550
+ "targets": [],
2551
+ "styles": [],
2552
+ }
2553
+
2554
+ part_ns = _word_namespace(root)
2555
+ if part_ns is None:
2556
+ return {
2557
+ "passed": False,
2558
+ "code": "format_namespace_unsupported",
2559
+ "targets": [],
2560
+ "styles": [],
2561
+ }
2562
+
2563
+ parents = {id(child): parent for parent in root.iter() for child in parent}
2564
+ def word(local):
2565
+ return Q(part_ns, local)
2566
+
2567
+ _, _, styles_catalog = _catalog_package_styles(graph, part_ns)
2568
+ try:
2569
+ compatibility_mode = _compatibility_mode(parts)
2570
+ except ValueError as error:
2571
+ return {
2572
+ "passed": False,
2573
+ "code": str(error),
2574
+ "targets": [],
2575
+ "styles": styles_catalog,
2576
+ }
2577
+
2578
+ # styles_authoring imports this module, so defer the shared script-property reader.
2579
+ from .styles_authoring import _read_script_properties
2580
+
2581
+ targets: list[dict[str, Any]] = []
2582
+ for p_idx, paragraph in enumerate(root.iter(word("p")), start=1):
2583
+ fingerprint = _mask_text(paragraph, part_ns)
2584
+ context_code = _detect_context_unsupported(paragraph) or _is_inside_sdt_or_unsupported(
2585
+ paragraph, parents
2586
+ )
2587
+
2588
+ # Inspect paragraph properties
2589
+ ppr = paragraph.find(word("pPr"))
2590
+ p_style = None
2591
+ p_align = None
2592
+ p_keep_next = False
2593
+ p_keep_lines = False
2594
+ p_page_break_before = False
2595
+ # Omitted w:widowControl reports the Word default (on); style inheritance is not resolved.
2596
+ p_widow_control = True
2597
+ p_tabs: list[dict[str, Any]] | None = None
2598
+ p_outline_lvl = None
2599
+ p_spacing = None
2600
+ p_indent = None
2601
+ p_shading = None
2602
+ p_suppress_auto_hyphens = False
2603
+ p_suppress_line_numbers = False
2604
+ p_frame: dict[str, Any] | None = None
2605
+ p_script: dict[str, Any] = {}
2606
+
2607
+ if ppr is not None:
2608
+ style_elem = ppr.find(word("pStyle"))
2609
+ if style_elem is not None:
2610
+ p_style = style_elem.get(word("val")) or style_elem.get("val")
2611
+
2612
+ jc_elem = ppr.find(word("jc"))
2613
+ if jc_elem is not None:
2614
+ p_align = jc_elem.get(word("val")) or jc_elem.get("val")
2615
+
2616
+ kn_elem = ppr.find(word("keepNext"))
2617
+ if kn_elem is not None:
2618
+ p_keep_next = _flag(kn_elem) is not False
2619
+
2620
+ kl_elem = ppr.find(word("keepLines"))
2621
+ if kl_elem is not None:
2622
+ p_keep_lines = _flag(kl_elem) is not False
2623
+
2624
+ pbb_elem = ppr.find(word("pageBreakBefore"))
2625
+ if pbb_elem is not None:
2626
+ p_page_break_before = _flag(pbb_elem) is not False
2627
+
2628
+ wc_elem = ppr.find(word("widowControl"))
2629
+ if wc_elem is not None:
2630
+ p_widow_control = _flag(wc_elem) is not False
2631
+
2632
+ sah_elem = ppr.find(word("suppressAutoHyphens"))
2633
+ if sah_elem is not None:
2634
+ p_suppress_auto_hyphens = _flag(sah_elem) is not False
2635
+
2636
+ sln_elem = ppr.find(word("suppressLineNumbers"))
2637
+ if sln_elem is not None:
2638
+ p_suppress_line_numbers = _flag(sln_elem) is not False
2639
+
2640
+ frame_elem = ppr.find(word("framePr"))
2641
+ if frame_elem is not None:
2642
+ p_frame = _read_frame(frame_elem, part_ns)
2643
+
2644
+ p_script = _read_script_properties(ppr, part_ns, paragraph=True)
2645
+
2646
+ tabs_elem = ppr.find(word("tabs"))
2647
+ if tabs_elem is not None:
2648
+ p_tabs = []
2649
+ for tab_elem in tabs_elem.findall(word("tab")):
2650
+ pos_raw = tab_elem.get(word("pos")) or tab_elem.get("pos")
2651
+ try:
2652
+ pos_val: int | str | None = int(pos_raw) if pos_raw is not None else None
2653
+ except ValueError:
2654
+ pos_val = pos_raw
2655
+ tab_info: dict[str, Any] = {
2656
+ "val": tab_elem.get(word("val")) or tab_elem.get("val"),
2657
+ "pos": pos_val,
2658
+ }
2659
+ leader = tab_elem.get(word("leader")) or tab_elem.get("leader")
2660
+ if leader is not None:
2661
+ tab_info["leader"] = leader
2662
+ p_tabs.append(tab_info)
2663
+
2664
+ shd_elem = ppr.find(word("shd"))
2665
+ if shd_elem is not None:
2666
+ fill_val = shd_elem.get(word("fill")) or shd_elem.get("fill")
2667
+ if fill_val and fill_val.lower() != "auto":
2668
+ p_shading = fill_val
2669
+
2670
+ ol_elem = ppr.find(word("outlineLvl"))
2671
+ ol_val = (
2672
+ (ol_elem.get(word("val")) or ol_elem.get("val")) if ol_elem is not None else None
2673
+ )
2674
+ if ol_val is not None and ol_val.isdigit():
2675
+ p_outline_lvl = int(ol_val)
2676
+
2677
+ sp_elem = ppr.find(word("spacing"))
2678
+ if sp_elem is not None:
2679
+ p_spacing = {}
2680
+ for attr_key in ("before", "after", "line", "lineRule"):
2681
+ val = sp_elem.get(word(attr_key)) or sp_elem.get(attr_key)
2682
+ if val is not None:
2683
+ snake = "line_rule" if attr_key == "lineRule" else attr_key
2684
+ # Twips measures are reported as integers so a discovered spacing
2685
+ # can be passed back unchanged as a request's ``spacing``.
2686
+ p_spacing[snake] = int(val) if val.isdecimal() else val
2687
+
2688
+ ind_elem = ppr.find(word("ind"))
2689
+ if ind_elem is not None:
2690
+ p_indent = {}
2691
+ for attr_key in (
2692
+ "left",
2693
+ "right",
2694
+ "firstLine",
2695
+ "hanging",
2696
+ "start",
2697
+ "end",
2698
+ ):
2699
+ val = ind_elem.get(word(attr_key)) or ind_elem.get(attr_key)
2700
+ if val is not None:
2701
+ snake = "first_line" if attr_key == "firstLine" else attr_key
2702
+ p_indent[snake] = val
2703
+
2704
+ pbdr_elem = ppr.find(word("pBdr"))
2705
+ p_borders = None
2706
+ if pbdr_elem is not None:
2707
+ b_dict: dict[str, Any] = {}
2708
+ for side in _PARAGRAPH_BORDER_SIDES:
2709
+ side_elem = pbdr_elem.find(word(side))
2710
+ if side_elem is not None:
2711
+ val = side_elem.get(word("val")) or side_elem.get("val") or "single"
2712
+ sz_val = side_elem.get(word("sz")) or side_elem.get("sz")
2713
+ sp_val = side_elem.get(word("space")) or side_elem.get("space")
2714
+ col_val = side_elem.get(word("color")) or side_elem.get("color") or "auto"
2715
+ b_dict[side] = {
2716
+ "val": val,
2717
+ "sz": int(sz_val) if sz_val and sz_val.isdigit() else 4,
2718
+ "space": int(sp_val) if sp_val and sp_val.isdigit() else 0,
2719
+ "color": col_val,
2720
+ }
2721
+ if b_dict:
2722
+ p_borders = b_dict
2723
+ else:
2724
+ p_borders = None
2725
+ runs_info: list[dict[str, Any]] = []
2726
+ editable_ranges: list[list[int]] = []
2727
+ p_text = ""
2728
+ p_breaks: list[dict[str, Any]] = []
2729
+ p_last_rendered: list[int] = []
2730
+
2731
+ if context_code is None:
2732
+ try:
2733
+ mapping = _format_paragraph_map(paragraph, part_ns)
2734
+ p_text = mapping.text
2735
+ editable_ranges = [[start, end] for start, end in mapping.editable_ranges]
2736
+ p_breaks, p_last_rendered = _read_breaks(mapping, part_ns)
2737
+ for r in mapping.runs:
2738
+ r_elem = r.element
2739
+ rpr = r_elem.find(word("rPr"))
2740
+ sc_elem = rpr.find(word("smallCaps")) if rpr is not None else None
2741
+ run_data: dict[str, Any] = {
2742
+ "start": r.start,
2743
+ "end": r.end,
2744
+ "text": r.text,
2745
+ "small_caps": _flag(sc_elem) is True,
2746
+ }
2747
+ ruby_data = _read_ruby(r_elem, part_ns)
2748
+ if ruby_data is not None:
2749
+ run_data["ruby"] = ruby_data
2750
+ if rpr is not None:
2751
+ w14_properties = _read_w14_properties(rpr)
2752
+ run_data.update(w14_properties)
2753
+ if w14_properties:
2754
+ run_data["w14_effects_active"] = (
2755
+ compatibility_mode is None or compatibility_mode >= 14
2756
+ )
2757
+ b_elem = rpr.find(word("b"))
2758
+ if b_elem is not None:
2759
+ run_data["bold"] = _flag(b_elem) is not False
2760
+ i_elem = rpr.find(word("i"))
2761
+ if i_elem is not None:
2762
+ run_data["italic"] = _flag(i_elem) is not False
2763
+ u_elem = rpr.find(word("u"))
2764
+ if u_elem is not None:
2765
+ run_data["underline"] = (
2766
+ u_elem.get(word("val")) or u_elem.get("val") or "single"
2767
+ )
2768
+ s_elem = rpr.find(word("strike"))
2769
+ if s_elem is not None:
2770
+ run_data["strike"] = _flag(s_elem) is not False
2771
+ c_elem = rpr.find(word("color"))
2772
+ if c_elem is not None:
2773
+ run_data["color"] = c_elem.get(word("val")) or c_elem.get("val")
2774
+ sz_elem = rpr.find(word("sz"))
2775
+ sz_val = (
2776
+ (sz_elem.get(word("val")) or sz_elem.get("val"))
2777
+ if sz_elem is not None
2778
+ else None
2779
+ )
2780
+ if sz_val and sz_val.isdigit():
2781
+ run_data["font_size"] = int(sz_val)
2782
+ va_elem = rpr.find(word("vertAlign"))
2783
+ if va_elem is not None:
2784
+ run_data["vertical_alignment"] = va_elem.get(
2785
+ word("val")
2786
+ ) or va_elem.get("val")
2787
+ st_elem = rpr.find(word("rStyle"))
2788
+ if st_elem is not None:
2789
+ run_data["style"] = st_elem.get(word("val")) or st_elem.get("val")
2790
+ rf_elem = rpr.find(word("rFonts"))
2791
+ if rf_elem is not None:
2792
+ run_data["font_face"] = (
2793
+ rf_elem.get(word("ascii"))
2794
+ or rf_elem.get(word("hAnsi"))
2795
+ or rf_elem.get("ascii")
2796
+ or rf_elem.get("hAnsi")
2797
+ )
2798
+ east_asia = rf_elem.get(word("eastAsia")) or rf_elem.get("eastAsia")
2799
+ if east_asia is not None:
2800
+ run_data["font_face_east_asia"] = east_asia
2801
+ hl_elem = rpr.find(word("highlight"))
2802
+ if hl_elem is not None:
2803
+ run_data["highlight"] = hl_elem.get(word("val")) or hl_elem.get("val")
2804
+ for tag, key in (("effect", "legacy_animation"), ("em", "emphasis_mark")):
2805
+ prop = rpr.find(word(tag))
2806
+ if prop is not None:
2807
+ run_data[key] = prop.get(word("val")) or prop.get("val")
2808
+ run_data.update(_read_script_properties(rpr, part_ns, paragraph=False))
2809
+ runs_info.append(run_data)
2810
+ except _ReviewContextError as err:
2811
+ context_code = err.code or "format_context_unsupported"
2812
+ p_text = "".join(t.text or "" for t in paragraph.iter(word("t")))
2813
+ editable_ranges = []
2814
+ else:
2815
+ p_text = "".join(t.text or "" for t in paragraph.iter(word("t")))
2816
+ editable_ranges = []
2817
+
2818
+ targets.append(
2819
+ {
2820
+ "part": part,
2821
+ "paragraph": p_idx,
2822
+ "structure_fingerprint_sha256": fingerprint,
2823
+ "text": p_text,
2824
+ "style": p_style,
2825
+ "alignment": p_align,
2826
+ "keep_next": p_keep_next,
2827
+ "keep_lines": p_keep_lines,
2828
+ "page_break_before": p_page_break_before,
2829
+ "widow_control": p_widow_control,
2830
+ "tabs": p_tabs,
2831
+ "outline_level": p_outline_lvl,
2832
+ "spacing": p_spacing,
2833
+ "indent": p_indent,
2834
+ "shading": p_shading,
2835
+ "borders": p_borders,
2836
+ "suppress_auto_hyphens": p_suppress_auto_hyphens,
2837
+ "suppress_line_numbers": p_suppress_line_numbers,
2838
+ "frame": p_frame,
2839
+ **p_script,
2840
+ "breaks": p_breaks,
2841
+ "last_rendered_page_breaks": p_last_rendered,
2842
+ "runs": runs_info,
2843
+ "editable_ranges": editable_ranges,
2844
+ "context_code": context_code,
2845
+ }
2846
+ )
2847
+
2848
+ return {
2849
+ "passed": True,
2850
+ "code": None,
2851
+ "source_sha256": graph.file_sha256,
2852
+ "part": part,
2853
+ "targets": targets,
2854
+ "styles": styles_catalog,
2855
+ "compatibility_mode": compatibility_mode,
2856
+ }
2857
+
2858
+
2859
+ def author_format(request: FormatRequest) -> FormatReport:
2860
+ """Execute source-bound run and paragraph formatting changes atomically."""
2861
+ source = request.source
2862
+ destination = request.destination
2863
+
2864
+ if not source.is_file():
2865
+ return _format_refusal(request, "format_source_not_found")
2866
+
2867
+ if _sha256(source) != request.source_sha256:
2868
+ return _format_refusal(request, "format_source_sha256_mismatch")
2869
+
2870
+ if destination.exists() or destination.is_symlink():
2871
+ return _format_refusal(request, "format_destination_invalid")
2872
+
2873
+ try:
2874
+ graph = PackageGraph.from_file(source)
2875
+ parts_bytes = {name: graph.read_part_bytes(name) for name in graph.parts}
2876
+ except (OSError, PackageError, zipfile.BadZipFile):
2877
+ return _format_refusal(request, "format_package_invalid")
2878
+
2879
+ if _DOCUMENT not in parts_bytes:
2880
+ return _format_refusal(request, "format_package_invalid")
2881
+
2882
+ try:
2883
+ doc_root = ET.fromstring(parts_bytes[_DOCUMENT])
2884
+ except ET.ParseError:
2885
+ return _format_refusal(request, "format_package_invalid")
2886
+
2887
+ main_ns = _word_namespace(doc_root)
2888
+ if main_ns is None or main_ns not in SUPPORTED_WORD_NAMESPACES:
2889
+ return _format_refusal(request, "format_namespace_unsupported")
2890
+
2891
+ allowed_parts = _review_parts(graph, doc_root, main_ns)
2892
+
2893
+ # Style catalog validation
2894
+ para_styles, char_styles, _ = _catalog_package_styles(graph, main_ns)
2895
+
2896
+ for r_edit in request.run_edits:
2897
+ if r_edit.color is not None and (
2898
+ not isinstance(r_edit.color, str)
2899
+ or (r_edit.color.lower() != "auto" and not _HEX_COLOR_PATTERN.match(r_edit.color))
2900
+ ):
2901
+ return _format_refusal(request, "format_color_invalid")
2902
+ if r_edit.highlight is not None and (
2903
+ isinstance(r_edit.highlight, bool)
2904
+ or not isinstance(r_edit.highlight, str)
2905
+ or r_edit.highlight.strip().lower() not in _HIGHLIGHT_CANONICAL_MAP
2906
+ ):
2907
+ return _format_refusal(request, "format_highlight_invalid")
2908
+
2909
+ # Style references resolve to the w:styleId written into w:rStyle/w:pStyle.
2910
+ run_edits: list[RunFormatEdit] = []
2911
+ for r_edit in request.run_edits:
2912
+ if r_edit.style is not None:
2913
+ if _STYLES not in graph.parts or r_edit.style not in char_styles:
2914
+ return _format_refusal(request, "format_style_missing")
2915
+ r_edit = replace(r_edit, style=char_styles[r_edit.style])
2916
+ run_edits.append(r_edit)
2917
+
2918
+ paragraph_edits: list[ParagraphFormatEdit] = []
2919
+ for p_edit in request.paragraph_edits:
2920
+ if p_edit.style is not None:
2921
+ if _STYLES not in graph.parts or p_edit.style not in para_styles:
2922
+ return _format_refusal(request, "format_style_missing")
2923
+ p_edit = replace(p_edit, style=para_styles[p_edit.style])
2924
+ paragraph_edits.append(p_edit)
2925
+
2926
+ # Group edits by part and paragraph
2927
+ run_edits_by_part_p: dict[tuple[str, int], list[RunFormatEdit]] = {}
2928
+ for r_edit in run_edits:
2929
+ if r_edit.part not in allowed_parts:
2930
+ return _format_refusal(request, "format_part_unsupported")
2931
+ run_edits_by_part_p.setdefault((r_edit.part, r_edit.paragraph), []).append(r_edit)
2932
+
2933
+ para_edits_by_part_p: dict[tuple[str, int], ParagraphFormatEdit] = {}
2934
+ for p_edit in paragraph_edits:
2935
+ if p_edit.part not in allowed_parts:
2936
+ return _format_refusal(request, "format_part_unsupported")
2937
+ key = (p_edit.part, p_edit.paragraph)
2938
+ if key in para_edits_by_part_p:
2939
+ return _format_refusal(request, "format_duplicate_paragraph_edit")
2940
+ para_edits_by_part_p[key] = p_edit
2941
+
2942
+ # Check for overlapping run edits within the same paragraph
2943
+ for key, p_run_edits in run_edits_by_part_p.items():
2944
+ sorted_edits = sorted(p_run_edits, key=lambda e: (e.start, e.end))
2945
+ for e1, e2 in itertools.pairwise(sorted_edits):
2946
+ if e1.end > e2.start:
2947
+ return _format_refusal(request, "format_edits_overlap")
2948
+
2949
+ # Load and parse roots for all touched parts
2950
+ touched_part_names = {part for part, _ in run_edits_by_part_p} | {
2951
+ part for part, _ in para_edits_by_part_p
2952
+ }
2953
+ part_roots: dict[str, ET.Element] = {}
2954
+ part_namespaces: dict[str, str] = {}
2955
+ part_parents: dict[str, dict[int, ET.Element]] = {}
2956
+
2957
+ for part_name in touched_part_names:
2958
+ try:
2959
+ root = parse_xml_with_preserved_qnames(parts_bytes[part_name])
2960
+ except ET.ParseError:
2961
+ return _format_refusal(request, "format_package_invalid")
2962
+ ns = _word_namespace(root)
2963
+ if ns is None:
2964
+ return _format_refusal(request, "format_namespace_unsupported")
2965
+ part_roots[part_name] = root
2966
+ part_namespaces[part_name] = ns
2967
+ part_parents[part_name] = {id(child): parent for parent in root.iter() for child in parent}
2968
+
2969
+ # Pre-validation of all edits against source document structure
2970
+ for (part_name, p_idx), p_run_edits in run_edits_by_part_p.items():
2971
+ root = part_roots[part_name]
2972
+ ns = part_namespaces[part_name]
2973
+ parents = part_parents[part_name]
2974
+ paragraphs = list(root.iter(Q(ns, "p")))
2975
+ if p_idx < 1 or p_idx > len(paragraphs):
2976
+ return _format_refusal(request, "format_paragraph_missing")
2977
+
2978
+ paragraph = paragraphs[p_idx - 1]
2979
+ fp = _mask_text(paragraph, ns)
2980
+
2981
+ for edit in p_run_edits:
2982
+ if fp != edit.structure_fingerprint_sha256:
2983
+ return _format_refusal(request, "format_structure_fingerprint_mismatch")
2984
+
2985
+ context_unsupported = _detect_context_unsupported(
2986
+ paragraph
2987
+ ) or _is_inside_sdt_or_unsupported(paragraph, parents)
2988
+ if context_unsupported:
2989
+ return _format_refusal(request, context_unsupported)
2990
+
2991
+ try:
2992
+ mapping = _format_paragraph_map(paragraph, ns)
2993
+ except _ReviewContextError:
2994
+ return _format_refusal(request, "format_context_unsupported")
2995
+
2996
+ p_text = mapping.text
2997
+ for edit in p_run_edits:
2998
+ if edit.start < 0 or edit.end > len(p_text) or edit.end <= edit.start:
2999
+ return _format_refusal(request, "format_range_invalid")
3000
+ if p_text[edit.start : edit.end] != edit.expected_old_text:
3001
+ return _format_refusal(request, "format_expected_text_mismatch")
3002
+ if edit.ruby is not None and edit.ruby.base_text != edit.expected_old_text:
3003
+ return _format_refusal(request, "format_ruby_base_text_mismatch")
3004
+ intersected = [
3005
+ run for run in mapping.runs if run.start < edit.end and run.end > edit.start
3006
+ ]
3007
+ if edit.ruby is not None and len(intersected) != 1:
3008
+ return _format_refusal(request, "format_ruby_multiple_runs_unsupported")
3009
+ for run in intersected:
3010
+ if run.element.find(Q(ns, "ruby")) is not None and (
3011
+ edit.start > run.start or edit.end < run.end
3012
+ ):
3013
+ return _format_refusal(request, "format_ruby_partial_range_unsupported")
3014
+ for run in intersected:
3015
+ if edit.break_type is not None and run.element.find(Q(ns, "ruby")) is not None:
3016
+ return _format_refusal(request, "format_break_ruby_unsupported")
3017
+ if not _is_break_run(run.element, ns):
3018
+ continue
3019
+ if edit.ruby is not None:
3020
+ return _format_refusal(request, "format_break_ruby_unsupported")
3021
+ if edit.start > run.start or edit.end < run.end:
3022
+ return _format_refusal(request, "format_break_partial_range_unsupported")
3023
+
3024
+ for (part_name, p_idx), p_edit in para_edits_by_part_p.items():
3025
+ root = part_roots[part_name]
3026
+ ns = part_namespaces[part_name]
3027
+ parents = part_parents[part_name]
3028
+ paragraphs = list(root.iter(Q(ns, "p")))
3029
+ if p_idx < 1 or p_idx > len(paragraphs):
3030
+ return _format_refusal(request, "format_paragraph_missing")
3031
+
3032
+ paragraph = paragraphs[p_idx - 1]
3033
+ fp = _mask_text(paragraph, ns)
3034
+ if fp != p_edit.structure_fingerprint_sha256:
3035
+ return _format_refusal(request, "format_structure_fingerprint_mismatch")
3036
+
3037
+ context_unsupported = _detect_context_unsupported(
3038
+ paragraph
3039
+ ) or _is_inside_sdt_or_unsupported(paragraph, parents)
3040
+ if context_unsupported:
3041
+ return _format_refusal(request, context_unsupported)
3042
+
3043
+ if any(edit.numeral_spacing is not None for edit in run_edits):
3044
+ try:
3045
+ compatibility_mode = _compatibility_mode(parts_bytes)
3046
+ except ValueError as error:
3047
+ return _format_refusal(request, str(error))
3048
+ if (
3049
+ compatibility_mode is not None
3050
+ and compatibility_mode < 14
3051
+ and any(isinstance(edit.numeral_spacing, str) for edit in run_edits)
3052
+ ):
3053
+ return _format_refusal(request, "format_w14_suppressed_by_compatibilityMode")
3054
+
3055
+ # Perform mutations
3056
+ # 1. Apply paragraph format edits
3057
+ for (part_name, p_idx), p_edit in para_edits_by_part_p.items():
3058
+ root = part_roots[part_name]
3059
+ ns = part_namespaces[part_name]
3060
+ paragraphs = list(root.iter(Q(ns, "p")))
3061
+ paragraph = paragraphs[p_idx - 1]
3062
+ _apply_paragraph_format(paragraph, p_edit, ns)
3063
+
3064
+ # 2. Apply run format edits
3065
+ for (part_name, p_idx), p_run_edits in run_edits_by_part_p.items():
3066
+ root = part_roots[part_name]
3067
+ ns = part_namespaces[part_name]
3068
+ paragraphs = list(root.iter(Q(ns, "p")))
3069
+ paragraph = paragraphs[p_idx - 1]
3070
+
3071
+ mapping = _format_paragraph_map(paragraph, ns)
3072
+ runs_by_id = {id(r.element): r for r in mapping.runs}
3073
+ boundaries = sorted({e.start for e in p_run_edits} | {e.end for e in p_run_edits})
3074
+
3075
+ child_list = list(paragraph)
3076
+ for child in child_list:
3077
+ run_data = runs_by_id.get(id(child))
3078
+ if run_data is None or not run_data.text:
3079
+ continue
3080
+
3081
+ cuts = [
3082
+ run_data.start,
3083
+ *(b for b in boundaries if run_data.start < b < run_data.end),
3084
+ run_data.end,
3085
+ ]
3086
+ new_runs: list[ET.Element] = []
3087
+ for lower, upper in itertools.pairwise(cuts):
3088
+ sub_text = run_data.text[lower - run_data.start : upper - run_data.start]
3089
+ cloned = (
3090
+ copy.deepcopy(child)
3091
+ if child.find(Q(ns, "ruby")) is not None or _is_break_run(child, ns)
3092
+ else _clone_run(child, ns, sub_text)
3093
+ )
3094
+
3095
+ # Check if this slice is within any edit
3096
+ matched_edit = next(
3097
+ (e for e in p_run_edits if e.start <= lower and upper <= e.end),
3098
+ None,
3099
+ )
3100
+ if matched_edit is not None:
3101
+ _apply_run_format(cloned, matched_edit, ns)
3102
+ if matched_edit.break_type is not None and upper == matched_edit.end:
3103
+ cloned.append(_break_element(matched_edit, ns))
3104
+
3105
+ new_runs.append(cloned)
3106
+
3107
+ # Replace child in paragraph with new_runs
3108
+ idx = list(paragraph).index(child)
3109
+ paragraph.remove(child)
3110
+ for offset, new_r in enumerate(new_runs):
3111
+ paragraph.insert(idx + offset, new_r)
3112
+
3113
+ # Serialize modified parts
3114
+ replacements: dict[str, bytes] = {}
3115
+ for part_name, root in part_roots.items():
3116
+ if any(
3117
+ edit.part == part_name and isinstance(edit.numeral_spacing, str) for edit in run_edits
3118
+ ):
3119
+ scope = dict(getattr(root, "_namespace_scope", ()))
3120
+ prefix = "wdx14"
3121
+ while prefix in scope and scope[prefix] != _W14:
3122
+ prefix += "x"
3123
+ root.set("xmlns:" + prefix, _W14)
3124
+ ignorable = root.get(Q(_MC, "Ignorable"), "").split()
3125
+ if prefix not in ignorable:
3126
+ ignorable.append(prefix)
3127
+ root.set(Q(_MC, "Ignorable"), " ".join(ignorable))
3128
+ replacements[part_name] = _preserve_unchanged_ruby(
3129
+ parts_bytes[part_name], serialize_xml_with_preserved_qnames(root)
3130
+ )
3131
+
3132
+ changed_targets = [e.to_dict() for e in run_edits] + [e.to_dict() for e in paragraph_edits]
3133
+
3134
+ def verifier(staged: Path) -> str | None:
3135
+ if not _unrelated_parts_preserved(source, staged, frozenset(replacements)):
3136
+ return "format_staged_verification_failed"
3137
+ return None
3138
+
3139
+ published: ReviewReport = _publish(
3140
+ source=source,
3141
+ output=destination,
3142
+ source_sha256=request.source_sha256,
3143
+ replacements=replacements,
3144
+ revisions=[],
3145
+ targets=changed_targets,
3146
+ verify=verifier,
3147
+ failure_code="format_staged_verification_failed",
3148
+ exists_code="format_destination_invalid",
3149
+ unavailable_code="format_publication_unavailable",
3150
+ )
3151
+
3152
+ return FormatReport(
3153
+ status=published.status,
3154
+ code=published.code,
3155
+ source_sha256=published.source_sha256,
3156
+ destination_sha256=published.output_sha256,
3157
+ run_edits=[e.to_dict() for e in run_edits],
3158
+ paragraph_edits=[e.to_dict() for e in paragraph_edits],
3159
+ changed_targets=changed_targets,
3160
+ )