This repository was archived by the owner on Jan 7, 2024. It is now read-only.
forked from holli-holzer/python-docx
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtext.py
More file actions
431 lines (378 loc) · 12.7 KB
/
Copy pathtext.py
File metadata and controls
431 lines (378 loc) · 12.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
# encoding: utf-8
"""
Custom element classes related to text, such as paragraph (CT_P) and runs
(CT_R).
"""
from ..enum.text import WD_ALIGN_PARAGRAPH, WD_UNDERLINE
from .ns import qn
from .simpletypes import ST_BrClear, ST_BrType
from .xmlchemy import (
BaseOxmlElement, OptionalAttribute, OxmlElement, RequiredAttribute,
ZeroOrMore, ZeroOrOne
)
class CT_Br(BaseOxmlElement):
"""
``<w:br>`` element, indicating a line, page, or column break in a run.
"""
type = OptionalAttribute('w:type', ST_BrType)
clear = OptionalAttribute('w:clear', ST_BrClear)
class CT_Jc(BaseOxmlElement):
"""
``<w:jc>`` element, specifying paragraph justification.
"""
val = RequiredAttribute('w:val', WD_ALIGN_PARAGRAPH)
class CT_P(BaseOxmlElement):
"""
``<w:p>`` element, containing the properties and text for a paragraph.
"""
pPr = ZeroOrOne('w:pPr')
r = ZeroOrMore('w:r')
def _insert_pPr(self, pPr):
self.insert(0, pPr)
return pPr
def add_p_before(self):
"""
Return a new ``<w:p>`` element inserted directly prior to this one.
"""
new_p = OxmlElement('w:p')
self.addprevious(new_p)
return new_p
@property
def alignment(self):
"""
The value of the ``<w:jc>`` grandchild element or |None| if not
present.
"""
pPr = self.pPr
if pPr is None:
return None
return pPr.alignment
@alignment.setter
def alignment(self, value):
pPr = self.get_or_add_pPr()
pPr.alignment = value
def clear_content(self):
"""
Remove all child elements, except the ``<w:pPr>`` element if present.
"""
for child in self[:]:
if child.tag == qn('w:pPr'):
continue
self.remove(child)
def set_sectPr(self, sectPr):
"""
Unconditionally replace or add *sectPr* as a grandchild in the
correct sequence.
"""
pPr = self.get_or_add_pPr()
pPr._remove_sectPr()
pPr._insert_sectPr(sectPr)
@property
def style(self):
"""
String contained in w:val attribute of ./w:pPr/w:pStyle grandchild,
or |None| if not present.
"""
pPr = self.pPr
if pPr is None:
return None
return pPr.style
@style.setter
def style(self, style):
pPr = self.get_or_add_pPr()
pPr.style = style
class CT_PPr(BaseOxmlElement):
"""
``<w:pPr>`` element, containing the properties for a paragraph.
"""
__child_sequence__ = (
'w:pStyle', 'w:keepNext', 'w:keepLines', 'w:pageBreakBefore',
'w:framePr', 'w:widowControl', 'w:numPr', 'w:suppressLineNumbers',
'w:pBdr', 'w:shd', 'w:tabs', 'w:suppressAutoHyphens', 'w:kinsoku',
'w:wordWrap', 'w:overflowPunct', 'w:topLinePunct', 'w:autoSpaceDE',
'w:autoSpaceDN', 'w:bidi', 'w:adjustRightInd', 'w:snapToGrid',
'w:spacing', 'w:ind', 'w:contextualSpacing', 'w:mirrorIndents',
'w:suppressOverlap', 'w:jc', 'w:textDirection', 'w:textAlignment',
'w:textboxTightWrap', 'w:outlineLvl', 'w:divId', 'w:cnfStyle',
'w:rPr', 'w:sectPr', 'w:pPrChange'
)
pStyle = ZeroOrOne('w:pStyle')
numPr = ZeroOrOne('w:numPr', successors=__child_sequence__[7:])
jc = ZeroOrOne('w:jc', successors=__child_sequence__[27:])
sectPr = ZeroOrOne('w:sectPr', successors=('w:pPrChange',))
def _insert_pStyle(self, pStyle):
self.insert(0, pStyle)
return pStyle
@property
def alignment(self):
"""
The value of the ``<w:jc>`` child element or |None| if not present.
"""
jc = self.jc
if jc is None:
return None
return jc.val
@alignment.setter
def alignment(self, value):
if value is None:
self._remove_jc()
return
jc = self.get_or_add_jc()
jc.val = value
@property
def style(self):
"""
String contained in <w:pStyle> child, or None if that element is not
present.
"""
pStyle = self.pStyle
if pStyle is None:
return None
return pStyle.val
@style.setter
def style(self, style):
"""
Set val attribute of <w:pStyle> child element to *style*, adding a
new element if necessary. If *style* is |None|, remove the <w:pStyle>
element if present.
"""
if style is None:
self._remove_pStyle()
return
pStyle = self.get_or_add_pStyle()
pStyle.val = style
class CT_R(BaseOxmlElement):
"""
``<w:r>`` element, containing the properties and text for a run.
"""
rPr = ZeroOrOne('w:rPr')
t = ZeroOrMore('w:t')
br = ZeroOrMore('w:br')
cr = ZeroOrMore('w:cr')
tab = ZeroOrMore('w:tab')
drawing = ZeroOrMore('w:drawing')
def _insert_rPr(self, rPr):
self.insert(0, rPr)
return rPr
def add_t(self, text):
"""
Return a newly added ``<w:t>`` element containing *text*.
"""
t = self._add_t(text=text)
if len(text.strip()) < len(text):
t.set(qn('xml:space'), 'preserve')
return t
def add_drawing(self, inline_or_anchor):
"""
Return a newly appended ``CT_Drawing`` (``<w:drawing>``) child
element having *inline_or_anchor* as its child.
"""
drawing = self._add_drawing()
drawing.append(inline_or_anchor)
return drawing
def clear_content(self):
"""
Remove all child elements except the ``<w:rPr>`` element if present.
"""
content_child_elms = self[1:] if self.rPr is not None else self[:]
for child in content_child_elms:
self.remove(child)
@property
def style(self):
"""
String contained in w:val attribute of <w:rStyle> grandchild, or
|None| if that element is not present.
"""
rPr = self.rPr
if rPr is None:
return None
return rPr.style
@style.setter
def style(self, style):
"""
Set the character style of this <w:r> element to *style*. If *style*
is None, remove the style element.
"""
rPr = self.get_or_add_rPr()
rPr.style = style
@property
def text(self):
"""
A string representing the textual content of this run, with content
child elements like ``<w:tab/>`` translated to their Python
equivalent.
"""
text = ''
for child in self:
if child.tag == qn('w:t'):
t_text = child.text
text += t_text if t_text is not None else ''
elif child.tag == qn('w:tab'):
text += '\t'
elif child.tag in (qn('w:br'), qn('w:cr')):
text += '\n'
return text
@text.setter
def text(self, text):
self.clear_content()
_RunContentAppender.append_to_run_from_text(self, text)
@property
def underline(self):
"""
String contained in w:val attribute of ./w:rPr/w:u grandchild, or
|None| if not present.
"""
rPr = self.rPr
if rPr is None:
return None
return rPr.underline
@underline.setter
def underline(self, value):
rPr = self.get_or_add_rPr()
rPr.underline = value
class CT_RPr(BaseOxmlElement):
"""
``<w:rPr>`` element, containing the properties for a run.
"""
rStyle = ZeroOrOne('w:rStyle', successors=('w:rPrChange',))
b = ZeroOrOne('w:b', successors=('w:rPrChange',))
bCs = ZeroOrOne('w:bCs', successors=('w:rPrChange',))
caps = ZeroOrOne('w:caps', successors=('w:rPrChange',))
cs = ZeroOrOne('w:cs', successors=('w:rPrChange',))
dstrike = ZeroOrOne('w:dstrike', successors=('w:rPrChange',))
emboss = ZeroOrOne('w:emboss', successors=('w:rPrChange',))
i = ZeroOrOne('w:i', successors=('w:rPrChange',))
iCs = ZeroOrOne('w:iCs', successors=('w:rPrChange',))
imprint = ZeroOrOne('w:imprint', successors=('w:rPrChange',))
noProof = ZeroOrOne('w:noProof', successors=('w:rPrChange',))
oMath = ZeroOrOne('w:oMath', successors=('w:rPrChange',))
outline = ZeroOrOne('w:outline', successors=('w:rPrChange',))
rtl = ZeroOrOne('w:rtl', successors=('w:rPrChange',))
shadow = ZeroOrOne('w:shadow', successors=('w:rPrChange',))
smallCaps = ZeroOrOne('w:smallCaps', successors=('w:rPrChange',))
snapToGrid = ZeroOrOne('w:snapToGrid', successors=('w:rPrChange',))
specVanish = ZeroOrOne('w:specVanish', successors=('w:rPrChange',))
strike = ZeroOrOne('w:strike', successors=('w:rPrChange',))
u = ZeroOrOne('w:u', successors=('w:rPrChange',))
vanish = ZeroOrOne('w:vanish', successors=('w:rPrChange',))
webHidden = ZeroOrOne('w:webHidden', successors=('w:rPrChange',))
@property
def style(self):
"""
String contained in <w:rStyle> child, or None if that element is not
present.
"""
rStyle = self.rStyle
if rStyle is None:
return None
return rStyle.val
@style.setter
def style(self, style):
"""
Set val attribute of <w:rStyle> child element to *style*, adding a
new element if necessary. If *style* is |None|, remove the <w:rStyle>
element if present.
"""
if style is None:
self._remove_rStyle()
elif self.rStyle is None:
self._add_rStyle(val=style)
else:
self.rStyle.val = style
@property
def underline(self):
"""
Underline type specified in <w:u> child, or None if that element is
not present.
"""
u = self.u
if u is None:
return None
return u.val
@underline.setter
def underline(self, value):
self._remove_u()
if value is not None:
u = self._add_u()
u.val = value
class CT_Text(BaseOxmlElement):
"""
``<w:t>`` element, containing a sequence of characters within a run.
"""
class CT_Underline(BaseOxmlElement):
"""
``<w:u>`` element, specifying the underlining style for a run.
"""
@property
def val(self):
"""
The underline type corresponding to the ``w:val`` attribute value.
"""
val = self.get(qn('w:val'))
underline = WD_UNDERLINE.from_xml(val)
if underline == WD_UNDERLINE.SINGLE:
return True
if underline == WD_UNDERLINE.NONE:
return False
return underline
@val.setter
def val(self, value):
# works fine without these two mappings, but only because True == 1
# and False == 0, which happen to match the mapping for WD_UNDERLINE
# .SINGLE and .NONE respectively.
if value is True:
value = WD_UNDERLINE.SINGLE
elif value is False:
value = WD_UNDERLINE.NONE
val = WD_UNDERLINE.to_xml(value)
self.set(qn('w:val'), val)
class _RunContentAppender(object):
"""
Service object that knows how to translate a Python string into run
content elements appended to a specified ``<w:r>`` element. Contiguous
sequences of regular characters are appended in a single ``<w:t>``
element. Each tab character ('\t') causes a ``<w:tab/>`` element to be
appended. Likewise a newline or carriage return character ('\n', '\r')
causes a ``<w:cr>`` element to be appended.
"""
def __init__(self, r):
self._r = r
self._bfr = []
@classmethod
def append_to_run_from_text(cls, r, text):
"""
Create a "one-shot" ``_RunContentAppender`` instance and use it to
append the run content elements corresponding to *text* to the
``<w:r>`` element *r*.
"""
appender = cls(r)
appender.add_text(text)
def add_text(self, text):
"""
Append the run content elements corresponding to *text* to the
``<w:r>`` element of this instance.
"""
for char in text:
self.add_char(char)
self.flush()
def add_char(self, char):
"""
Process the next character of input through the translation finite
state maching (FSM). There are two possible states, buffer pending
and not pending, but those are hidden behind the ``.flush()`` method
which must be called at the end of text to ensure any pending
``<w:t>`` element is written.
"""
if char == '\t':
self.flush()
self._r.add_tab()
elif char in '\r\n':
self.flush()
self._r.add_br()
else:
self._bfr.append(char)
def flush(self):
text = ''.join(self._bfr)
if text:
self._r.add_t(text)
del self._bfr[:]