ps-python-docx 1.3.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 (126) hide show
  1. docx/__init__.py +68 -0
  2. docx/api.py +37 -0
  3. docx/blkcntnr.py +101 -0
  4. docx/comments.py +163 -0
  5. docx/dml/__init__.py +0 -0
  6. docx/dml/color.py +112 -0
  7. docx/document.py +275 -0
  8. docx/drawing/__init__.py +59 -0
  9. docx/enum/__init__.py +0 -0
  10. docx/enum/base.py +150 -0
  11. docx/enum/dml.py +103 -0
  12. docx/enum/section.py +86 -0
  13. docx/enum/shape.py +19 -0
  14. docx/enum/style.py +452 -0
  15. docx/enum/table.py +136 -0
  16. docx/enum/text.py +367 -0
  17. docx/exceptions.py +18 -0
  18. docx/image/__init__.py +23 -0
  19. docx/image/bmp.py +43 -0
  20. docx/image/constants.py +172 -0
  21. docx/image/exceptions.py +13 -0
  22. docx/image/gif.py +38 -0
  23. docx/image/helpers.py +86 -0
  24. docx/image/image.py +234 -0
  25. docx/image/jpeg.py +425 -0
  26. docx/image/png.py +253 -0
  27. docx/image/tiff.py +289 -0
  28. docx/opc/__init__.py +0 -0
  29. docx/opc/constants.py +306 -0
  30. docx/opc/coreprops.py +142 -0
  31. docx/opc/exceptions.py +12 -0
  32. docx/opc/oxml.py +247 -0
  33. docx/opc/package.py +219 -0
  34. docx/opc/packuri.py +109 -0
  35. docx/opc/part.py +247 -0
  36. docx/opc/parts/__init__.py +0 -0
  37. docx/opc/parts/coreprops.py +48 -0
  38. docx/opc/phys_pkg.py +119 -0
  39. docx/opc/pkgreader.py +254 -0
  40. docx/opc/pkgwriter.py +115 -0
  41. docx/opc/rel.py +153 -0
  42. docx/opc/shared.py +31 -0
  43. docx/opc/spec.py +24 -0
  44. docx/oxml/__init__.py +261 -0
  45. docx/oxml/comments.py +124 -0
  46. docx/oxml/coreprops.py +298 -0
  47. docx/oxml/document.py +88 -0
  48. docx/oxml/drawing.py +11 -0
  49. docx/oxml/exceptions.py +10 -0
  50. docx/oxml/ns.py +109 -0
  51. docx/oxml/numbering.py +109 -0
  52. docx/oxml/parser.py +62 -0
  53. docx/oxml/section.py +537 -0
  54. docx/oxml/settings.py +138 -0
  55. docx/oxml/shape.py +299 -0
  56. docx/oxml/shared.py +52 -0
  57. docx/oxml/simpletypes.py +434 -0
  58. docx/oxml/styles.py +341 -0
  59. docx/oxml/table.py +977 -0
  60. docx/oxml/text/__init__.py +0 -0
  61. docx/oxml/text/font.py +333 -0
  62. docx/oxml/text/hyperlink.py +45 -0
  63. docx/oxml/text/pagebreak.py +278 -0
  64. docx/oxml/text/paragraph.py +106 -0
  65. docx/oxml/text/parfmt.py +392 -0
  66. docx/oxml/text/run.py +307 -0
  67. docx/oxml/xmlchemy.py +696 -0
  68. docx/package.py +110 -0
  69. docx/parts/__init__.py +0 -0
  70. docx/parts/comments.py +51 -0
  71. docx/parts/document.py +182 -0
  72. docx/parts/hdrftr.py +53 -0
  73. docx/parts/image.py +80 -0
  74. docx/parts/numbering.py +32 -0
  75. docx/parts/settings.py +50 -0
  76. docx/parts/story.py +95 -0
  77. docx/parts/styles.py +42 -0
  78. docx/parts/theme.py +53 -0
  79. docx/py.typed +0 -0
  80. docx/section.py +479 -0
  81. docx/settings.py +35 -0
  82. docx/shape.py +103 -0
  83. docx/shared.py +382 -0
  84. docx/styles/__init__.py +40 -0
  85. docx/styles/latent.py +198 -0
  86. docx/styles/style.py +264 -0
  87. docx/styles/styles.py +147 -0
  88. docx/table.py +537 -0
  89. docx/templates/default-comments.xml +12 -0
  90. docx/templates/default-docx-template/[Content_Types].xml +17 -0
  91. docx/templates/default-docx-template/_rels/.rels +7 -0
  92. docx/templates/default-docx-template/customXml/_rels/item1.xml.rels +4 -0
  93. docx/templates/default-docx-template/customXml/item1.xml +2 -0
  94. docx/templates/default-docx-template/customXml/itemProps1.xml +6 -0
  95. docx/templates/default-docx-template/docProps/app.xml +36 -0
  96. docx/templates/default-docx-template/docProps/core.xml +13 -0
  97. docx/templates/default-docx-template/docProps/thumbnail.jpeg +0 -0
  98. docx/templates/default-docx-template/word/_rels/document.xml.rels +11 -0
  99. docx/templates/default-docx-template/word/document.xml +11 -0
  100. docx/templates/default-docx-template/word/fontTable.xml +61 -0
  101. docx/templates/default-docx-template/word/numbering.xml +201 -0
  102. docx/templates/default-docx-template/word/settings.xml +53 -0
  103. docx/templates/default-docx-template/word/styles.xml +11844 -0
  104. docx/templates/default-docx-template/word/stylesWithEffects.xml +11800 -0
  105. docx/templates/default-docx-template/word/theme/theme1.xml +318 -0
  106. docx/templates/default-docx-template/word/webSettings.xml +5 -0
  107. docx/templates/default-footer.xml +27 -0
  108. docx/templates/default-header.xml +27 -0
  109. docx/templates/default-settings.xml +26 -0
  110. docx/templates/default-styles.xml +190 -0
  111. docx/templates/default.docx +0 -0
  112. docx/text/__init__.py +0 -0
  113. docx/text/font.py +472 -0
  114. docx/text/hyperlink.py +121 -0
  115. docx/text/pagebreak.py +104 -0
  116. docx/text/paragraph.py +173 -0
  117. docx/text/parfmt.py +286 -0
  118. docx/text/run.py +257 -0
  119. docx/text/tabstops.py +123 -0
  120. docx/theme.py +67 -0
  121. docx/types.py +34 -0
  122. ps_python_docx-1.3.0.dist-info/METADATA +77 -0
  123. ps_python_docx-1.3.0.dist-info/RECORD +126 -0
  124. ps_python_docx-1.3.0.dist-info/WHEEL +5 -0
  125. ps_python_docx-1.3.0.dist-info/licenses/LICENSE +20 -0
  126. ps_python_docx-1.3.0.dist-info/top_level.txt +1 -0
docx/oxml/table.py ADDED
@@ -0,0 +1,977 @@
1
+ """Custom element classes for tables."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING, Callable, cast
6
+
7
+ from docx.enum.table import WD_CELL_VERTICAL_ALIGNMENT, WD_ROW_HEIGHT_RULE, WD_TABLE_DIRECTION
8
+ from docx.exceptions import InvalidSpanError
9
+ from docx.oxml.ns import nsdecls, qn
10
+ from docx.oxml.parser import parse_xml
11
+ from docx.oxml.shared import CT_DecimalNumber
12
+ from docx.oxml.simpletypes import (
13
+ ST_Merge,
14
+ ST_TblLayoutType,
15
+ ST_TblWidth,
16
+ ST_TwipsMeasure,
17
+ XsdInt,
18
+ )
19
+ from docx.oxml.text.paragraph import CT_P
20
+ from docx.oxml.xmlchemy import (
21
+ BaseOxmlElement,
22
+ OneAndOnlyOne,
23
+ OneOrMore,
24
+ OptionalAttribute,
25
+ RequiredAttribute,
26
+ ZeroOrMore,
27
+ ZeroOrOne,
28
+ )
29
+ from docx.shared import Emu, Length, Twips
30
+
31
+ if TYPE_CHECKING:
32
+ from docx.enum.table import WD_TABLE_ALIGNMENT
33
+ from docx.enum.text import WD_ALIGN_PARAGRAPH
34
+ from docx.oxml.shared import CT_OnOff, CT_String
35
+ from docx.oxml.text.parfmt import CT_Jc
36
+
37
+
38
+ class CT_Height(BaseOxmlElement):
39
+ """Used for `w:trHeight` to specify a row height and row height rule."""
40
+
41
+ val: Length | None = OptionalAttribute( # pyright: ignore[reportAssignmentType]
42
+ "w:val", ST_TwipsMeasure
43
+ )
44
+ hRule: WD_ROW_HEIGHT_RULE | None = OptionalAttribute( # pyright: ignore[reportAssignmentType]
45
+ "w:hRule", WD_ROW_HEIGHT_RULE
46
+ )
47
+
48
+
49
+ class CT_Row(BaseOxmlElement):
50
+ """``<w:tr>`` element."""
51
+
52
+ add_tc: Callable[[], CT_Tc]
53
+ get_or_add_trPr: Callable[[], CT_TrPr]
54
+ _add_trPr: Callable[[], CT_TrPr]
55
+
56
+ tc_lst: list[CT_Tc]
57
+ # -- custom inserter below --
58
+ tblPrEx: CT_TblPrEx | None = ZeroOrOne("w:tblPrEx") # pyright: ignore[reportAssignmentType]
59
+ # -- custom inserter below --
60
+ trPr: CT_TrPr | None = ZeroOrOne("w:trPr") # pyright: ignore[reportAssignmentType]
61
+ tc = ZeroOrMore("w:tc")
62
+
63
+ @property
64
+ def grid_after(self) -> int:
65
+ """The number of unpopulated layout-grid cells at the end of this row."""
66
+ trPr = self.trPr
67
+ if trPr is None:
68
+ return 0
69
+ return trPr.grid_after
70
+
71
+ @property
72
+ def grid_before(self) -> int:
73
+ """The number of unpopulated layout-grid cells at the start of this row."""
74
+ trPr = self.trPr
75
+ if trPr is None:
76
+ return 0
77
+ return trPr.grid_before
78
+
79
+ def tc_at_grid_offset(self, grid_offset: int) -> CT_Tc:
80
+ """The `tc` element in this tr at exact `grid offset`.
81
+
82
+ Raises ValueError when this `w:tr` contains no `w:tc` with exact starting `grid_offset`.
83
+ """
84
+ # -- account for omitted cells at the start of the row --
85
+ remaining_offset = grid_offset - self.grid_before
86
+
87
+ for tc in self.tc_lst:
88
+ # -- We've gone past grid_offset without finding a tc, no sense searching further. --
89
+ if remaining_offset < 0:
90
+ break
91
+ # -- We've arrived at grid_offset, this is the `w:tc` we're looking for. --
92
+ if remaining_offset == 0:
93
+ return tc
94
+ # -- We're not there yet, skip forward the number of layout-grid cells this cell
95
+ # -- occupies.
96
+ remaining_offset -= tc.grid_span
97
+
98
+ raise ValueError(f"no `tc` element at grid_offset={grid_offset}")
99
+
100
+ @property
101
+ def tr_idx(self) -> int:
102
+ """Index of this `w:tr` element within its parent `w:tbl` element."""
103
+ tbl = cast(CT_Tbl, self.getparent())
104
+ return tbl.tr_lst.index(self)
105
+
106
+ @property
107
+ def trHeight_hRule(self) -> WD_ROW_HEIGHT_RULE | None:
108
+ """The value of `./w:trPr/w:trHeight/@w:hRule`, or |None| if not present."""
109
+ trPr = self.trPr
110
+ if trPr is None:
111
+ return None
112
+ return trPr.trHeight_hRule
113
+
114
+ @trHeight_hRule.setter
115
+ def trHeight_hRule(self, value: WD_ROW_HEIGHT_RULE | None):
116
+ trPr = self.get_or_add_trPr()
117
+ trPr.trHeight_hRule = value
118
+
119
+ @property
120
+ def trHeight_val(self):
121
+ """Return the value of `w:trPr/w:trHeight@w:val`, or |None| if not present."""
122
+ trPr = self.trPr
123
+ if trPr is None:
124
+ return None
125
+ return trPr.trHeight_val
126
+
127
+ @trHeight_val.setter
128
+ def trHeight_val(self, value: Length | None):
129
+ trPr = self.get_or_add_trPr()
130
+ trPr.trHeight_val = value
131
+
132
+ def _insert_tblPrEx(self, tblPrEx: CT_TblPrEx):
133
+ self.insert(0, tblPrEx)
134
+
135
+ def _insert_trPr(self, trPr: CT_TrPr):
136
+ tblPrEx = self.tblPrEx
137
+ if tblPrEx is not None:
138
+ tblPrEx.addnext(trPr)
139
+ else:
140
+ self.insert(0, trPr)
141
+
142
+ def _new_tc(self):
143
+ return CT_Tc.new()
144
+
145
+
146
+ class CT_Tbl(BaseOxmlElement):
147
+ """``<w:tbl>`` element."""
148
+
149
+ add_tr: Callable[[], CT_Row]
150
+ tr_lst: list[CT_Row]
151
+
152
+ tblPr: CT_TblPr = OneAndOnlyOne("w:tblPr") # pyright: ignore[reportAssignmentType]
153
+ tblGrid: CT_TblGrid = OneAndOnlyOne("w:tblGrid") # pyright: ignore[reportAssignmentType]
154
+ tr = ZeroOrMore("w:tr")
155
+
156
+ @property
157
+ def bidiVisual_val(self) -> bool | None:
158
+ """Value of `./w:tblPr/w:bidiVisual/@w:val` or |None| if not present.
159
+
160
+ Controls whether table cells are displayed right-to-left or left-to-right.
161
+ """
162
+ bidiVisual = self.tblPr.bidiVisual
163
+ if bidiVisual is None:
164
+ return None
165
+ return bidiVisual.val
166
+
167
+ @bidiVisual_val.setter
168
+ def bidiVisual_val(self, value: WD_TABLE_DIRECTION | None):
169
+ tblPr = self.tblPr
170
+ if value is None:
171
+ tblPr._remove_bidiVisual() # pyright: ignore[reportPrivateUsage]
172
+ else:
173
+ tblPr.get_or_add_bidiVisual().val = bool(value)
174
+
175
+ @property
176
+ def col_count(self):
177
+ """The number of grid columns in this table."""
178
+ return len(self.tblGrid.gridCol_lst)
179
+
180
+ def iter_tcs(self):
181
+ """Generate each of the `w:tc` elements in this table, left to right and top to
182
+ bottom.
183
+
184
+ Each cell in the first row is generated, followed by each cell in the second
185
+ row, etc.
186
+ """
187
+ for tr in self.tr_lst:
188
+ for tc in tr.tc_lst:
189
+ yield tc
190
+
191
+ @classmethod
192
+ def new_tbl(cls, rows: int, cols: int, width: Length) -> CT_Tbl:
193
+ """Return a new `w:tbl` element having `rows` rows and `cols` columns.
194
+
195
+ `width` is distributed evenly between the columns.
196
+ """
197
+ return cast(CT_Tbl, parse_xml(cls._tbl_xml(rows, cols, width)))
198
+
199
+ @property
200
+ def tblStyle_val(self) -> str | None:
201
+ """`w:tblPr/w:tblStyle/@w:val` (a table style id) or |None| if not present."""
202
+ tblStyle = self.tblPr.tblStyle
203
+ if tblStyle is None:
204
+ return None
205
+ return tblStyle.val
206
+
207
+ @tblStyle_val.setter
208
+ def tblStyle_val(self, styleId: str | None) -> None:
209
+ """Set the value of `w:tblPr/w:tblStyle/@w:val` (a table style id) to `styleId`.
210
+
211
+ If `styleId` is None, remove the `w:tblStyle` element.
212
+ """
213
+ tblPr = self.tblPr
214
+ tblPr._remove_tblStyle() # pyright: ignore[reportPrivateUsage]
215
+ if styleId is None:
216
+ return
217
+ tblPr._add_tblStyle().val = styleId # pyright: ignore[reportPrivateUsage]
218
+
219
+ @classmethod
220
+ def _tbl_xml(cls, rows: int, cols: int, width: Length) -> str:
221
+ col_width = Emu(width // cols) if cols > 0 else Emu(0)
222
+ return (
223
+ f"<w:tbl {nsdecls('w')}>\n"
224
+ f" <w:tblPr>\n"
225
+ f' <w:tblW w:type="auto" w:w="0"/>\n'
226
+ f' <w:tblLook w:firstColumn="1" w:firstRow="1"\n'
227
+ f' w:lastColumn="0" w:lastRow="0" w:noHBand="0"\n'
228
+ f' w:noVBand="1" w:val="04A0"/>\n'
229
+ f" </w:tblPr>\n"
230
+ f"{cls._tblGrid_xml(cols, col_width)}"
231
+ f"{cls._trs_xml(rows, cols, col_width)}"
232
+ f"</w:tbl>\n"
233
+ )
234
+
235
+ @classmethod
236
+ def _tblGrid_xml(cls, col_count: int, col_width: Length) -> str:
237
+ xml = " <w:tblGrid>\n"
238
+ for _ in range(col_count):
239
+ xml += ' <w:gridCol w:w="%d"/>\n' % col_width.twips
240
+ xml += " </w:tblGrid>\n"
241
+ return xml
242
+
243
+ @classmethod
244
+ def _trs_xml(cls, row_count: int, col_count: int, col_width: Length) -> str:
245
+ return f" <w:tr>\n{cls._tcs_xml(col_count, col_width)} </w:tr>\n" * row_count
246
+
247
+ @classmethod
248
+ def _tcs_xml(cls, col_count: int, col_width: Length) -> str:
249
+ return (
250
+ f" <w:tc>\n"
251
+ f" <w:tcPr>\n"
252
+ f' <w:tcW w:type="dxa" w:w="{col_width.twips}"/>\n'
253
+ f" </w:tcPr>\n"
254
+ f" <w:p/>\n"
255
+ f" </w:tc>\n"
256
+ ) * col_count
257
+
258
+
259
+ class CT_TblGrid(BaseOxmlElement):
260
+ """`w:tblGrid` element.
261
+
262
+ Child of `w:tbl`, holds `w:gridCol> elements that define column count, width, etc.
263
+ """
264
+
265
+ add_gridCol: Callable[[], CT_TblGridCol]
266
+ gridCol_lst: list[CT_TblGridCol]
267
+
268
+ gridCol = ZeroOrMore("w:gridCol", successors=("w:tblGridChange",))
269
+
270
+
271
+ class CT_TblGridCol(BaseOxmlElement):
272
+ """`w:gridCol` element, child of `w:tblGrid`, defines a table column."""
273
+
274
+ w: Length | None = OptionalAttribute( # pyright: ignore[reportAssignmentType]
275
+ "w:w", ST_TwipsMeasure
276
+ )
277
+
278
+ @property
279
+ def gridCol_idx(self) -> int:
280
+ """Index of this `w:gridCol` element within its parent `w:tblGrid` element."""
281
+ tblGrid = cast(CT_TblGrid, self.getparent())
282
+ return tblGrid.gridCol_lst.index(self)
283
+
284
+
285
+ class CT_TblLayoutType(BaseOxmlElement):
286
+ """`w:tblLayout` element.
287
+
288
+ Specifies whether column widths are fixed or can be automatically adjusted based on
289
+ content.
290
+ """
291
+
292
+ type: str | None = OptionalAttribute( # pyright: ignore[reportAssignmentType]
293
+ "w:type", ST_TblLayoutType
294
+ )
295
+
296
+
297
+ class CT_TblPr(BaseOxmlElement):
298
+ """``<w:tblPr>`` element, child of ``<w:tbl>``, holds child elements that define
299
+ table properties such as style and borders."""
300
+
301
+ get_or_add_bidiVisual: Callable[[], CT_OnOff]
302
+ get_or_add_jc: Callable[[], CT_Jc]
303
+ get_or_add_tblLayout: Callable[[], CT_TblLayoutType]
304
+ _add_tblStyle: Callable[[], CT_String]
305
+ _remove_bidiVisual: Callable[[], None]
306
+ _remove_jc: Callable[[], None]
307
+ _remove_tblStyle: Callable[[], None]
308
+
309
+ _tag_seq = (
310
+ "w:tblStyle",
311
+ "w:tblpPr",
312
+ "w:tblOverlap",
313
+ "w:bidiVisual",
314
+ "w:tblStyleRowBandSize",
315
+ "w:tblStyleColBandSize",
316
+ "w:tblW",
317
+ "w:jc",
318
+ "w:tblCellSpacing",
319
+ "w:tblInd",
320
+ "w:tblBorders",
321
+ "w:shd",
322
+ "w:tblLayout",
323
+ "w:tblCellMar",
324
+ "w:tblLook",
325
+ "w:tblCaption",
326
+ "w:tblDescription",
327
+ "w:tblPrChange",
328
+ )
329
+ tblStyle: CT_String | None = ZeroOrOne( # pyright: ignore[reportAssignmentType]
330
+ "w:tblStyle", successors=_tag_seq[1:]
331
+ )
332
+ bidiVisual: CT_OnOff | None = ZeroOrOne( # pyright: ignore[reportAssignmentType]
333
+ "w:bidiVisual", successors=_tag_seq[4:]
334
+ )
335
+ jc: CT_Jc | None = ZeroOrOne( # pyright: ignore[reportAssignmentType]
336
+ "w:jc", successors=_tag_seq[8:]
337
+ )
338
+ tblLayout: CT_TblLayoutType | None = ZeroOrOne( # pyright: ignore[reportAssignmentType]
339
+ "w:tblLayout", successors=_tag_seq[13:]
340
+ )
341
+ del _tag_seq
342
+
343
+ @property
344
+ def alignment(self) -> WD_TABLE_ALIGNMENT | None:
345
+ """Horizontal alignment of table, |None| if `./w:jc` is not present."""
346
+ jc = self.jc
347
+ if jc is None:
348
+ return None
349
+ return cast("WD_TABLE_ALIGNMENT | None", jc.val)
350
+
351
+ @alignment.setter
352
+ def alignment(self, value: WD_TABLE_ALIGNMENT | None):
353
+ self._remove_jc()
354
+ if value is None:
355
+ return
356
+ jc = self.get_or_add_jc()
357
+ jc.val = cast("WD_ALIGN_PARAGRAPH", value)
358
+
359
+ @property
360
+ def autofit(self) -> bool:
361
+ """|False| when there is a `w:tblLayout` child with `@w:type="fixed"`.
362
+
363
+ Otherwise |True|.
364
+ """
365
+ tblLayout = self.tblLayout
366
+ return True if tblLayout is None else tblLayout.type != "fixed"
367
+
368
+ @autofit.setter
369
+ def autofit(self, value: bool):
370
+ tblLayout = self.get_or_add_tblLayout()
371
+ tblLayout.type = "autofit" if value else "fixed"
372
+
373
+ @property
374
+ def style(self):
375
+ """Return the value of the ``val`` attribute of the ``<w:tblStyle>`` child or
376
+ |None| if not present."""
377
+ tblStyle = self.tblStyle
378
+ if tblStyle is None:
379
+ return None
380
+ return tblStyle.val
381
+
382
+ @style.setter
383
+ def style(self, value: str | None):
384
+ self._remove_tblStyle()
385
+ if value is None:
386
+ return
387
+ self._add_tblStyle().val = value
388
+
389
+
390
+ class CT_TblPrEx(BaseOxmlElement):
391
+ """`w:tblPrEx` element, exceptions to table-properties.
392
+
393
+ Applied at a lower level, like a `w:tr` to modify the appearance. Possibly used when
394
+ two tables are merged. For more see:
395
+ http://officeopenxml.com/WPtablePropertyExceptions.php
396
+ """
397
+
398
+
399
+ class CT_TblWidth(BaseOxmlElement):
400
+ """Used for `w:tblW` and `w:tcW` and others, specifies a table-related width."""
401
+
402
+ # the type for `w` attr is actually ST_MeasurementOrPercent, but using
403
+ # XsdInt for now because only dxa (twips) values are being used. It's not
404
+ # entirely clear what the semantics are for other values like -01.4mm
405
+ w: int = RequiredAttribute("w:w", XsdInt) # pyright: ignore[reportAssignmentType]
406
+ type = RequiredAttribute("w:type", ST_TblWidth)
407
+
408
+ @property
409
+ def width(self) -> Length | None:
410
+ """EMU length indicated by the combined `w:w` and `w:type` attrs."""
411
+ if self.type != "dxa":
412
+ return None
413
+ return Twips(self.w)
414
+
415
+ @width.setter
416
+ def width(self, value: Length):
417
+ self.type = "dxa"
418
+ self.w = Emu(value).twips
419
+
420
+
421
+ class CT_Tc(BaseOxmlElement):
422
+ """`w:tc` table cell element."""
423
+
424
+ add_p: Callable[[], CT_P]
425
+ get_or_add_tcPr: Callable[[], CT_TcPr]
426
+ p_lst: list[CT_P]
427
+ tbl_lst: list[CT_Tbl]
428
+ _insert_tbl: Callable[[CT_Tbl], CT_Tbl]
429
+ _new_p: Callable[[], CT_P]
430
+
431
+ # -- tcPr has many successors, `._insert_tcPr()` is overridden below --
432
+ tcPr: CT_TcPr | None = ZeroOrOne("w:tcPr") # pyright: ignore[reportAssignmentType]
433
+ p = OneOrMore("w:p")
434
+ tbl = OneOrMore("w:tbl")
435
+
436
+ @property
437
+ def bottom(self) -> int:
438
+ """The row index that marks the bottom extent of the vertical span of this cell.
439
+
440
+ This is one greater than the index of the bottom-most row of the span, similar
441
+ to how a slice of the cell's rows would be specified.
442
+ """
443
+ if self.vMerge is not None:
444
+ tc_below = self._tc_below
445
+ if tc_below is not None and tc_below.vMerge == ST_Merge.CONTINUE:
446
+ return tc_below.bottom
447
+ return self._tr_idx + 1
448
+
449
+ def clear_content(self):
450
+ """Remove all content elements, preserving `w:tcPr` element if present.
451
+
452
+ Note that this leaves the `w:tc` element in an invalid state because it doesn't
453
+ contain at least one block-level element. It's up to the caller to add a
454
+ `w:p`child element as the last content element.
455
+ """
456
+ # -- remove all cell inner-content except a `w:tcPr` when present. --
457
+ for e in self.xpath("./*[not(self::w:tcPr)]"):
458
+ self.remove(e)
459
+
460
+ @property
461
+ def grid_offset(self) -> int:
462
+ """Starting offset of `tc` in the layout-grid columns of its table.
463
+
464
+ A cell in the leftmost grid-column has offset 0.
465
+ """
466
+ grid_before = self._tr.grid_before
467
+ preceding_tc_grid_spans = sum(
468
+ tc.grid_span for tc in self.xpath("./preceding-sibling::w:tc")
469
+ )
470
+ return grid_before + preceding_tc_grid_spans
471
+
472
+ @property
473
+ def grid_span(self) -> int:
474
+ """The integer number of columns this cell spans.
475
+
476
+ Determined by ./w:tcPr/w:gridSpan/@val, it defaults to 1.
477
+ """
478
+ tcPr = self.tcPr
479
+ return 1 if tcPr is None else tcPr.grid_span
480
+
481
+ @grid_span.setter
482
+ def grid_span(self, value: int):
483
+ tcPr = self.get_or_add_tcPr()
484
+ tcPr.grid_span = value
485
+
486
+ @property
487
+ def inner_content_elements(self) -> list[CT_P | CT_Tbl]:
488
+ """Generate all `w:p` and `w:tbl` elements in this document-body.
489
+
490
+ Elements appear in document order. Elements shaded by nesting in a `w:ins` or
491
+ other "wrapper" element will not be included.
492
+ """
493
+ return self.xpath("./w:p | ./w:tbl")
494
+
495
+ def iter_block_items(self):
496
+ """Generate a reference to each of the block-level content elements in this
497
+ cell, in the order they appear."""
498
+ block_item_tags = (qn("w:p"), qn("w:tbl"), qn("w:sdt"))
499
+ for child in self:
500
+ if child.tag in block_item_tags:
501
+ yield child
502
+
503
+ @property
504
+ def left(self) -> int:
505
+ """The grid column index at which this ``<w:tc>`` element appears."""
506
+ return self.grid_offset
507
+
508
+ def merge(self, other_tc: CT_Tc) -> CT_Tc:
509
+ """Return top-left `w:tc` element of a new span.
510
+
511
+ Span is formed by merging the rectangular region defined by using this tc
512
+ element and `other_tc` as diagonal corners.
513
+ """
514
+ top, left, height, width = self._span_dimensions(other_tc)
515
+ top_tc = self._tbl.tr_lst[top].tc_at_grid_offset(left)
516
+ top_tc._grow_to(width, height)
517
+ return top_tc
518
+
519
+ @classmethod
520
+ def new(cls) -> CT_Tc:
521
+ """A new `w:tc` element, containing an empty paragraph as the required EG_BlockLevelElt."""
522
+ return cast(CT_Tc, parse_xml("<w:tc %s><w:p/></w:tc>" % nsdecls("w")))
523
+
524
+ @property
525
+ def right(self) -> int:
526
+ """The grid column index that marks the right-side extent of the horizontal span
527
+ of this cell.
528
+
529
+ This is one greater than the index of the right-most column of the span, similar
530
+ to how a slice of the cell's columns would be specified.
531
+ """
532
+ return self.grid_offset + self.grid_span
533
+
534
+ @property
535
+ def top(self) -> int:
536
+ """The top-most row index in the vertical span of this cell."""
537
+ if self.vMerge is None or self.vMerge == ST_Merge.RESTART:
538
+ return self._tr_idx
539
+ return self._tc_above.top
540
+
541
+ @property
542
+ def vMerge(self) -> str | None:
543
+ """Value of ./w:tcPr/w:vMerge/@val, |None| if w:vMerge is not present."""
544
+ tcPr = self.tcPr
545
+ if tcPr is None:
546
+ return None
547
+ return tcPr.vMerge_val
548
+
549
+ @vMerge.setter
550
+ def vMerge(self, value: str | None):
551
+ tcPr = self.get_or_add_tcPr()
552
+ tcPr.vMerge_val = value
553
+
554
+ @property
555
+ def width(self) -> Length | None:
556
+ """EMU length represented in `./w:tcPr/w:tcW` or |None| if not present."""
557
+ tcPr = self.tcPr
558
+ if tcPr is None:
559
+ return None
560
+ return tcPr.width
561
+
562
+ @width.setter
563
+ def width(self, value: Length):
564
+ tcPr = self.get_or_add_tcPr()
565
+ tcPr.width = value
566
+
567
+ def _add_width_of(self, other_tc: CT_Tc):
568
+ """Add the width of `other_tc` to this cell.
569
+
570
+ Does nothing if either this tc or `other_tc` does not have a specified width.
571
+ """
572
+ if self.width and other_tc.width:
573
+ self.width = Length(self.width + other_tc.width)
574
+
575
+ def _grow_to(self, width: int, height: int, top_tc: CT_Tc | None = None):
576
+ """Grow this cell to `width` grid columns and `height` rows.
577
+
578
+ This is accomplished by expanding horizontal spans and creating continuation
579
+ cells to form vertical spans.
580
+ """
581
+
582
+ def vMerge_val(top_tc: CT_Tc):
583
+ return (
584
+ ST_Merge.CONTINUE
585
+ if top_tc is not self
586
+ else None
587
+ if height == 1
588
+ else ST_Merge.RESTART
589
+ )
590
+
591
+ top_tc = self if top_tc is None else top_tc
592
+ self._span_to_width(width, top_tc, vMerge_val(top_tc))
593
+ if height > 1:
594
+ tc_below = self._tc_below
595
+ assert tc_below is not None
596
+ tc_below._grow_to(width, height - 1, top_tc)
597
+
598
+ def _insert_tcPr(self, tcPr: CT_TcPr) -> CT_TcPr:
599
+ """Override default `._insert_tcPr()`."""
600
+ # -- `tcPr`` has a large number of successors, but always comes first if it appears,
601
+ # -- so just using insert(0, ...) rather than spelling out successors.
602
+ self.insert(0, tcPr)
603
+ return tcPr
604
+
605
+ @property
606
+ def _is_empty(self) -> bool:
607
+ """True if this cell contains only a single empty `w:p` element."""
608
+ block_items = list(self.iter_block_items())
609
+ if len(block_items) > 1:
610
+ return False
611
+ # -- cell must include at least one block item but can be a `w:tbl`, `w:sdt`,
612
+ # -- `w:customXml` or a `w:p`
613
+ only_item = block_items[0]
614
+ return isinstance(only_item, CT_P) and len(only_item.r_lst) == 0
615
+
616
+ def _move_content_to(self, other_tc: CT_Tc):
617
+ """Append the content of this cell to `other_tc`.
618
+
619
+ Leaves this cell with a single empty ``<w:p>`` element.
620
+ """
621
+ if other_tc is self:
622
+ return
623
+ if self._is_empty:
624
+ return
625
+ other_tc._remove_trailing_empty_p()
626
+ # -- appending moves each element from self to other_tc --
627
+ for block_element in self.iter_block_items():
628
+ other_tc.append(block_element)
629
+ # -- add back the required minimum single empty <w:p> element --
630
+ self.append(self._new_p())
631
+
632
+ def _new_tbl(self) -> None:
633
+ raise NotImplementedError(
634
+ "use CT_Tbl.new_tbl() to add a new table, specifying rows and columns"
635
+ )
636
+
637
+ @property
638
+ def _next_tc(self) -> CT_Tc | None:
639
+ """The `w:tc` element immediately following this one in this row, or |None| if
640
+ this is the last `w:tc` element in the row."""
641
+ following_tcs = self.xpath("./following-sibling::w:tc")
642
+ return following_tcs[0] if following_tcs else None
643
+
644
+ def _remove(self):
645
+ """Remove this `w:tc` element from the XML tree."""
646
+ parent_element = self.getparent()
647
+ assert parent_element is not None
648
+ parent_element.remove(self)
649
+
650
+ def _remove_trailing_empty_p(self):
651
+ """Remove last content element from this cell if it's an empty `w:p` element."""
652
+ block_items = list(self.iter_block_items())
653
+ last_content_elm = block_items[-1]
654
+ if not isinstance(last_content_elm, CT_P):
655
+ return
656
+ p = last_content_elm
657
+ if len(p.r_lst) > 0:
658
+ return
659
+ self.remove(p)
660
+
661
+ def _span_dimensions(self, other_tc: CT_Tc) -> tuple[int, int, int, int]:
662
+ """Return a (top, left, height, width) 4-tuple specifying the extents of the
663
+ merged cell formed by using this tc and `other_tc` as opposite corner
664
+ extents."""
665
+
666
+ def raise_on_inverted_L(a: CT_Tc, b: CT_Tc):
667
+ if a.top == b.top and a.bottom != b.bottom:
668
+ raise InvalidSpanError("requested span not rectangular")
669
+ if a.left == b.left and a.right != b.right:
670
+ raise InvalidSpanError("requested span not rectangular")
671
+
672
+ def raise_on_tee_shaped(a: CT_Tc, b: CT_Tc):
673
+ top_most, other = (a, b) if a.top < b.top else (b, a)
674
+ if top_most.top < other.top and top_most.bottom > other.bottom:
675
+ raise InvalidSpanError("requested span not rectangular")
676
+
677
+ left_most, other = (a, b) if a.left < b.left else (b, a)
678
+ if left_most.left < other.left and left_most.right > other.right:
679
+ raise InvalidSpanError("requested span not rectangular")
680
+
681
+ raise_on_inverted_L(self, other_tc)
682
+ raise_on_tee_shaped(self, other_tc)
683
+
684
+ top = min(self.top, other_tc.top)
685
+ left = min(self.left, other_tc.left)
686
+ bottom = max(self.bottom, other_tc.bottom)
687
+ right = max(self.right, other_tc.right)
688
+
689
+ return top, left, bottom - top, right - left
690
+
691
+ def _span_to_width(self, grid_width: int, top_tc: CT_Tc, vMerge: str | None):
692
+ """Incorporate `w:tc` elements to the right until this cell spans `grid_width`.
693
+
694
+ Incorporated `w:tc` elements are removed (replaced by gridSpan value).
695
+
696
+ Raises |ValueError| if `grid_width` cannot be exactly achieved, such as when a
697
+ merged cell would drive the span width greater than `grid_width` or if not
698
+ enough grid columns are available to make this cell that wide. All content from
699
+ incorporated cells is appended to `top_tc`. The val attribute of the vMerge
700
+ element on the single remaining cell is set to `vMerge`. If `vMerge` is |None|,
701
+ the vMerge element is removed if present.
702
+ """
703
+ self._move_content_to(top_tc)
704
+ while self.grid_span < grid_width:
705
+ self._swallow_next_tc(grid_width, top_tc)
706
+ self.vMerge = vMerge
707
+
708
+ def _swallow_next_tc(self, grid_width: int, top_tc: CT_Tc):
709
+ """Extend the horizontal span of this `w:tc` element to incorporate the
710
+ following `w:tc` element in the row and then delete that following `w:tc`
711
+ element.
712
+
713
+ Any content in the following `w:tc` element is appended to the content of
714
+ `top_tc`. The width of the following `w:tc` element is added to this one, if
715
+ present. Raises |InvalidSpanError| if the width of the resulting cell is greater
716
+ than `grid_width` or if there is no next `<w:tc>` element in the row.
717
+ """
718
+
719
+ def raise_on_invalid_swallow(next_tc: CT_Tc | None):
720
+ if next_tc is None:
721
+ raise InvalidSpanError("not enough grid columns")
722
+ if self.grid_span + next_tc.grid_span > grid_width:
723
+ raise InvalidSpanError("span is not rectangular")
724
+
725
+ next_tc = self._next_tc
726
+ raise_on_invalid_swallow(next_tc)
727
+ assert next_tc is not None
728
+ next_tc._move_content_to(top_tc)
729
+ self._add_width_of(next_tc)
730
+ self.grid_span += next_tc.grid_span
731
+ next_tc._remove()
732
+
733
+ @property
734
+ def _tbl(self) -> CT_Tbl:
735
+ """The tbl element this tc element appears in."""
736
+ return cast(CT_Tbl, self.xpath("./ancestor::w:tbl[position()=1]")[0])
737
+
738
+ @property
739
+ def _tc_above(self) -> CT_Tc:
740
+ """The `w:tc` element immediately above this one in its grid column."""
741
+ return self._tr_above.tc_at_grid_offset(self.grid_offset)
742
+
743
+ @property
744
+ def _tc_below(self) -> CT_Tc | None:
745
+ """The tc element immediately below this one in its grid column."""
746
+ tr_below = self._tr_below
747
+ if tr_below is None:
748
+ return None
749
+ return tr_below.tc_at_grid_offset(self.grid_offset)
750
+
751
+ @property
752
+ def _tr(self) -> CT_Row:
753
+ """The tr element this tc element appears in."""
754
+ return cast(CT_Row, self.xpath("./ancestor::w:tr[position()=1]")[0])
755
+
756
+ @property
757
+ def _tr_above(self) -> CT_Row:
758
+ """The tr element prior in sequence to the tr this cell appears in.
759
+
760
+ Raises |ValueError| if called on a cell in the top-most row.
761
+ """
762
+ tr_aboves = self.xpath("./ancestor::w:tr[position()=1]/preceding-sibling::w:tr[1]")
763
+ if not tr_aboves:
764
+ raise ValueError("no tr above topmost tr in w:tbl")
765
+ return tr_aboves[0]
766
+
767
+ @property
768
+ def _tr_below(self) -> CT_Row | None:
769
+ """The tr element next in sequence after the tr this cell appears in, or |None|
770
+ if this cell appears in the last row."""
771
+ tr_lst = self._tbl.tr_lst
772
+ tr_idx = tr_lst.index(self._tr)
773
+ try:
774
+ return tr_lst[tr_idx + 1]
775
+ except IndexError:
776
+ return None
777
+
778
+ @property
779
+ def _tr_idx(self) -> int:
780
+ """The row index of the tr element this tc element appears in."""
781
+ return self._tbl.tr_lst.index(self._tr)
782
+
783
+
784
+ class CT_TcPr(BaseOxmlElement):
785
+ """``<w:tcPr>`` element, defining table cell properties."""
786
+
787
+ get_or_add_gridSpan: Callable[[], CT_DecimalNumber]
788
+ get_or_add_tcW: Callable[[], CT_TblWidth]
789
+ get_or_add_vAlign: Callable[[], CT_VerticalJc]
790
+ _add_vMerge: Callable[[], CT_VMerge]
791
+ _remove_gridSpan: Callable[[], None]
792
+ _remove_vAlign: Callable[[], None]
793
+ _remove_vMerge: Callable[[], None]
794
+
795
+ _tag_seq = (
796
+ "w:cnfStyle",
797
+ "w:tcW",
798
+ "w:gridSpan",
799
+ "w:hMerge",
800
+ "w:vMerge",
801
+ "w:tcBorders",
802
+ "w:shd",
803
+ "w:noWrap",
804
+ "w:tcMar",
805
+ "w:textDirection",
806
+ "w:tcFitText",
807
+ "w:vAlign",
808
+ "w:hideMark",
809
+ "w:headers",
810
+ "w:cellIns",
811
+ "w:cellDel",
812
+ "w:cellMerge",
813
+ "w:tcPrChange",
814
+ )
815
+ tcW: CT_TblWidth | None = ZeroOrOne( # pyright: ignore[reportAssignmentType]
816
+ "w:tcW", successors=_tag_seq[2:]
817
+ )
818
+ gridSpan: CT_DecimalNumber | None = ZeroOrOne( # pyright: ignore[reportAssignmentType]
819
+ "w:gridSpan", successors=_tag_seq[3:]
820
+ )
821
+ vMerge: CT_VMerge | None = ZeroOrOne( # pyright: ignore[reportAssignmentType]
822
+ "w:vMerge", successors=_tag_seq[5:]
823
+ )
824
+ vAlign: CT_VerticalJc | None = ZeroOrOne( # pyright: ignore[reportAssignmentType]
825
+ "w:vAlign", successors=_tag_seq[12:]
826
+ )
827
+ del _tag_seq
828
+
829
+ @property
830
+ def grid_span(self) -> int:
831
+ """The integer number of columns this cell spans.
832
+
833
+ Determined by ./w:gridSpan/@val, it defaults to 1.
834
+ """
835
+ gridSpan = self.gridSpan
836
+ return 1 if gridSpan is None else gridSpan.val
837
+
838
+ @grid_span.setter
839
+ def grid_span(self, value: int):
840
+ self._remove_gridSpan()
841
+ if value > 1:
842
+ self.get_or_add_gridSpan().val = value
843
+
844
+ @property
845
+ def vAlign_val(self):
846
+ """Value of `w:val` attribute on `w:vAlign` child.
847
+
848
+ Value is |None| if `w:vAlign` child is not present. The `w:val` attribute on
849
+ `w:vAlign` is required.
850
+ """
851
+ vAlign = self.vAlign
852
+ if vAlign is None:
853
+ return None
854
+ return vAlign.val
855
+
856
+ @vAlign_val.setter
857
+ def vAlign_val(self, value: WD_CELL_VERTICAL_ALIGNMENT | None):
858
+ if value is None:
859
+ self._remove_vAlign()
860
+ return
861
+ self.get_or_add_vAlign().val = value
862
+
863
+ @property
864
+ def vMerge_val(self):
865
+ """The value of the ./w:vMerge/@val attribute, or |None| if the w:vMerge element
866
+ is not present."""
867
+ vMerge = self.vMerge
868
+ if vMerge is None:
869
+ return None
870
+ return vMerge.val
871
+
872
+ @vMerge_val.setter
873
+ def vMerge_val(self, value: str | None):
874
+ self._remove_vMerge()
875
+ if value is not None:
876
+ self._add_vMerge().val = value
877
+
878
+ @property
879
+ def width(self) -> Length | None:
880
+ """EMU length in `./w:tcW` or |None| if not present or its type is not 'dxa'."""
881
+ tcW = self.tcW
882
+ if tcW is None:
883
+ return None
884
+ return tcW.width
885
+
886
+ @width.setter
887
+ def width(self, value: Length):
888
+ tcW = self.get_or_add_tcW()
889
+ tcW.width = value
890
+
891
+
892
+ class CT_TrPr(BaseOxmlElement):
893
+ """``<w:trPr>`` element, defining table row properties."""
894
+
895
+ get_or_add_trHeight: Callable[[], CT_Height]
896
+
897
+ _tag_seq = (
898
+ "w:cnfStyle",
899
+ "w:divId",
900
+ "w:gridBefore",
901
+ "w:gridAfter",
902
+ "w:wBefore",
903
+ "w:wAfter",
904
+ "w:cantSplit",
905
+ "w:trHeight",
906
+ "w:tblHeader",
907
+ "w:tblCellSpacing",
908
+ "w:jc",
909
+ "w:hidden",
910
+ "w:ins",
911
+ "w:del",
912
+ "w:trPrChange",
913
+ )
914
+ gridAfter: CT_DecimalNumber | None = ZeroOrOne( # pyright: ignore[reportAssignmentType]
915
+ "w:gridAfter", successors=_tag_seq[4:]
916
+ )
917
+ gridBefore: CT_DecimalNumber | None = ZeroOrOne( # pyright: ignore[reportAssignmentType]
918
+ "w:gridBefore", successors=_tag_seq[3:]
919
+ )
920
+ trHeight: CT_Height | None = ZeroOrOne( # pyright: ignore[reportAssignmentType]
921
+ "w:trHeight", successors=_tag_seq[8:]
922
+ )
923
+ del _tag_seq
924
+
925
+ @property
926
+ def grid_after(self) -> int:
927
+ """The number of unpopulated layout-grid cells at the end of this row."""
928
+ gridAfter = self.gridAfter
929
+ return 0 if gridAfter is None else gridAfter.val
930
+
931
+ @property
932
+ def grid_before(self) -> int:
933
+ """The number of unpopulated layout-grid cells at the start of this row."""
934
+ gridBefore = self.gridBefore
935
+ return 0 if gridBefore is None else gridBefore.val
936
+
937
+ @property
938
+ def trHeight_hRule(self) -> WD_ROW_HEIGHT_RULE | None:
939
+ """Return the value of `w:trHeight@w:hRule`, or |None| if not present."""
940
+ trHeight = self.trHeight
941
+ return None if trHeight is None else trHeight.hRule
942
+
943
+ @trHeight_hRule.setter
944
+ def trHeight_hRule(self, value: WD_ROW_HEIGHT_RULE | None):
945
+ if value is None and self.trHeight is None:
946
+ return
947
+ trHeight = self.get_or_add_trHeight()
948
+ trHeight.hRule = value
949
+
950
+ @property
951
+ def trHeight_val(self):
952
+ """Return the value of `w:trHeight@w:val`, or |None| if not present."""
953
+ trHeight = self.trHeight
954
+ return None if trHeight is None else trHeight.val
955
+
956
+ @trHeight_val.setter
957
+ def trHeight_val(self, value: Length | None):
958
+ if value is None and self.trHeight is None:
959
+ return
960
+ trHeight = self.get_or_add_trHeight()
961
+ trHeight.val = value
962
+
963
+
964
+ class CT_VerticalJc(BaseOxmlElement):
965
+ """`w:vAlign` element, specifying vertical alignment of cell."""
966
+
967
+ val: WD_CELL_VERTICAL_ALIGNMENT = RequiredAttribute( # pyright: ignore[reportAssignmentType]
968
+ "w:val", WD_CELL_VERTICAL_ALIGNMENT
969
+ )
970
+
971
+
972
+ class CT_VMerge(BaseOxmlElement):
973
+ """``<w:vMerge>`` element, specifying vertical merging behavior of a cell."""
974
+
975
+ val: str | None = OptionalAttribute( # pyright: ignore[reportAssignmentType]
976
+ "w:val", ST_Merge, default=ST_Merge.CONTINUE
977
+ )