/
html.py
603 lines (473 loc) · 19 KB
/
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
"""
HTML Fragments
This module defines a HTML fragment class, which holds a piece of
HTML. This is primarily used in browser-based notebooks, though it
might be useful for creating static pages as well.
This module defines :class:`MathJax`, an object of which performs the task of
producing an HTML representation of any object. The produced HTML is
renderable in a browser-based notebook with the help of MathJax.
"""
#*****************************************************************************
# Copyright (C) 2008 William Stein <wstein@gmail.com>
#
# Distributed under the terms of the GNU General Public License (GPL)
# as published by the Free Software Foundation; either version 2 of
# the License, or (at your option) any later version.
# http://www.gnu.org/licenses/
#*****************************************************************************
import re
from sage.misc.latex import latex
from sage.misc.sage_eval import sage_eval
from sage.structure.sage_object import SageObject
macro_regex = re.compile(r'\\newcommand{(?P<name>\\[a-zA-Z]+)}(\[.+\])?{(?P<definition>.+)}')
class HtmlFragment(str, SageObject):
r"""
A HTML fragment.
This is a piece of HTML, usually not a complete document. For
example, just a ``<div>...</div>`` piece and not the entire
``<html>...</html>``.
EXAMPLES::
sage: from sage.misc.html import HtmlFragment
sage: HtmlFragment('<b>test</b>')
<b>test</b>
.. automethod:: _rich_repr_
"""
def _rich_repr_(self, display_manager, **kwds):
"""
Rich Output Magic Method
See :mod:`sage.repl.rich_output` for details.
EXAMPLES::
sage: from sage.repl.rich_output import get_display_manager
sage: dm = get_display_manager()
sage: h = sage.misc.html.HtmlFragment('<b>old</b>')
sage: h._rich_repr_(dm) # the doctest backend does not support html
OutputPlainText container
"""
OutputHtml = display_manager.types.OutputHtml
if OutputHtml in display_manager.supported_output():
return OutputHtml(self)
else:
return display_manager.types.OutputPlainText(self)
def math_parse(s):
r"""
Transform the string ``s`` with TeX maths to an HTML string renderable by
MathJax.
INPUT:
- ``s`` -- a string
OUTPUT:
A :class:`HtmlFragment` instance.
Specifically this method does the following:
* Replace all ``\$text\$``\'s by ``\(text\)``
* Replace all ``\$\$text\$\$``\'s by ``\[text\]``
* Replace all ``\\\$``\'s by ``\$``\'s. Note that this has precedence over
the above two cases.
EXAMPLES::
sage: print(sage.misc.html.math_parse('This is $2+2$.'))
This is \(2+2\).
sage: print(sage.misc.html.math_parse('This is $$2+2$$.'))
This is \[2+2\].
sage: print(sage.misc.html.math_parse('This is \\[2+2\\].'))
This is \[2+2\].
sage: print(sage.misc.html.math_parse(r'\$2+2\$ is rendered to $2+2$.'))
<span>$</span>2+2<span>$</span> is rendered to \(2+2\).
"""
# Below t always has the "parsed so far" version of s, and s is
# just the part of the original input s that hasn't been parsed.
t = ''
while True:
i = s.find('$')
if i == -1:
# No dollar signs -- definitely done.
return HtmlFragment(t + s)
elif i > 0 and s[i-1] == '\\':
# A dollar sign with a backslash right before it, so this is a
# normal dollar sign. If processEscapes is enabled in MathJax, "\$"
# will do the job. But as we do not assume that, we use the span
# tag safely.
t += s[:i-1] + '<span>$</span>'
s = s[i+1:]
continue
elif i+1 < len(s) and s[i+1] == '$':
# Found a math environment. Double dollar sign so display mode.
disp = True
else:
# Found math environment. Single dollar sign so default mode.
disp = False
# Now find the matching $ sign and form the html string.
if disp:
j = s[i+2:].find('$$')
if j == -1:
j = len(s)
s += '$$'
else:
j += i + 2
txt = s[i+2:j]
else:
j = s[i+2:].find('$')
if j == -1:
j = len(s)
s += '$'
else:
j += i + 2
txt = s[i+1:j]
if disp:
t += s[:i] + r'\[{0}\]'.format(' '.join(txt.splitlines()))
else:
t += s[:i] + r'\({0}\)'.format(' '.join(txt.splitlines()))
s = s[j+1:]
if disp:
s = s[1:]
return HtmlFragment(t)
class MathJaxExpr:
"""
An arbitrary MathJax expression that can be nicely concatenated.
EXAMPLES::
sage: from sage.misc.html import MathJaxExpr
sage: MathJaxExpr("a^{2}") + MathJaxExpr("x^{-1}")
a^{2}x^{-1}
"""
def __init__(self, y):
"""
Initialize a MathJax expression.
INPUT:
- ``y`` - a string
Note that no error checking is done on the type of ``y``.
EXAMPLES::
sage: from sage.misc.html import MathJaxExpr
sage: jax = MathJaxExpr(3); jax # indirect doctest
3
sage: TestSuite(jax).run(skip ="_test_pickling")
"""
self.__y = y
def __repr__(self):
"""
Print representation.
EXAMPLES::
sage: from sage.misc.html import MathJaxExpr
sage: jax = MathJaxExpr('3')
sage: jax.__repr__()
'3'
"""
return str(self.__y)
def __add__(self, y):
"""
'Add' MathJaxExpr ``self`` to ``y``. This concatenates them
(assuming that they're strings).
EXAMPLES::
sage: from sage.misc.html import MathJaxExpr
sage: j3 = MathJaxExpr('3')
sage: jx = MathJaxExpr('x')
sage: j3 + jx
3x
"""
return MathJaxExpr(self.__y + y)
def __radd__(self, y):
"""
'Add' MathJaxExpr ``y`` to ``self``. This concatenates them
(assuming that they're strings).
EXAMPLES::
sage: from sage.misc.html import MathJaxExpr
sage: j3 = MathJaxExpr('3')
sage: jx = MathJaxExpr('x')
sage: j3.__radd__(jx)
x3
"""
return MathJaxExpr(y + self.__y)
class MathJax:
r"""
Render LaTeX input using MathJax. This returns a :class:`MathJaxExpr`.
EXAMPLES::
sage: from sage.misc.html import MathJax
sage: MathJax()(3)
<html>\[3\]</html>
sage: MathJax()(ZZ)
<html>\[\newcommand{\Bold}[1]{\mathbf{#1}}\Bold{Z}\]</html>
"""
def __call__(self, x, combine_all=False):
r"""
Render LaTeX input using MathJax. This returns a :class:`MathJaxExpr`.
INPUT:
- ``x`` - a Sage object
- ``combine_all`` - boolean (Default: ``False``): If ``combine_all`` is
``True`` and the input is a tuple, then it does not return a tuple
and instead returns a string with all the elements separated by
a single space.
OUTPUT:
A :class:`MathJaxExpr`
EXAMPLES::
sage: from sage.misc.html import MathJax
sage: MathJax()(3)
<html>\[3\]</html>
sage: str(MathJax().eval(ZZ['x'], mode='display')) == str(MathJax()(ZZ['x']))
True
"""
return self.eval(x, combine_all=combine_all)
def eval(self, x, globals=None, locals=None, mode='display', combine_all=False):
r"""
Render LaTeX input using MathJax. This returns a :class:`MathJaxExpr`.
INPUT:
- ``x`` - a Sage object
- ``globals`` - a globals dictionary
- ``locals`` - extra local variables used when
evaluating Sage code in ``x``.
- ``mode`` - string (optional, default ``'display'``):
``'display'`` for displaymath, ``'inline'`` for inline
math, or ``'plain'`` for just the LaTeX code without the
surrounding html and script tags.
- ``combine_all`` - boolean (Default: ``False``): If ``combine_all`` is
``True`` and the input is a tuple, then it does not return a tuple
and instead returns a string with all the elements separated by
a single space.
OUTPUT:
A :class:`MathJaxExpr`
EXAMPLES::
sage: from sage.misc.html import MathJax
sage: MathJax().eval(3, mode='display')
<html>\[3\]</html>
sage: MathJax().eval(3, mode='inline')
<html>\(3\)</html>
sage: MathJax().eval(type(3), mode='inline')
<html>\(\verb|<class|\verb| |\verb|'sage.rings.integer.Integer'>|\)</html>
TESTS:
sage: from sage.misc.html import MathJax
sage: MathJax().eval(IntegerModRing(6))
<html>\[\newcommand{\ZZ}{\Bold{Z}}\newcommand{\Bold}[1]{\mathbf{#1}}\ZZ/6\ZZ\]</html>
"""
# Get a regular LaTeX representation of x
x = latex(x, combine_all=combine_all)
# The "\text{\texttt{...}}" blocks are reformed to be renderable by MathJax.
# These blocks are produced by str_function() defined in sage.misc.latex.
prefix = r"\text{\texttt{"
parts = x.split(prefix)
for i, part in enumerate(parts):
if i == 0:
continue # Nothing to do with the head part
n = 1
for closing, c in enumerate(part):
if c == "{" and part[closing - 1] != "\\":
n += 1
if c == "}" and part[closing - 1] != "\\":
n -= 1
if n == -1:
break
# part should end in "}}", so omit the last two characters
# from y
y = part[:closing-1]
for delimiter in r"""|"'`#%&,.:;?!@_~^+-/\=<>()[]{}0123456789E""":
if delimiter not in y:
break
if delimiter == "E":
# y is too complicated
delimiter = "|"
y = "(complicated string)"
wrapper = r"\verb" + delimiter + "%s" + delimiter
y = y.replace("{ }", " ").replace("{-}", "-")
for c in r"#$%&\^_{}~":
char_wrapper = r"{\char`\%s}" % c
y = y.replace(char_wrapper, c)
subparts = []
nspaces = 0
for subpart in y.split(" "):
if subpart == "":
nspaces += 1
continue
if nspaces > 0:
subparts.append(wrapper % (" " * nspaces))
nspaces = 1
subparts.append(wrapper % subpart)
subparts.append(part[closing + 1:])
parts[i] = "".join(subparts)
from sage.misc.latex_macros import sage_latex_macros
from sage.misc.latex import _Latex_prefs
latex_string = ''.join([_Latex_prefs._option['macros']] + parts)
# add a macro definition only if it appears in the latex string
macros_string = ''
latex_macros = sage_latex_macros()
test_string = latex_string
while test_string:
new_test_string = ''
for line in latex_macros:
m = macro_regex.match(line)
if m['name'] in test_string:
macros_string += line
new_test_string += '{' + m['definition'] + '}'
test_string = new_test_string
latex_string = macros_string + latex_string
mathjax_string = latex_string.replace('<', '<')
if mode == 'display':
html = r'<html>\[{0}\]</html>'
elif mode == 'inline':
html = r'<html>\({0}\)</html>'
elif mode == 'display_left':
html = r'<html>\(\displaystyle {0}\)</html>'
elif mode == 'plain':
return mathjax_string
else:
raise ValueError("mode must be either 'display', 'inline', 'display_left' or 'plain'")
return MathJaxExpr(html.format(mathjax_string))
class HTMLFragmentFactory(SageObject):
def _repr_(self):
"""
Return string representation
OUTPUT:
String.
EXAMPLES::
sage: html
Create HTML output (see html? for details)
"""
return 'Create HTML output (see html? for details)'
def __call__(self, obj, concatenate=True, strict=False):
r"""
Construct a HTML fragment
INPUT:
- ``obj`` -- anything. An object for which you want an HTML
representation.
- ``concatenate`` -- if ``True``, combine HTML representations of
elements of the container ``obj``
- ``strict`` -- if ``True``, construct an HTML representation of
``obj`` even if ``obj`` is a string
OUTPUT:
A :class:`HtmlFragment` instance.
EXAMPLES::
sage: h = html('<hr>'); pretty_print(h)
<hr>
sage: type(h)
<class 'sage.misc.html.HtmlFragment'>
sage: html(1/2)
<html>\(\displaystyle \frac{1}{2}\)</html>
sage: html('<a href="http://sagemath.org">sagemath</a>')
<a href="http://sagemath.org">sagemath</a>
sage: html('<a href="http://sagemath.org">sagemath</a>', strict=True)
<html>\(\displaystyle \verb|<a|\verb| |\verb|href="http://sagemath.org">sagemath</a>|\)</html>
Display preference ``align_latex`` affects rendering of LaTeX expressions::
sage: from sage.repl.rich_output.display_manager import get_display_manager
sage: dm = get_display_manager()
sage: dm.preferences.align_latex = 'left'
sage: html(1/2)
<html>\(\displaystyle \frac{1}{2}\)</html>
sage: dm.preferences.align_latex = 'center'
sage: html(1/2)
<html>\[\frac{1}{2}\]</html>
sage: dm.preferences.align_latex = None # same with left
sage: html(1/2)
<html>\(\displaystyle \frac{1}{2}\)</html>
"""
# string obj is interpreted as an HTML in not strict mode
if isinstance(obj, str) and not strict:
return HtmlFragment(math_parse(obj))
# prefer dedicated _html_() method
try:
result = obj._html_()
return HtmlFragment(result)
except AttributeError:
pass
from sage.repl.rich_output.display_manager import get_display_manager
dm = get_display_manager()
if dm.preferences.align_latex == 'center':
mode = 'display'
elif dm.preferences.align_latex == 'left':
mode = 'display_left'
else:
mode = 'display_left'
# otherwise convert latex to html
if concatenate:
if isinstance(obj, (tuple, list)):
obj = tuple(obj)
result = MathJax().eval(obj, mode=mode, combine_all=True)
else:
result = MathJax().eval(obj, mode=mode, combine_all=False)
return HtmlFragment(result)
def eval(self, s, locals=None):
r"""
Evaluate embedded <sage> tags
INPUT:
- ``s`` -- string.
- ``globals`` -- dictionary. The global variables when
evaluating ``s``. Default: the current global variables.
OUTPUT:
A :class:`HtmlFragment` instance.
EXAMPLES::
sage: a = 123
sage: html.eval('<sage>a</sage>')
\(123\)
sage: html.eval('<sage>a</sage>', locals={'a': 456})
\(456\)
"""
if locals is None:
from sage.repl.user_globals import get_globals
locals = get_globals()
s = str(s)
s = math_parse(s)
t = ''
while s:
i = s.find('<sage>')
if i == -1:
t += s
break
j = s.find('</sage>')
if j == -1:
t += s
break
t += s[:i] + r'\({}\)'.format(latex(sage_eval(s[6+i:j], locals=locals)))
s = s[j+7:]
return HtmlFragment(t)
def iframe(self, url, height=400, width=800):
r"""
Generate an iframe HTML fragment
INPUT:
- ``url`` -- string. A url, either with or without URI scheme
(defaults to "http"), or an absolute file path.
- ``height`` -- the number of pixels for the page height.
Defaults to 400.
- ``width`` -- the number of pixels for the page width.
Defaults to 800.
OUTPUT:
A :class:`HtmlFragment` instance.
EXAMPLES::
sage: pretty_print(html.iframe("sagemath.org"))
<iframe height="400" width="800"
src="http://sagemath.org"></iframe>
sage: pretty_print(html.iframe("http://sagemath.org",30,40))
<iframe height="30" width="40"
src="http://sagemath.org"></iframe>
sage: pretty_print(html.iframe("https://sagemath.org",30))
<iframe height="30" width="800"
src="https://sagemath.org"></iframe>
sage: pretty_print(html.iframe("/home/admin/0/data/filename"))
<iframe height="400" width="800"
src="file:///home/admin/0/data/filename"></iframe>
sage: pretty_print(html.iframe('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAA'
....: 'AUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBA'
....: 'AO9TXL0Y4OHwAAAABJRU5ErkJggg=="'))
<iframe height="400" width="800"
src="http://data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==""></iframe>
"""
if url.startswith('/'):
url = 'file://{0}'.format(url)
elif '://' not in url:
url = 'http://{0}'.format(url)
return HtmlFragment('<iframe height="{0}" width="{1}" src="{2}"></iframe>'
.format(height, width, url))
html = HTMLFragmentFactory()
html.__doc__ = HTMLFragmentFactory.__call__.__doc__
def pretty_print_default(enable=True):
r"""
Enable or disable default pretty printing.
Pretty printing means rendering things in HTML and by MathJax so that a
browser-based frontend can render real math.
This function is pretty useless without the notebook, it should not
be in the global namespace.
INPUT:
- ``enable`` -- bool (optional, default ``True``). If ``True``, turn on
pretty printing; if ``False``, turn it off.
EXAMPLES::
sage: pretty_print_default(True)
sage: 'foo' # the doctest backend does not support html
'foo'
sage: pretty_print_default(False)
sage: 'foo'
'foo'
"""
from sage.repl.rich_output import get_display_manager
dm = get_display_manager()
dm.preferences.text = 'latex' if enable else None