-
Notifications
You must be signed in to change notification settings - Fork 13
/
writer.py
executable file
·2630 lines (2218 loc) · 97.5 KB
/
writer.py
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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""
sphinx-docxwriter
~~~~~~~~~~~~~~~~~~~~~~~~~~
Modified custom docutils writer for OpenXML (docx).
Original code from 'sphinxcontrib-documentwriter'
:copyright:
Copyright 2011 by haraisao at gmail dot com
:license: MIT, see LICENSE for details.
sphinxcontrib-docxwriter
~~~~~~~~~~~~~~~~~~~~~~~~~~
Custom docutils writer for OpenXML (docx).
:copyright:
Copyright 2010 by shimizukawa at gmail dot com (Sphinx-users.jp).
:license: BSD, see LICENSE for details.
"""
import hashlib
import os
import posixpath
import re
import sys
from docutils import nodes, writers
from sphinx import addnodes, version_info
from sphinx.environment.adapters.toctree import TocTree
from sphinx.ext import graphviz
from sphinx.locale import admonitionlabels, _
from sphinx.util import logging
from docxbuilder import docx
from docxbuilder.highlight import DocxPygmentsBridge
# Is the PIL imaging library installed?
try:
from PIL import Image
except ImportError as exp:
Image = None
# Is the math libraries installed?
try:
import html.entities
import mathml2omml
import latex2mathml.converter
def latex2omml(latex):
mathml = latex2mathml.converter.convert(latex)
entities = {'dtdot': 0x22f1, 'midot': 0x00b7}
entities.update(html.entities.name2codepoint)
return docx.fromstring(mathml2omml.convert(mathml, entities))[0]
except ImportError:
def latex2omml(latex):
return docx.make_omath_run(latex)
# Utility functions
def is_sphinx_version_lower_than(version):
"""Return true if current Sphinx version is less than specified version
"""
major, minor, patch, _, _ = version_info
return (major, minor, patch) < version
def get_image_size(filename):
if Image is None:
raise RuntimeError(
'image size not fully specified and PIL not installed')
with Image.open(filename, 'r') as imageobj:
dpi = imageobj.info.get('dpi', (72, 72))
# dpi information can be (xdpi, ydpi) or xydpi
try:
iter(dpi)
except StopIteration:
dpi = (dpi, dpi)
width = imageobj.size[0]
height = imageobj.size[1]
cmperin = 2.54
return (width * cmperin / dpi[0], height * cmperin / dpi[1])
def convert_to_twip_size(size_with_unit, max_width):
if size_with_unit is None:
return None
if size_with_unit.endswith('%'):
return max_width * float(size_with_unit[:-1]) / 100
match = re.match(r'^(\d+(?:\.\d*)?)(\D*)$', size_with_unit)
if not match:
raise RuntimeError('Unexpected length unit: %s' % size_with_unit)
size = float(match.group(1))
unit = match.group(2)
if not unit:
unit = 'px'
twipperin = 1440.0
cmperin = 2.54
twippercm = twipperin / cmperin
ratio_map = {
'em': 12 * twipperin / 144, # TODO: Use Body Text font size
'ex': 12 * twipperin / 144,
'mm': twippercm / 10, 'cm': twippercm, 'in': twipperin,
'px': twipperin / 96, 'pt': twipperin / 72, 'pc': twipperin / 6,
}
ratio = ratio_map.get(unit)
if ratio is None:
raise RuntimeError('Unknown length unit: %s' % size_with_unit)
return size * ratio
def convert_to_cm_size(twip_size):
if twip_size is None:
return None
twipperin = 1440.0
cmperin = 2.54
return twip_size / twipperin * cmperin
def adjust_size(max_size, size, other_size):
if size > max_size:
ratio = max_size / size
return max_size, other_size * ratio
return size, other_size
def has_caption(image_node):
parent = image_node.parent
if not isinstance(parent, nodes.figure):
return False
index = parent.index(image_node)
caption_index = parent.first_child_matching_class(nodes.caption, index + 1)
return caption_index is not None
def is_first_class_child(node):
parent = node.parent
first_child_index = parent.first_child_matching_class(node.__class__)
return parent[first_child_index] is node
def make_bookmark_name(docname, node_id):
# The pattern Office enables to handle as a bookmark is ^(?!\d)\w{1,40}$
md5 = hashlib.md5(('%s/%s' % (docname, node_id)).encode('utf8'))
return '_' + md5.hexdigest()
def count_colspec(table_node):
tgroup = next(
(c for c in table_node.children if isinstance(c, nodes.tgroup)),
None)
if tgroup is None:
return 0
return sum((1 for c in tgroup.children if isinstance(c, nodes.colspec)))
#
# DocxWriter class for sphinx
#
class DocxWriter(writers.Writer):
supported = ('docx',)
settings_spec = ('No options here.', '', ())
settings_defaults = {}
output = None
def __init__(self, builder):
writers.Writer.__init__(self)
self.builder = builder
self._title = ''
self._author = ''
self._props = {}
def set_doc_properties(self, title, author, props):
self._title = title
self._author = author
self._props = props
def translate(self):
visitor = self.builder.create_translator(self.document, self.builder)
self.document.walkabout(visitor)
self.output = visitor.asbytes()
#
# DocxTranslator class for sphinx
#
def to_error_string(contents):
from xml.etree.ElementTree import tostring
func = lambda xml: tostring(xml, encoding='utf8').decode('utf8')
return type(contents).__name__ + '\n' + func(contents.to_xml())
class BookmarkElement(object):
pass
class ParagraphElement(object):
pass
class TableElement(object):
pass
class SdtElement(object):
pass
class BookmarkStart(BookmarkElement):
def __init__(self, bookmark_id, name):
self._id = bookmark_id
self._name = name
def to_xml(self):
return docx.make_bookmark_start(self._id, self._name)
class BookmarkEnd(BookmarkElement):
def __init__(self, bookmark_id):
self._id = bookmark_id
def to_xml(self):
return docx.make_bookmark_end(self._id)
class Paragraph(ParagraphElement):
DEFAULT_STYLE = 0
DOCXBUILDER_STYLE = 1
TABLE_BOTTOM_MARGIN_STYLE = 2
def __init__(self, indent=None, right_indent=None,
paragraph_style=None, style_kind=DEFAULT_STYLE, align=None,
keep_lines=False, keep_next=False,
list_info=None, preserve_space=False):
self._contents_stack = [[]]
self._text_style_stack = []
self._preserve_space = preserve_space
self._indent = indent
self._right_indent = right_indent
self._style = paragraph_style
self._style_kind = style_kind
self._align = align
self._keep_lines = keep_lines
self._keep_next = keep_next
self._list_info = list_info
@property
def is_default_style(self):
return self._style_kind == Paragraph.DEFAULT_STYLE
@property
def is_table_bottom_margin_style(self):
return self._style_kind == Paragraph.TABLE_BOTTOM_MARGIN_STYLE
def add_text(self, text):
style = {}
for text_style in self._text_style_stack:
style.update(text_style)
self._contents_stack[-1].append(
docx.make_run(text, style, self._preserve_space))
def add_break(self):
self._contents_stack[-1].append(docx.make_break_run())
def add_picture(self, rid, picid, filename, width, height, alt):
self._contents_stack[-1].append(
docx.make_inline_picture_run(
rid, picid, filename, width, height, alt))
def add_math(self, equation):
try:
self._contents_stack[-1].append(latex2omml(equation))
except:
self._contents_stack[-1].append(docx.make_omath_run(equation))
raise
def add_footnote_reference(self, footnote_id, style_id):
self._contents_stack[-1].append(
docx.make_footnote_reference(footnote_id, style_id))
def add_footnote_ref(self, style_id):
self._contents_stack[-1].append(docx.make_footnote_ref(style_id))
def add_textbox(self, style, color, contents, wrap_style=None):
self._contents_stack[-1].append(docx.make_vml_textbox(
style, color, (c.to_xml() for c in contents), wrap_style))
def push_style(self, text_style):
self._text_style_stack.append(text_style)
def pop_style(self):
self._text_style_stack.pop()
def begin_hyperlink(self, hyperlink_style_id):
self._contents_stack.append([])
self._text_style_stack.append(
docx.make_run_style_property(hyperlink_style_id))
def end_hyperlink(self, rid, anchor):
self._text_style_stack.pop()
if rid is not None or anchor is not None:
hyperlink = docx.make_hyperlink(rid, anchor)
hyperlink.extend(self._contents_stack.pop())
self._contents_stack[-1].append(hyperlink)
else:
run_list = self._contents_stack.pop()
self._contents_stack[-1].extend(run_list)
def keep_next(self):
self._keep_next = True
def extract_contents(self):
return self._contents_stack.pop()
def append(self, contents):
if isinstance(contents, Paragraph): # for nested line_block or list_item
self._contents_stack[-1].extend(contents.extract_contents())
elif isinstance(contents, BookmarkElement):
self._contents_stack[-1].append(contents.to_xml())
else:
raise RuntimeError('Can not append %s' % to_error_string(contents))
def to_xml(self):
para = docx.make_paragraph(
self._indent, self._right_indent, self._style, self._align,
self._keep_lines, self._keep_next, self._list_info)
para.extend(self._contents_stack[0])
return para
class Table(TableElement):
def __init__(
self, table_style, table_width, colsize_list, indent, align,
keep_next, cant_split_row, set_table_header, rotation_header_height,
fit_content):
self._style = table_style
self._table_width = table_width # (max table width(dax), table width(%))
self._colspec_list = []
self._colsize_list = colsize_list
self._indent = indent
self._align = align
self._stub = 0
self._head = []
self._body = []
self._current_target = self._body
self._current_row_index = -1
self._current_cell_index = -1
# 0: not set, 1: set header, 2: set first row, 3: set all rows
self._keep_next = keep_next
self._cant_split_row = cant_split_row
self._set_table_header = set_table_header
self._rotation_header_height = rotation_header_height
self._fit_content = fit_content
@property
def style(self):
return self._style
def keep_next(self):
'''Set keep_next to set first row. This method is supposed to be
called from only Table.make_cell.
'''
self._keep_next = 2
def add_colspec(self, colspec):
self._colspec_list.append(colspec)
def add_stub(self):
self._stub += 1
def start_head(self):
self._current_target = self._head
self._current_row_index = -1
def start_body(self):
self._current_target = self._body
self._current_row_index = -1
def add_row(self):
self._current_row_index += 1
if self._current_row_index < len(self._current_target):
row = self._current_target[self._current_row_index]
for index, cell in enumerate(row):
if cell is not None and cell[0] != 'continue':
self._current_cell_index = index - 1
break
else:
self._current_cell_index = index
else:
self._current_target.append([])
self._current_cell_index = -1
def add_cell(self, morerows, morecols):
row = self._current_target[self._current_row_index]
self._current_cell_index += (
Table._get_grid_span(row, self._current_cell_index))
if not self._current_cell_index < len(row):
row.append([None if morerows == 0 else 'restart', []])
cell_index = self._current_cell_index
start = cell_index + 1
row[start:start + morecols] = (None for _ in range(morecols))
for idx in range(1, morerows + 1):
if not self._current_row_index + idx < len(self._current_target):
self._current_target.append([])
row = self._current_target[self._current_row_index + idx]
if cell_index < len(row):
row[cell_index] = ['continue', []]
else:
row.extend([None, []] for _ in range(cell_index - len(row)))
row.append(['continue', []])
row[start:start + morecols] = (None for _ in range(morecols))
def current_cell_width(self):
if self._colspec_list:
self._reset_colsize_list()
self._colspec_list = []
index = self._current_cell_index
if not index < len(self._colsize_list):
return None
grid_span = Table._get_grid_span(
self._current_target[self._current_row_index], index)
ratio = sum(self._colsize_list[index:index + grid_span])
return int(self._table_width[0] * ratio)
def append(self, contents):
row = self._current_target[self._current_row_index]
row[self._current_cell_index][1].append(contents)
def to_xml(self):
table = docx.make_table(
self._style,
self._table_width[1],
self._indent, self._align,
(self._table_width[0] * col for col in self._colsize_list),
self._head, self._stub > 0)
for index, row in enumerate(self._head):
table.append(self.make_row(index, row, True))
for index, row in enumerate(self._body):
table.append(self.make_row(index, row, False))
return table
def make_row(self, index, row, is_head):
# Non-first header needs tblHeader to be applied first row style
set_tbl_header = is_head and (self._set_table_header or index > 0)
rotation = is_head and (self._rotation_header_height is not None)
if rotation:
height = self._rotation_header_height * self._table_width[0] // 100
else:
height = None
row_elem = docx.make_row(
index, is_head, self._cant_split_row, set_tbl_header, height)
keep_next = self._set_keep_next(is_head, index)
for idx, elem in enumerate(row):
if elem is None: # Merged with the previous cell
continue
vmerge, cell = elem
row_elem.append(
self.make_cell(idx, vmerge, cell, row, keep_next, rotation))
return row_elem
def make_cell(self, index, vmerge, cell, row, keep_next, rotation):
grid_span = Table._get_grid_span(row, index)
is_stub = index < self._stub
if self._fit_content:
cellsize = None
no_wrap = is_stub
else:
cellsize = sum(self._colsize_list[index:index + grid_span])
no_wrap = None
cell_elem = docx.make_cell(
index, is_stub, cellsize, grid_span, vmerge, rotation, no_wrap)
contents_types = (ParagraphElement, TableElement, SdtElement)
# The last element must be paragraph for Microsoft word
last = next(
(e for e in reversed(cell) if isinstance(e, contents_types)),
None)
if last is None or isinstance(last, TableElement):
cell.append(Paragraph())
if keep_next:
first = next(e for e in cell if isinstance(e, contents_types))
first.keep_next()
cell_elem.extend(c.to_xml() for c in cell)
return cell_elem
def _reset_colsize_list(self):
total = float(sum(self._colspec_list))
self._colsize_list = [colspec / total for colspec in self._colspec_list]
@staticmethod
def _get_grid_span(row, cell_index):
grid_span = 1
for cell in row[cell_index + 1:]:
if cell is not None:
break
grid_span += 1
return grid_span
def _set_keep_next(self, is_head, index):
if self._keep_next == 0:
return False
if self._keep_next == 1:
return is_head
if self._keep_next == 2:
return (is_head or not self._head) and index == 0
if self._keep_next == 3:
return True
return False
class TOC(SdtElement):
def __init__(
self, title, title_style_id, maxlevel, bookmark, paragraph_width,
outlines):
self._title = title
self._title_style_id = title_style_id
self._maxlevel = maxlevel
self._bookmark = bookmark
self._paragraph_width = paragraph_width
self._outlines = outlines
def to_xml(self):
return docx.make_table_of_contents(
self._title, self._title_style_id,
self._maxlevel, self._bookmark, self._paragraph_width,
self._outlines)
class SectionPropertyManager(object):
def __init__(self, default_orient, sect_props):
self._default_orient = default_orient
self._sect_props = sect_props
self._current_orient = self._default_orient
self._current_sect_index = {'portrait': 0, 'landscape': 0}
self._last_section = None
self._no_title_page = [False, False] # [current, last]
def get_current_section(self):
orient, index = self._current_section
return self._sect_props[orient][index]
def get_last_section(self):
if self._last_section is None:
orient, index = self._current_section
no_title_page = self._no_title_page[0]
else:
orient, index = self._last_section
no_title_page = self._no_title_page[1]
return self._sect_props[orient][index], no_title_page
def rotate_to(self, orient=None):
if orient is None:
orient = self._default_orient
if self._current_orient != orient:
if self._last_section is not None:
# last_orient must be equal to orient, then addition of section
# property is enable to be postponed
self._last_section = None
self._no_title_page[0] = self._no_title_page[1]
else:
self._last_section = self._current_section
self._no_title_page[1] = self._no_title_page[0]
self._no_title_page[0] = True
self._current_orient = orient
def set_current_section(self, index, orient=None):
if orient is None:
orient = self._default_orient
if index >= len(self._sect_props[orient]):
raise RuntimeError("Not found %dth %s section" % (index, orient))
if self._last_section is None:
self._last_section = self._current_section
self._no_title_page[1] = self._no_title_page[0]
self._no_title_page[0] = False
else:
if self._last_section == (orient, index):
self._last_section = None
self._no_title_page[0] = self._no_title_page[1]
else:
self._no_title_page[0] = False
self._current_orient = orient
self._current_sect_index[orient] = index
def pop_last_section(self):
if self._last_section is None:
return None
orient, index = self._last_section
section_prop = self._sect_props[orient][index]
self._last_section = None
return section_prop, self._no_title_page[1]
@property
def _current_section(self):
current_orient = self._current_orient
current_index = self._current_sect_index[current_orient]
return (current_orient, current_index)
class Document(object):
def __init__(self, body, default_orient, sect_props):
self._body = body
self._add_pagebreak = False
self._section = SectionPropertyManager(default_orient, sect_props)
self._last_table_bottom_margin_index = None
def add_pagebreak(self):
self._add_pagebreak = True
def add_last_section_property(self):
section_prop, no_title_page = self._section.get_last_section()
section_prop = docx.copy_section_property(section_prop, no_title_page)
self._body.append(section_prop)
def set_page_oriented(self, orient=None):
self._section.rotate_to(orient)
def set_section(self, index, orient):
self._section.set_current_section(index, orient)
def get_current_page_width(self):
return docx.get_contents_width(self._section.get_current_section())
def get_current_page_height(self):
return docx.get_contents_height(self._section.get_current_section())
def append(self, contents):
xml = contents.to_xml()
if not isinstance(contents, BookmarkElement):
self._add_section_prop_if_necessary()
if self._add_pagebreak:
self._remove_last_table_bottom_margin_paragraph()
docx.add_page_break_before_to_first_paragraph(xml)
self._add_pagebreak = False
if Document._is_table_bottom_margin_paragraph(contents):
self._last_table_bottom_margin_index = len(self._body)
else:
self._last_table_bottom_margin_index = None
self._body.append(xml)
def _remove_last_table_bottom_margin_paragraph(self):
if self._last_table_bottom_margin_index is not None:
del self._body[self._last_table_bottom_margin_index]
self._last_table_bottom_margin_index = None
def _add_section_prop_if_necessary(self):
section = self._section.pop_last_section()
if section is None:
return
self._remove_last_table_bottom_margin_paragraph()
section_prop, no_title_page = section
section_prop = docx.copy_section_property(section_prop, no_title_page)
self._body.append(docx.make_section_prop_paragraph(section_prop))
@staticmethod
def _is_table_bottom_margin_paragraph(contents):
return (isinstance(contents, Paragraph)
and contents.is_table_bottom_margin_style)
class Raw(object):
def __init__(self, raw_xml):
self._raw_xml = raw_xml
def to_xml(self):
return self._raw_xml
class LiteralBlock(ParagraphElement):
def __init__(self, highlighted, style_id, indent, right_indent, keep_lines):
self._args = [highlighted, style_id, indent, right_indent, keep_lines]
self._keep_next = False
def keep_next(self):
self._keep_next = True
def to_xml(self):
highlighted, style_id, indent, right_indent, keep_lines = self._args
highlighted = docx.fromstring(highlighted)[0]
para = docx.make_paragraph(
indent, right_indent, style_id, None,
keep_lines, self._keep_next, None,
properties=docx.get_paragraph_properties(highlighted))
para.extend(docx.get_paragraph_contents(highlighted))
return para
class LiteralBlockTable(TableElement):
def __init__(
self, highlighted, top_space,
style_id, table_width, indent, keep_next):
self._args = [highlighted, top_space, style_id, table_width, indent]
# 0: not set, 1: set header, 2: set first row, 3: set all rows
self._keep_next = 3 if keep_next else 0
def keep_next(self):
self._keep_next = max(2, self._keep_next)
def to_xml(self):
highlighted, top_space, style_id, table_width, indent = self._args
org_tbl = docx.fromstring(highlighted)[0]
table = docx.make_table(
None, table_width[1], indent, None,
[table_width[0] * 0.1, table_width[0] * 0.9], False, True,
properties=[
docx.make_table_cell_spacing_property(None),
docx.make_table_cell_margin_property(
top=None, left=108, bottom=None, right=108),
])
no_spacing = docx.make_paragraph_spacing_property(before=0, after=0)
lineno_border = docx.make_paragraph_border_property(
top=None, bottom=None, left=None, right=None)
middle_border = docx.make_paragraph_border_property(
top=None, bottom=None)
last_index = len(org_tbl) - 1
if last_index == 0:
border = {0: docx.make_paragraph_border_property()}
else:
border = {
0: docx.make_paragraph_border_property(bottom=None),
last_index: docx.make_paragraph_border_property(top=None),
}
for index, org_row in enumerate(org_tbl):
row = docx.make_row(index, False, False, False, None)
if index == 0:
spacing = docx.make_paragraph_spacing_property(
before=(top_space or 0), after=0)
else:
spacing = no_spacing
cell1 = docx.make_cell(
0, True, None, 1, None, False, no_wrap=True, valign='top')
keep_next = self._is_keep_next(index)
para1_props = docx.get_paragraph_properties(org_row[0][0])
para1_props.extend([spacing, lineno_border])
para1 = docx.make_paragraph(
None, None, style_id, 'right', False, keep_next, None,
properties=para1_props)
para1.extend(docx.get_paragraph_contents(org_row[0][0]))
cell1.append(para1)
row.append(cell1)
cell2 = docx.make_cell(
1, False, 0.99, 1, None, False, no_wrap=False, valign='top')
para2_props = docx.get_paragraph_properties(org_row[1][0])
para2_props.extend([no_spacing, border.get(index, middle_border)])
para2 = docx.make_paragraph(
None, None, style_id, None, False, False, None,
properties=para2_props)
para2.extend(docx.get_paragraph_contents(org_row[1][0]))
cell2.append(para2)
row.append(cell2)
table.append(row)
return table
def _is_keep_next(self, index):
return (self._keep_next == 2 and index == 0) or (self._keep_next == 3)
class MathBlock(ParagraphElement):
def __init__(self, equations, indent, right_indent, style_id):
self._equations = equations
self._indent = indent
self._right_indent = right_indent
self._style_id = style_id
self._keep_next = False
def keep_next(self):
self._keep_next = True
def to_xml(self):
para = docx.make_paragraph(
self._indent, self._right_indent, self._style_id, None,
False, self._keep_next, None)
para.append(docx.make_omath_paragraph(self._equations))
return para
class ContentsList(object):
def __init__(self):
self._contents_list = []
def append(self, contents):
self._contents_list.append(contents)
def __iter__(self):
return iter(self._contents_list)
def __len__(self):
return len(self._contents_list)
def __getitem__(self, key):
return self._contents_list[key]
class FixedTopParagraphList(ContentsList):
def __init__(self, top_paragraph):
super(FixedTopParagraphList, self).__init__()
self._top_paragraph = top_paragraph
self._available_top_paragraph = True
super(FixedTopParagraphList, self).append(self._top_paragraph)
def append(self, contents):
if len(self) == 1:
if isinstance(contents, BookmarkElement):
self._top_paragraph.append(contents)
return
if self._available_top_paragraph:
self._available_top_paragraph = False
if isinstance(contents, Paragraph) and contents.is_default_style:
self._top_paragraph.append(contents)
return
super(FixedTopParagraphList, self).append(contents)
class DefinitionListItem(ContentsList):
def __init__(self):
super(DefinitionListItem, self).__init__()
self._last_term = None
@property
def last_term(self):
return self._last_term
def add_term(self, term_paragraph):
self._contents_list.append(term_paragraph)
self._last_term = term_paragraph
class Contenxt(object):
def __init__(self, indent, right_indent, width, list_level):
self.indent = indent
self.right_indent = right_indent
self.width = width
self.list_level = list_level
@property
def paragraph_width(self):
return self.width - self.indent - self.right_indent
class DocxTranslator(nodes.NodeVisitor):
# pylint: disable=too-many-public-methods
"""Visitor to generate a docx document.
:var builder: Sphinx builder.
"""
TABLE_BOTTOM_MARGIN_STYLE_NAME = 'Table Bottom Margin'
def __init__(self, document, builder):
nodes.NodeVisitor.__init__(self, document)
self._builder = builder
self.builder = self._builder # Needs for graphviz.render_dot
stylefile = builder.config['docx_style']
if stylefile:
stylefile = os.path.join(builder.confdir, os.path.join(stylefile))
else: # Use default style file
stylefile = os.path.join(
os.path.dirname(__file__), 'docx/style.docx')
self._docx = docx.DocxComposer(
stylefile, builder.config['docx_coverpage'])
default_orient, sect_props = self._docx.get_section_properties()
self._doc_stack = []
self._doc_stack.append(
Document(self._docx.docbody, default_orient, sect_props))
self._docname_stack = []
self._section_level = 0
self._ctx_stack = [
Contenxt(0, 0, self._doc_stack[-1].get_current_page_width(), 0)
]
self._relationship_stack = ['document']
self._line_block_level = 0
self._list_id_stack = []
self._basic_indent = self._docx.get_indent('List Paragraph', 320)
self._language = builder.config.highlight_language
self._linenothreshold = sys.maxsize
if is_sphinx_version_lower_than((1, 8, 0)):
trim_doctest_flags = builder.config.trim_doctest_flags
else:
trim_doctest_flags = None
self._highlighter = DocxPygmentsBridge(
'html', builder.config.pygments_style, trim_doctest_flags)
self._numsec_map = builder.make_numsec_map()
self._numfig_map = builder.make_numfig_map()
self._bookmark_id = self._docx.get_max_bookmark_id()
self._bookmark_id_map = {} # bookmark name => BookmarkStart id
self._logger = logging.getLogger('docxbuilder')
self._create_docxbuilder_styles()
self._bullet_list_id = self._docx.get_bullet_list_num_id('List Bullet')
bullet_list_indents = self._docx.get_numbering_left('List Bullet')
if not bullet_list_indents:
self._logger.info('List Bullet style has no numbering style')
self._bullet_list_indents = bullet_list_indents
number_list_indents = self._docx.get_numbering_left('List Number')
if not number_list_indents:
self._logger.info('List Number style has no numbering style')
self._number_list_indent = 0
else:
self._number_list_indent = number_list_indents[0]
self._default_paragraph_style_stack = []
self._append_default_paragraph_style('Body Text')
def asbytes(self):
props = self._builder.doc_properties
props, invalids = docx.classify_properties(props)
for key, reason in invalids.items():
self._logger.warning(
'invalid property is found in docx_documents "%s"(%s)'
% (key, reason))
props['core'].setdefault(
'language', self._builder.config.language or 'en')
return self._docx.asbytes(self._builder.config.docx_update_fields, props)
def _get_custom_style(self, classes, style_type):
custom_styles = self._builder.config.docx_style_names
for cls in classes:
style_name = custom_styles.get(cls)
if style_name is None:
continue
if self._docx.get_style_id(style_name, style_type) is None:
continue
return style_name
return None
def _get_custom_charcter_styles(self, classes):
custom_styles = self._builder.config.docx_style_names
return (custom_styles[c] for c in classes if c in custom_styles)
def _append_default_paragraph_style(self, style_name):
self._default_paragraph_style_stack.append(
self._docx.get_style_id(style_name, 'paragraph'))
def _pop_default_paragraph_style(self):
self._default_paragraph_style_stack.pop()
def _pop_and_append(self):
contents = self._doc_stack.pop()
if isinstance(contents, ContentsList):
for content in contents:
self._doc_stack[-1].append(content)
else:
self._doc_stack[-1].append(contents)
def _append_bookmark_start(self, ids):
docname = self._docname_stack[-1]
for node_id in ids:
name = make_bookmark_name(docname, node_id)
self._bookmark_id += 1
self._bookmark_id_map[name] = self._bookmark_id
self._doc_stack[-1].append(BookmarkStart(self._bookmark_id, name))
def _append_bookmark_end(self, ids):
docname = self._docname_stack[-1]
for node_id in ids:
name = make_bookmark_name(docname, node_id)
bookmark_id = self._bookmark_id_map.pop(name, None)
if bookmark_id is None:
continue
self._doc_stack[-1].append(BookmarkEnd(bookmark_id))
def _make_paragraph(
self, indent=None, right_indent=None, style=None, align=None,
keep_lines=False, keep_next=False,
list_info=None, preserve_space=False):
if style is not None:
style_id = self._docx.get_style_id(style, 'paragraph')
if style == DocxTranslator.TABLE_BOTTOM_MARGIN_STYLE_NAME:
style_kind = Paragraph.TABLE_BOTTOM_MARGIN_STYLE
else:
style_kind = Paragraph.DOCXBUILDER_STYLE
else:
style_id = self._default_paragraph_style_stack[-1]
style_kind = Paragraph.DEFAULT_STYLE
if align == 'default':
align = 'center'
return Paragraph(
indent, right_indent, style_id, style_kind, align,
keep_lines, keep_next, list_info, preserve_space)
def _append_table(
self, table_style, table_width, colsize_list, is_indent, align=None,
in_single_page=False, row_splittable=True,
header_in_all_page=False, rotation_header_height=None,
fit_content=False, is_fixed_width=True):
self._append_default_paragraph_style(None)
table_style_id = self._docx.get_style_id(table_style, 'table')
indent = self._ctx_stack[-1].indent if is_indent else 0
if align == 'default':
align = 'center'
keep_next = 3 if in_single_page else 1
max_table_width = table_width
if is_fixed_width:
table_width = float(table_width) / self._ctx_stack[-1].width
else:
table_width = None
tbl = Table(
table_style_id,
(max_table_width, table_width),
colsize_list, indent, align,
keep_next, not row_splittable, header_in_all_page,
rotation_header_height, fit_content)
self._doc_stack.append(tbl)
self._append_new_ctx(indent=0, right_indent=0, width=table_width)
return tbl
def _pop_and_append_table(self):
self._ctx_stack.pop()
self._pop_and_append()
# Append a paragaph as a margin between the table and the next element
self._doc_stack[-1].append(
self._make_paragraph(
style=DocxTranslator.TABLE_BOTTOM_MARGIN_STYLE_NAME))
self._pop_default_paragraph_style()
def _add_table_cell(self, morerows=0, morecols=0):
tbl = self._doc_stack[-1]
tbl.add_cell(morerows, morecols)
width = tbl.current_cell_width()