-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathconvert_html.py
2342 lines (2020 loc) · 76.5 KB
/
convert_html.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
import argparse
import typing as ty
import hashlib
import base64
from pathlib import Path
import re
import functools
from urllib.parse import urlparse
from xml.etree import ElementTree as ET
import importlib
import warnings
T = ty.TypeVar('T')
def has(module: str):
try:
mod = importlib.import_module(module)
except (ImportError, ModuleNotFoundError):
return False
return mod
class Pat:
whitespace = re.compile(r'[\t ]+')
newline = re.compile(r'\n') # must be matched after linebreak
linebreak = re.compile(r'\n{2,}')
slashsquare_math_block = re.compile(r'(\\\[|\\])', flags=re.MULTILINE)
slashparenthesis_inline_math = re.compile(
r'(\\\(|\\\))', flags=re.MULTILINE)
dollar_inline_math = re.compile(r'\$[^$\s][^$]*[^$\s]\$|\$[^$\s]\$')
def subset_dict(
dict_: ty.Mapping[str, T],
keys: ty.List[str],
) -> ty.Dict[str, T]:
ss = {}
for k in keys:
if k in dict_:
ss[k] = dict_[k]
return ss
def bookmark_hash(text: str) -> str:
return hashlib.sha1(text.encode('utf-8')).hexdigest()[:6]
class StartElement:
__slots__ = ['tag', 'attrib']
def __init__(
self,
tag: str,
attrib: ty.Dict[str, str] = None,
):
self.tag = tag
self.attrib = attrib or {}
def paired_with(self, e):
if isinstance(e, EndElement):
return self.tag == e.tag
return False
def __eq__(self, other):
if isinstance(other, StartElement):
return self.tag == other.tag and self.attrib == other.attrib
if isinstance(other, str):
return self.tag == other
return NotImplemented
def __hash__(self):
return hash((self.tag, self.attrib))
def __repr__(self):
return 'StartElement(tag={!r}, attrib={!r})'.format(
self.tag, self.attrib)
class EndElement:
__slots__ = ['tag']
def __init__(self, tag: str):
self.tag = tag
def paired_with(self, e):
if isinstance(e, StartElement):
return self.tag == e.tag
return False
def __eq__(self, other):
if isinstance(other, EndElement):
return self.tag == other.tag
if isinstance(other, str):
return self.tag == other
return NotImplemented
def __hash__(self):
return hash(self.tag)
def __repr__(self):
return 'EndElement(tag={!r})'.format(self.tag)
SupportedElementType = ty.Union[StartElement, EndElement, str]
class KeepOnlySupportedTarget:
"""
This target keeps only supported elements.
"""
def __init__(self, strict: bool):
self.strict = strict
self.nodes: ty.List[SupportedElementType] = []
self.stack: ty.List[str] = []
self.active = False
def start(self, tag, attrib):
self.active = True
tag = tag.lower()
# the separator
if tag == 'hr':
self.nodes.append(StartElement(tag))
self.stack.append(tag)
# headers
elif tag in ['h1', 'h2', 'h3', 'h4', 'h5', 'h6']:
self.nodes.append(StartElement(tag, subset_dict(attrib, ['id'])))
self.stack.append(tag)
# lists
elif tag == 'li':
self.nodes.append(StartElement(tag, subset_dict(attrib, ['id'])))
self.stack.append(tag)
elif tag == 'ul':
self.nodes.append(StartElement(tag))
self.stack.append(tag)
elif tag == 'ol':
self.nodes.append(
StartElement(tag, subset_dict(attrib, ['start'])))
self.stack.append(tag)
# paragraphs
elif tag == 'p':
self.nodes.append(StartElement(tag))
self.stack.append(tag)
# anchors
elif tag == 'a':
self.nodes.append(
StartElement(tag, subset_dict(attrib, ['id', 'href'])))
self.stack.append(tag)
# quotes
elif tag == 'blockquote':
self.nodes.append(StartElement(tag))
self.stack.append(tag)
# tables, <tbody> and <thead> are not supported currently
elif tag in ['table', 'tr', 'th', 'td']:
self.nodes.append(StartElement(tag))
self.stack.append(tag)
# figures
elif tag == 'img':
self.nodes.append(
StartElement(tag, subset_dict(attrib, ['src', 'alt'])))
self.stack.append(tag)
# basic text layout
elif tag in ['b', 'strong', 'i', 'em', 'mark', 'del', 's']:
self.nodes.append(StartElement(tag))
self.stack.append(tag)
# sub and sup
elif tag in ['sub', 'sup']:
self.nodes.append(StartElement(tag, subset_dict(attrib, ['id'])))
self.stack.append(tag)
# code blocks
elif tag == 'pre':
self.nodes.append(StartElement(tag))
self.stack.append(tag)
elif tag == 'div':
if 'class' in attrib:
for v in attrib['class'].split():
if v.startswith('language-'):
self.nodes.append(StartElement(tag, {'class': v}))
self.stack.append(tag)
break
# also math
if v == 'math':
self.nodes.append(StartElement(tag, {'class': 'math'}))
self.stack.append(tag)
break
# misc
else:
self.nodes.append(
StartElement(tag, subset_dict(attrib, ['id'])))
self.stack.append(tag)
# misc
else:
self.nodes.append(
StartElement(tag, subset_dict(attrib, ['id'])))
self.stack.append(tag)
elif tag in ['code', 'samp', 'kbd']:
self.nodes.append(StartElement(tag, attrib))
self.stack.append(tag)
# math (alternative)
elif tag == 'span':
if 'class' in attrib:
if attrib['class'] == 'math':
self.nodes.append(StartElement(tag, {'class': 'math'}))
self.stack.append(tag)
else:
self.nodes.append(
StartElement(tag, subset_dict(attrib, ['id'])))
self.stack.append(tag)
else:
self.nodes.append(
StartElement(tag, subset_dict(attrib, ['id'])))
self.stack.append(tag)
# mathml (requiring lxml):
# See https://developer.mozilla.org/en-US/docs/Web/MathML/Element
elif has('lxml') and tag in [
'math', 'maction', 'annotation', 'annotation-xml', 'menclose',
'merror', 'mfenced', 'mfrac', 'mi', 'mmultiscripts', 'mn',
'mo', 'mover', 'mpadded', 'mphantom', 'mprescripts', 'mroot',
'mrow', 'ms', 'semantics', 'mspace', 'msqrt', 'mstyle', 'msub',
'msup', 'msubsup', 'mtable', 'mtd', 'mtext', 'mtr', 'munder',
'munderover'
]:
self.nodes.append(StartElement(tag, attrib))
self.stack.append(tag)
else:
self.active = False
def end(self, tag):
if self.stack and self.stack[-1] == tag:
self.nodes.append(EndElement(tag))
del self.stack[-1]
self.active = True
def data(self, data):
if self.active:
data = data.replace('\r\n', '\n')
self.nodes.append(data)
def close(self):
if self.stack:
if self.strict:
raise ValueError('stack not empty at EOF')
warnings.warn('stack not empty at EOF')
while self.stack:
self.nodes.append(EndElement(self.stack.pop()))
res = self.nodes.copy()
self.nodes.clear()
return res
class PhantomElement:
"""Represents a partially resolved element."""
def __eq__(self, other):
return type(self) is type(other)
def __str__(self):
return ''
def __repr__(self):
return type(self).__name__
class Anchor(PhantomElement):
__slots__ = ['id_']
def __eq__(self, other):
return super().__eq__(other) and self.id_ == other.id_
def __init__(self, id_: str):
self.id_ = id_
def __repr__(self):
return '{}(id={!r})'.format(type(self).__name__, self.id_)
class MdList(PhantomElement):
__slots__ = []
class MdListItemIndentPointAtBullet(PhantomElement):
"""Should be replaced by proper indentation"""
__slots__ = []
class MdLIstItemIndentPointOtherwise(PhantomElement):
"""Should be replaced by proper indentation"""
__slots__ = []
class MdListItemBullet(PhantomElement):
"""Should be replaced by bullet"""
__slots__ = []
class MdTableCell(PhantomElement):
__slots__ = []
class MdTableRow(PhantomElement):
__slots__ = ['n_cells']
def __init__(self, n_cells: int):
self.n_cells = n_cells
def __eq__(self, other):
return super().__eq__(other) and self.n_cells == other.n_cells
def __repr__(self):
return '{}(n_cells={!r})'.format(type(self).__name__, self.n_cells)
class VerbText:
"""
Group of text free from being escaped.
"""
__slots__ = ['text']
def __init__(self, text: str):
self.text = text
def __eq__(self, other):
return type(self) is type(other) and self.text == other.text
def __str__(self):
return self.text
def __repr__(self):
return '{}({})'.format(type(self).__name__, repr(self.text))
class SyntacticMarker:
Asterisk = VerbText('*')
Underscore = VerbText('_')
Tilde = VerbText('~')
Eq = VerbText('=')
class InlineMath(VerbText):
def __init__(self, text):
super().__init__(text)
self.text = self.text
def __str__(self):
return '${}$'.format(self.text)
class Indentation(VerbText):
def __str__(self):
return self.text
def search_dollar_inline_math(text: str) -> ty.List[ty.Union[str, InlineMath]]:
res = []
start = 0
for m in Pat.dollar_inline_math.finditer(text):
if start < m.start():
res.append(text[start:m.start()])
res.append(InlineMath(m.group()[1:-1]))
start = m.end()
if start < len(text):
res.append(text[start:])
return res
def search_slashparenthesis_inline_math(
text: str) -> ty.List[ty.Union[str, InlineMath]]:
tokens = Pat.slashparenthesis_inline_math.split(text)
res = []
i = 0
while i < len(tokens):
if (tokens[i] == '\\(' and i + 2 < len(tokens)
and tokens[i + 2] == '\\)'):
res.append(InlineMath(tokens[i + 1].strip()))
i += 3
else:
if tokens[i]:
res.append(tokens[i])
i += 1
return res
class MathBlock(VerbText):
def __init__(self, text):
super().__init__(text)
self.text = self.text.strip()
def __str__(self):
return '$$\n{}\n$$'.format(self.text)
def search_slashsquare_math_block(
text: str) -> ty.List[ty.Union[str, MathBlock]]:
tokens = Pat.slashsquare_math_block.split(text)
res = []
i = 0
while i < len(tokens):
if (tokens[i] == '\\[' and i + 2 < len(tokens)
and tokens[i + 2] == '\\]'):
res.append(MathBlock(tokens[i + 1]))
i += 3
else:
res.append(tokens[i])
i += 1
return res
class InlineCode(VerbText):
def __str__(self):
return '`{}`'.format(self.text)
class CodeBlock(VerbText):
def __init__(self, text: str, language: str = None):
super().__init__(text)
self.language = language
def __str__(self):
sbuf = ['```']
if self.language:
sbuf.append(self.language)
if not self.text.startswith('\n'):
sbuf.append('\n')
sbuf.append(self.text)
if not self.text.endswith('\n'):
sbuf.append('\n')
sbuf.append('```')
return ''.join(sbuf)
class HeaderHashes(VerbText):
def __init__(self, text: str):
super().__init__(text)
if set(self.text) != {'#'}:
raise ValueError('invalid characters in HeaderHashes: {}'.format(
self.text))
@property
def n(self):
return len(self.text)
@n.setter
def n(self, value):
value = int(value)
if value < 1 or value > 6:
raise ValueError('invalid value: {}'.format(value))
self.text = '#' * value
class Whitespace:
__slots__ = []
def __eq__(self, other):
return type(self) is type(other)
def __repr__(self):
return type(self).__name__
class LineBreak(Whitespace):
def __str__(self):
return '\n\n'
class Newline(Whitespace):
def __str__(self):
return '\n'
class Space(Whitespace):
def __str__(self):
return ' '
class Tab(Whitespace):
def __str__(self):
return '\t'
def lstrip_whitespace(
elements: ty.List[T],
strip_type: ty.Union[ty.Type, ty.List[ty.Type]] = Whitespace,
) -> ty.List[T]:
"""
Strip leading whitespace elements in place.
:param elements:
:param strip_type: whitespace type(s)
:return: stripped elements
"""
if not isinstance(strip_type, list):
strip_type = [strip_type]
for t in strip_type:
if not issubclass(t, Whitespace):
raise TypeError('strip_type ({}) is not Whitespace'.format(
strip_type.__name__))
stripped_elements = []
i = index_beg(elements)
while i is not None and isinstance(elements[i], tuple(strip_type)):
stripped_elements.append(elements[i])
del elements[i]
i = index_beg(elements)
return stripped_elements
def rstrip_whitespace(
elements: ty.List[T],
strip_type: ty.Union[ty.Type, ty.List[ty.Type]] = Whitespace,
) -> ty.List[T]:
"""
Strip trailing whitespace elements in place.
:param elements:
:param strip_type: whitespace type(s)
:return: stripped elements (not in reversed order)
"""
if not isinstance(strip_type, list):
strip_type = [strip_type]
for t in strip_type:
if not issubclass(t, Whitespace):
raise TypeError('strip_type ({}) is not Whitespace'.format(
strip_type.__name__))
stripped_elements = []
i = index_end(elements)
while i is not None and isinstance(elements[i], tuple(strip_type)):
stripped_elements.append(elements[i])
del elements[i]
i = index_end(elements)
stripped_elements.reverse()
return stripped_elements
def index_beg(elements) -> ty.Optional[int]:
"""
Returns the first non-Phantom index of ``elements``.
"""
for i, e in enumerate(elements):
if not isinstance(e, PhantomElement):
return i
return None
def index_end(elements) -> ty.Optional[int]:
"""
Returns the last non-Phantom index of ``elements``.
"""
index_el = list(enumerate(elements))
for i, e in reversed(index_el):
if not isinstance(e, PhantomElement):
return i
return None
def stack_merge(
elements: ty.List[T],
rule: ty.Callable[[ty.Optional[T], T], ty.Union[None, T,
ty.List[ty.Optional[T]]]],
) -> ty.List[T]:
"""
:param elements: elements to merge
:param rule: a callable, if returning ``None``, current two elements cannot
be merged; otherwise, current two elements are merged into the
return value. If a list is returned, the first of current two
elements is replaced by the list. If a list starting with ``None``
is returned, the list is appended after the first of current two
elements. The first arg of the callable may be ``None``, when
the first of current two elements is not present yet.
:return: merged elements
"""
res = []
prev_e = None
for e in elements:
new = rule(prev_e, e)
if new is None:
res.append(e)
elif isinstance(new, list):
if new[0] is not None:
del res[-1]
else:
new = new[1:]
res.extend(new)
else:
del res[-1]
res.append(new)
prev_e = res[-1]
return res
def stop_merging_on_seen(
stop_instance,
rule: ty.Callable,
) -> ty.Callable:
"""The ``rule`` perform merging before seen the ``stop_instance``."""
class _StoppableRule:
def __init__(self):
self.seen_stop_instance = False
def __call__(self, e1, e2):
if not self.seen_stop_instance:
if e2 == stop_instance:
self.seen_stop_instance = True
else:
return rule(e1, e2)
return None
return _StoppableRule()
def merge_whitespace_rule(e1, e2):
"""
Returns a ``Whitespace`` if both ``e1`` and ``e2`` are of type
``Whitespace``, otherwise returns ``None``.
"""
if isinstance(e1, Whitespace) and isinstance(e2, Whitespace):
if isinstance(e1, LineBreak) and isinstance(e2, LineBreak):
return LineBreak()
if isinstance(e1, LineBreak) and isinstance(e2, Newline):
return LineBreak()
if isinstance(e1, LineBreak) and isinstance(e2, Space):
return LineBreak()
if isinstance(e1, LineBreak) and isinstance(e2, Tab):
return LineBreak()
if isinstance(e1, Newline) and isinstance(e2, LineBreak):
return LineBreak()
if isinstance(e1, Newline) and isinstance(e2, Newline):
return LineBreak()
if isinstance(e1, Newline) and isinstance(e2, Space):
return Newline()
if isinstance(e1, Newline) and isinstance(e2, Tab):
return Newline()
if isinstance(e1, Space) and isinstance(e2, LineBreak):
return LineBreak()
if isinstance(e1, Space) and isinstance(e2, Newline):
return Newline()
if isinstance(e1, Space) and isinstance(e2, Space):
return Space()
if isinstance(e1, Space) and isinstance(e2, Tab):
return Space()
if isinstance(e1, Tab) and isinstance(e2, LineBreak):
return LineBreak()
if isinstance(e1, Tab) and isinstance(e2, Newline):
return Newline()
if isinstance(e1, Tab) and isinstance(e2, Space):
return Space()
return Space()
return None
def recognize_whitespace(text: str) -> ty.List[ty.Union[str, Whitespace]]:
tr_dict = {
' ': Space(),
'\n': Newline(),
'\t': Tab(),
}
res = [tr_dict.get(ch, ch) for ch in text]
def merge_str_rule(e1, e2):
if isinstance(e1, str) and isinstance(e2, str):
return e1 + e2
return None
res = stack_merge(res, merge_str_rule)
return res
def recognize_merge_whitespace(
text: str) -> ty.List[ty.Union[str, Whitespace]]:
# recognize linebreaks
res1 = []
start = 0
for m in Pat.linebreak.finditer(text):
if start < m.start():
res1.append(text[start:m.start()])
res1.append(LineBreak())
start = m.end()
if start < len(text):
res1.append(text[start:])
# recognize remaining newlines
res2 = []
for text in res1:
if isinstance(text, str):
start = 0
for m in Pat.newline.finditer(text):
if start < m.start():
res2.append(text[start:m.start()])
res2.append(Newline())
start = m.end()
if start < len(text):
res2.append(text[start:])
else:
res2.append(text)
# recognize remaining whitespaces
res3 = []
for text in res2:
if isinstance(text, str):
start = 0
for m in Pat.whitespace.finditer(text):
if start < m.start():
res3.append(text[start:m.start()])
res3.append(Space())
start = m.end()
if start < len(text):
res3.append(text[start:])
else:
res3.append(text)
# merge whitespace objects
res4 = stack_merge(res3, merge_whitespace_rule)
return res4
class LocalHref:
"""
Represents the text part of an <a> tag referencing a within-document
location.
"""
__slots__ = ['elements', 'href', 'ref']
def __init__(self, elements: ty.List[ty.Union[str, VerbText, Whitespace]],
href: str):
"""
:param elements: children elements
:param href: the href without the leading '#'
"""
self.elements = elements
self.href = href
self.ref = None
def __repr__(self):
return '{}(href={!r}, ref={!r}, elements={!r})'.format(
type(self).__name__, self.href, self.ref, self.elements)
def as_text(self):
if self.ref is None:
raise ValueError('self.ref is None')
res = ['[[#', self.ref, '|']
res.extend(self.elements)
res.append(']]')
return res
class BookmarkHash:
__slots__ = ['hash_']
def __init__(self, hash_: str):
self.hash_ = hash_
def __repr__(self):
return '{}(hash_={!r})'.format(type(self).__name__, self.hash_)
def __str__(self):
return ' ^' + self.hash_
IntermediateElementType = ty.Union[SupportedElementType, PhantomElement,
VerbText, Whitespace, LocalHref,
BookmarkHash]
def resolve_local_hrefs(
elements: ty.List[IntermediateElementType],
ref_context: ty.Dict[str, 'RefContextEntry'],
) -> None:
"""Resolve ``LocalHref``s inplace."""
for e in elements:
if isinstance(e, LocalHref):
try:
ctx = ref_context[e.href]
if ctx.type_ == 'header':
e.ref = ctx.ref
else:
e.ref = '^' + ctx.ref
ref_context[e.href].used = True
except KeyError:
pass
def resolve_bookmark_hashes(
elements: ty.List[IntermediateElementType],
ref_context: ty.Dict[str, 'RefContextEntry'],
) -> ty.List[IntermediateElementType]:
"""Resolve ``BookmarkHash``s."""
res = []
for e in elements:
if isinstance(e, BookmarkHash):
for ctx in ref_context.values():
if ctx.type_ == 'hash' and ctx.ref == e.hash_ and ctx.used:
res.append(str(e))
break
else:
res.append(e)
return res
def escape(text: str) -> str:
"""Escape backslashes, asterisks and underscores."""
text = text.replace('\\', '\\\\')
text = text.replace('*', '\\*')
text = text.replace('_', '\\_')
return text
def as_text(
elements: ty.List[IntermediateElementType],
phantom_policy: ty.Literal['pass', 'ignore', 'warn', 'raise'],
tag_policy: ty.Literal['pass', 'raise'] = 'raise',
merge_whitespace: bool = True,
eval_local_href: ty.Literal['elements', 'text'] = False,
bookmark_hash_policy: ty.Literal['pass', 'ignore', 'eval',
'raise'] = 'pass',
eval_whitespace: bool = False,
escape_text: bool = False,
eval_verb: bool = False,
) -> ty.List[IntermediateElementType]:
"""
:param elements: elements to collapse
:param phantom_policy: policy when finding ``PhantomElement``
:param tag_policy: policy when finding ``StartElement`` or ``EndElement``
:param merge_whitespace: if ``True``, successive linebreaks are
substituted by one single ``LineBreak``, and then remaining
successive whitespace characters are substituded by one ``Space``
:param eval_local_href: if 'text', evaluate ``LocalHref`` to text; if
'elements', evaluate it to its children elements; if ``False``,
don't evaluate it
:param bookmark_hash_policy: if 'pass', pass ``BookmarkHash`` object as is;
if 'ignore', evalutate to empty string; if 'eval', evaluate using
its ``__str__`` method; if 'raise', raise ``TypeError``
:param eval_whitespace: if ``True``, evaluate ``Whitespace`` after
evaluating ``LocalHref``
:param escape_text: if ``True``, escape non-``VerbText`` text after
evaluating whitespace
:param eval_verb: also evaluate ``VerbText`` to ``str`` after escaping
:raise TypeError: if ``elements`` contain types other than ``str`` or
``VerbText``
"""
# escape and type check
res1 = []
for e in elements:
if isinstance(e, (str, VerbText, Whitespace, LocalHref, BookmarkHash)):
res1.append(e)
elif isinstance(e, PhantomElement):
if phantom_policy == 'pass':
res1.append(e)
elif phantom_policy == 'ignore':
pass
elif phantom_policy == 'warn':
warnings.warn('unexpected PhantomElement: {!r}'.format(e))
else:
raise TypeError('unexpected PhantomElement: {!r}'.format(e))
elif isinstance(e, (StartElement, EndElement)):
if tag_policy == 'raise':
raise TypeError('invalid type: {}'.format(type(e)))
res1.append(e)
else:
raise TypeError('invalid type: {}'.format(type(e)))
# merge whitespace in each element
res2 = []
sbuf = []
for e in res1:
if isinstance(e, str):
sbuf.append(e)
else:
s = ''.join(sbuf)
if merge_whitespace:
res2.extend(recognize_merge_whitespace(s))
else:
res2.extend(recognize_whitespace(s))
sbuf.clear()
res2.append(e)
if sbuf:
s = ''.join(sbuf)
if merge_whitespace:
res2.extend(recognize_merge_whitespace(s))
else:
res2.extend(recognize_whitespace(s))
if merge_whitespace:
# merge whitespace across elements
res3 = stack_merge(res2, merge_whitespace_rule)
else:
res3 = res2.copy()
if eval_local_href == 'text':
res3_2 = res3.copy()
res3.clear()
for e in res3_2:
if isinstance(e, LocalHref):
res3.extend(e.as_text())
else:
res3.append(e)
del res3_2
elif eval_local_href == 'elements':
res3_2 = res3.copy()
res3.clear()
for e in res3_2:
if isinstance(e, LocalHref):
res3.extend(e.elements)
else:
res3.append(e)
del res3_2
elif eval_local_href:
raise ValueError(
'invalid eval_local_href value: {}'.format(eval_local_href))
if bookmark_hash_policy == 'pass':
pass
elif bookmark_hash_policy == 'ignore':
res3 = [e for e in res3 if not isinstance(e, BookmarkHash)]
elif bookmark_hash_policy == 'eval':
res3 = [str(e) if isinstance(e, BookmarkHash) else e for e in res3]
elif bookmark_hash_policy == 'raise':
if any(isinstance(e, BookmarkHash) for e in res3):
raise TypeError('unexpected BookmarkHash encountered')
else:
raise ValueError(
'invalid bookmark_hash_policy: {}'.format(bookmark_hash_policy))
if eval_whitespace:
res3 = [str(e) if isinstance(e, Whitespace) else e for e in res3]
if escape_text:
res3 = [escape(e) if isinstance(e, str) else e for e in res3]
if eval_verb:
res3 = [str(e) if isinstance(e, VerbText) else e for e in res3]
def merge_str_rule(e1, e2):
if isinstance(e1, str) and isinstance(e2, str):
return e1 + e2
return None
res4 = stack_merge(res3, merge_str_rule)
return res4
def check_converged(elements: ty.List[IntermediateElementType]) -> bool:
"""
Returns ``True`` when ``elements`` only consists of ``str``,
``VerbTect`` and ``Whitespace``.
"""
for e in elements:
if not (isinstance(e, (str, VerbText, Whitespace, PhantomElement)) or
(isinstance(e, LocalHref) and e.ref is not None)
or isinstance(e, BookmarkHash)):
return False
return True
def contains_unparsed_element(
elements: ty.List[IntermediateElementType]) -> bool:
return any(isinstance(e, (StartElement, EndElement)) for e in elements)
def collect_phantom(
elements: ty.List[IntermediateElementType],
phantom_type: ty.Type[T],
) -> ty.Tuple[ty.List[IntermediateElementType], ty.List[T]]:
res = []
phantoms = []
if not phantom_type:
phantom_type = PhantomElement
for e in elements:
if isinstance(e, phantom_type):
phantoms.append(e)
else:
res.append(e)
return res, phantoms
class ProcessingNotConvergedError(Exception):
pass
class RefContextEntry:
__slots__ = ['type_', 'ref', 'used']
def __init__(
self,
type_: ty.Literal['hash', 'header'],
ref: str,
) -> None:
self.type_: str = type_
self.ref: str = ref
self.used: bool = False
def regenerate_xml(
root_tag: str,
attrib: ty.Dict[str, str],
elements: ty.List[SupportedElementType],
) -> str:
"""
Regenerate XML string from root tag and enclosing elements.
:param root_tag: the tag name
:param attrib: the attributes
:param elements: the enclosing elements
:return: the XML bytes
"""
elements = elements.copy()
elements.insert(0, StartElement(root_tag, attrib))
elements.append(EndElement(root_tag))
stack = []
for e in elements:
if isinstance(e, EndElement):
enclosed = []
while not isinstance(stack[-1], StartElement):
enclosed.append(stack.pop())