forked from sergiocorreia/parse-smcl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
smcl_parser.py
1108 lines (906 loc) · 34.8 KB
/
smcl_parser.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
# -------------------------------------------------------------
# Imports
# -------------------------------------------------------------
import os
import re
import shlex
from lxml import etree # http://infohost.nmt.edu/~shipman/soft/pylxml/web/index.html
# -------------------------------------------------------------
# Constants
# -------------------------------------------------------------
pclass = re.compile(r'p(std|see|hang\d?|more\d?|in\d?)')
opt_pat = re.compile("""
(?P<outside>
[^(]*
)
\(
(?P<inside>
[^)]*
)
\)
""", re.VERBOSE)
# -------------------------------------------------------------
# Functions
# -------------------------------------------------------------
def parse_improvements(root):
"""Replace certain tables into lists or code blocks"""
convert_code(root)
for element in root.cssselect('table.standard'):
if detect_ul(element):
convert_ul(element)
elif detect_ol(element):
convert_ol(element)
#ok_paras = {'std', 'see', 'hang', 'more', 'in', 'hang2', 'more2'}
#for p in root.cssselect('p'):
# cl = p.attrib.get('class', None)
# if cl and cl not in ok_paras:
# print(cl)
return root
def detect_ul(table):
"""Detect unordered list"""
if not len(table):
return False
for tr in table:
if len(tr)!=2:
return False
td1 = tr[0]
if len(td1) or td1.text.strip()!='-':
return False
return True
def convert_ul(table):
"""Convert table to unordered list"""
table.tag = 'ul'
if table.get('class'):
del table.attrib['class']
for tr in table:
tr.tag = 'li'
tr.text = tr[1].text.lstrip()
for el in tr[1]:
tr.append(el)
for td in tr[:2]:
tr.remove(td)
def detect_ol(table):
"""Detect ordered list"""
if not len(table):
return False
for tr in table:
if len(tr)!=2:
return False
td1 = tr[0]
# Only keep plausible ordered lists
if td1.text is None:
return False
text = td1.text.strip()
if not text or len(text)>3:
return False
if text[-1] not in ('.', ')'):
return False
if not text[:-1].isalpha() and not text[:-1].isdigit():
return False
if len(td1):
return False
return True
def convert_ol(table):
"""Convert table to ordered list"""
table.tag = 'ol'
if table.get('class'):
del table.attrib['class']
for tr in table:
tr.tag = 'li'
tr.text = tr[1].text.lstrip()
for el in tr[1]:
tr.append(el)
for td in tr[:2]:
tr.remove(td)
def convert_code(root):
candidates = root.cssselect('p.hang2 > code.command')
last_pos = -1
last_valid_code = last_valid_pre = None
for candidate in candidates:
p = candidate.getparent()
empty_tail = candidate.tail is None or not candidate.tail.strip()
starts_with_dot = candidate.text and (candidate.text.startswith('. ') or candidate.text=='.')
valid = p.text is None and empty_tail and candidate.text is not None and starts_with_dot
if valid:
pos = root.index(p)
assert pos>last_pos
candidate.text = candidate.text[2:] # Remove dot and add that in CSS so people can copy easily
# Move to pre block
if pos == last_pos + 1:
append_to_tail(last_valid_pre[-1], '\n')
candidate.set('class', 'language-stata')
last_valid_pre.append(candidate)
if p.tail is not None:
append_to_tail(last_valid_pre, p.tail)
root.remove(p)
# Start new pre block
else:
p.tag = 'pre'
del p.attrib["class"]
candidate.set('class', 'language-stata')
last_valid_code = candidate
last_valid_pre = p
last_pos = pos
def parse_inlines(root, current_file):
assert root.tag=='div'
valid_tags = ('h1', 'h2', 'h3', 'h4', 'p',
'table', 'thead', 'tbody', 'tfoot', 'tr', 'td',
'a', 'nav', 'ul', 'li', 'hr',
'code', 'kbd', 'var', 'samp', 'br', 'span', 'strong', 'b')
custom_tags = ('newvar', 'var', 'vars', 'depvar', 'depvars', 'indepvars',
'varname', 'varlist', 'depvarlist',
'ifin', 'weight', 'dtype')
formatting_directives = ('sf', 'it', 'bf',
'input', 'error', 'result', 'text',
'inp', 'err', 'res', 'txt',
'hilite', 'hi', 'ul')
for element in root.iterdescendants():
tag = element.tag
opt = element.get('options')
if tag in valid_tags:
continue
if tag == 'cmd' and (element.text or len(element)):
parse_cmd(element)
elif tag == 'cmdab':
parse_cmdab(element)
elif tag == 'opt':
parse_opt(element, current_file)
elif tag == 'opth':
parse_opt(element, current_file, help=True)
elif tag == 'help':
parse_browse(element, current_file, is_help=True)
elif tag == 'helpb':
parse_browse(element, current_file, is_help=True, is_bold=True)
elif tag == 'manhelp':
parse_browse(element, current_file, is_help=True, is_man=True)
elif tag == 'manhelpi':
parse_browse(element, current_file, is_help=True, is_man=True, is_italics=True)
elif tag == 'browse':
parse_browse(element, current_file)
elif tag == 'manpage':
parse_pdf_link(element, is_manpage=True)
elif tag == 'mansection':
parse_pdf_link(element, is_mansection=True)
elif tag == 'manlink':
parse_pdf_link(element, is_manlink=True)
elif tag == 'manlinki':
parse_pdf_link(element, is_manlink=True, is_italics=True)
elif tag == 'break':
parse_break(element)
elif tag in custom_tags:
parse_custom(element)
elif tag in formatting_directives and (element.text or len(element)):
parse_formatting(element)
elif tag == 'hline' and opt is not None:
parse_hline(element, opt)
elif tag == 'stata':
parse_stata(element, opt)
elif tag == 'bind':
parse_bind(element)
else:
print('UNUSED INLINE:', etree.tostring(element))
element.tag = 'span'
if element.text is None:
element.text = ''
element.text = '{{{} {}{}{}}}'.format(tag, opt, ':' if element.text else '', element.text)
return root
def parse_blocks(root, current_file):
# New tree
div = etree.Element('div')
div.set('class', 'smcl')
div.text = root.text
div.tail = root.tail
# Title
title = etree.SubElement(div, 'h1')
title.text = 'Help for ' + current_file
# Navigation menus
nav_internal = etree.Element('nav', id='table-of-contents')
nav_internal.set('class', 'smcl-nav')
ul_internal = etree.SubElement(nav_internal, 'ul')
etree.SubElement(ul_internal, 'li', attrib={'class':'description'}).text = 'Jump to:'
div.append(nav_internal)
nav_external = etree.Element('nav', id='related-content')
nav_external.set('class', 'smcl-nav')
ul_external = etree.SubElement(nav_external, 'ul')
etree.SubElement(ul_external, 'li', attrib={'class':'description'}).text = 'Also see:'
div.append(nav_external)
# Misc
table_margins = {'active':'', 'default': [0, 31, 35, 0]}
syntab_margins = {'active':'', 'default': [20]}
nobreak = False
link_id = None
remaining = 0
while len(root):
element = root[0]
tag = element.tag
opt = element.get('options')
syntab_bug = tag=='p2col' and len(root)>4 \
and root[1].tag=='p_end' and root[2].tag=='newline' and root[3].tag=='synopt'
# Meta directives
if tag == 'comment' and opt.startswith('*! '):
parse_starbang(div, element, opt)
elif tag == 'viewerjumpto':
parse_viewer(ul_internal, element, opt, current_file)
elif tag == 'vieweralsosee':
parse_viewer(ul_external, element, opt, current_file)
elif tag == 'viewerdialog':
remove(element, div, nested=True) # Can't access dialog tabs
# Margins (don't get saved into tree but affect subsequent blocks)
elif tag in ('p2colset','p2colreset','synoptset'):
parse_margins(table_margins, syntab_margins, element, opt, div)
# Line breaks
elif tag == 'nobreak':
nobreak = True
remove(element, div, nested=True)
elif nobreak and tag == 'newline':
nobreak = False
remove(element, div, nested=True)
# Marker tags are added as id's for the next block
elif tag == 'marker':
link_id = opt.strip()
remove(element, div, nested=True)
# Heading blocks (title and dlgtab)
elif tag in ('title', 'dlgtab'):
parse_heading(div, element, opt)
link_id = add_id(div, link_id)
# Horizontal rules
elif tag == 'hline':
parse_thematic_break(div, element)
# Para blocks (paragraphs)
elif tag == 'p' or pclass.match(tag):
parse_para(div, element, opt)
link_id = add_id(div, link_id)
# Table blocks (2 cols)
elif tag == 'p2col' and not syntab_bug:
parse_table(div, element, opt, table_margins, syntab_margins)
link_id = add_id(div, link_id)
# Syntax Table blocks (3 cols)
elif tag in ('synopthdr', 'synoptline', 'syntab', 'synopt', 'p2coldent') or syntab_bug:
if syntab_bug:
element.tag = 'syntab'
root.remove(root[1])
parse_syntab(div, element, opt, table_margins, syntab_margins)
link_id = add_id(div, link_id)
elif tag == 'newline':
if element.tail is None:
element.tail = ''
remove(element, div, nested=True, prefix='\n')
elif tag =='col':
parse_col(div, element, opt)
link_id = add_id(div, link_id)
else:
#print('UNUSED BLOCK', etree.tostring(element))
div.append(element)
remaining += 1
# Remove navigation menus if not needed
if len(ul_internal)==1:
remove(nav_internal, div, nested=True) # Attach to previous element div<nav
if len(ul_external)==1:
remove(nav_external, div, nested=True) # Attach to previous element div<nav
#print('[TODO] Remaining elements:', remaining)
return div
# -------------------------------------------------------------
def parse_starbang(div, element, opt):
"""Store *! comments in SMCL root node"""
k, v = opt[2:].strip().split(maxsplit=1)
div.set(k, v)
remove(element, div, nested=True)
def parse_viewer(ul, element, opt, current_file):
assert opt is not None, etree.tostring(element)
try:
text, link = shlex.split(opt)
except ValueError:
print(etree.tostring(element))
assert 0
if link != '--':
li = etree.SubElement(ul, 'li', attrib={'class':'link'})
if link.startswith('manpage '):
href = resolve_pdf_link(link.split(' ', maxsplit=1)[1], is_manpage=True)
elif link.startswith('mansection '):
href = resolve_pdf_link(link.split(' ', maxsplit=1)[1], is_mansection=True)
elif link.startswith('manlink '):
href = resolve_pdf_link(link.split(' ', maxsplit=1)[1], is_manlink=True)
elif link.startswith('manlinki '):
href = resolve_pdf_link(link.split(' ', maxsplit=1)[1], is_manlinki=True)
else:
href = fix_link(link, current_file)
a = etree.SubElement(li, 'a', href=href)
a.text = text
remove(element, ul, nested=False)
def parse_margins(table_margins, syntab_margins, element, opt, destination):
if element.tag=='p2colset':
table_margins['active'] = [int(subopt) for subopt in opt.split()]
elif element.tag=='p2colreset':
# Restore margins
table_margins['active'] = table_margins['default']
elif element.tag=='synoptset':
syntab_margins['active'] = opt.split()
remove(element, destination, nested=True)
def parse_heading(div, element, opt):
element.tag ='h2' if element.tag=='title' else 'h3'
if opt:
element.set('margins', opt.strip())
# Discard first newline after title, use subsequent to leave larger bottom margins
eat_blank_lines(element, num_discard=1)
div.append(element) # Must be at the end
def parse_thematic_break(div, element):
# the <hr> element is now more akin to a thematic break:
# http://html5doctor.com/small-hr-element/
element.tag = 'hr'
eat_blank_lines(element, num_discard=1)
div.append(element) # Must be at the end
def parse_para(div, para, opt):
if opt:
del para.attrib['options']
opt = parse_options(opt, 'para') if para.tag=='p' else para.tag[1:]
para.tag = 'p'
para.set('class', opt)
move_tail_inside(para)
root = para.getparent()
last_was_empty = False
while len(root)>1:
element = root[1]
tag = element.tag
# End the paragraph
if tag == 'p_end' or (tag == 'newline' and last_was_empty):
safe_remove(element, para)
# Pop newline if it follows {p_end}
if len(root)>1 and root[1].tag=='newline':
remove(root[1], para, nested=False)
break
last_was_empty = False
# Replace new lines with spaces
if tag == 'newline':
if element.tail is None or not len(element.tail.strip()):
last_was_empty = True
element.tail = ''
remove(element, para, nested=True, prefix = ' ')
else:
para.append(element)
# Remove leading spaces; no real effect
if para.text is not None:
para.text = para.text.lstrip()
## We can use subsequent newlines to leave wider bottom margins
eat_blank_lines(element, num_discard=0)
div.append(para)
def parse_table(div, element, opt, table_margins, syntab_margins):
root = element.getparent()
table = etree.Element('table') #, border='1')
table.set('class', 'standard')
last_tag = None
if opt is not None:
opt = parse_options(opt, 'table')
table.set('margins', str(opt))
del element.attrib['options']
last_was_empty = False
while len(root):
element = root[0]
tag = element.tag
opt = element.get('options')
# First column of a new row
if tag == 'p2col':
tr = etree.SubElement(table, 'tr')
td1 = element
td1.tag = 'td'
tr.append(td1) # First column
td2 = etree.SubElement(tr, 'td') # Second column
if td1.tail is not None:
td2.text = td1.tail
td1.tail = None
# END OF TABLE?
elif tag==last_tag=='newline' and last_was_empty:
if len(root)==1 or root[1].tag not in ('p_end', 'p2col', 'p2colset', 'p2colreset'):
safe_remove(element, table)
break
else:
safe_remove(element, table[-1] if len(table) else table)
# End of the second column
elif tag == 'p_end':
remove(element, td2)
# Update margins
elif tag in ('p2colset','p2colreset','synoptset'):
parse_margins(table_margins, syntab_margins, element, opt, table)
elif tag=='newline':
if element.tail is None or not len(element.tail.strip()):
last_was_empty = True
else:
last_was_empty = False
td2 = table[-1][1]
if element.tail is None:
element.tail = ''
remove(element, table[-1][1], nested=True, prefix=' ')
elif tag=='nobreak':
remove(element, table, nested=True)
# Attach to second column of active row
else:
table[-1][1].append(element)
last_tag = tag
if tag!='newline': last_was_empty = False
# We can use subsequent newlines to leave wider bottom margins
eat_blank_lines(table)
div.append(table)
def parse_syntab(div, element, opt, table_margins, syntab_margins):
root = element.getparent()
table = etree.Element('table') #, border='1')
table.set('class', 'syntab')
tfoot = etree.Element('tfoot')
last_tag = None
while len(root):
element = root[0]
tag = element.tag
opt = element.get('options')
# TABLE HEADINGS - {synopthdr} or {synopthdr:Col1}
if tag=='synopthdr':
thead = etree.SubElement(table, 'thead')
tr = etree.SubElement(thead, 'tr')
td1 = element
td1.tag = 'td'
if not len(td1) and td1.text is None:
td1.text = 'Options'
td1.set('colspan', '2')
tr.append(td1) # First column
td2 = etree.SubElement(tr, 'td') # Second column
td2.text = 'Description'
if td1.tail is not None:
td2.text += td1.tail
td1.tail = None
elif tag=='synoptline':
pass # we shouldn't need to set the table lines explicitly
safe_remove(element, table[-1] if len(table) else table)
# SECTION HEADINGS - {syntab:text}
elif tag=='syntab':
tbody = etree.SubElement(table, 'tbody')
tr = etree.SubElement(tbody, 'tr', {'class': 'section'})
td = element
td.tag = 'td'
td.set('colspan', '3')
move_tail_inside(td) # BUGBUG (not what Stata does)
tr.append(td) # Only column
# STANDARD ROWS - {synopt:text1}text2
elif tag=='synopt':
if not (len(table) and table[-1].tag=='tbody'):
tbody = etree.SubElement(table, 'tbody')
tr = etree.SubElement(tbody, 'tr')
# Column 1 is empty
etree.SubElement(tr, 'td', {'class': 'normal'})
# Column 2 is text1
td2 = element
td2.tag = 'td'
tr.append(td2)
# Column 3 is text2
td3 = etree.Element('td')
if td2.tail is not None:
td3.text = td2.tail
td2.tail = None
eat_row(root, td3)
tr.append(td3)
# MARGIN DIRECTIVES
elif tag in ('p2colset','p2colreset','synoptset'):
parse_margins(table_margins, syntab_margins, element, opt, table)
# END OF TABLE?
elif tag==last_tag=='newline':
if len(root)==1 or root[1].tag not in ('syntab', 'synopt'):
safe_remove(element, table)
break # End the table
else:
safe_remove(element, table[-1] if len(table) else table)
elif tag=='newline':
# Add a space with newline
add_leading_space_to_tail(element)
safe_remove(element, table[-1] if len(table) else table)
elif tag=='nobreak':
safe_remove(element, table[-1] if len(table) else table)
# {p2coldent char text1}text2
elif tag=='p2coldent':
if not (len(table) and table[-1].tag=='tbody'):
tbody = etree.SubElement(table, 'tbody')
tr = etree.SubElement(tbody, 'tr')
text = element.text.strip() if element.text is not None else ''
has_footnote = len(text) and len(text[:2].strip())==1
if has_footnote:
tr.set('style', 'has_footnote')
footnote = text[:2].strip()
element.text = text[2:].strip()
td1 = etree.SubElement(tr, 'td')
td1.text = footnote
td2 = element
td2.tag = 'td'
tr.append(td2)
if not has_footnote:
td2.set('colspan', '2')
# Column 3 is text2
td3 = etree.Element('td')
if td2.tail is not None:
td3.text = td2.tail
td2.tail = None
eat_row(root, td3)
tr.append(td3)
# Para blocks will be treated as footnotes
elif tag=='p' or pclass.match(tag):
tr = etree.SubElement(tfoot, 'tr', {'class': 'footnote'})
td = etree.SubElement(tr, 'td', colspan='3')
remove(element, td) # Will always append to text b/c td.text is empty
# We'll ignore the paragraph margins and just align with table, so we can discard the current directive
while len(root):
subelement = root[0]
subtag = subelement.tag
subopt = subelement.get('options')
if subtag=='p_end': # Only use {p_end} to stop, not line breaks (and don't allow them!)
safe_remove(subelement, tr)
break # End the paragraph
elif subtag=='newline':
if subelement.tail is None:
subelement.tail = ''
remove(subelement, td, nested=True, prefix=' ')
else:
td.append(subelement)
else:
print('UNUSED IN SYNTAB:', etree.tostring(element))
safe_remove(element, table[-1] if len(table) else table)
last_tag = tag
if len(tfoot):
table.append(tfoot)
# We can use subsequent newlines to leave wider bottom margins
eat_blank_lines(table)
div.append(table)
def parse_col(div, para, opt):
def calculate_offset(opt):
return opt * 0.5
assert opt and opt.isdigit()
opt = int(opt)
para.tag = 'p'
move_tail_inside(para)
root = para.getparent()
offset = calculate_offset(opt)
if offset:
para.set('style', 'padding-left: {}rem;'.format(offset))
del para.attrib['options']
while len(root)>1:
element = root[1]
tag = element.tag
opt = int(element.get('options')) if tag == 'col' else None
# End the paragraph
if tag == 'newline':
safe_remove(element, para)
break
# Attach
elif tag == 'col':
element.tag = 'span'
delta = calculate_offset(opt) - offset # New Offset - Old Offset
offset += delta # This is just New Offset
element.set('style', 'padding-left: {}rem;'.format(offset))
del element.attrib['options']
para.append(element)
else:
para.append(element)
div.append(para)
# -------------------------------------------------------------
def parse_cmd(element):
element.tag = 'code'
element.attrib['class'] = 'command'
def parse_cmdab(element):
element.tag = 'code'
element.attrib['class'] = 'command'
# Deal with abbreviation
split_text = element.text.split(sep=':', maxsplit=1)
if len(split_text)==2:
element.text = ''
abbrev = etree.Element('u')
abbrev.text = split_text[0]
abbrev.tail = split_text[1]
element.insert(0, abbrev)
def parse_opt(element, current_file, help=False):
assert len(element)==0, "An {opt} directives cannot contain other directives: " + etree.tostring(element).decode('latin1')
element.tag = 'code'
element.attrib['class'] = 'command'
# Move options to text for simplicity
if element.text is None:
element.text = ''
if element.get('options') is not None:
element.text = element.get('options') + (':' + element.text if element.text else '')
# Create subelements contained inside parens
if '(' in element.text:
m = opt_pat.match(element.text)
element.text = m.group('outside') + '('
inside = m.group('inside')
sep = ',' if ',' in inside else '|'
inside = inside.split(sep)
for subtext in inside:
subelement = etree.SubElement(element, 'var')
if help:
split_subtext = subtext.split(sep=':', maxsplit=1)
if len(split_subtext)==2:
link = split_subtext[0]
subtext = split_subtext[1]
else:
link = subtext
link = 'help ' + link
a = etree.SubElement(subelement, 'a', href=fix_link(link, current_file))
a.text = subtext
else:
subelement.text = subtext
subelement.tail = ','
element[-1].tail = ')'
# Deal with abbreviation
split_text = element.text.split(sep=':', maxsplit=1)
if len(split_text)==2:
element.text = ''
abbrev = etree.Element('u')
abbrev.text = split_text[0]
abbrev.tail = split_text[1]
element.insert(0, abbrev)
def resolve_pdf_link(link, is_manlink=False, is_mansection=False, is_manpage=False):
assert is_mansection + is_manpage + is_manlink == 1
page = ''
if is_manlink:
href = link.lower()
for char in (' ', '`', "'", '#', '$', '~', '{', '}', '[', ']'):
href = href.replace(char, '')
elif is_mansection:
href = link.replace(' ', '').lower()
elif is_manpage:
href, page = link.split(maxsplit=1)
page = page.strip()
assert page.isdigit()
href = fix_link('pdf ' + href, '', page=page)
return href
def parse_pdf_link(element, is_mansection=False, is_manpage=False, is_manlink=False, is_italics=False):
"""Parse {mansection} {manpage} {manlink} {manlinki}"""
assert is_mansection + is_manpage + is_manlink == 1
element.tag = 'a'
link = element.get('options')
del element.attrib['options']
if is_manlink:
assert element.text is None
# Resolve link
href = resolve_pdf_link(link, is_manlink=is_manlink, is_mansection=is_mansection, is_manpage=is_manpage)
element.set('href', href)
text = element.text if element.text is not None else link
element.text = None
if is_manlink:
bold = etree.SubElement(element, 'b')
manual, entry = link.split(maxsplit=1)
if is_italics:
bold.text = '[{}]'.format(manual)
italics = etree.SubElement(bold, 'i')
italics.text = entry
else:
bold.text = '[{}] {}'.format(manual, entry)
else:
element.text = text
def parse_browse(element, current_file, is_help=False, is_bold=True, is_man=False, is_italics=False):
"""Parse {help} {helpb} {browse} {manhelp} {manhelpi}"""
element.tag = 'a'
link = element.get('options')
del element.attrib['options']
if is_man:
link, manual = link.split(maxsplit=1)
is_bold = True
extra = ' ' + (element.text if element.text is not None else link)
element.text = '[' + manual + ']'
element.attrib['class'] = 'command'
prefix = 'help ' if is_help else ''
element.set('href', fix_link(prefix + link, current_file))
if element.text is None and len(element)==0:
element.text = link
if is_bold: # {helpb} and first part of {manhelp[i]}
bold = etree.SubElement(element, 'b')
bold.text = element.text
element.text = None
if is_man: # {manhelp} and {manhelpi}
if is_italics:
italics = etree.SubElement(element, 'i')
italics.text = extra
else:
bold.tail = extra
def parse_break(element):
assert len(element)==0
if element.text is not None:
append_to_tail(element, element.text)
element.text = None
element.tag = 'br'
def parse_custom(element):
element.attrib['class'] = 'command'
shortcuts = {'var': 'varname', 'vars': 'varlist', 'depvars': 'depvarlist'}
tag = element.tag
tag = shortcuts.get(tag, tag)
standard_list = ('newvar', 'varname', 'varlist', 'depvar', 'depvarlist', 'indepvars')
element.tag = 'a' if tag in standard_list else 'span'
if tag in standard_list:
element.set('href', fix_link('help ' + tag, ''))
element.text = tag + element.text if element.text else tag
elif tag=='ifin':
element.text = '['
var = etree.SubElement(element, 'var')
a = etree.SubElement(var, 'a', href=fix_link('help if', ''))
a.text = 'if'
var.tail = '] ['
var = etree.SubElement(element, 'var')
a = etree.SubElement(var, 'a', href=fix_link('help in', ''))
a.text = 'in'
var.tail = ']'
elif tag=='weight':
element.text = '['
var = etree.SubElement(element, 'var')
a = etree.SubElement(var, 'a', href=fix_link('help weight', ''))
a.text = 'weight'
var.tail = ']'
elif tag=='dtype':
element.text = '['
var = etree.SubElement(element, 'var')
a = etree.SubElement(var, 'a', href=fix_link('help datatypes', ''))
a.text = 'type'
var.tail = '] ['
else:
raise Exception
def parse_formatting(element):
shortcuts = {'inp': 'input', 'err': 'error', 'res': 'result', 'hi': 'hilite'}
tag = shortcuts.get(element.tag, element.tag)
if tag == 'input':
element.tag = 'kbd' # for keyboard or command line input
elif tag == 'error':
element.tag = 'samp'
element.set('class', 'error')
elif tag == 'result':
element.tag = 'samp'
element.set('class', 'result')
elif tag == 'hilite':
element.tag = 'strong' # strong is like bold but semantic, fits with the defn in the smcl help file
elif tag == 'ul':
element.tag = 'u'
elif tag == 'it':
# Not sure if 'var', 'i', or 'em' are better
element.tag = 'var'
element.set('class', 'command')
elif tag == 'bf':
element.tag = 'b'
elif tag == 'sf':
element.tag = 'span'
element.set('class', 'no-format')
else:
assert 0
def parse_hline(element, options):
# Do not confuse with parse_thematic_break !!
# This is for inline hlines
element.tag = 'span'
if options=='2':
del element.attrib['options']
element.append(etree.Entity('#8212')) # Decimal code for em dash
def parse_stata(element, opt):
"""Transform to p.hang2 > code.command so its picked by parse_improvements"""
del element.attrib['options']
parent = element.getparent()
if parent.tag=='div':
element.tag = 'p'
element.set('class', 'hang2')
element.text = None
code = etree.SubElement(element, 'code')
code.text = '. ' + opt.strip('"')
code.set('class', 'command')
elif parent.tag=='p' and parent.text is None and len(parent)==1:
if parent.get('style'):
del parent.attrib['style']
parent.set('class', 'hang2')
element.tag = 'code'
element.set('class', 'command')
element.text = '. ' + opt.strip('"')
else:
element.tag = 'code'
element.set('class', 'command')
element.text = '. ' + opt.strip('"')
def parse_bind(element):
element.tag = 'span'
element.set('class', 'nowrap') # .nowrap { white-space: nowrap; }
# -------------------------------------------------------------
def append_to_tail(element, text):
if element.tail is None:
element.tail = text
else:
element.tail += text
def append_to_text(element, text):
if element.text is None:
element.text = text
else:
element.text += text
def move_tail_inside(element):
if element.tail is not None:
if len(element):
append_to_tail(element[-1], element.tail)
else:
append_to_text(element, element.tail)
element.tail = None
def safe_remove(element, destination):
if element.tail is not None:
# Always append to tail; appending to text might be wrong
# as the prev. element might be e.g. a title and then you add it inside
append_to_tail(destination, element.tail)
element.getparent().remove(element)
def remove(element, destination, nested=False, prefix=''):
if element.tail is not None: