-
Notifications
You must be signed in to change notification settings - Fork 4
/
docxwriter.py
1613 lines (1328 loc) · 43.3 KB
/
docxwriter.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.
"""
import re
from docutils import nodes, writers, utils
from sphinx import addnodes
from sphinx import highlighting
from sphinx.locale import admonitionlabels, versionlabels, _
from sphinx.ext import graphviz
import docx
import urllib2
import sys
import os
import zipfile
import tempfile
from lxml import etree
from docxhighlight import *
#
# Is the PIL imaging library installed?
try:
import PIL.Image
except ImportError:
try: # sometimes PIL modules are put in PYTHONPATH's root
import Image
class PIL(object): pass # dummy wrapper
PIL.Image = Image
except ImportError:
PIL = None
#
# Logging for debugging
#
import logging
logging.basicConfig(filename='docx.log', filemode='w', level=logging.INFO,
format="%(asctime)-15s %(message)s")
logger = logging.getLogger('docx')
def dprint(_func=None, **kw):
f = sys._getframe(1)
if kw:
text = ', '.join('%s = %s' % (k, v) for k, v in kw.items())
else:
try:
text = dict((k, repr(v)) for k, v in f.f_locals.items()
if k != 'self')
text = unicode(text)
except:
text = ''
if _func is None:
_func = f.f_code.co_name
logger.info(' '.join([_func, text]))
# Utility functions
def remove_items(src, target):
for x in target:
src.remove(x)
def get_items_list(src):
result = []
for x in src:
if x and x != [[]]:
result.append(x)
return result
def findElement(elem, tag):
res = None
if not elem:
return res
for x in elem:
try:
if x.tagname == tag:
return x
else:
res = findElement(x.children, tag)
except:
res = None
return res
def get_toc_maxdepth(builder, docname):
toc_maxdepth = 0
try:
toc = findElement(builder.env.tocs[docname], 'toctree')
if toc:
toc_maxdepth = toc['maxdepth']
except:
toc_maxdepth = 0
return toc_maxdepth
#
# 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.docx = docx.DocxComposer()
self.title = self.builder.config['docx_title']
self.subject = self.builder.config['docx_subject']
self.creator = self.builder.config['docx_creator']
self.company = self.builder.config['docx_company']
self.category = self.builder.config['docx_category']
self.descriptions = self.builder.config['docx_descriptions']
self.keywords = self.builder.config['docx_keywords']
try:
self.coverpage = self.builder.config['docx_coverpage']
except:
self.coverpage = True
stylefile = self.builder.config['docx_style']
if stylefile:
self.docx.new_document(stylefile)
else:
self.docx.new_document('style.docx')
def save(self, filename):
self.docx.set_coverpage(self.coverpage)
self.docx.set_props(title=self.title,
subject=self.subject,
creator=self.creator,
company=self.company,
category=self.category,
descriptions=self.descriptions,
keywords=self.keywords)
self.docx.save(filename)
def translate(self):
visitor = DocxTranslator(self.document, self.builder, self.docx)
self.document.walkabout(visitor)
self.output = '' # visitor.body
#
# DocxTranslator class for sphinx
#
class DocxTranslator(nodes.NodeVisitor):
def __init__(self, document, builder, docx):
self.builder = builder
self.docx = docx
nodes.NodeVisitor.__init__(self, document)
self.states = [[]]
self.list_style = []
self.sectionlevel = 0
self.table = None
self.line_block_level = 0
self.list_item_flushed = False
self.current_block = []
self.list_level = 0
self.block_level = 0
self.num_list_id = docx.get_max_numbering_id() + 1
self.max_num_list_id = self.num_list_id
self.enum_prefix_style = []
self.field_name = None
self.image_count = 0
self.image_dict = {}
self.embedded_file_list = []
self.admonition_body = None
self.current_field_list = None
self.current_option_list = None
self.literal_block_lang = None
self.highlighter = DocxPygmentsBridge(
'html', builder.config.pygments_style, builder.config.trim_doctest_flags)
self.option = []
def add_text(self, text):
'''
Add text in states
'''
dprint()
if not self.states:
if self.states[-1] is not []:
self.states.append([])
self.states[-1].append(text)
def add_linebreak(self):
'''
Add linebreak-text(:br) in states
'''
dprint()
self.add_text(':br')
def new_state(self):
'''
create a new state
'''
dprint()
if len(self.current_block) == 0:
self.ensure_state()
if self.states[-1] is not []:
self.states.append([])
def ensure_state(self):
'''
ensure state and flush all states
'''
dprint()
self.flush_state()
def flush_state(self, _sty=None, typ=-1, enumprefix=None, enumprefixtype=None, start_num=1):
'''
flush all states
'''
dprint()
result = False
if _sty is 'List_item':
self.flush_enum_list_item()
else:
if _sty is None:
if len(self.current_block) > 0 and self.current_block[-1] == 'List_item':
self.flush_enum_list_item()
result = True
self.flush_state_all(_sty)
return result
def flush_state_all(self, _sty=None, _create_only=False):
'''
flush all states
'''
dprint()
p = []
b_level = self.block_level + self.list_level
for texts in self.states:
if texts:
if _sty:
# if _sty == 'LiteralBlock':
# print texts
# pass
p.append(self.docx.paragraph(
texts, style=_sty, block_level=b_level, create_only=_create_only))
else:
p.append(
self.docx.paragraph(texts, block_level=b_level, create_only=_create_only))
self.states = [[]]
return p
def end_state(self, first=None):
'''
clear states
'''
dprint()
try:
result = self.states.pop()
if first is not None and result:
item = result[0]
if item:
result.insert(0, [first + item[0]])
result[1] = item[1:]
if not self.states:
if self.states[-1] is not []:
self.states.append([])
self.states[-1].extend(result)
except:
self.states = [[]]
pass
def flush_enum_list_item(self):
'''
flush an enum list item
'''
if len(self.current_block) > 1 and self.current_block[-2] == 'Number_list':
num_style = self.enum_prefix_style[-1]
# change numbering
if num_style[0] < self.max_num_list_id:
self.max_num_list_id += 1
paras = self.docx.find_numbering_paragraph(num_style[0])
num_style[1][0] = len(paras) + 1
num_style[0] = self.max_num_list_id
self.flush_list_item(num_style[0], start_num=num_style[1][0],
enumprefix=num_style[1][1],
enumprefixtype=num_style[1][2])
else:
self.flush_list_item()
def flush_list_item(self, typ=-1, enumprefix=None, enumprefixtype=None, start_num=1):
'''
flush a list item
'''
dprint()
text_list = get_items_list(self.states)
b_level = self.list_level + self.block_level
for i, x in enumerate(text_list):
sty = self.list_style[-1]
if i == 0 and not self.list_item_flushed:
self.docx.list_item(x, sty, b_level, typ,
enum_prefix=enumprefix,
enum_prefix_type=enumprefixtype, start=start_num)
self.list_item_flushed = True
else:
self.docx.list_item(x, sty, b_level, 0)
del self.states
self.states = [[]]
def append_style(self, style):
'''
append a list style...
'''
dprint()
txt_list = self.states.pop()
txt = txt_list.pop()
txt_list.append([txt, style])
self.states.append(txt_list)
def visit_start_of_file(self, node):
'''
start of a file
'''
dprint()
self.new_state()
self.sectionlevel = 0
# self.docx.pagebreak(type='page', orient='portrait')
def depart_start_of_file(self, node):
'''
end of a file
'''
dprint()
self.end_state()
def visit_document(self, node):
'''
start of a document
'''
dprint()
self.toc_out = False
self.new_state()
def depart_document(self, node):
'''
end of a document
'''
dprint()
self.end_state()
def visit_highlightlang(self, node):
'''
start of a hight light
'''
dprint()
raise nodes.SkipNode
def visit_section(self, node):
'''
start of a section
'''
dprint()
self.sectionlevel += 1
def depart_section(self, node):
'''
end of a section
'''
dprint()
self.ensure_state()
if self.sectionlevel > 0:
self.sectionlevel -= 1
def visit_topic(self, node):
'''
start of a topic (ignore)
'''
dprint()
#raise nodes.SkipNode
# self.new_state()
def depart_topic(self, node):
'''
end of a topic (ignore)
'''
dprint()
#raise nodes.SkipNode
# self.end_state()
visit_sidebar = visit_topic
depart_sidebar = depart_topic
def visit_rubric(self, node):
'''
start of a rubric (ignore)
'''
dprint()
#raise nodes.SkipNode
# self.new_state()
#self.add_text('-[ ')
def depart_rubric(self, node):
'''
end of a rubric (ignore)
'''
dprint()
raise nodes.SkipNode
#self.add_text(' ]-')
# self.end_state()
def visit_compound(self, node):
'''
start of a compound (pass a text)
'''
if len(self.states[-1]) >0 and self.states[-1][0] == 'Contents:':
self.states.pop()
self.states.append([' '])
if not self.toc_out:
self.toc_out = True
self.ensure_state()
maxdepth = get_toc_maxdepth(self.builder, 'index')
self.docx.table_of_contents(toc_text='Contents', maxlevel=maxdepth)
self.docx.pagebreak(type='page', orient='portrait')
dprint()
pass
def depart_compound(self, node):
'''
end of a compound (pass a text)
'''
dprint()
pass
def visit_glossary(self, node):
'''
start of a glossary (pass a text)
'''
dprint()
pass
def depart_glossary(self, node):
'''
end of a glossary (pass a text)
'''
dprint()
pass
def visit_title(self, node):
'''
start of a title
'''
dprint()
self.new_state()
def depart_title(self, node):
'''
end of a title
'''
dprint()
text = self.states.pop()
dprint(_func='* heading', text=repr(text), level=self.sectionlevel)
if self.table is not None:
self.docx.paragraph(text, style='TableHeading')
else:
self.docx.heading(text, self.sectionlevel)
def visit_subtitle(self, node):
'''
start of a subtitle (pass a text)
'''
dprint()
pass
def depart_subtitle(self, node):
'''
end of a subtitle (pass a text)
'''
dprint()
pass
def visit_attribution(self, node):
'''
start of a attribution (ignore)
'''
dprint()
#raise nodes.SkipNode
#self.add_text('-- ')
def depart_attribution(self, node):
'''
end of a attribution (ignore)
'''
dprint()
pass
def visit_desc(self, node):
'''
start of a desc (pass a text)
'''
dprint()
pass
def depart_desc(self, node):
'''
start of a desc (pass a text)
'''
dprint()
pass
def visit_desc_signature(self, node):
'''
start of a desc signature (ignore)
'''
dprint()
#raise nodes.SkipNode
# self.new_state()
# if node.parent['objtype'] in ('class', 'exception'):
# self.add_text('%s ' % node.parent['objtype'])
def depart_desc_signature(self, node):
'''
end of a desc signature (ignore)
'''
dprint()
#raise nodes.SkipNode
# XXX: wrap signatures in a way that makes sense
# self.end_state()
def visit_desc_name(self, node):
'''
start of a desc name (pass a text)
'''
dprint()
pass
def depart_desc_name(self, node):
'''
end of a desc name (pass a text)
'''
dprint()
pass
def visit_desc_addname(self, node):
'''
start of a desc addname (pass a text)
'''
dprint()
pass
def depart_desc_addname(self, node):
'''
end of a desc addname (pass a text)
'''
dprint()
pass
def visit_desc_type(self, node):
'''
start of a desc type (pass a text)
'''
dprint()
pass
def depart_desc_type(self, node):
'''
end of a desc type (pass a text)
'''
dprint()
pass
def visit_desc_returns(self, node):
'''
start of a desc returns (ignore)
'''
dprint()
#raise nodes.SkipNode
#self.add_text(' -> ')
def depart_desc_returns(self, node):
'''
end of a desc returns (ignore)
'''
dprint()
pass
def visit_desc_parameterlist(self, node):
dprint()
#raise nodes.SkipNode
# self.add_text('(')
#self.first_param = 1
def depart_desc_parameterlist(self, node):
dprint()
#raise nodes.SkipNode
# self.add_text(')')
def visit_desc_parameter(self, node):
dprint()
#raise nodes.SkipNode
# if not self.first_param:
# self.add_text(', ')
# else:
# self.first_param = 0
# self.add_text(node.astext())
##raise nodes.SkipNode
def visit_desc_optional(self, node):
dprint()
#raise nodes.SkipNode
# self.add_text('[')
def depart_desc_optional(self, node):
dprint()
#raise nodes.SkipNode
# self.add_text(']')
def visit_desc_annotation(self, node):
dprint()
pass
def depart_desc_annotation(self, node):
dprint()
pass
def visit_refcount(self, node):
dprint()
pass
def depart_refcount(self, node):
dprint()
pass
def visit_desc_content(self, node):
dprint()
#raise nodes.SkipNode
# self.new_state()
# self.add_text('\n')
def depart_desc_content(self, node):
dprint()
#raise nodes.SkipNode
# self.end_state()
def visit_figure(self, node):
# FIXME: figure text become normal paragraph instead of caption.
dprint()
self.new_state()
def depart_figure(self, node):
dprint()
self.end_state()
def visit_caption(self, node):
dprint()
pass
def depart_caption(self, node):
self.flush_state('ImageCaption')
dprint()
pass
def visit_productionlist(self, node):
dprint()
#raise nodes.SkipNode
# self.new_state()
#names = []
# for production in node:
# names.append(production['tokenname'])
#maxlen = max(len(name) for name in names)
# for production in node:
# if production['tokenname']:
# self.add_text(production['tokenname'].ljust(maxlen) + ' ::=')
# lastname = production['tokenname']
# else:
# self.add_text('%s ' % (' '*len(lastname)))
# self.add_text(production.astext() + '\n')
# self.end_state()
##raise nodes.SkipNode
def visit_seealso(self, node):
dprint()
self.new_state()
def depart_seealso(self, node):
dprint()
self.end_state(first='')
def visit_footnote(self, node):
dprint()
#raise nodes.SkipNode
#self._footnote = node.children[0].astext().strip()
# self.new_state()
def depart_footnote(self, node):
dprint()
#raise nodes.SkipNode
#self.end_state(first='[%s] ' % self._footnote)
def visit_citation(self, node):
dprint()
#raise nodes.SkipNode
# if len(node) and isinstance(node[0], nodes.label):
# self._citlabel = node[0].astext()
# else:
# self._citlabel = ''
# self.new_state()
def depart_citation(self, node):
dprint()
#raise nodes.SkipNode
#self.end_state(first='[%s] ' % self._citlabel)
def visit_label(self, node):
dprint()
#raise nodes.SkipNode
# XXX: option list could use some better styling
def visit_option_list(self, node):
dprint()
self.flush_state()
self.current_option_list = self.docx.insert_option_list_table()
pass
def depart_option_list(self, node):
dprint()
self.current_option_list = None
pass
def visit_option_list_item(self, node):
dprint()
def depart_option_list_item(self, node):
dprint()
self.docx.insert_option_list_item(
self.current_option_list, get_items_list(self.states), 0)
self.states = [[]]
def visit_option_group(self, node):
dprint()
def depart_option_group(self, node):
dprint()
if self.states[-1][-1] == ', ':
self.states[-1].pop()
self.docx.insert_option_list_item(
self.current_option_list, get_items_list(self.states), 1)
self.states = [[]]
def visit_option(self, node):
dprint()
def depart_option(self, node):
self.add_text(', ')
dprint()
pass
def visit_option_string(self, node):
dprint()
pass
def depart_option_string(self, node):
dprint()
pass
def visit_option_argument(self, node):
dprint()
if self.states[-1][-1][:2] == '--':
self.add_text('=')
else:
self.add_text(' ')
def depart_option_argument(self, node):
dprint()
pass
def visit_description(self, node):
dprint()
pass
def depart_description(self, node):
dprint()
pass
def visit_tabular_col_spec(self, node):
dprint()
#raise nodes.SkipNode
def visit_colspec(self, node):
dprint()
self.table[0].append(node['colwidth'])
def depart_colspec(self, node):
dprint()
def visit_tgroup(self, node):
dprint()
pass
def depart_tgroup(self, node):
dprint()
pass
def visit_thead(self, node):
dprint()
pass
def depart_thead(self, node):
dprint()
pass
def visit_tbody(self, node):
dprint()
self.table.append('sep')
def depart_tbody(self, node):
dprint()
pass
def visit_row(self, node):
dprint()
self.table.append([])
def depart_row(self, node):
dprint()
pass
def visit_entry(self, node):
dprint()
if 'morerows' in node or 'morecols' in node:
raise NotImplementedError('Column or row spanning cells are '
'not implemented.')
self.new_state()
def depart_entry(self, node):
dprint()
text = self.states.pop()
#text = '\n'.join('\n'.join(x) for x in self.states.pop())
self.table[-1].append(text)
def visit_table(self, node):
dprint()
if self.table:
raise NotImplementedError('Nested tables are not supported.')
self.new_state()
self.table = [[]]
def depart_table(self, node):
dprint()
colsize_chars = self.table[0]
colsize = []
for i, x in enumerate(colsize_chars):
colsize.append(int(x) * 110)
lines = self.table[1:]
fmted_rows = []
# don't allow paragraphs in table cells for now
for line in lines:
if line == 'sep':
pass
else:
fmted_rows.append(line)
self.docx.table(fmted_rows, colsize)
self.docx.paragraph("")
self.table = None
self.end_state()
def visit_acks(self, node):
dprint()
#raise nodes.SkipNode
# self.new_state()
# self.add_text(', '.join(n.astext() for n in node.children[0].children)
# + '.')
# self.end_state()
#raise nodes.SkipNode
def check_file_exists(self, path):
if os.path.exists(path):
return 1
else:
return 0
def visit_image(self, node):
dprint()
self.flush_state()
if 'uri' in node.attributes:
source = node.attributes['uri']
if not source.startswith('http:'):
if not source.startswith(os.sep):
docsource, line = utils.get_source_line(node)
if docsource:
dirname = self.builder.env.srcdir
if dirname:
source = '%s%s%s' % (dirname, os.sep, source, )
if not self.check_file_exists(source):
self.document.reporter.warning(
'Cannot find image file %s.' % (source, ))
return
else:
return
if source in self.image_dict:
spec = self.image_dict[source]
else:
self.image_count += 1
filename = os.path.split(source)[1]
destination = 'Pictures/1%08x%s' % (self.image_count, filename, )
if source.startswith('http:'):
try:
imgfile = urllib2.urlopen(source)
content = imgfile.read()
imgfile.close()
imgfile2 = tempfile.NamedTemporaryFile('wb', delete=False)
imgfile2.write(content)
imgfile2.close()
imgfilename = imgfile2.name
source = imgfilename
except urllib2.HTTPError, e:
self.document.reporter.warning(
"Can't open image url %s." % (source, ))
spec = (source, destination,)
else:
source = os.path.abspath(source)
destination = source
spec = (source, destination,)
self.embedded_file_list.append(spec)
self.image_dict[source] = spec
filename, destination = spec
dprint(_func=' image ', uri=filename)
file_path = os.path.join(destination, filename)
width, height = self.get_image_scaled_width_height(node, file_path)
self.docx.picture(file_path, '', width, height)
def depart_image(self, node):
dprint()
def depart_index(self, node):
pass
def depart_substitution_definition(self, node):
pass
def get_image_width_height(self, node, attr):
size = None
if attr in node.attributes:
size = node.attributes[attr]
if size[-1] == '%':
size = float(size[:-1])
size = [size, '%']
else: