-
-
Notifications
You must be signed in to change notification settings - Fork 395
/
latex.py
2994 lines (2416 loc) · 96.5 KB
/
latex.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
"""
LaTeX printing support
In order to support latex formatting, an object should define a
special method ``_latex_(self)`` that returns a string, which will be typeset
in a mathematical mode (the exact mode depends on circumstances).
AUTHORS:
- William Stein: original implementation
- Joel B. Mohler: latex_variable_name() drastic rewrite and many doc-tests
"""
#*****************************************************************************
# Copyright (C) 2005 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/
#*****************************************************************************
EMBEDDED_MODE = False
COMMON_HEADER = \
r'''\usepackage{amsmath}
\usepackage{amssymb}
\usepackage{amsfonts}
\usepackage{graphicx}
\usepackage{mathrsfs}
\pagestyle{empty}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
'''
LATEX_HEADER = (
r'''\documentclass{article}
''' + COMMON_HEADER +
r'''\oddsidemargin 0.0in
\evensidemargin 0.0in
\textwidth 6.45in
\topmargin 0.0in
\headheight 0.0in
\headsep 0.0in
\textheight 9.0in
''')
SLIDE_HEADER = (
r'''\documentclass[a0,8pt]{beamer}
''' + COMMON_HEADER +
r'''\textwidth=1.1\textwidth
\textheight=2\textheight
''')
import sys
import shutil, re
import os.path
import random
import subprocess
import types
from sage.misc.temporary_file import tmp_dir, graphics_filename
import sage_eval
from sage.misc.sage_ostools import have_program
from sage.misc.cachefunc import cached_function, cached_method
@cached_function
def have_latex():
"""
Return ``True`` if this computer has the program ``latex``.
If this computer doesn't have LaTeX installed, you may obtain it
from http://ctan.org/.
EXAMPLES::
sage: from sage.misc.latex import have_latex
sage: have_latex() # random
True
"""
return have_program('latex')
@cached_function
def have_pdflatex():
"""
Return ``True`` if this computer has the program ``pdflatex``.
If this computer doesn't have pdflatex installed, you may obtain it
from http://ctan.org/.
EXAMPLES::
sage: from sage.misc.latex import have_pdflatex
sage: have_pdflatex() # random
True
"""
return have_program('pdflatex')
@cached_function
def have_xelatex():
"""
Return ``True`` if this computer has the program ``xelatex``.
If this computer doesn't have xelatex installed, you may obtain it
from http://ctan.org/.
EXAMPLES::
sage: from sage.misc.latex import have_xelatex
sage: have_xelatex() # random
True
"""
return have_program('xelatex')
@cached_function
def have_dvipng():
"""
Return ``True`` if this computer has the program ``dvipng``.
If this computer doesn't have dvipng installed, you may obtain it
from http://sourceforge.net/projects/dvipng/
EXAMPLES::
sage: from sage.misc.latex import have_dvipng
sage: have_dvipng() # random
True
"""
return have_program('dvipng')
@cached_function
def have_convert():
"""
Return ``True`` if this computer has the program ``convert``.
If this computer doesn't have convert installed, you may obtain it
(along with the rest of the ImageMagick suite) from
http://www.imagemagick.org
EXAMPLES::
sage: from sage.misc.latex import have_convert
sage: have_convert() # random
True
"""
return have_program('convert')
def list_function(x):
r"""
Returns the LaTeX code for a list ``x``.
INPUT: ``x`` - a list
EXAMPLES::
sage: from sage.misc.latex import list_function
sage: list_function([1,2,3])
'\\left[1, 2, 3\\right]'
sage: latex([1,2,3]) # indirect doctest
\left[1, 2, 3\right]
sage: latex([Matrix(ZZ,3,range(9)), Matrix(ZZ,3,range(9))]) # indirect doctest
\left[\left(\begin{array}{rrr}
0 & 1 & 2 \\
3 & 4 & 5 \\
6 & 7 & 8
\end{array}\right), \left(\begin{array}{rrr}
0 & 1 & 2 \\
3 & 4 & 5 \\
6 & 7 & 8
\end{array}\right)\right]
"""
return "\\left[" + ", ".join([latex(v) for v in x]) + "\\right]"
def tuple_function(x, combine_all=False):
r"""
Returns the LaTeX code for a tuple ``x``.
INPUT:
- ``x`` -- a tuple
- ``combine_all`` -- boolean (Default: ``False``) If ``combine_all`` is
``True``, then it does not return a tuple and instead returns a string
with all the elements separated by a single space. It does not collapse
tuples which are inside tuples.
EXAMPLES::
sage: from sage.misc.latex import tuple_function
sage: tuple_function((1,2,3))
'\\left(1, 2, 3\\right)'
Check that :trac:`11775` is fixed::
sage: tuple_function((1,2,3), combine_all=True)
'1 2 3'
sage: tuple_function(((1,2),3), combine_all=True)
'\\left(1, 2\\right) 3'
"""
if combine_all:
return " ".join([latex(v) for v in x])
return "\\left(" + ", ".join([latex(v) for v in x]) + "\\right)"
def bool_function(x):
r"""
Returns the LaTeX code for a boolean ``x``.
INPUT:
- ``x`` -- boolean
EXAMPLES::
sage: from sage.misc.latex import bool_function
sage: print bool_function(2==3)
\mathrm{False}
sage: print bool_function(3==(2+1))
\mathrm{True}
"""
return r"\mathrm{%s}" % bool(x)
def builtin_constant_function(x):
r"""
Returns the LaTeX code for a builtin constant ``x``.
INPUT:
- ``x`` -- builtin constant
.. SEEALSO:: Python built-in Constants http://docs.python.org/library/constants.html
EXAMPLES::
sage: from sage.misc.latex import builtin_constant_function
sage: builtin_constant_function(True)
'\\mbox{\\rm True}'
sage: builtin_constant_function(None)
'\\mbox{\\rm None}'
sage: builtin_constant_function(NotImplemented)
'\\mbox{\\rm NotImplemented}'
sage: builtin_constant_function(Ellipsis)
'\\mbox{\\rm Ellipsis}'
TESTS::
sage: sage.misc.latex.EMBEDDED_MODE = True
sage: builtin_constant_function(True)
'{\\rm True}'
sage: sage.misc.latex.EMBEDDED_MODE = False
"""
if EMBEDDED_MODE:
return "{\\rm %s}"%x
return "\mbox{\\rm %s}"%x
def None_function(x):
r"""
Returns the LaTeX code for ``None``.
INPUT:
- ``x`` -- ``None``
EXAMPLES::
sage: from sage.misc.latex import None_function
sage: print None_function(None)
\mathrm{None}
"""
assert x is None
return r"\mathrm{None}"
def str_function(x):
r"""
Return a LaTeX representation of the string ``x``.
The main purpose of this function is to generate LaTeX representation for
classes that do not provide a customized method.
If ``x`` contains only digits with, possibly, a single decimal point and/or
a sign in front, it is considered to be its own representation. Otherwise
each line of ``x`` is wrapped in a ``\texttt`` command and these lines are
assembled in a left-justified array. This gives to complicated strings the
closest look to their "terminal representation".
.. WARNING::
Such wrappers **cannot** be used as arguments of LaTeX
commands or in command definitions. If this causes you any problems,
they probably can be solved by implementing a suitable ``_latex_``
method for an appropriate class.
INPUT:
- ``x`` -- a string.
OUTPUT:
A string
EXAMPLES::
sage: from sage.misc.latex import str_function
sage: str_function('34')
'34'
sage: str_function('34.5')
'34.5'
sage: str_function('-34.5')
'-34.5'
sage: str_function('+34.5')
'+34.5'
sage: str_function('hello_world')
'\\text{\\texttt{hello{\\char`\\_}world}}'
sage: str_function('-1.00000?') # trac 12178
'-1.00000?'
"""
# Check if x is just a number with a possible sign, and/or decimal
# point, and/or ends with "?"
if re.match(r'(\+|-)?[0-9]*\.?[0-9]*\??$', x):
return x
# Deal with special characters
char_wrapper = r"{\char`\%s}"
x = "".join(char_wrapper % c if c in "#$%&\^_{}~" else c for c in x)
# Avoid grouping spaces into one
x = x.replace(" ", "{ }")
# And dashes too, since it causes issues for the command line...
x = x.replace("-", "{-}")
# Make it work in math mode, but look like typewriter
line_wrapper = r"\text{\texttt{%s}}"
x = "\\\\\n".join(line_wrapper % line for line in x.split("\n"))
# Preserve line breaks
if "\n" in x:
x = "\\begin{array}{l}\n%s\n\\end{array}" % x
return x
def dict_function(x):
r"""
Returns the LaTeX code for a dictionary ``x``.
INPUT:
- ``x`` -- a dictionary
EXAMPLES::
sage: from sage.misc.latex import dict_function
sage: x,y,z = var('x,y,z')
sage: print dict_function({x/2: y^2})
\left\{\frac{1}{2} \, x : y^{2}\right\}
sage: d = {(1,2,x^2): [sin(z^2), y/2]}
sage: latex(d)
\left\{\left(1, 2, x^{2}\right) :
\left[\sin\left(z^{2}\right), \frac{1}{2} \, y\right]\right\}
"""
return "".join([r"\left\{",
", ".join(r"%s : %s" % (latex(key), latex(value))
for key, value in x.iteritems()),
r"\right\}"])
# One can add to the latex_table in order to install latexing
# functionality for other types. (Suggested by Robert Kerns of Enthought.)
def float_function(x):
r"""
Returns the LaTeX code for a python float ``x``.
INPUT:
- ``x`` -- a python float
EXAMPLES::
sage: from sage.misc.latex import float_function
sage: float_function(float(3.14))
3.14
sage: float_function(float(1e-10))
1 \times 10^{-10}
sage: float_function(float(2e10))
20000000000.0
TESTS:
Check that :trac:`7356` is fixed::
sage: latex(float(2e-13))
2 \times 10^{-13}
"""
from sage.all import RDF
return latex(RDF(x))
latex_table = {types.NoneType: None_function,
bool: bool_function,
dict: dict_function,
float: float_function,
int: str,
list: list_function,
long: str,
str: str_function,
tuple: tuple_function,
type(None):builtin_constant_function,
type(NotImplemented):builtin_constant_function,
type(Ellipsis):builtin_constant_function}
class LatexExpr(str):
r"""
A class for LaTeX expressions.
Normally, objects of this class are created by a :func:`latex` call. It is
also possible to generate :class:`LatexExpr` directly from a string, which
must contain valid LaTeX code for typesetting in math mode (without dollar
signs). In the Sage notebook, use :func:`pretty_print` or the "Typeset"
checkbox to actually see the typeset LaTeX code; alternatively, from
either the command-line or the notebook, use the :func:`view` function.
INPUT:
- ``str`` -- a string with valid math mode LaTeX code (or something
which can be converted to such a string).
OUTPUT:
- :class:`LatexExpr` wrapping the string representation of the input.
EXAMPLES::
sage: latex(x^20 + 1)
x^{20} + 1
sage: LatexExpr(r"\frac{x^2 + 1}{x - 2}")
\frac{x^2 + 1}{x - 2}
``LatexExpr`` simply converts to string without doing anything
extra, it does *not* call :func:`latex`::
sage: latex(ZZ)
\Bold{Z}
sage: LatexExpr(ZZ)
Integer Ring
The result of :func:`latex` is of type ``LatexExpr``::
sage: L = latex(x^20 + 1)
sage: L
x^{20} + 1
sage: type(L)
<class 'sage.misc.latex.LatexExpr'>
A ``LatexExpr`` can be converted to a plain string::
sage: str(latex(x^20 + 1))
'x^{20} + 1'
"""
def __add__(self, other):
r"""
Add a LatexExpr and another LatexExpr (or a string).
EXAMPLES::
sage: o = LatexExpr(r"\Delta\neq") + LatexExpr(r"\frac{x}{2}"); o
\Delta\neq \frac{x}{2}
sage: type(o)
<class 'sage.misc.latex.LatexExpr'>
sage: o = LatexExpr(r"\Delta\neq") + r"\frac{x}{2}"; o
\Delta\neq \frac{x}{2}
sage: type(o)
<class 'sage.misc.latex.LatexExpr'>
We add extra space only if it wasn't there yet::
sage: LatexExpr("foo ") + LatexExpr("bar")
foo bar
sage: LatexExpr("foo") + LatexExpr(" bar")
foo bar
sage: str(LatexExpr("") + LatexExpr("bar"))
'bar'
sage: str(LatexExpr("foo") + LatexExpr(""))
'foo'
"""
left = str(self)
right = str(other)
# Add a space if self ends with a non-space and other starts
# with a non-space
try:
if left[-1] != ' ' and right[0] != ' ':
left += ' '
except IndexError:
pass
return LatexExpr(left + right)
def __radd__(self, other):
r"""
Add a string and a LatexExpr.
EXAMPLES::
sage: o = "a =" + LatexExpr("b")
sage: o
a = b
sage: type(o)
<class 'sage.misc.latex.LatexExpr'>
"""
return LatexExpr(other) + self
def __repr__(self):
"""
Return a string representation of ``self``.
EXAMPLES::
sage: LatexExpr("abc").__repr__()
'abc'
"""
return str(self)
def _latex_(self):
"""
Return a LaTeX representation of ``self``.
EXAMPLES::
sage: latex(LatexExpr("abc")) # indirect doctest
abc
"""
return str(self)
def has_latex_attr(x):
"""
Return ``True`` if ``x`` has a ``_latex_`` attribute, except if ``x``
is a ``type``, in which case return ``False``.
EXAMPLES::
sage: from sage.misc.latex import has_latex_attr
sage: has_latex_attr(identity_matrix(3))
True
sage: has_latex_attr("abc") # strings have no _latex_ method
False
Types inherit the ``_latex_`` method of the class to which they refer,
but calling it is broken::
sage: T = type(identity_matrix(3)); T
<type 'sage.matrix.matrix_integer_dense.Matrix_integer_dense'>
sage: hasattr(T, '_latex_')
True
sage: T._latex_()
Traceback (most recent call last):
...
TypeError: descriptor '_latex_' of 'sage.matrix.matrix0.Matrix' object needs an argument
sage: has_latex_attr(T)
False
"""
return hasattr(x, '_latex_') and not isinstance(x, type)
from sage.structure.sage_object import SageObject
class _Latex_prefs_object(SageObject):
"""
An object that holds LaTeX global preferences.
"""
def __init__(self, bb=False, delimiters=["(", ")"],
matrix_column_alignment="r"):
"""
Define an object that holds LaTeX global preferences.
EXAMPLES::
sage: from sage.misc.latex import _Latex_prefs_object
sage: latex_prefs = _Latex_prefs_object()
sage: TestSuite(latex_prefs).run(skip ="_test_pickling")
"""
self._option = {}
self._option["blackboard_bold"] = bb
self._option["matrix_delimiters"] = list(delimiters)
self._option["vector_delimiters"] = list(delimiters)
self._option["matrix_column_alignment"] = matrix_column_alignment
self._option["macros"] = ""
self._option["preamble"] = ""
self._option["engine"] = "pdflatex"
self._option["engine_name"] = "LaTeX"
self._option["mathjax_avoid"] = []
_Latex_prefs = _Latex_prefs_object()
##############################################################
# The Latex class is used to make slides and LaTeX output in
# the Sage Notebook
#########################################
def latex_extra_preamble():
r"""
Return the string containing the user-configured preamble,
``sage_latex_macros``, and any user-configured macros. This is
used in the :meth:`~Latex.eval` method for the :class:`Latex`
class, and in :func:`_latex_file_`; it follows either
``LATEX_HEADER`` or ``SLIDE_HEADER`` (defined at the top of this
file) which is a string containing the documentclass and standard
usepackage commands.
EXAMPLES::
sage: from sage.misc.latex import latex_extra_preamble
sage: print latex_extra_preamble()
...
<BLANKLINE>
\newcommand{\ZZ}{\Bold{Z}}
\newcommand{\NN}{\Bold{N}}
\newcommand{\RR}{\Bold{R}}
\newcommand{\CC}{\Bold{C}}
\newcommand{\QQ}{\Bold{Q}}
\newcommand{\QQbar}{\overline{\QQ}}
\newcommand{\GF}[1]{\Bold{F}_{#1}}
\newcommand{\Zp}[1]{\ZZ_{#1}}
\newcommand{\Qp}[1]{\QQ_{#1}}
\newcommand{\Zmod}[1]{\ZZ/#1\ZZ}
\newcommand{\CDF}{\Bold{C}}
\newcommand{\CIF}{\Bold{C}}
\newcommand{\CLF}{\Bold{C}}
\newcommand{\RDF}{\Bold{R}}
\newcommand{\RIF}{\Bold{I} \Bold{R}}
\newcommand{\RLF}{\Bold{R}}
\newcommand{\CFF}{\Bold{CFF}}
\newcommand{\Bold}[1]{\mathbf{#1}}
<BLANKLINE>
"""
from sage.misc.latex_macros import sage_latex_macros
return "\n".join([_Latex_prefs._option['preamble'],
"\n".join(sage_latex_macros()),
_Latex_prefs._option['macros']])
def _run_latex_(filename, debug=False, density=150, engine=None, png=False, do_in_background=False):
"""
This runs LaTeX on the TeX file "filename.tex". It produces files
"filename.dvi" (or "filename.pdf"` if engine is either ``pdflatex``
or ``xelatex``) and if ``png`` is ``True``, "filename.png". If ``png``
is ``True`` and dvipng can't convert the dvi file to png (because of
postscript specials or other issues), then dvips is called, and the
PS file is converted to a png file.
INPUT:
- ``filename`` -- string: file to process, including full path
- ``debug`` -- bool (optional, default ``False``): whether to print
verbose debugging output
- ``density`` -- integer (optional, default 150): how big output
image is.
- ``engine`` -- string: latex engine to use.
- ``png`` -- bool (optional, default ``False``): whether to produce a
png file.
- ``do_in_background`` -- bool (optional, default ``False``). Unused,
kept for backwards compatibility.
OUTPUT:
A string which could be a string starting with 'Error' (if
there was a problem), or it could be 'pdf' or 'dvi'. If
engine is latex or ``None``, then a dvi file is created, but if there
appear to be problems with it (because of PS special commands, for
example), then a pdf file is created instead. The function
returns 'dvi' or 'pdf' to indicate which type of file is created.
(Detecting problems requires that dvipng be installed; if it is
not, then the dvi file is not checked for problems and 'dvi' is
returned.) If engine is pdflatex or xelatex and there are no errors, then
'pdf' is returned.
.. WARNING::
If ``png`` is ``True``, then when using latex (the default), you
must have 'dvipng' (or 'dvips' and 'convert') installed on your
operating system, or this command won't work. When using
pdflatex or xelatex, you must have 'convert' installed.
EXAMPLES::
sage: from sage.misc.latex import _run_latex_, _latex_file_
sage: file = os.path.join(SAGE_TMP, "temp.tex")
sage: O = open(file, 'w')
sage: O.write(_latex_file_([ZZ[x], RR])); O.close()
sage: _run_latex_(file) # random - depends on whether latex is installed
'dvi'
"""
if engine is None:
engine = _Latex_prefs._option["engine"]
if not engine or engine == "latex":
if not have_latex():
print("Error: LaTeX does not seem to be installed. Download it from")
print("ctan.org and try again.")
return "Error"
command = "latex"
# 'suffix' is used in the 'convert' command list
suffix = "ps"
return_suffix = "dvi"
elif engine == "pdflatex":
if not have_pdflatex():
print("Error: PDFLaTeX does not seem to be installed. Download it from")
print("ctan.org and try again.")
return "Error"
command = "pdflatex"
suffix = "pdf"
return_suffix = "pdf"
elif engine == "xelatex":
if not have_xelatex():
print("Error: XeLaTeX does not seem to be installed. Download it from")
print("ctan.org and try again.")
return "Error"
command = "xelatex"
suffix = "pdf"
return_suffix = "pdf"
else:
raise ValueError("Unsupported LaTeX engine.")
# if png output + latex, check to see if dvipng or convert is installed.
if png:
if (not engine or engine == "latex") and not (have_dvipng() or have_convert()):
print()
print("Error: neither dvipng nor convert (from the ImageMagick suite)")
print("appear to be installed. Displaying LaTeX, PDFLaTeX output")
print("requires at least one of these programs, so please install")
print("and try again.")
print()
print("Go to http://sourceforge.net/projects/dvipng/ and")
print("http://www.imagemagick.org to download these programs.")
return "Error"
# if png output + pdflatex, check to see if convert is installed.
elif engine == "pdflatex" and not have_convert():
print()
print("Error: convert (from the ImageMagick suite) does not")
print("appear to be installed. Displaying PDFLaTeX output")
print("requires this program, so please install and try again.")
print()
print("Go to http://www.imagemagick.org to download it.")
return "Error"
elif engine == "xelatex" and not have_convert():
print()
print("Error: convert (from the ImageMagick suite) does not")
print("appear to be installed. Displaying XeLaTeX output")
print("requires this program, so please install and try again.")
print()
print("Go to http://www.imagemagick.org to download it.")
return "Error"
# check_validity: check to see if the dvi file is okay by trying
# to convert to a png file. if this fails, return_suffix will be
# set to "pdf". return_suffix is the return value for this
# function.
#
# thus if not png output, check validity of dvi output if dvipng
# or convert is installed.
else:
check_validity = have_dvipng()
# set up filenames, other strings:
base, filename = os.path.split(filename)
filename = os.path.splitext(filename)[0] # get rid of extension
if len(filename.split()) > 1:
raise ValueError("filename must contain no spaces")
if not debug:
redirect = subprocess.PIPE
else:
redirect = None
# if do_in_background:
# background = ' &'
# else:
# background = ''
# Define the commands to be used:
lt = ['sage-native-execute', command, r'\nonstopmode', r'\input{' + filename + '.tex}']
# dvipng is run with the 'picky' option: this means that if
# there are warnings, no png file is created.
dvipng = ['sage-native-execute', 'dvipng', '--picky', '-q', '-T', 'tight',
'-D', str(density), filename + '.dvi', '-o', filename + '.png']
dvips = ['sage-native-execute', 'dvips', filename + '.dvi']
ps2pdf = ['sage-native-execute', 'ps2pdf', filename + '.ps']
# We seem to need a larger size when using convert compared to
# when using dvipng:
density = int(1.4 * density / 1.3)
convert = ['sage-native-execute', 'convert', '-density',
'{0}x{0}'.format(density), '-trim', filename + '.' + suffix,
filename + '.png']
e = False # it is possible to get through the following commands
# without running a program, so in that case we force error
# our standard way of calling programs here; change this if we want
# finer-grained analysis of the return code. Think of the output as
# a boolean: "the command exited normally"
subpcall = lambda x: not subprocess.call(x, stdout=redirect,
stderr=redirect, cwd=base)
if engine == "pdflatex" or engine == "xelatex":
if debug:
print(lt)
if png:
print(convert)
e = subpcall(lt)
if png:
e = e and subpcall(convert)
else: # latex
if (png or check_validity):
if have_dvipng():
if debug:
print(lt)
print(dvipng)
e = subpcall(lt) and subpcall(dvipng)
dvipng_error = not os.path.exists(os.path.join(base, filename + '.png'))
# If there is no png file, then either the latex
# process failed or dvipng failed. Assume that dvipng
# failed, and try running dvips and convert. (If the
# latex process failed, then dvips and convert will
# fail also, so we'll still catch the error.)
if dvipng_error:
if png:
if have_convert():
if debug:
print("'dvipng' failed; trying 'convert' instead...")
print(dvips)
print(convert)
e = subpcall(dvips) and subpcall(convert)
else:
print("Error: 'dvipng' failed and 'convert' is not installed.")
return "Error: dvipng failed."
else: # not png, i.e., check_validity
return_suffix = "pdf"
if debug:
print("bad dvi file; running dvips and ps2pdf instead...")
print(dvips)
print(ps2pdf)
e = subpcall(dvips) and subpcall(ps2pdf)
if not e: # error running dvips and/or ps2pdf
pdflt = lt[:]
pdflt[1] = 'pdflatex'
if debug:
print("error running dvips and ps2pdf; trying pdflatex instead...")
print(pdflt)
e = subpcall(pdflt)
else: # don't have dvipng, so must have convert. run latex, dvips, convert.
if debug:
print(lt)
print(dvips)
print(convert)
e = subpcall(lt) and subpcall(dvips) and subpcall(convert)
if not e:
print("An error occurred.")
try:
print(open(base + '/' + filename + '.log').read())
except IOError:
pass
return "Error latexing slide."
return return_suffix
class LatexCall:
"""
Typeset Sage objects via a ``__call__`` method to this class,
typically by calling those objects' ``_latex_`` methods. The
class :class:`Latex` inherits from this. This class is used in
:mod:`~sage.misc.latex_macros`, while functions from
:mod:`~sage.misc.latex_macros` are used in :class:`Latex`, so this
is here primarily to avoid circular imports.
EXAMPLES::
sage: from sage.misc.latex import LatexCall
sage: LatexCall()(ZZ)
\Bold{Z}
sage: LatexCall().__call__(ZZ)
\Bold{Z}
This returns an instance of the class :class:`LatexExpr`::
sage: type(LatexCall()(ZZ))
<class 'sage.misc.latex.LatexExpr'>
"""
def __call__(self, x, combine_all=False):
r"""
Return a :class:`LatexExpr` built out of the argument ``x``.
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:`LatexExpr` built from ``x``
EXAMPLES::
sage: latex(Integer(3)) # indirect doctest
3
sage: latex(1==0)
\mathrm{False}
sage: print latex([x,2])
\left[x, 2\right]
Check that :trac:`11775` is fixed::
sage: latex((x,2), combine_all=True)
x 2
"""
if has_latex_attr(x):
return LatexExpr(x._latex_())
try:
f = latex_table[type(x)]
if isinstance(x, tuple):
return LatexExpr(f(x, combine_all=combine_all))
return LatexExpr(f(x))
except KeyError:
return LatexExpr(str_function(str(x)))
class Latex(LatexCall):
r"""nodetex
Enter, e.g.,
::
%latex
The equation $y^2 = x^3 + x$ defines an elliptic curve.
We have $2006 = \sage{factor(2006)}$.
in an input cell in the notebook to get a typeset version. Use
``%latex_debug`` to get debugging output.
Use ``latex(...)`` to typeset a Sage object. Use :class:`LatexExpr`
to typeset LaTeX code that you create by hand.
Use ``%slide`` instead to typeset slides.
.. WARNING::
You must have dvipng (or dvips and convert) installed
on your operating system, or this command won't work.
EXAMPLES::
sage: latex(x^20 + 1)
x^{20} + 1
sage: latex(FiniteField(25,'a'))
\Bold{F}_{5^{2}}
sage: latex("hello")
\text{\texttt{hello}}
sage: LatexExpr(r"\frac{x^2 - 1}{x + 1} = x - 1")
\frac{x^2 - 1}{x + 1} = x - 1
LaTeX expressions can be added; note that a space is automatically
inserted::
sage: LatexExpr(r"y \neq") + latex(x^20 + 1)
y \neq x^{20} + 1
"""
def __init__(self, debug=False, slide=False, density=150, pdflatex=None, engine=None):
"""
Initialize the latex builder.
EXAMPLES::
sage: from sage.misc.latex import Latex
sage: l = Latex()
sage: TestSuite(l).run(skip ="_test_pickling")
"""
self.__debug = debug
self.__slide = slide
self.__pdflatex = pdflatex
self.__engine = engine
self.__density = density
def _relation_symbols(self):
"""
Returns a dictionary whose keys are attributes of the
:mod:`operator` module and whose values are the corresponding
LaTeX expressions.
EXAMPLES::
sage: import operator
sage: latex._relation_symbols()[operator.ge]
' \\geq '
"""
import operator
return {operator.lt:' < ', operator.le:' \\leq ',
operator.eq:' = ', operator.ne:' \\neq ',