forked from jem/jemdoc
-
Notifications
You must be signed in to change notification settings - Fork 89
/
jemdoc
executable file
·1639 lines (1341 loc) · 43.5 KB
/
jemdoc
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
#!/usr/bin/env python
"""jemdoc version 0.7.3, 2012-11-27."""
# Copyright (C) 2007-2012 Jacob Mattingley ([email protected]).
#
# This file is part of jemdoc.
#
# jemdoc is free software; you can redistribute it and/or modify it under the
# terms of the GNU General Public License as published by the Free Software
# Foundation; either version 3 of the License, or (at your option) any later
# version.
#
# jemdoc is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
# A PARTICULAR PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with
# this program. If not, see <http://www.gnu.org/licenses/>.
#
# The LaTeX equation portions of this file were initially based on
# latexmath2png, by Kamil Kisiel ([email protected]).
#
from __future__ import print_function
import sys
import os
import re
import time
import io
from subprocess import *
from types import *
import tempfile
def info():
print(__doc__)
print('Platform: ' + sys.platform + '.')
print('Python: %s, located at %s.' % (sys.version[:5], sys.executable))
print('Equation support:', end=' ')
(supported, message) = testeqsupport()
if supported:
print('yes.')
else:
print('no.')
print(message)
def testeqsupport():
supported = True
msg = ''
p = Popen('latex --version', shell=True, stdout=PIPE, stderr=PIPE)
rc = p.wait()
if rc != 0:
msg += ' latex: not found.\n'
supported = False
else:
msg += ' latex: ' + p.stdout.readlines()[0].rstrip() + '.\n'
p = Popen('dvipng --version', shell=True, stdout=PIPE, stderr=PIPE)
rc = p.wait()
if rc != 0:
msg += ' dvipng: not found.\n'
supported = False
else:
msg += ' dvipng: ' + p.stdout.readlines()[0].rstrip() + '.\n'
return (supported, msg[:-1])
class controlstruct(object):
def __init__(self, infile, outfile=None, conf=None, inname=None, eqs=True,
eqdir='eqs', eqdpi=130):
self.inname = inname
self.inf = infile
self.outf = outfile
self.conf = conf
self.linenum = 0
self.otherfiles = []
self.eqs = eqs
self.eqdir = eqdir
self.eqdpi = eqdpi
# Default to supporting equations until we know otherwise.
self.eqsupport = True
self.eqcache = True
self.eqpackages = []
self.texlines = []
self.analytics = None
self.eqbd = {} # equation base depth.
self.baseline = None
def pushfile(self, newfile):
self.otherfiles.insert(0, self.inf)
self.inf = io.open(newfile, 'rb')
def nextfile(self):
self.inf.close()
self.inf = self.otherfiles.pop(0)
def showhelp():
a = """Usage: jemdoc [OPTIONS] [SOURCEFILE]
Produces html markup from a jemdoc SOURCEFILE.
Most of the time you can use jemdoc without any additional flags.
For example, typing
jemdoc index
will produce an index.html from index.jemdoc, using a default
configuration.
Some configuration options can be overridden by specifying a
configuration file. You can use
jemdoc --show-config
to print a sample configuration file (which includes all of the
default options). Any or all of the configuration [blocks] can be
overwritten by including them in a configuration file, and running,
for example,
jemdoc -c mywebsite.conf index.jemdoc
You can view version and installation details with
jemdoc --version
See http://jemdoc.jaboc.net/ for many more details."""
b = ''
for l in a.splitlines(True):
if l.startswith(' '*4):
b += l[4:]
else:
b += l
print(b)
def standardconf():
a = """[firstbit]
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta name="generator" content="jemdoc, see http://jemdoc.jaboc.net/" />
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
[defaultcss]
<link rel="stylesheet" href="jemdoc.css" type="text/css" />
[windowtitle]
# used in header for window title.
<title>|</title>
[fwtitlestart]
<div id="fwtitle">
[fwtitleend]
</div>
[doctitle]
# used at top of document.
<div id="toptitle">
<h1>|</h1>
[subtitle]
<div id="subtitle">|</div>
[doctitleend]
</div>
[bodystart]
</head>
<body>
[analytics]
<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
try {
var pageTracker = _gat._getTracker("|");
pageTracker._trackPageview();
} catch(err) {}</script>
[menustart]
<table summary="Table for page layout." id="tlayout">
<tr valign="top">
<td id="layout-menu">
[menuend]
</td>
<td id="layout-content">
[menucategory]
<div class="menu-category">|</div>
[menuitem]
<div class="menu-item"><a href="|1"|3>|2</a></div>
[specificcss]
<link rel="stylesheet" href="|" type="text/css" />
[specificjs]
<script src="|.js" type="text/javascript"></script>
[currentmenuitem]
<div class="menu-item"><a href="|1" class="current"|3>|2</a></div>
[nomenu]
<div id="layout-content">
[menulastbit]
</td>
</tr>
</table>
[nomenulastbit]
</div>
[bodyend]
</body>
</html>
[infoblock]
<div class="infoblock">
[codeblock]
<div class="codeblock">
[blocktitle]
<div class="blocktitle">|</div>
[infoblockcontent]
<div class="blockcontent">
[codeblockcontent]
<div class="blockcontent"><pre>
[codeblockend]
</pre></div></div>
[codeblockcontenttt]
<div class="blockcontent"><tt class="tthl">
[codeblockendtt]
</tt></div></div>
[infoblockend]
</div></div>
[footerstart]
<div id="footer">
<div id="footer-text">
[footerend]
</div>
</div>
[lastupdated]
Page generated |, by <a href="https://github.com/wsshin/jemdoc_mathjax" target="blank">jemdoc+MathJax</a>.
[sourcelink]
(<a href="|">source</a>)
"""
b = ''
for l in a.splitlines(True):
if l.startswith(' #'):
continue
elif l.startswith(' '):
b += l[2:]
else:
b += l
return b
class JandalError(Exception):
pass
class NoEqSupport(Exception):
pass
def raisejandal(msg, line=0):
if line == 0:
s = "%s" % msg
else:
s = "line %d: %s" % (line, msg)
raise JandalError(s)
def readnoncomment(f):
l = f.readline().decode('utf-8')
if l == '':
return l
elif l[0] == '#': # jem: be a little more generous with the comments we accept?
return readnoncomment(f)
else:
return l.rstrip() + '\n' # leave just one \n and no spaces etc.
def parseconf(cns):
syntax = {}
warn = False # jem. make configurable?
# manually add the defaults as a file handle.
fs = [io.BytesIO(standardconf().encode('utf-8'))]
for sname in cns:
fs.append(io.open(sname, 'rb'))
for f in fs:
while pc(controlstruct(f)) != '':
l = readnoncomment(f)
r = re.match(r'\[(.*)\]\n', l)
if r:
tag = r.group(1)
s = ''
l = readnoncomment(f)
while l not in ('\n', ''):
s += l
l = readnoncomment(f)
syntax[tag] = s
f.close()
return syntax
def insertmenuitems(f, mname, current, prefix):
m = io.open(mname, 'rb')
while pc(controlstruct(m)) != '':
l = readnoncomment(m)
l = l.strip()
if l == '':
continue
r = re.match(r'\s*(.*?)\s*\[(.*)\]', l)
if r: # then we have a menu item.
link = r.group(2)
if link[0] == '\\':
option = ' target="blank"'
link = link[1:]
else:
option = ''
# Don't use prefix if we have an absolute link.
if '://' not in r.group(2):
link = prefix + allreplace(link)
# replace spaces with nbsps.
# do do this, even though css would make it work - ie ignores.
# only replace spaces that aren't in {{ blocks.
in_quote = False
menuitem = ""
for group in re.split(r'({{|}})', r.group(1)):
if in_quote:
if group == '}}':
in_quote = False
next
else:
menuitem += group
else:
if group == '{{':
in_quote = True
next
else:
menuitem += br(re.sub(r'(?<!\\n) +', '~', group), f)
if link[-len(current):] == current:
hb(f.outf, f.conf['currentmenuitem'], link, menuitem, option)
else:
hb(f.outf, f.conf['menuitem'], link, menuitem, option)
else: # menu category.
hb(f.outf, f.conf['menucategory'], br(l, f))
m.close()
def out(f, s):
# print(type(s))
if sys.version_info[0] == 2 and type(s) is StringType:
f.write(s.decode('utf-8'))
else:
f.write(s)
def mathjaxussub(link):
link = link.replace('_', 'UNDERSCORE65358')
return link
def mathjaxusresub(r):
r = re.sub('UNDERSCORE65358', '_', r)
return r
def mathjaxeqsub(eqtext):
eqtext = eqtext.replace('\\', 'BACKSLASH65358')
eqtext = eqtext.replace('[', 'OPENBRACKET65358')
eqtext = eqtext.replace(']', 'CLOSEBRACKET65358')
eqtext = eqtext.replace('*', 'ASTERISK65358')
eqtext = eqtext.replace('+', 'PLUS65358')
eqtext = eqtext.replace('&', 'AMPERSAND65358')
eqtext = eqtext.replace('<', 'LESSTHAN65358')
eqtext = eqtext.replace('>', 'GREATERTHAN65358')
# eqtext = eqtext.replace('\n', ' ')
eqtext = eqtext.replace('_', 'UNDERSCORE65358')
eqtext = eqtext.replace('/', 'SLASH65358')
return eqtext
def mathjaxeqresub(r):
r = re.sub('BACKSLASH65358', r'\\', r)
r = re.sub('OPENBRACKET65358', '[', r)
r = re.sub('CLOSEBRACKET65358', ']', r)
r = re.sub('ASTERISK65358', '*', r)
r = re.sub('PLUS65358', '+', r)
r = re.sub('AMPERSAND65358', '&', r)
r = re.sub('LESSTHAN65358', '<', r)
r = re.sub('GREATERTHAN65358', '>', r)
r = re.sub('QUOTATION65358', '"', r)
r = re.sub('UNDERSCORE65358', '_', r)
r = re.sub('SLASH65358', '/', r)
return r
def hb(f, tag, content1, content2=None, content3=None):
"""Writes out a halfblock (hb)."""
if content1 is None:
content1 = ""
if content3 is None:
content3 = ""
if content2 is None:
# out(f, re.sub(r'\|', content1, tag))
r = re.sub(r'\|', content1, tag)
r = re.sub(r'\|3', content3, r)
r = mathjaxeqresub(r)
out(f, r)
else:
r = re.sub(r'\|1', content1, tag)
r = re.sub(r'\|3', content3, r)
r = re.sub(r'\|2', content2, r)
r = mathjaxeqresub(r)
out(f, r)
def pc(f, ditchcomments=True):
"""Peeks at next character in the file."""
# Should only be used to look at the first character of a new line.
c = f.inf.read(1).decode('cp1252')
if c: # only undo forward movement if we're not at the end.
if ditchcomments and c == '#':
l = nl(f)
if doincludes(f, l):
return "#"
if c in ' \t':
return pc(f)
if c == '\\':
c += pc(f)
f.inf.seek(-1, 1)
elif f.otherfiles:
f.nextfile()
return pc(f, ditchcomments)
return c
def doincludes(f, l):
ir = 'includeraw{'
i = 'include{'
l = l.rstrip()
if l.startswith(ir):
nf = io.open(l[len(ir):-1], 'rb')
f.outf.write(nf.read().decode('utf-8'))
nf.close()
elif l.startswith(i):
f.pushfile(l[len(i):-1])
else:
return False
return True
def nl(f, withcount=False, codemode=False):
"""Get input file line."""
s = f.inf.readline().decode('utf-8')
if not s and f.otherfiles:
f.nextfile()
return nl(f, withcount, codemode)
f.linenum += 1
if not codemode:
# remove any special characters - assume they were checked by pc()
# before we got here.
# remove any trailing comments.
s = s.lstrip(' \t')
s = re.sub(r'\s*(?<!\\)#.*', '', s)
if withcount:
if s[0] == '.':
m = r'\.'
else:
m = s[0]
r = re.match('(%s+) ' % m, s)
if not r:
raise SyntaxError("couldn't handle the jandal (code 12039) on line"
" %d" % f.linenum)
if not codemode:
s = s.lstrip('-.=:')
return (s, len(r.group(1)))
else:
if not codemode:
s = s.lstrip('-.=:')
return s
def np(f, withcount=False, eatblanks=True):
"""Gets the next paragraph from the input file."""
# New paragraph markers signalled by characters in following tuple.
if withcount:
(s, c) = nl(f, withcount)
else:
s = nl(f)
# Determine if the current line has an open inline equation block or not.
r = re.compile(r'(?<!\\)\$')
m = r.findall(s)
lm = len(m) % 2
isopeneq = lm == 1
# The followings characters signal a new paragraph when appeared right after '\n'.
# The original list included '-', which should not signal a new paragraph when used as the first character of a matrix row inside inline equation blocks. Therefore, '-' is handled separately.
nl_signals = ('\n', '.', ':', '', '=', '~', '{', '\\(', '\\)')
pcf = pc(f)
while (not isopeneq and pcf != '-' and pcf not in nl_signals) or (isopeneq and pcf not in nl_signals):
if isopeneq and pcf == '-':
s += '-'
ns = nl(f)
m = r.findall(ns)
lm = (lm + len(m)) % 2
isopeneq = lm == 1
s += ns
pcf = pc(f)
while eatblanks and pc(f) == '\n':
nl(f) # burn blank line.
# in both cases, ditch the trailing \n.
if withcount:
return (s, c)
else:
return s
def quote(s):
return re.sub(r"""[\\*/+"'<>&$%\.~[\]-]""", r'\\\g<0>', s)
def replacequoted(b):
"""Quotes {{raw html}} sections."""
r = re.compile(r'\{\{(.*?)\}\}', re.M + re.S)
m = r.search(b)
while m:
qb = quote(m.group(1))
b = b[:m.start()] + qb + b[m.end():]
m = r.search(b, m.start())
return b
def replacepercents(b):
# replace %sections% as +{{sections}}+. Do not replace if within a link.
r = re.compile(r'(?<!\\)%(.*?)(?<!\\)%', re.M + re.S)
m = r.search(b)
while m:
#qb = '+' + quote(m.group(1)) + '+'
a = re.sub(r'\[', r'BSNOTLINKLEFT12039XX', m.group(1))
a = re.sub(r'\]', r'BSNOTLINKRIGHT12039XX', a)
qb = '+{{' + a + '}}+'
b = b[:m.start()] + qb + b[m.end():]
m = r.search(b, m.start())
return b
def replaceequations(b, f):
# replace $sections$ and \(sections\) as equations.
rs = ((re.compile(r'(?<!\\)\$(.*?)(?<!\\)\$', re.M + re.S), False),
(re.compile(r'(?<!\\)\\\((.*?)(?<!\\)\\\)', re.M + re.S), True))
for (r, wl) in rs:
m = r.search(b)
while m:
eq = m.group(1)
if wl:
fn = str(abs(hash(eq + 'wl120930alsdk')))
else:
fn = str(abs(hash(eq)))
eqtext = allreplace(eq)
# print eqtext
# eqtext = eqtext.replace('\\', '')
eqtext = mathjaxeqsub(eqtext)
# Double braces will cause problems with escaping of image tag.
eqtext = eqtext.replace('{{', 'DOUBLEOPENBRACE')
eqtext = eqtext.replace('}}', 'DOUBLECLOSEBRACE')
if wl:
# b = b[:m.start()] + \
# '{{\n<div class="eqwl"><img class="eqwl" src="%s" alt="%s" />\n<br /></div>}}' % (fullfn, eqtext) + b[m.end():]
#b = b[:m.start()] + 'BACKSLASH65358OPENBRACKET65358\n' + eqtext + '\nBACKSLASH65358CLOSEBRACKET65358'+ b[m.end():]
b = b[:m.start()] + 'BACKSLASH65358OPENBRACKET65358' + eqtext + 'BACKSLASH65358CLOSEBRACKET65358'+ b[m.end():]
#b = b[:m.start()] + 'BACKSLASH(BACKSLASHbegin{equation}\n' + eqtext + '\nBACKSLASHend{equation}BACKSLASH)'+ b[m.end():]
b = '<p style=QUOTATION65358text-align:centerQUOTATION65358>\n' + b + '\n</p>'
b = mathjaxeqsub(b)
else:
# b = b[:m.start()] + \
# '{{<img class="eq" src="%s" alt="%s" style="vertical-align: -%dpx" />}}' % (fullfn, eqtext, offset) + b[m.end():]
b = b[:m.start()] + 'BACKSLASH65358(' + eqtext + 'BACKSLASH65358)' + b[m.end():]
# jem: also clean out line breaks in the alttext?
m = r.search(b, m.start())
return replacequoted(b)
def replaceimages(b):
# works with [img{width}{height}{alttext} location caption].
r = re.compile(r'(?<!\\)\[img((?:\{.*?\}){,3})\s(.*?)(?:\s(.*?))?(?<!\\)\]',
re.M + re.S)
m = r.search(b)
s = re.compile(r'{(.*?)}', re.M + re.S)
while m:
m1 = list(s.findall(m.group(1)))
m1 += ['']*(3 - len(m1))
bits = []
link = m.group(2).strip()
bits.append(r'src=\"%s\"' % quote(link))
if m1[0]:
if m1[0].isdigit():
s = m1[0] + 'px'
else:
s = m1[0]
bits.append(r'width=\"%s\"' % quote(s))
if m1[1]:
if m1[1].isdigit():
s = m1[1] + 'px'
else:
s = m1[1]
bits.append(r'height=\"%s\"' % quote(s))
if m1[2]:
bits.append(r'alt=\"%s\"' % quote(m1[2]))
else:
bits.append(r'alt=\"\"')
b = b[:m.start()] + r'<img %s />' % " ".join(bits) + b[m.end():]
m = r.search(b, m.start())
return b
def replacelinks(b):
# works with [link.html new link style].
r = re.compile(r'(?<!\\)\[(.*?)(?:\s(.*?))?(?<!\\)\]', re.M + re.S)
m = r.search(b)
while m:
m1 = m.group(1).strip()
if m1[0] == '/':
option = ''
m1 = m1[1:]
else:
option = ' target="blank"'
if '@' in m1 and not m1.startswith('mailto:') and not \
m1.startswith('http://'):
link = 'mailto:' + m1
else:
link = m1
# first unquote any hashes (e.g. for in-page links).
link = re.sub(r'\\#', '#', link)
# remove any +{{ or }}+ links.
link = re.sub(r'(\+\{\{|\}\}\+)', r'%', link)
link = quote(link)
link = mathjaxussub(link) # to prevent _ in address from changing
if m.group(2):
linkname = m.group(2).strip()
else:
# remove any mailto before labelling.
linkname = re.sub('^mailto:', '', link)
b = b[:m.start()] + r'<a href=\"%s\"%s>%s<\/a>' % (link, option, linkname) + b[m.end():]
m = r.search(b, m.start())
return b
def br(b, f, tableblock=False):
"""Does simple text replacements on a block of text. ('block replacements')"""
# Deal with environment variables (say, for Michael Grant).
r = re.compile(r"!\$(\w{2,})\$!", re.M + re.S)
for m in r.findall(b):
repl = os.environ.get(m)
if repl == None:
b = re.sub("!\$%s\$!" % m, 'FAILED_MATCH_' + m, b)
else:
b = re.sub("!\$%s\$!" % m, repl, b)
# Deal with literal backspaces.
if f.eqs and f.eqsupport:
b = replaceequations(b, f)
b = re.sub(r'\\\\', 'jemLITerl33talBS', b)
# Deal with {{html embedding}}.
b = replacequoted(b)
b = allreplace(b)
b = b.lstrip('-. \t') # remove leading spaces, tabs, dashes, dots.
b = replaceimages(b) # jem not sure if this is still used.
# Slightly nasty hackery in this next bit.
b = replacepercents(b)
b = replacelinks(b)
b = re.sub(r'BSNOTLINKLEFT12039XX', r'[', b)
b = re.sub(r'BSNOTLINKRIGHT12039XX', r']', b)
b = replacequoted(b)
# Deal with /italics/ first because the '/' in other tags would otherwise
# interfere.
r = re.compile(r'(?<!\\)/(.*?)(?<!\\)/', re.M + re.S)
b = re.sub(r, r'<i>\1</i>', b)
# Deal with *bold*.
r = re.compile(r'(?<!\\)\*(.*?)(?<!\\)\*', re.M + re.S)
b = re.sub(r, r'<b>\1</b>', b)
# Deal with _underscore_.
r = re.compile(r'(?<!\\)_(.*?)(?<!\\)_', re.M + re.S)
b = re.sub(r, r'<u>\1</u>', b)
b = mathjaxusresub(b)
# Deal with +monospace+.
r = re.compile(r'(?<!\\)\+(.*?)(?<!\\)\+', re.M + re.S)
b = re.sub(r, r'<tt>\1</tt>', b)
# Deal with "double quotes".
r = re.compile(r'(?<!\\)"(.*?)(?<!\\)"', re.M + re.S)
b = re.sub(r, r'“\1”', b)
# Deal with left quote `.
r = re.compile(r"(?<!\\)`", re.M + re.S)
b = re.sub(r, r'‘', b)
# Deal with apostrophe '.
# Add an assertion that the next character's not a letter, to deal with
# apostrophes properly.
r = re.compile(r"(?<!\\)'(?![a-zA-Z])", re.M + re.S)
b = re.sub(r, r'’', b)
# Deal with em dash ---.
r = re.compile(r"(?<!\\)---", re.M + re.S)
b = re.sub(r, r' — ', b)
# Deal with en dash --.
r = re.compile(r"(?<!\\)--", re.M + re.S)
b = re.sub(r, r'–', b)
# Deal with ellipsis ....
r = re.compile(r"(?<!\\)\.\.\.", re.M + re.S)
b = re.sub(r, r'…', b)
# Deal with non-breaking space ~.
r = re.compile(r"(?<!\\)~", re.M + re.S)
b = re.sub(r, r' ', b)
b = re.sub('TILDE', '~', b)
# Deal with registered trademark \R.
r = re.compile(r"(?<!\\)\\R", re.M + re.S)
b = re.sub(r, r'®', b)
# Deal with copyright \C.
r = re.compile(r"(?<!\\)\\C", re.M + re.S)
b = re.sub(r, r'©', b)
# Deal with middot \M.
r = re.compile(r"(?<!\\)\\M", re.M + re.S)
b = re.sub(r, r'·', b)
# Deal with line break.
r = re.compile(r"(?<!\\)\\n", re.M + re.S)
b = re.sub(r, r'<br />', b)
# Deal with paragraph break. Caution! Should only use when we're already in
# a paragraph.
r = re.compile(r"(?<!\\)\\p", re.M + re.S)
b = re.sub(r, r'</p><p>', b)
if tableblock:
# Deal with ||, meaning </td></tr><tr><td>
r = re.compile(r"(?<!\\)\|\|", re.M + re.S)
f.tablecol = 2
bcopy = b
b = ""
r2 = re.compile(r"(?<!\\)\|", re.M + re.S)
for l in bcopy.splitlines():
f.tablerow += 1
l = re.sub(r, r'</td></tr>\n<tr class="r%d"><td class="c1">' \
% f.tablerow, l)
l2 = ''
col = 2
r2s = r2.split(l)
for x in r2s[:-1]:
l2 += x + ('</td><td class="c%d">' % col)
col += 1
l2 += r2s[-1]
b += l2
# Second to last, remove any remaining quoting backslashes.
b = re.sub(r'\\(?!\\)', '', b)
# Deal with literal backspaces.
b = re.sub('jemLITerl33talBS', r'\\', b)
# Also fix up DOUBLEOPEN and DOUBLECLOSEBRACES.
b = re.sub('DOUBLEOPENBRACE', '{{', b)
b = re.sub('DOUBLECLOSEBRACE', '}}', b)
return b
def allreplace(b):
"""Replacements that should be done on everything."""
# The following replace &, >, < in LaTeX code with &, >, <. Is this necessary?
r = re.compile(r"(?<!\\)&", re.M + re.S)
b = re.sub(r, r'&', b)
r = re.compile(r"(?<!\\)>", re.M + re.S)
b = re.sub(r, r'>', b)
r = re.compile(r"(?<!\\)<", re.M + re.S)
b = re.sub(r, r'<', b)
return b
def pyint(f, l):
l = l.rstrip()
l = allreplace(l)
r = re.compile(r'(#.*)')
l = r.sub(r'<span class = "comment">\1</span>', l)
if l.startswith('>>>'):
hb(f, '<span class="pycommand">|</span>\n', l)
else:
out(f, l + '\n')
def putbsbs(l):
for i in range(len(l)):
l[i] = '\\b' + l[i] + '\\b'
return l
def gethl(lang):
# disable comments by default, by choosing unlikely regex.
d = {'strings':False}
if lang in ('py', 'python'):
d['statement'] = ['break', 'continue', 'del', 'except', 'exec',
'finally', 'pass', 'print', 'raise', 'return', 'try',
'with', 'global', 'assert', 'lambda', 'yield', 'def',
'class', 'for', 'while', 'if', 'elif', 'else',
'import', 'from', 'as', 'assert']
d['builtin'] = ['True', 'False', 'set', 'open', 'frozenset',
'enumerate', 'object', 'hasattr', 'getattr', 'filter',
'eval', 'zip', 'vars', 'unicode', 'type', 'str',
'repr', 'round', 'range', 'and', 'in', 'is', 'not',
'or']
d['special'] = ['cols', 'optvar', 'param', 'problem', 'norm2', 'norm1',
'value', 'minimize', 'maximize', 'rows', 'rand',
'randn', 'printval', 'matrix']
d['error'] = ['\w*Error',]
d['commentuntilend'] = '#'
d['strings'] = True
elif lang in ['c', 'c++', 'cpp']:
d['statement'] = ['if', 'else', 'printf', 'return', 'for']
d['builtin'] = ['static', 'typedef', 'int', 'float', 'double', 'void',
'clock_t', 'struct', 'long', 'extern', 'char']
d['operator'] = ['#include.*', '#define', '@pyval{', '}@', '@pyif{',
'@py{']
d['error'] = ['\w*Error',]
d['commentuntilend'] = ['//', '/*', ' * ', '*/']
elif lang in ('rb', 'ruby'):
d['statement'] = putbsbs(['while', 'until', 'unless', 'if', 'elsif',
'when', 'then', 'else', 'end', 'begin',
'rescue', 'class', 'def'])
d['operator'] = putbsbs(['and', 'not', 'or'])
d['builtin'] = putbsbs(['true', 'false', 'require', 'warn'])
d['special'] = putbsbs(['IO'])
d['error'] = putbsbs(['\w*Error',])
d['commentuntilend'] = '#'
d['strings'] = True
d['strings'] = True
if lang in ['c++', 'cpp']:
d['builtin'] += ['bool', 'virtual']
d['statement'] += ['new', 'delete']
d['operator'] += ['<<', '>>']
d['special'] = ['public', 'private', 'protected', 'template',
'ASSERT']
elif lang == 'sh':
d['statement'] = ['cd', 'ls', 'sudo', 'cat', 'alias', 'for', 'do',
'done', 'in', ]
d['operator'] = ['>', r'\\', r'\|', ';', '2>', 'monolith>',
'kiwi>', 'ant>', 'kakapo>', 'client>']
d['builtin'] = putbsbs(['gem', 'gcc', 'python', 'curl', 'wget', 'ssh',
'latex', 'find', 'sed', 'gs', 'grep', 'tee',
'gzip', 'killall', 'echo', 'touch',
'ifconfig', 'git', '(?<!\.)tar(?!\.)'])
d['commentuntilend'] = '#'
d['strings'] = True
elif lang == 'matlab':
d['statement'] = putbsbs(['max', 'min', 'find', 'rand', 'cumsum', 'randn', 'help',
'error', 'if', 'end', 'for'])
d['operator'] = ['>', 'ans =', '>>', '~', '\.\.\.']
d['builtin'] = putbsbs(['csolve'])
d['commentuntilend'] = '%'
d['strings'] = True
elif lang == 'commented':
d['commentuntilend'] = '#'
# Add bsbs (whatever those are).
for x in ['statement', 'builtin', 'special', 'error']:
if x in d:
d[x] = putbsbs(d[x])
return d
def language(f, l, hl):
l = l.rstrip()
l = allreplace(l)
# handle strings.
if hl['strings']:
r = re.compile(r'(".*?")')
l = r.sub(r'<span CLCLclass="string">\1</span>', l)
r = re.compile(r"('.*?')")
l = r.sub(r'<span CLCLclass="string">\1</span>', l)
if 'statement' in hl:
r = re.compile('(' + '|'.join(hl['statement']) + ')')
l = r.sub(r'<span class="statement">\1</span>', l)
if 'operator' in hl:
r = re.compile('(' + '|'.join(hl['operator']) + ')')
l = r.sub(r'<span class="operator">\1</span>', l)
if 'builtin' in hl:
r = re.compile('(' + '|'.join(hl['builtin']) + ')')
l = r.sub(r'<span class="builtin">\1</span>', l)
if 'special' in hl:
r = re.compile('(' + '|'.join(hl['special']) + ')')
l = r.sub(r'<span class="special">\1</span>', l)
if 'error' in hl:
r = re.compile('(' + '|'.join(hl['error']) + ')')
l = r.sub(r'<span class="error">\1</span>', l)
l = re.sub('CLCLclass', 'class', l)
if 'commentuntilend' in hl:
cue = hl['commentuntilend']
if isinstance(cue, (list, tuple)):
for x in cue:
if l.strip().startswith(x):
hb(f, '<span class="comment">|</span>\n', allreplace(l))
return
if '//' in cue: # Handle this separately.
r = re.compile(r'\/\/.*')
l = r.sub(r'<span class="comment">\g<0></span>', l)
elif cue == '#': # Handle this separately.
r = re.compile(r'#.*')
l = r.sub(r'<span class="comment">\g<0></span>', l)
elif cue == '%': # Handle this separately.
r = re.compile(r'%.*')
l = r.sub(r'<span class="comment">\g<0></span>', l)
elif l.strip().startswith(cue):
hb(f, '<span class="comment">|</span>\n', allreplace(l))