This repository has been archived by the owner on Jan 9, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 17
/
fixups.py
3621 lines (3147 loc) · 139 KB
/
fixups.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
""" fixups.py - Refine the HTML document produced by transform.py.
The HTML markup produced by transform.py is extremely crude.
These fixups add links, lists, a stylesheet, and sections.
A great deal of the work done here is document-specific.
The entry point is fixup().
"""
import htmodel as html
from warnings import warn
import collections, contextlib, os, time, re, json
from hacks import declare_hack, using_hack, warn_about_unused_hacks
# === Useful functions
def findall(e, name):
if e.name == name:
yield e
for k in e.content:
if not isinstance(k, str):
for d in findall(k, name):
yield d
def all_parent_index_child_triples(e):
for i, k in enumerate(e.content):
if not isinstance(k, str):
yield e, i, k
for t in all_parent_index_child_triples(k):
yield t
def all_parent_index_child_triples_reversed(e):
i = len(e.content) - 1
while i >= 0:
k = e.content[i]
if not isinstance(k, str):
for t in all_parent_index_child_triples_reversed(k):
yield t
assert e.content[i] is k
yield e, i, k
i -= 1
def spec_is_intl(docx):
return os.path.basename(docx.filename).lower().startswith('es-intl')
def spec_is_lang(docx):
return not os.path.basename(docx.filename).lower().startswith('es-intl')
def version_is_5(docx):
return os.path.basename(docx.filename).lower().startswith('es5')
def version_is_51_final(docx):
return os.path.basename(docx.filename) == 'es5.1-final.dotx'
def version_is_intl_1_final(docx):
return os.path.basename(docx.filename) == 'es-intl-1-final.docx'
# === Kinds of fixups
class Fixup:
def __init__(self, fn):
self.fn = fn
self.name = fn.__name__
def __call__(self, doc, docx):
result = self.fn(doc, docx)
assert result is not None
assert isinstance(result, html.Element)
return result
class InPlaceFixup:
"""
A kind of fixup that modifies the document in-place
rather than creating a copy with some changes.
"""
def __init__(self, fn):
self.fn = fn
self.name = fn.__name__
def __call__(self, doc, docx):
result = self.fn(doc, docx)
assert result is None
return doc
# === Fixups
@Fixup
def fixup_strip_empty_paragraphs(doc, docx):
""" Empty paragraphs are meaningless in HTML. Drop them. """
def is_empty_para(e):
return e.name == 'p' and len(e.content) == 0
return doc.find_replace(is_empty_para, lambda e: [])
def int_to_lower_roman(i):
""" Convert an integer to Roman numerals.
From Paul Winkler's recipe: https://code.activestate.com/recipes/81611-roman-numerals/
"""
if i < 1 or i > 3999:
raise ValueError("Argument must be between 1 and 3999")
vals = (1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1)
syms = ('m', 'cm', 'd', 'cd','c', 'xc','l','xl','x','ix','v','iv','i')
result = ""
for val, symbol in zip(vals, syms):
count = i // val
result += symbol * count
i -= val * count
return result
def int_to_lower_letter(i):
letters = "abcdefghijklmnopqrstuvwxyz"
if i <= 26:
return letters[i - 1]
elif i == 27:
return "aa" # well, you learn something every day
else:
# but not sure if the next letter is "bb" or "ab", so:
raise ValueError("Don't know any more letters after z, except of course \"aa\".")
list_formatters = {
'lowerLetter': int_to_lower_letter,
'upperLetter': lambda i: int_to_lower_letter(i).upper(),
'decimal': str,
'lowerRoman': int_to_lower_roman,
'upperRoman': lambda i: int_to_lower_roman(i).upper()
}
def render_list_marker(levels, numbers):
def repl(m):
ilvl = int(m.group(1)) - 1
level = levels[ilvl]
return list_formatters[level.numFmt](numbers[ilvl]) # should ignore numFmt if isLgl
this_level = levels[len(numbers) - 1]
text = re.sub(r'%([1-9])', repl, this_level.lvlText)
return text + this_level.suff
@Fixup
def fixup_add_numbering(doc, docx):
""" Add span.marker elements and -ooxml-indentation style properties to the document. """
# The current state of every numbered thing in the document.
# Numbering is very stateful; it must be done in a single forward pass over
# the whole document.
numbering_context = collections.defaultdict(list)
seen_numids = set()
def add_numbering(p):
cls = p.attrs and p.attrs.get('class')
paragraph_style = docx.styles[cls]
numid = ilvl = None
def computed_style(name, default_value):
"""
Get computed style for the given property name.
Returns a string, or default_value if no such property is defined anywhere.
"""
# This paragraph's properties override everything else.
if p.style and name in p.style:
return p.style[name]
# If pPr>numPr>numId is present on the paragraph, then
# properties inherited from the corresponding w:lvl>w:pPr are
# next-highest in precedence.
def fetch_from_numbering(style):
if style is None or name in ('-ooxml-numId', '-ooxml-ilvl'):
return None
_numid = int(style.get('-ooxml-numId', '0'))
if _numid == 0:
return None
_ilvl = int(style.get('-ooxml-ilvl', '0'))
lvl = docx.get_list_style_at_level(_numid, _ilvl)
if lvl is not None and name in lvl.full_style:
return lvl.full_style[name]
val = fetch_from_numbering(p.style)
if val is not None:
return val
# After that come the properties defined in paragraph
# style. Note that full_style incorporates properties that are
# inherited via the w:basedOn chain.
if name in paragraph_style.full_style:
return paragraph_style.full_style[name]
# Lastly, properties inherted from numbering based on the paragraph
# style.
val = fetch_from_numbering(paragraph_style.full_style)
if val is not None:
return val
# Not specified anywhere.
return default_value
numid = int(computed_style('-ooxml-numId', '0'))
has_numbering = numid != 0
if has_numbering:
# Figure out the level of this paragraph.
ilvl = int(computed_style('-ooxml-ilvl', '0'))
# Bump the numbering accordingly.
abstract_num_id, levels = docx.numbering.get_abstract_num_id_and_levels(numid)
current_number = numbering_context[abstract_num_id]
if len(current_number) <= ilvl:
while len(current_number) <= ilvl:
lvl = levels[len(current_number)]
current_number.append(lvl.start)
else:
del current_number[ilvl + 1:]
# Apparent special case in Word: The first time a numId is
# seen, the numbering for that ilvl is always reset to the
# starting value for that numId-ilvl combo, even if the numId
# refers to an abstractNumId that has already been used.
if numid not in seen_numids:
current_number[ilvl] = levels[ilvl].start
else:
current_number[ilvl] += 1
# Create a suitable marker.
marker = render_list_marker(levels, current_number)
s = html.span(marker, class_="marker")
s.style = {}
content = [s] + p.content
else:
content = p.content
seen_numids.add(numid)
# Figure out the actual physical indentation of the number on this
# paragraph, net of everything. (This is used in fixup_lists to infer
# nesting lists, whether a paragraph is inside a list item, etc.)
def points(s):
if s == '0':
return 0
assert s.endswith('pt')
return float(s[:-2])
margin_left = points(computed_style('margin-left', '0'))
text_indent = points(computed_style('text-indent', '0'))
if p.style is None:
css = {}
else:
css = p.style.copy()
if has_numbering:
# In case this element's numbering is due to paragraph style, copy
# that to the paragraph's own .style.
css['-ooxml-ilvl'] = str(ilvl)
css['-ooxml-numId'] = str(numid)
css['-ooxml-indentation'] = str(margin_left + text_indent) + 'pt'
return p.with_(style=css, content=content)
def fix_body(body):
result = []
for p in body.content:
if p.name == 'p':
try:
p = add_numbering(p)
except Exception as exc:
if not hasattr(exc, "_already_dumped_context"):
print("*** Error happened while processing paragraph:")
print(p)
exc._already_dumped_context = True
raise
result.append(p)
return [body.with_content(result)]
return doc.find_replace(lambda e: e.name in ('body', 'td'), fix_body)
def has_bullet(docx, p):
""" True if the given paragraph is of a style that has a bullet. """
if not p.style:
return False
numId = int(p.style.get('-ooxml-numId', '0'))
if numId == 0:
return False
ilvl = p.style.get('-ooxml-ilvl', '0')
s = docx.get_list_style_at_level(numId, ilvl)
return s is not None and s.numFmt == 'bullet'
@InPlaceFixup
def fixup_list_styles(doc, docx):
""" Make sure bullet lists are never p.Alg4 or other particular styles.
Alg4 style indicates a numbered list, with Times New Roman font. It's used
for algorithms. However there are a few places in the Word document where
a paragraph is style Alg4 but manually hacked to have a bullet instead of a
number and the default font instead of Times New Roman. Lol.
In short, this screws everything up, so we manually hack it in the general
direction of sanity before doing anything else.
Precedes fixup_formatting, which would spew a bunch of
<span style="font-family: sans-serif"> if we did it first.
"""
wrong_types = ('Alg4', 'MathSpecialCase3', 'BulletNotlast', 'BulletLast')
for t in wrong_types:
declare_hack("fixup_list_styles: " + t)
for p in findall(doc, 'p'):
if p.attrs.get("class") in wrong_types and has_bullet(docx, p):
using_hack("fixup_list_styles: " + p.attrs['class'])
p.attrs['class'] = "Normal"
def map_body(doc, f):
head, body = doc.content
return doc.with_content([head, f(body)])
def title_get_argument_names(title):
""" Given a section title, return a list of argument names.
If title is a string like "Get (O, P)", this returns a list of strings,
the arguments: ["O", "P"]. Otherwise it returns an empty list.
"""
if title == '19.1.2.3.1\tRuntime Semantics: ObjectDefineProperties ( O. Properties )':
using_hack("fixup_vars_tweak_19.1.2.3.1")
title = title.replace(" O. Prop", " O, Prop")
algorithm_arguments_re = r'''(?x)
^
# Ignore optional section number.
(?: \d+ (?: \. \d+ )* \s* )?
# Ignore optional "Runtime Semantics:" label
(?: (?:Runtime|Static) \s* Semantics \s* : \s* )?
# Actual algorithm name
(?:
(?: new \s*)?
%?[A-Z][A-Za-z0-9.%]{3,}
(?: \s* \[ \s* @@[A-Za-z0-9.%]* \s* \]
| \s* \[\[ \s* [A-Za-z0-9.%]* \s* \]\] )?
\s* \( (.*) \) \s*
|
new \s* (?:Map|Set) \s*
)
(?: Abstract \s+ Operation \s*)?
$
'''
m = re.match(algorithm_arguments_re, title)
if m is None:
return []
arguments = m.group(1)
ignore_re = r'\.\s*\.\s*\.|\[|\]|' + "\N{HORIZONTAL ELLIPSIS}"
arguments = re.sub(ignore_re, '', arguments)
arguments = arguments.strip()
if arguments == '' or arguments == 'all other argument combinations':
return []
pieces = arguments.split(',')
names = []
for piece in pieces:
if piece.strip() == '':
continue
m = re.match(r'^\s*(?:\.\s*\.\s*\.\s*)?(\w+)\s*(?:=.*)?$', piece)
if m is None:
if piece == "reserved1 .":
warn("FIXME working around https://bugs.ecmascript.org/show_bug.cgi?id=2626")
names.append("reserved1")
elif piece == "typedArray offset":
warn("FIXME working around https://bugs.ecmascript.org/show_bug.cgi?id=2627")
names += piece.split()
else:
raise ValueError("title looks like it might be an argument list, but maybe not? %r has argument %r" % (title, piece))
else:
names.append(m.group(1))
return names
def ht_text(ht):
if isinstance(ht, str):
return ht
elif isinstance(ht, list):
return ''.join(map(ht_text, ht))
else:
return ht_text(ht.content)
tag_names = {
'ANNEX': 'h1.l1',
# These appear as "a2", "a3", "a4", "a5" in the Word UI,
# but they are mapped to internal styleIDs a20, a30, a40, a50.
# Note that the document also contains styles named "??", "]", "...", and ".."
# whose internal styleIDs are a2, a3, a4, and a5. Of course there are.
'a20': 'h1.l2',
'a30': 'h1.l3',
'a40': 'h1.l4',
'a50': 'h1.l5',
'a6': 'h1.l6',
# Algorithm styles are handled via their list attributes.
'Alg2': None,
'Alg3': None,
'Alg4': None,
'Alg40': None,
'Alg41': None,
'Algorithm': None,
'bibliography': 'li.bibliography-entry',
'BulletNotlast': 'li',
'Caption': 'figcaption',
'DateTitle': 'h1',
'ECMAWorkgroup': 'h1.ECMAWorkgroup',
'Example': '.Note',
'Figuretitle': 'figcaption',
'Heading1': 'h1.l1',
'Heading2': 'h1.l2',
'Heading3': 'h1.l3',
'Heading4': 'h1.l4',
'Heading5': 'h1.l5',
'Introduction': 'h1',
'ListBullet': 'li.ul',
'M0': None,
'M4': None,
'M20': 'div.math-display',
'MathDefinition4': 'div.display',
'MathSpecialCase3': 'li',
'Note': '.Note',
'RefNorm': 'p.formal-reference',
'StandardNumber': 'h1.StandardNumber',
'StandardTitle': 'h1',
'Syntax': 'h2',
'SyntaxDefinition': 'div.rhs',
'SyntaxDefinition2': 'div.rhs',
'SyntaxRule': 'div.lhs',
'SyntaxRule2': 'div.lhs',
'Tabletitle': 'figcaption',
'TermNum': 'h1',
'Terms': 'p.Terms',
'zzBiblio': 'h1',
'zzSTDTitle': 'div.inner-title'
}
heading_styles = {k for k, v in tag_names.items()
if v == 'h1' or v == 'h2' or (v is not None and v.startswith('h1.'))}
@Fixup
def fixup_vars(doc, docx):
"""
Convert italicized variable names to <var> elements.
"""
declare_hack("fixup_vars_tweak_19.1.2.3.1")
def slices_by(iterable, break_before):
"""Break an iterable into slices, using the given predicate
to determine when to break. Yields nonempty lists.
`slice_by(range(6), is_even)` would yield [0, 1], then [2, 3],
then [4, 5].
"""
x = []
for v in iterable:
if break_before(v):
if x:
yield x
x = []
x.append(v)
if x:
yield x
def is_heading(p):
return ht_name_is(p, 'p') and p.attrs.get('class', '') in heading_styles
class ProseParser:
def __init__(self, text):
self.text = text
self.tokens = re.findall(r'(?:\s*)([0-9A-Za-z_-]+|.)', text)
self.i = 0
def parse(self):
tokens = self.tokens
n = len(tokens)
hits = []
while self.i < n:
if tokens[self.i:self.i + 3] == ['is', 'called', 'with']:
#print("OK", tokens[self.i:self.i + 20])
# look back to match 'method of Obj is called with'
if self.i >= 3 and tokens[self.i - 3:self.i - 1] == ['method', 'of']:
hits.append(tokens[self.i - 1])
self.i += 3 # skip "is called with"
# skip these pointless phrases if they appear...
if tokens[self.i:self.i + 3] == ['a', 'single', 'parameter']:
self.i += 3
elif tokens[self.i:self.i + 1] == ['parameters']:
self.i += 1
result = self.parse_arg()
if result is None:
warn("parse failed in {!r}".format(self.text))
else:
hits.append(result)
while ((self.skip_optional(",") and not self.i == len(self.tokens))
or self.looking_at("and")):
if self.skip_optional("and"):
self.skip_optional("with") # lame
result = self.parse_arg()
if result is None:
warn("parse failed in {!r} after ','".format(self.text))
else:
hits.append(result)
else:
self.i += 1
return hits
def looking_at(self, *options):
return self.i < len(self.tokens) and self.tokens[self.i] in options
def skip_optional(self, *options):
hit = self.looking_at(*options)
if hit:
self.i += 1
return hit
def parse_arg(self):
# Arg : "optionally"_opt Article_opt Type_opt "argument"_opt Identifier Suffix_opt
# Article : one of "a" "an"
self.skip_optional("optionally")
self.skip_optional("a", "an")
self.skip_optional_type(deferring=True)
self.skip_optional("as")
self.skip_optional("argument", "arguments")
tokens = self.tokens
n = len(tokens)
i = self.i
if i >= n:
return None
t = tokens[i]
if re.match(r'^[a-zA-Z0-9_-]+$', t) is not None and t not in ('and', 'where'):
self.i += 1
self.skip_optional_suffix()
return t
return None
def skip_optional_suffix(self):
# Suffix : "," Article Type [lookahead in {".", ","}]
tokens = self.tokens
n = len(tokens)
i = self.i
if i >= n:
return
if tokens[i] != ",":
return
i += 1
if i >= n:
return
if tokens[i] not in ("a", "an"):
return
i += 1
if i >= n:
return
# Transactionally attempt skip_optional_type and roll all the way
# back to the beginning if it doesn't match.
saved_place = self.i
self.i = i
self.skip_optional_type(deferring=False)
if self.i == i or not (self.looking_at(",") or self.looking_at(".")):
# No match! Roll back.
self.i = saved_place
def skip_optional_type(self, deferring):
if self.skip_optional("ECMAScript"):
self.skip_optional("language")
tokens = self.tokens
n = len(tokens)
i = self.i
if i >= n:
return
tok = tokens[i].lower()
if tok == 'list':
self.i += 1
if i + 1 < len(tokens) and tokens[i + 1] == 'of':
self.i += 1
self.skip_optional_type(deferring=False)
elif tok == 'either':
self.i += 1
self.skip_optional("a", "an")
self.skip_optional_type(deferring=False)
if self.skip_optional("or"):
self.skip_optional("with") # mmmmm rather bogus, grammatically
self.skip_optional("a", "an")
self.skip_optional_type(deferring=False)
else:
for t in types:
if [w.lower() for w in tokens[i:i + len(t)]] == t:
if deferring and i + len(t) < len(tokens) and tokens[i + len(t)] == ',':
# In "is called with argument string," don't treat
# "string" as a type. It's the argument name.
return
self.i += len(t)
return
types = [[w.lower() for w in s.split()] for s in [
'object',
'integer',
'string',
'null',
'boolean flag',
'boolean value',
'boolean',
'Property Descriptor',
'Property Descriptors',
'Lexical Environment',
'environment record',
'grammar production',
'value',
'values',
'function Object',
'property key'
]]
def para_get_argument_names(para):
text = ht_text(para)
return ProseParser(text).parse()
def testp(text, expected):
actual = list(para_get_argument_names(text))
expected = expected.split()
if actual != expected:
raise ValueError("test failed: para_get_argument_names({!r})\n"
" got {!r},\n"
"expected {!r}\n".format(text, actual, expected))
testp("is called with arguments O and proto,", "O proto")
testp("is called with argument string,", "string")
testp("internal method of O is called with argument V", "O V")
testp("is called with Property Descriptor Desc", "Desc")
testp("is called with object Obj", "Obj")
testp("is called with Property Descriptors Desc and LikeDesc", "Desc LikeDesc")
testp("is called with integer argument size", "size")
testp("is called with arguments O, P, V, and Throw where", "O P V Throw")
testp("is called with arguments O, P , and optionally args where", "O P args")
testp("is called with Object F", "F")
testp("is called with Object F and List argumentsList", "F argumentsList")
testp("is called with a Lexical Environment lex, a String name, and a Boolean flag strict.",
"lex name strict")
testp("is called with either a Lexical Environment or null as argument E", "E")
testp("is called with an Object O and a Lexical Environment E (or null) as arguments", "O E")
testp("is called with an ECMAScript function Object F and an ECMAScript value T as arguments",
"F T")
testp("is called with an ECMAScript Object G as its argument", "G")
testp("is called with Object O and with property key P,", "O P")
testp("is called with Boolean value Extensible, and Property Descriptors Desc, and Current",
"Extensible Desc Current")
testp("is called with Object O, property key P, Boolean value extensible, and "
"Property Descriptors Desc, and current",
"O P extensible Desc current")
testp("is called with property key P and ECMAScript language value Receiver", "P Receiver")
testp("is called with a single parameter argumentsList which is a possibly empty List of "
"ECMAScript language values.",
"argumentsList")
testp("is called with parameters thisArgument and argumentsList, a List of ECMAScript "
"language values.",
"thisArgument argumentsList")
testp("is called with obj as its argument.", "obj")
testp("is called with a function object function, an object newHome, and a property key "
"newName as its argument.",
"function newHome newName")
testp("is called with a list of arguments ExtraArgs", "ExtraArgs")
testp("is called with object func, grammar production formals, List argumentsList, and "
"environment record env.",
"func formals argumentsList env")
def markup_vars(section):
if not is_heading(section[0]):
return section # unchanged.
## look in the heading for parameter names - we already have code for this somewhere
title = ht_text(section[0])
arguments = title_get_argument_names(title)
## look in each paragraph that precedes a list for arguments ("is
## called with Object O and with property key P")
for i in range(1, len(section) - 1):
if ht_name_is(section[i], 'p') and ht_name_is(section[i + 1], 'ol'):
list_args = arguments + para_get_argument_names(section[i])
## look in the body for declarations of the form "Let script be" in a list
## and of certain other forms outside of lists
## Then change them all from whatever markup they're using to <var>.
## That part should be easy using section.replace('*').
##
## Oh wait but it is hard to decide where to put the var and whether to join the
## neighboring runs. I knew there was a reason I hadn't done this yet.
return section #unchanged for now ???
def replace_sections(body, fn):
new_content = []
for slice in slices_by(body.content, is_heading):
new_content += markup_vars(slice)
return body.with_content(new_content)
return map_body(doc, lambda body: replace_sections(body, markup_vars))
## TODO: use a similar approach for span.nt. Scan the whole document for the
## pattern /NonTerminalLookinThing :+/ to compile a list of all nonterminals in
## the grammar. Even though we will do it again later. No pain no gain.
## Then use .replace() to change correctly formatted nonterminals to span.nt.
## TODO: use a similar approach for bold Courier New => <code></code>.
## TODO: use a similar approach for values "undefined", "true", "false" => b.val.
## TODO: figure out what to do with "SyntaxError", "empty" (when used as a
## special magic value), "normal", "break", "continue", "return" and "throw"
## as in the NormalCompletion algorithm:
##
## 1. Return Completion{[[type]]: normal, [[value]]: argument,
## [[target]]:empty}.
def looks_like_nonterminal(text):
return re.match(r'^(?:uri(?:[A-Z][A-Za-z0-9]*)?|[A-Z]+[a-z][A-Za-z0-9]*)$', text) is not None
def is_marker(e):
return ht_name_is(e, 'span') and e.attrs.get('class') == 'marker'
@Fixup
def fixup_formatting(doc, docx):
"""
Convert runs of span elements to more HTML-like code.
The OOXML schema starts out like this:
- w:body contains w:p elements (paragraphs)
- w:p contains w:r elements (runs)
- w:r contains an optional w:rPr (style data) followed by some amount of text
and/or tabs, line breaks, and other junk (w:t, w:tab, w:br, etc.)
But note that w:r elements don't nest.
In Word, when someone selects a whole paragraph, already containing markup,
and changes the font, the result is a paragraph containing many runs, every
one of which has its own w:r>w:rPr>w:rFonts element. This fixup turns the
redundant formatting into nested HTML markup.
"""
def new_span(content, style):
# Merge adjacent strings, if any.
i = 0
while i < len(content) - 1:
a = content[i]
b = content[i + 1]
if isinstance(a, str) and isinstance(b, str):
content[i] = a + b
del content[i + 1]
else:
i += 1
result = html.span(*content)
if style:
result.style = style
return result
def rewrite_spans(parent):
# Figure out where to start rewriting. If Word numbering inserted a
# span.marker, skip it.
rewritable_content_start = 0
if parent.content and not isinstance(parent.content[rewritable_content_start], str):
first = parent.content[rewritable_content_start]
if is_marker(first):
rewritable_content_start += 1
cls = parent.attrs['class']
inherited_style = docx.styles[cls].full_style
# Determine the style of each run of content in the paragraph.
items = []
for kid in parent.content[rewritable_content_start:]:
if not isinstance(kid, str) and kid.name == 'span':
run_style = inherited_style.copy()
run_style.update(kid.style)
if 'class' in kid.attrs:
run_style.update(docx.styles[kid.attrs['class']].full_style)
items.append((kid.content, run_style))
else:
items.append(([kid], inherited_style))
# Drop trailing whitespace at end of paragraph.
while items and all(isinstance(ht, str) and ht.isspace() for ht in items[-1][0]):
del items[-1]
# If the paragraph begins and ends in the same font, treat that font
# as the paragraph's font, which we will drop.
paragraph_style = inherited_style.copy()
if paragraph_style.get('font-family') == 'monospace':
del paragraph_style['font-family']
if items:
start_font = items[0][1].get('font-family')
if start_font is not None and start_font != 'monospace':
end_font = items[-1][1].get('font-family')
if start_font == end_font:
paragraph_style['font-family'] = start_font
# Build the ranges.
all_content = []
ranges = collections.defaultdict(dict)
current_style = {}
def set_current_style_to(style):
here = len(all_content)
for prop, (start, old_val) in list(current_style.items()):
if style.get(prop, not old_val) != old_val:
# note end of earlier style
ranges[start, here][prop] = old_val
del current_style[prop]
for prop, val in style.items():
if prop not in current_style:
# note start of new style
current_style[prop] = here, val
else:
assert current_style[prop][1] == val
assert {k: v for k, (_, v) in current_style.items()} == style
for content, run_style in items:
set_current_style_to({p: v for p, v in run_style.items() if paragraph_style.get(p) != v})
all_content += content
set_current_style_to({})
# Convert ranges to a list.
ranges = [(start, stop, style) for (start, stop), style in ranges.items()]
ranges.sort(key=lambda triple: (triple[0], -triple[1]))
def build_result(ranges, i0, i1):
result = []
content_index = i0
while ranges:
start, stop, style = ranges[0]
assert i0 <= start < stop <= i1
assert content_index <= start
result += all_content[content_index:start] # add any plain content
# split 'ranges' into two parts
inner_ranges = []
after_ranges = []
for triple in ranges[1:]:
r0, r1, rs = triple
assert start <= r0 < r1 <= i1
if r1 <= stop:
inner_ranges.append(triple)
elif stop <= r0:
after_ranges.append(triple)
else:
# the gross case, hopefully rare
inner_ranges.append((r0, stop, rs))
after_ranges.append((stop, r1, rs))
# recurse to build the child, add that to the result
child_content = build_result(inner_ranges, start, stop)
result.append(new_span(child_content, style))
content_index = stop
ranges = after_ranges
result += all_content[content_index:i1] # add any trailing plain content
return result
return [parent.with_content_slice(rewritable_content_start,
len(parent.content),
build_result(ranges, 0, len(all_content)))]
return doc.replace('p', rewrite_spans)
@Fixup
def fixup_lists(doc, docx):
""" Group numbered paragraphs into lists. """
declare_hack("fixup_lists_unindented_nested_lists")
# A List represents either an element that is <ol>, <ul>, or <body>.
#
# parent: The List that contains this List, or None if this List is the
# document body.
#
# left_margin: The x coordinate of the list marker, in points.
#
# content: This ol/ul/body element's .content list.
#
# numId, ilvl: The OOXML numbering info for this element, used only for
# assertions. (List structure is recovered from indentation alone.)
#
# marker_type: 'bullet' or an integer indicating the level of nesting, so
# that an outermost ol.proc has marker_type=0, the first nested ol.block
# gets marker_type=1, and so on. Used only to assert that the markers
# are correct.
#
List = collections.namedtuple('List', ['parent', 'left_margin', 'content',
'numId', 'ilvl', 'marker_type'])
def without_numbering_info(style):
""" Return a dictionary just like style but without numbering entries. """
s = None
for k in ('-ooxml-numId', '-ooxml-ilvl'):
if k in style:
if s is None:
s = style.copy()
del s[k]
if s is None:
return style
return s
def fix_body(body):
# In a single left-to-right pass over the document, group paragraphs
# into lists. We start and end lists based on indentation alone.
result = []
# current is the current innermost List.
current = List(parent=None, left_margin=-1e300, content=result,
numId=0, ilvl=None, marker_type=None)
def append_non_list_item(e):
if current.parent is None:
# The enclosing element is the <body>. Just add this element to it.
current.content.append(e)
else:
# The enclosing element is a list. It can contain only list
# items, so put this paragraph or list in with the preceding
# list item.
assert(ht_name_is(current.content[-1], 'li'))
current.content[-1].content.append(e)
def open_list(p, numId, ilvl, margin):
nonlocal current
assert margin >= current.left_margin
s = docx.get_list_style_at_level(numId, ilvl)
is_bulleted_list = s is not None and s.numFmt == 'bullet'
if is_bulleted_list:
lst = html.ul()
marker_type = 'bullet'
else:
if margin > current.left_margin and numId == current.numId:
assert ilvl > current.ilvl
if current.parent is None or current.marker_type == 'bullet':
cls = 'proc'
marker_type = 0
elif (margin > (current.left_margin + 3/8 * 72)
and p.content
and is_marker(p.content[0])
and p.content[0].content == ['1.\t']):
# Deeply nested list with decimal numbering.
cls = 'nested proc'
marker_type = 0
else:
cls = 'block'
marker_type = current.marker_type + 1
lst = html.ol(class_=cls)
append_non_list_item(lst)
current = List(parent=current, left_margin=margin, content=lst.content,
numId=numId, ilvl=ilvl, marker_type=marker_type)
def close_list():
nonlocal current
current = current.parent
assert current is not None
for i, p in enumerate(body.content):
# Get numbering info for this paragraph.
numId = ilvl = None
if p.style and '-ooxml-numId' in p.style and p.style['-ooxml-numId'] != '0':
numId = int(p.style['-ooxml-numId'])
ilvl = int(p.style.get('-ooxml-ilvl', '0'))
# Determine the indentation depth.
margin = 0.0
if p.style and '-ooxml-indentation' in p.style:
margin_str = p.style['-ooxml-indentation']
if margin_str.endswith('pt'):
margin = float(margin_str[:-2])
else:
assert margin_str == '0' and margin == 0.0
# Figure out if this paragraph is a list item.
is_list_item = (numId is not None
and numId != 0
and p.attrs.get('class') not in heading_styles
and len(p.content) != 0
and is_marker(p.content[0])
and re.match(r'^(?:\uf0b7|[1-9][0-9]*\.|[a-z]\.?|[ivxlcdm]+\.)\t$',
p.content[0].content[0]))
# Close any more-indented active lists.
#
# Since -ooxml-indentation refers to the indentation of the numbering, not the text,
# treat non-numbered paragraphs as being an additional 36pt (1/2 inch) to the left.