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/section.py ADDED
@@ -0,0 +1,537 @@
1
+ """Section-related custom element classes."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from copy import deepcopy
6
+ from typing import Callable, Iterator, List, Sequence, cast
7
+
8
+ from lxml import etree
9
+ from typing_extensions import TypeAlias
10
+
11
+ from docx.enum.section import WD_HEADER_FOOTER, WD_ORIENTATION, WD_SECTION_START
12
+ from docx.oxml.ns import nsmap
13
+ from docx.oxml.shared import CT_OnOff
14
+ from docx.oxml.simpletypes import ST_SignedTwipsMeasure, ST_TwipsMeasure, XsdString
15
+ from docx.oxml.table import CT_Tbl
16
+ from docx.oxml.text.paragraph import CT_P
17
+ from docx.oxml.xmlchemy import (
18
+ BaseOxmlElement,
19
+ OptionalAttribute,
20
+ RequiredAttribute,
21
+ ZeroOrMore,
22
+ ZeroOrOne,
23
+ )
24
+ from docx.shared import Length, lazyproperty
25
+
26
+ BlockElement: TypeAlias = "CT_P | CT_Tbl"
27
+
28
+
29
+ class CT_HdrFtr(BaseOxmlElement):
30
+ """`w:hdr` and `w:ftr`, the root element for header and footer part respectively."""
31
+
32
+ add_p: Callable[[], CT_P]
33
+ p_lst: List[CT_P]
34
+ tbl_lst: List[CT_Tbl]
35
+
36
+ _insert_tbl: Callable[[CT_Tbl], CT_Tbl]
37
+
38
+ p = ZeroOrMore("w:p", successors=())
39
+ tbl = ZeroOrMore("w:tbl", successors=())
40
+
41
+ @property
42
+ def inner_content_elements(self) -> List[CT_P | CT_Tbl]:
43
+ """Generate all `w:p` and `w:tbl` elements in this header or footer.
44
+
45
+ Elements appear in document order. Elements shaded by nesting in a `w:ins` or
46
+ other "wrapper" element will not be included.
47
+ """
48
+ return self.xpath("./w:p | ./w:tbl")
49
+
50
+
51
+ class CT_HdrFtrRef(BaseOxmlElement):
52
+ """`w:headerReference` and `w:footerReference` elements."""
53
+
54
+ type_: WD_HEADER_FOOTER = RequiredAttribute( # pyright: ignore[reportAssignmentType]
55
+ "w:type", WD_HEADER_FOOTER
56
+ )
57
+ rId: str = RequiredAttribute("r:id", XsdString) # pyright: ignore[reportAssignmentType]
58
+
59
+
60
+ class CT_PageMar(BaseOxmlElement):
61
+ """``<w:pgMar>`` element, defining page margins."""
62
+
63
+ top: Length | None = OptionalAttribute( # pyright: ignore[reportAssignmentType]
64
+ "w:top", ST_SignedTwipsMeasure
65
+ )
66
+ right: Length | None = OptionalAttribute( # pyright: ignore[reportAssignmentType]
67
+ "w:right", ST_TwipsMeasure
68
+ )
69
+ bottom: Length | None = OptionalAttribute( # pyright: ignore[reportAssignmentType]
70
+ "w:bottom", ST_SignedTwipsMeasure
71
+ )
72
+ left: Length | None = OptionalAttribute( # pyright: ignore[reportAssignmentType]
73
+ "w:left", ST_TwipsMeasure
74
+ )
75
+ header: Length | None = OptionalAttribute( # pyright: ignore[reportAssignmentType]
76
+ "w:header", ST_TwipsMeasure
77
+ )
78
+ footer: Length | None = OptionalAttribute( # pyright: ignore[reportAssignmentType]
79
+ "w:footer", ST_TwipsMeasure
80
+ )
81
+ gutter: Length | None = OptionalAttribute( # pyright: ignore[reportAssignmentType]
82
+ "w:gutter", ST_TwipsMeasure
83
+ )
84
+
85
+
86
+ class CT_PageSz(BaseOxmlElement):
87
+ """``<w:pgSz>`` element, defining page dimensions and orientation."""
88
+
89
+ w: Length | None = OptionalAttribute( # pyright: ignore[reportAssignmentType]
90
+ "w:w", ST_TwipsMeasure
91
+ )
92
+ h: Length | None = OptionalAttribute( # pyright: ignore[reportAssignmentType]
93
+ "w:h", ST_TwipsMeasure
94
+ )
95
+ orient: WD_ORIENTATION = OptionalAttribute( # pyright: ignore[reportAssignmentType]
96
+ "w:orient", WD_ORIENTATION, default=WD_ORIENTATION.PORTRAIT
97
+ )
98
+
99
+
100
+ class CT_SectPr(BaseOxmlElement):
101
+ """`w:sectPr` element, the container element for section properties."""
102
+
103
+ get_or_add_pgMar: Callable[[], CT_PageMar]
104
+ get_or_add_pgSz: Callable[[], CT_PageSz]
105
+ get_or_add_titlePg: Callable[[], CT_OnOff]
106
+ get_or_add_type: Callable[[], CT_SectType]
107
+ _add_footerReference: Callable[[], CT_HdrFtrRef]
108
+ _add_headerReference: Callable[[], CT_HdrFtrRef]
109
+ _remove_titlePg: Callable[[], None]
110
+ _remove_type: Callable[[], None]
111
+
112
+ _tag_seq = (
113
+ "w:footnotePr",
114
+ "w:endnotePr",
115
+ "w:type",
116
+ "w:pgSz",
117
+ "w:pgMar",
118
+ "w:paperSrc",
119
+ "w:pgBorders",
120
+ "w:lnNumType",
121
+ "w:pgNumType",
122
+ "w:cols",
123
+ "w:formProt",
124
+ "w:vAlign",
125
+ "w:noEndnote",
126
+ "w:titlePg",
127
+ "w:textDirection",
128
+ "w:bidi",
129
+ "w:rtlGutter",
130
+ "w:docGrid",
131
+ "w:printerSettings",
132
+ "w:sectPrChange",
133
+ )
134
+ headerReference = ZeroOrMore("w:headerReference", successors=_tag_seq)
135
+ footerReference = ZeroOrMore("w:footerReference", successors=_tag_seq)
136
+ type: CT_SectType | None = ZeroOrOne( # pyright: ignore[reportAssignmentType]
137
+ "w:type", successors=_tag_seq[3:]
138
+ )
139
+ pgSz: CT_PageSz | None = ZeroOrOne( # pyright: ignore[reportAssignmentType]
140
+ "w:pgSz", successors=_tag_seq[4:]
141
+ )
142
+ pgMar: CT_PageMar | None = ZeroOrOne( # pyright: ignore[reportAssignmentType]
143
+ "w:pgMar", successors=_tag_seq[5:]
144
+ )
145
+ titlePg: CT_OnOff | None = ZeroOrOne( # pyright: ignore[reportAssignmentType]
146
+ "w:titlePg", successors=_tag_seq[14:]
147
+ )
148
+ del _tag_seq
149
+
150
+ def add_footerReference(self, type_: WD_HEADER_FOOTER, rId: str) -> CT_HdrFtrRef:
151
+ """Return newly added CT_HdrFtrRef element of `type_` with `rId`.
152
+
153
+ The element tag is `w:footerReference`.
154
+ """
155
+ footerReference = self._add_footerReference()
156
+ footerReference.type_ = type_
157
+ footerReference.rId = rId
158
+ return footerReference
159
+
160
+ def add_headerReference(self, type_: WD_HEADER_FOOTER, rId: str) -> CT_HdrFtrRef:
161
+ """Return newly added CT_HdrFtrRef element of `type_` with `rId`.
162
+
163
+ The element tag is `w:headerReference`.
164
+ """
165
+ headerReference = self._add_headerReference()
166
+ headerReference.type_ = type_
167
+ headerReference.rId = rId
168
+ return headerReference
169
+
170
+ @property
171
+ def bottom_margin(self) -> Length | None:
172
+ """Value of the `w:bottom` attr of `<w:pgMar>` child element, as |Length|.
173
+
174
+ |None| when either the element or the attribute is not present.
175
+ """
176
+ pgMar = self.pgMar
177
+ if pgMar is None:
178
+ return None
179
+ return pgMar.bottom
180
+
181
+ @bottom_margin.setter
182
+ def bottom_margin(self, value: int | Length | None):
183
+ pgMar = self.get_or_add_pgMar()
184
+ pgMar.bottom = value if value is None or isinstance(value, Length) else Length(value)
185
+
186
+ def clone(self) -> CT_SectPr:
187
+ """Return an exact duplicate of this ``<w:sectPr>`` element tree suitable for
188
+ use in adding a section break.
189
+
190
+ All rsid* attributes are removed from the root ``<w:sectPr>`` element.
191
+ """
192
+ cloned_sectPr = deepcopy(self)
193
+ cloned_sectPr.attrib.clear()
194
+ return cloned_sectPr
195
+
196
+ @property
197
+ def footer(self) -> Length | None:
198
+ """Distance from bottom edge of page to bottom edge of the footer.
199
+
200
+ This is the value of the `w:footer` attribute in the `w:pgMar` child element,
201
+ as a |Length| object, or |None| if either the element or the attribute is not
202
+ present.
203
+ """
204
+ pgMar = self.pgMar
205
+ if pgMar is None:
206
+ return None
207
+ return pgMar.footer
208
+
209
+ @footer.setter
210
+ def footer(self, value: int | Length | None):
211
+ pgMar = self.get_or_add_pgMar()
212
+ pgMar.footer = value if value is None or isinstance(value, Length) else Length(value)
213
+
214
+ def get_footerReference(self, type_: WD_HEADER_FOOTER) -> CT_HdrFtrRef | None:
215
+ """Return footerReference element of `type_` or None if not present."""
216
+ path = "./w:footerReference[@w:type='%s']" % WD_HEADER_FOOTER.to_xml(type_)
217
+ footerReferences = self.xpath(path)
218
+ if not footerReferences:
219
+ return None
220
+ return footerReferences[0]
221
+
222
+ def get_headerReference(self, type_: WD_HEADER_FOOTER) -> CT_HdrFtrRef | None:
223
+ """Return headerReference element of `type_` or None if not present."""
224
+ matching_headerReferences = self.xpath(
225
+ "./w:headerReference[@w:type='%s']" % WD_HEADER_FOOTER.to_xml(type_)
226
+ )
227
+ if len(matching_headerReferences) == 0:
228
+ return None
229
+ return matching_headerReferences[0]
230
+
231
+ @property
232
+ def gutter(self) -> Length | None:
233
+ """The value of the ``w:gutter`` attribute in the ``<w:pgMar>`` child element,
234
+ as a |Length| object, or |None| if either the element or the attribute is not
235
+ present."""
236
+ pgMar = self.pgMar
237
+ if pgMar is None:
238
+ return None
239
+ return pgMar.gutter
240
+
241
+ @gutter.setter
242
+ def gutter(self, value: int | Length | None):
243
+ pgMar = self.get_or_add_pgMar()
244
+ pgMar.gutter = value if value is None or isinstance(value, Length) else Length(value)
245
+
246
+ @property
247
+ def header(self) -> Length | None:
248
+ """Distance from top edge of page to top edge of header.
249
+
250
+ This value comes from the `w:header` attribute on the `w:pgMar` child element.
251
+ |None| if either the element or the attribute is not present.
252
+ """
253
+ pgMar = self.pgMar
254
+ if pgMar is None:
255
+ return None
256
+ return pgMar.header
257
+
258
+ @header.setter
259
+ def header(self, value: int | Length | None):
260
+ pgMar = self.get_or_add_pgMar()
261
+ pgMar.header = value if value is None or isinstance(value, Length) else Length(value)
262
+
263
+ def iter_inner_content(self) -> Iterator[CT_P | CT_Tbl]:
264
+ """Generate all `w:p` and `w:tbl` elements in this section.
265
+
266
+ Elements appear in document order. Elements shaded by nesting in a `w:ins` or
267
+ other "wrapper" element will not be included.
268
+ """
269
+ return _SectBlockElementIterator.iter_sect_block_elements(self)
270
+
271
+ @property
272
+ def left_margin(self) -> Length | None:
273
+ """The value of the ``w:left`` attribute in the ``<w:pgMar>`` child element, as
274
+ a |Length| object, or |None| if either the element or the attribute is not
275
+ present."""
276
+ pgMar = self.pgMar
277
+ if pgMar is None:
278
+ return None
279
+ return pgMar.left
280
+
281
+ @left_margin.setter
282
+ def left_margin(self, value: int | Length | None):
283
+ pgMar = self.get_or_add_pgMar()
284
+ pgMar.left = value if value is None or isinstance(value, Length) else Length(value)
285
+
286
+ @property
287
+ def orientation(self) -> WD_ORIENTATION:
288
+ """`WD_ORIENTATION` member indicating page-orientation for this section.
289
+
290
+ This is the value of the `orient` attribute on the `w:pgSz` child, or
291
+ `WD_ORIENTATION.PORTRAIT` if not present.
292
+ """
293
+ pgSz = self.pgSz
294
+ if pgSz is None:
295
+ return WD_ORIENTATION.PORTRAIT
296
+ return pgSz.orient
297
+
298
+ @orientation.setter
299
+ def orientation(self, value: WD_ORIENTATION | None):
300
+ pgSz = self.get_or_add_pgSz()
301
+ pgSz.orient = value if value else WD_ORIENTATION.PORTRAIT
302
+
303
+ @property
304
+ def page_height(self) -> Length | None:
305
+ """Value in EMU of the `h` attribute of the `w:pgSz` child element.
306
+
307
+ |None| if not present.
308
+ """
309
+ pgSz = self.pgSz
310
+ if pgSz is None:
311
+ return None
312
+ return pgSz.h
313
+
314
+ @page_height.setter
315
+ def page_height(self, value: Length | None):
316
+ pgSz = self.get_or_add_pgSz()
317
+ pgSz.h = value
318
+
319
+ @property
320
+ def page_width(self) -> Length | None:
321
+ """Value in EMU of the ``w`` attribute of the ``<w:pgSz>`` child element.
322
+
323
+ |None| if not present.
324
+ """
325
+ pgSz = self.pgSz
326
+ if pgSz is None:
327
+ return None
328
+ return pgSz.w
329
+
330
+ @page_width.setter
331
+ def page_width(self, value: Length | None):
332
+ pgSz = self.get_or_add_pgSz()
333
+ pgSz.w = value
334
+
335
+ @property
336
+ def preceding_sectPr(self) -> CT_SectPr | None:
337
+ """SectPr immediately preceding this one or None if this is the first."""
338
+ # -- [1] predicate returns list of zero or one value --
339
+ preceding_sectPrs = self.xpath("./preceding::w:sectPr[1]")
340
+ return preceding_sectPrs[0] if len(preceding_sectPrs) > 0 else None
341
+
342
+ def remove_footerReference(self, type_: WD_HEADER_FOOTER) -> str:
343
+ """Return rId of w:footerReference child of `type_` after removing it."""
344
+ footerReference = self.get_footerReference(type_)
345
+ if footerReference is None:
346
+ # -- should never happen, but to satisfy type-check and just in case --
347
+ raise ValueError("CT_SectPr has no footer reference")
348
+ rId = footerReference.rId
349
+ self.remove(footerReference)
350
+ return rId
351
+
352
+ def remove_headerReference(self, type_: WD_HEADER_FOOTER):
353
+ """Return rId of w:headerReference child of `type_` after removing it."""
354
+ headerReference = self.get_headerReference(type_)
355
+ if headerReference is None:
356
+ # -- should never happen, but to satisfy type-check and just in case --
357
+ raise ValueError("CT_SectPr has no header reference")
358
+ rId = headerReference.rId
359
+ self.remove(headerReference)
360
+ return rId
361
+
362
+ @property
363
+ def right_margin(self) -> Length | None:
364
+ """The value of the ``w:right`` attribute in the ``<w:pgMar>`` child element, as
365
+ a |Length| object, or |None| if either the element or the attribute is not
366
+ present."""
367
+ pgMar = self.pgMar
368
+ if pgMar is None:
369
+ return None
370
+ return pgMar.right
371
+
372
+ @right_margin.setter
373
+ def right_margin(self, value: Length | None):
374
+ pgMar = self.get_or_add_pgMar()
375
+ pgMar.right = value
376
+
377
+ @property
378
+ def start_type(self) -> WD_SECTION_START:
379
+ """The member of the ``WD_SECTION_START`` enumeration corresponding to the value
380
+ of the ``val`` attribute of the ``<w:type>`` child element, or
381
+ ``WD_SECTION_START.NEW_PAGE`` if not present."""
382
+ type = self.type
383
+ if type is None or type.val is None:
384
+ return WD_SECTION_START.NEW_PAGE
385
+ return type.val
386
+
387
+ @start_type.setter
388
+ def start_type(self, value: WD_SECTION_START | None):
389
+ if value is None or value is WD_SECTION_START.NEW_PAGE:
390
+ self._remove_type()
391
+ return
392
+ type = self.get_or_add_type()
393
+ type.val = value
394
+
395
+ @property
396
+ def titlePg_val(self) -> bool:
397
+ """Value of `w:titlePg/@val` or |False| if `./w:titlePg` is not present."""
398
+ titlePg = self.titlePg
399
+ if titlePg is None:
400
+ return False
401
+ return titlePg.val
402
+
403
+ @titlePg_val.setter
404
+ def titlePg_val(self, value: bool | None):
405
+ if value in [None, False]:
406
+ self._remove_titlePg()
407
+ else:
408
+ self.get_or_add_titlePg().val = True
409
+
410
+ @property
411
+ def top_margin(self) -> Length | None:
412
+ """The value of the ``w:top`` attribute in the ``<w:pgMar>`` child element, as a
413
+ |Length| object, or |None| if either the element or the attribute is not
414
+ present."""
415
+ pgMar = self.pgMar
416
+ if pgMar is None:
417
+ return None
418
+ return pgMar.top
419
+
420
+ @top_margin.setter
421
+ def top_margin(self, value: Length | None):
422
+ pgMar = self.get_or_add_pgMar()
423
+ pgMar.top = value
424
+
425
+
426
+ class CT_SectType(BaseOxmlElement):
427
+ """``<w:sectType>`` element, defining the section start type."""
428
+
429
+ val: WD_SECTION_START | None = OptionalAttribute( # pyright: ignore[reportAssignmentType]
430
+ "w:val", WD_SECTION_START
431
+ )
432
+
433
+
434
+ # == HELPERS =========================================================================
435
+
436
+
437
+ class _SectBlockElementIterator:
438
+ """Generates the block-item XML elements in a section.
439
+
440
+ A block-item element is a `CT_P` (paragraph) or a `CT_Tbl` (table).
441
+ """
442
+
443
+ _compiled_blocks_xpath: etree.XPath | None = None
444
+ _compiled_count_xpath: etree.XPath | None = None
445
+
446
+ def __init__(self, sectPr: CT_SectPr):
447
+ self._sectPr = sectPr
448
+
449
+ @classmethod
450
+ def iter_sect_block_elements(cls, sectPr: CT_SectPr) -> Iterator[BlockElement]:
451
+ """Generate each CT_P or CT_Tbl element within extents governed by `sectPr`."""
452
+ return cls(sectPr)._iter_sect_block_elements()
453
+
454
+ def _iter_sect_block_elements(self) -> Iterator[BlockElement]:
455
+ """Generate each CT_P or CT_Tbl element in section."""
456
+ # -- General strategy is to get all block (<w;p> and <w:tbl>) elements from
457
+ # -- start of doc to and including this section, then compute the count of those
458
+ # -- elements that came from prior sections and skip that many to leave only the
459
+ # -- ones in this section. It's possible to express this "between here and
460
+ # -- there" (end of prior section and end of this one) concept in XPath, but it
461
+ # -- would be harder to follow because there are special cases (e.g. no prior
462
+ # -- section) and the boundary expressions are fairly hairy. I also believe it
463
+ # -- would be computationally more expensive than doing it this straighforward
464
+ # -- albeit (theoretically) slightly wasteful way.
465
+
466
+ sectPr, sectPrs = self._sectPr, self._sectPrs
467
+ sectPr_idx = sectPrs.index(sectPr)
468
+
469
+ # -- count block items belonging to prior sections --
470
+ n_blks_to_skip = (
471
+ 0
472
+ if sectPr_idx == 0
473
+ else self._count_of_blocks_in_and_above_section(sectPrs[sectPr_idx - 1])
474
+ )
475
+
476
+ # -- and skip those in set of all blks from doc start to end of this section --
477
+ for element in self._blocks_in_and_above_section(sectPr)[n_blks_to_skip:]:
478
+ yield element
479
+
480
+ def _blocks_in_and_above_section(self, sectPr: CT_SectPr) -> Sequence[BlockElement]:
481
+ """All ps and tbls in section defined by `sectPr` and all prior sections."""
482
+ if self._compiled_blocks_xpath is None:
483
+ self._compiled_blocks_xpath = etree.XPath(
484
+ self._blocks_in_and_above_section_xpath,
485
+ namespaces=nsmap,
486
+ regexp=False,
487
+ )
488
+ xpath = self._compiled_blocks_xpath
489
+ # -- XPath callable results are Any (basically), so need a cast. --
490
+ return cast(Sequence[BlockElement], xpath(sectPr))
491
+
492
+ @lazyproperty
493
+ def _blocks_in_and_above_section_xpath(self) -> str:
494
+ """XPath expr for ps and tbls in context of a sectPr and all prior sectPrs."""
495
+ # -- "p_sect" is a section with sectPr located at w:p/w:pPr/w:sectPr.
496
+ # -- "body_sect" is a section with sectPr located at w:body/w:sectPr. The last
497
+ # -- section in the document is a "body_sect". All others are of the "p_sect"
498
+ # -- variety. "term" means "terminal", like the last p or tbl in the section.
499
+ # -- "pred" means "predecessor", like a preceding p or tbl in the section.
500
+
501
+ # -- the terminal block in a p-based sect is the p the sectPr appears in --
502
+ p_sect_term_block = "./parent::w:pPr/parent::w:p"
503
+ # -- the terminus of a body-based sect is the sectPr itself (not a block) --
504
+ body_sect_term = "self::w:sectPr[parent::w:body]"
505
+ # -- all the ps and tbls preceding (but not including) the context node --
506
+ pred_ps_and_tbls = "preceding-sibling::*[self::w:p | self::w:tbl]"
507
+
508
+ # -- p_sect_term_block and body_sect_term(inus) are mutually exclusive. So the
509
+ # -- result is either the union of nodes found by the first two selectors or the
510
+ # -- nodes found by the last selector, never both.
511
+ return (
512
+ # -- include the p containing a sectPr --
513
+ f"{p_sect_term_block}"
514
+ # -- along with all the blocks that precede it --
515
+ f" | {p_sect_term_block}/{pred_ps_and_tbls}"
516
+ # -- or all the preceding blocks if sectPr is body-based (last sectPr) --
517
+ f" | {body_sect_term}/{pred_ps_and_tbls}"
518
+ )
519
+
520
+ def _count_of_blocks_in_and_above_section(self, sectPr: CT_SectPr) -> int:
521
+ """All ps and tbls in section defined by `sectPr` and all prior sections."""
522
+ if self._compiled_count_xpath is None:
523
+ self._compiled_count_xpath = etree.XPath(
524
+ f"count({self._blocks_in_and_above_section_xpath})",
525
+ namespaces=nsmap,
526
+ regexp=False,
527
+ )
528
+ xpath = self._compiled_count_xpath
529
+ # -- numeric XPath results are always float, so need an int() conversion --
530
+ return int(cast(float, xpath(sectPr)))
531
+
532
+ @lazyproperty
533
+ def _sectPrs(self) -> Sequence[CT_SectPr]:
534
+ """All w:sectPr elements in document, in document-order."""
535
+ return self._sectPr.xpath(
536
+ "/w:document/w:body/w:p/w:pPr/w:sectPr | /w:document/w:body/w:sectPr",
537
+ )
docx/oxml/settings.py ADDED
@@ -0,0 +1,138 @@
1
+ """Custom element classes related to document settings."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING, Callable
6
+
7
+ from docx.oxml.xmlchemy import BaseOxmlElement, ZeroOrOne
8
+
9
+ if TYPE_CHECKING:
10
+ from docx.oxml.shared import CT_OnOff
11
+
12
+
13
+ class CT_Settings(BaseOxmlElement):
14
+ """`w:settings` element, root element for the settings part."""
15
+
16
+ get_or_add_evenAndOddHeaders: Callable[[], CT_OnOff]
17
+ _remove_evenAndOddHeaders: Callable[[], None]
18
+
19
+ _tag_seq = (
20
+ "w:writeProtection",
21
+ "w:view",
22
+ "w:zoom",
23
+ "w:removePersonalInformation",
24
+ "w:removeDateAndTime",
25
+ "w:doNotDisplayPageBoundaries",
26
+ "w:displayBackgroundShape",
27
+ "w:printPostScriptOverText",
28
+ "w:printFractionalCharacterWidth",
29
+ "w:printFormsData",
30
+ "w:embedTrueTypeFonts",
31
+ "w:embedSystemFonts",
32
+ "w:saveSubsetFonts",
33
+ "w:saveFormsData",
34
+ "w:mirrorMargins",
35
+ "w:alignBordersAndEdges",
36
+ "w:bordersDoNotSurroundHeader",
37
+ "w:bordersDoNotSurroundFooter",
38
+ "w:gutterAtTop",
39
+ "w:hideSpellingErrors",
40
+ "w:hideGrammaticalErrors",
41
+ "w:activeWritingStyle",
42
+ "w:proofState",
43
+ "w:formsDesign",
44
+ "w:attachedTemplate",
45
+ "w:linkStyles",
46
+ "w:stylePaneFormatFilter",
47
+ "w:stylePaneSortMethod",
48
+ "w:documentType",
49
+ "w:mailMerge",
50
+ "w:revisionView",
51
+ "w:trackRevisions",
52
+ "w:doNotTrackMoves",
53
+ "w:doNotTrackFormatting",
54
+ "w:documentProtection",
55
+ "w:autoFormatOverride",
56
+ "w:styleLockTheme",
57
+ "w:styleLockQFSet",
58
+ "w:defaultTabStop",
59
+ "w:autoHyphenation",
60
+ "w:consecutiveHyphenLimit",
61
+ "w:hyphenationZone",
62
+ "w:doNotHyphenateCaps",
63
+ "w:showEnvelope",
64
+ "w:summaryLength",
65
+ "w:clickAndTypeStyle",
66
+ "w:defaultTableStyle",
67
+ "w:evenAndOddHeaders",
68
+ "w:bookFoldRevPrinting",
69
+ "w:bookFoldPrinting",
70
+ "w:bookFoldPrintingSheets",
71
+ "w:drawingGridHorizontalSpacing",
72
+ "w:drawingGridVerticalSpacing",
73
+ "w:displayHorizontalDrawingGridEvery",
74
+ "w:displayVerticalDrawingGridEvery",
75
+ "w:doNotUseMarginsForDrawingGridOrigin",
76
+ "w:drawingGridHorizontalOrigin",
77
+ "w:drawingGridVerticalOrigin",
78
+ "w:doNotShadeFormData",
79
+ "w:noPunctuationKerning",
80
+ "w:characterSpacingControl",
81
+ "w:printTwoOnOne",
82
+ "w:strictFirstAndLastChars",
83
+ "w:noLineBreaksAfter",
84
+ "w:noLineBreaksBefore",
85
+ "w:savePreviewPicture",
86
+ "w:doNotValidateAgainstSchema",
87
+ "w:saveInvalidXml",
88
+ "w:ignoreMixedContent",
89
+ "w:alwaysShowPlaceholderText",
90
+ "w:doNotDemarcateInvalidXml",
91
+ "w:saveXmlDataOnly",
92
+ "w:useXSLTWhenSaving",
93
+ "w:saveThroughXslt",
94
+ "w:showXMLTags",
95
+ "w:alwaysMergeEmptyNamespace",
96
+ "w:updateFields",
97
+ "w:hdrShapeDefaults",
98
+ "w:footnotePr",
99
+ "w:endnotePr",
100
+ "w:compat",
101
+ "w:docVars",
102
+ "w:rsids",
103
+ "m:mathPr",
104
+ "w:attachedSchema",
105
+ "w:themeFontLang",
106
+ "w:clrSchemeMapping",
107
+ "w:doNotIncludeSubdocsInStats",
108
+ "w:doNotAutoCompressPictures",
109
+ "w:forceUpgrade",
110
+ "w:captions",
111
+ "w:readModeInkLockDown",
112
+ "w:smartTagType",
113
+ "sl:schemaLibrary",
114
+ "w:shapeDefaults",
115
+ "w:doNotEmbedSmartTags",
116
+ "w:decimalSymbol",
117
+ "w:listSeparator",
118
+ )
119
+ evenAndOddHeaders: CT_OnOff | None = ZeroOrOne( # pyright: ignore[reportAssignmentType]
120
+ "w:evenAndOddHeaders", successors=_tag_seq[48:]
121
+ )
122
+ del _tag_seq
123
+
124
+ @property
125
+ def evenAndOddHeaders_val(self) -> bool:
126
+ """Value of `w:evenAndOddHeaders/@w:val` or |None| if not present."""
127
+ evenAndOddHeaders = self.evenAndOddHeaders
128
+ if evenAndOddHeaders is None:
129
+ return False
130
+ return evenAndOddHeaders.val
131
+
132
+ @evenAndOddHeaders_val.setter
133
+ def evenAndOddHeaders_val(self, value: bool | None):
134
+ if value is None or value is False:
135
+ self._remove_evenAndOddHeaders()
136
+ return
137
+
138
+ self.get_or_add_evenAndOddHeaders().val = value