LaTeX printing support

In order to support latex formatting, an object should define a special method _latex_(self) that returns a string.

class sage.misc.latex.JSMath

Render LaTeX input using JSMath. This returns a JSMathExpr.

EXAMPLES:

sage: from sage.misc.latex import JSMath
sage: JSMath()(3)
<html><div class="math">\newcommand{\Bold}[1]{\mathbf{#1}}3</div></html>
sage: JSMath()(ZZ)
<html><div class="math">\newcommand{\Bold}[1]{\mathbf{#1}}\Bold{Z}</div></html>
eval(x, globals=None, locals=None, mode='display')

Render LaTeX input using JSMath. This returns a JSMathExpr.

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 or ‘inline’ for inline math

OUTPUT: a JSMathExpr

EXAMPLES:

sage: from sage.misc.latex import JSMath
sage: JSMath().eval(3, mode='display')
<html><div class="math">\newcommand{\Bold}[1]{\mathbf{#1}}3</div></html>
sage: JSMath().eval(3, mode='inline')
<html><span class="math">\newcommand{\Bold}[1]{\mathbf{#1}}3</span></html>
sage: JSMath().eval(type(3), mode='inline')
<html><span class="math">\newcommand{\Bold}[1]{\mathbf{#1}}\hbox{ < type 'sage.rings.integer.Integer' > }</span></html>
class sage.misc.latex.JSMathExpr(y)

An arbitrary JSMath expression that can be nicely concatenated.

EXAMPLES:

sage: from sage.misc.latex import JSMathExpr
sage: JSMathExpr("a^{2}") + JSMathExpr("x^{-1}")
a^{2}x^{-1}
class sage.misc.latex.Latex(debug=False, slide=False, density=150, pdflatex=None, engine=None)

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 %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.

add_macro(macro)

Append to the string of extra LaTeX macros, for use with %latex, %html, and %jsmath.

INPUT: macro - string

EXAMPLES:

sage: latex.extra_macros()
''
sage: latex.add_macro("\\newcommand{\\foo}{bar}")
sage: latex.extra_macros()
'\\newcommand{\\foo}{bar}'
sage: latex.extra_macros("")  # restore to default
add_package_to_preamble_if_available(package_name)

INPUT:

  • package_name – a string

Adds a \usepackage{package_name} instruction to the latex preamble if not yet present there, and if package_name.sty is available in the LaTeX installation.

See also add_to_preamble() and has_file().

TESTS:

sage: latex.add_package_to_preamble_if_available("xypic")
sage: latex.add_package_to_preamble_if_available("nonexistent_package")
sage: latex.extra_preamble()       # optional - latex
'\\usepackage{xypic}\n'
sage: latex.extra_preamble('')
add_to_jsmath_avoid_list(s)

Add to the list of strings which signal that jsMath should not be used when ‘view’ing.

INPUT: s - string – add s to the list of ‘jsMath avoid’ strings

If you want to replace the current list instead of adding to it, use latex.jsmath_avoid_list.

EXAMPLES:

sage: latex.add_to_jsmath_avoid_list("\\mathsf")
sage: latex.jsmath_avoid_list()  # display current setting
['\\mathsf']
sage: latex.add_to_jsmath_avoid_list("tkz-graph")
sage: latex.jsmath_avoid_list()  # display current setting
['\\mathsf', 'tkz-graph']
sage: latex.jsmath_avoid_list([])  # reset to default
sage: latex.jsmath_avoid_list()
[]
add_to_preamble(s)

Append to the string of extra LaTeX macros, for use with %latex. Anything in this string won’t be processed by %jsmath.

EXAMPLES:

sage: latex.extra_preamble()
''
sage: latex.add_to_preamble("\\DeclareMathOperator{\\Ext}{Ext}")

At this point, a notebook cell containing

%latex
$\Ext_A^*(\GF{2}, \GF{2}) \Rightarrow \pi_*^s*(S^0)$

will be typeset correctly.

sage: latex.add_to_preamble("\\usepackage{xypic}")
sage: latex.extra_preamble()
'\\DeclareMathOperator{\\Ext}{Ext}\\usepackage{xypic}'

Now one can put various xypic diagrams into a %latex cell, such as

%latex
\[ \xymatrix{ \circ \ar `r[d]^{a} `[rr]^{b} `/4pt[rr]^{c} `[rrr]^{d} 
`_dl[drrr]^{e} [drrr]^{f} & \circ & \circ & \circ \\ \circ & \circ &
\circ & \circ } \]

Reset the preamble to its default, the empty string:

sage: latex.extra_preamble('')
sage: latex.extra_preamble()
''
blackboard_bold(t=None)

Controls whether Sage uses blackboard bold or ordinary bold face for typesetting ZZ, RR, etc.

INPUT:

  • t – boolean or None

OUTPUT: if t is None, return the current setting (True or False).

If t == True, use blackboard bold (\mathbb); otherwise use boldface (\mathbf).

EXAMPLES:

sage: latex.blackboard_bold()
False
sage: latex.blackboard_bold(True)
sage: latex.blackboard_bold()
True
sage: latex.blackboard_bold(False)
check_file(*args, **kwds)
INPUT:
  • file_name – a string
  • more_info – a string (default: “”)

Emit a warning if the local LaTeX installation does not include file_name. The string more_info is appended to the warning message. The warning is only emitted the first time this method is called.

EXAMPLES:

sage: latex.check_file("article.cls")       # optional - latex
sage: latex.check_file("some_inexistent_file.sty")
Warning: `some_inexistent_file.sty` is not part of this computer's TeX installation.
sage: latex.check_file("some_inexistent_file.sty")
sage: latex.check_file("some_inexistent_file.sty", "This file is required for blah. It can be downloaded from: http://blah.org/")
Warning: `some_inexistent_file.sty` is not part of this computer's TeX installation.
This file is required for blah. It can be downloaded from: http://blah.org/

This test checks that the bug in Trac #9091 is fixed.

sage: latex.check_file("article.cls", "The article class is really critical.")    # optional - latex
engine(e=None)

Set Sage to use e as latex engine when typesetting with view(), in %latex cells, etc.

INPUT:

  • e – ‘latex’, ‘pdflatex’, ‘xelatex’ or None

If e is None, return the current engine.

If using the XeLaTeX engine, it will almost always be necessary to set the proper preamble with extra_preamble() or add_to_preamble(). For example:

latex.extra_preamble(r'''\usepackage{fontspec,xunicode,xltxtra}
\setmainfont[Mapping=tex-text]{some font here}
\setmonofont[Mapping=tex-text]{another font here}''')

EXAMPLES:

sage: latex.engine()
'latex'
sage: latex.engine("pdflatex")
sage: latex.engine()
'pdflatex'
sage: latex.engine("xelatex")
sage: latex.engine()
'xelatex'
eval(x, globals, strip=False, filename=None, debug=None, density=None, pdflatex=None, engine=None, locals={})

INPUT:

  • globals – a globals dictionary
  • x - string to evaluate.
  • strip - ignored
  • filename - output filename
  • debug - whether to print verbose debugging output
  • density - how big output image is.
  • pdflatex - whether to use pdflatex. This is deprecated. Use engine option instead.
  • engine - latex engine to use. Currently latex, pdflatex, and xelatex are supported.
  • locals - extra local variables used when evaluating Sage code in x.

Warning

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.

extra_macros(macros=None)

String containing extra LaTeX macros to use with %latex, %html, and %jsmath.

INPUT: macros - string

If macros is None, return the current string. Otherwise, set it to macros. If you want to append to the string of macros instead of replacing it, use latex.add_macro.

EXAMPLES:

sage: latex.extra_macros("\\newcommand{\\foo}{bar}")
sage: latex.extra_macros()
'\\newcommand{\\foo}{bar}'
sage: latex.extra_macros("")
sage: latex.extra_macros()
''
extra_preamble(s=None)

String containing extra preamble to be used with %latex. Anything in this string won’t be processed by %jsmath.

INPUT: s - string or None

If s is None, return the current preamble. Otherwise, set it to s. If you want to append to the current extra preamble instead of replacing it, use latex.add_to_preamble.

You will almost certainly need to use this when using the XeLaTeX engine; see below or the documentation for engine() for a suggested preamble.

EXAMPLES:

sage: latex.extra_preamble("\\DeclareMathOperator{\\Ext}{Ext}")
sage: latex.extra_preamble()
'\\DeclareMathOperator{\\Ext}{Ext}'
sage: latex.extra_preamble("\\"+r"usepackage{fontspec,xunicode,xltxtra}\setmainfont[Mapping=tex-text]{UnBatang}\setmonofont[Mapping=tex-text]{UnDotum}")
sage: latex.extra_preamble()
'\\usepackage{fontspec,xunicode,xltxtra}\\setmainfont[Mapping=tex-text]{UnBatang}\\setmonofont[Mapping=tex-text]{UnDotum}'
sage: latex.extra_preamble("")
sage: latex.extra_preamble()
''
has_file(*args, **kwds)
INPUT:
  • file_name – a string

Tests whether the local LaTeX installation includes file_name.

EXAMPLES:

sage: latex.has_file("article.cls")      # optional - latex
True
sage: latex.has_file("some_inexistent_file.sty")
False
jsmath_avoid_list(L=None)

List of strings which signal that jsMath should not be used when ‘view’ing.

INPUT: L - list or None

If L is None, then return the current list. Otherwise, set it to L. If you want to append to the current list instead of replacing it, use latex.add_to_jsmath_avoid_list.

EXAMPLES:

sage: latex.jsmath_avoid_list(["\\mathsf", "pspicture"])
sage: latex.jsmath_avoid_list()  # display current setting
['\\mathsf', 'pspicture']
sage: latex.jsmath_avoid_list([])  # reset to default
sage: latex.jsmath_avoid_list()
[]
matrix_delimiters(left=None, right=None)

Change the left and right delimiters for the LaTeX representation of matrices

INPUT:

  • left, right - strings or None

If both left and right are None, then return the current delimiters. Otherwise, set the left and/or right delimiters, whichever are specified.

Good choices for left and right are any delimiters which LaTeX understands and knows how to resize; some examples are:

  • parentheses: ‘(‘, ‘)’
  • brackets: ‘[‘, ‘]’
  • braces: ‘\{‘, ‘\}’
  • vertical lines: ‘|’
  • angle brackets: ‘\langle’, ‘\rangle’

Note

Putting aside aesthetics, you may combine these in any way imaginable; for example, you could set left to be a right-hand bracket ‘]’ and right to be a right-hand brace ‘\}’, and it will be typeset correctly.

EXAMPLES:

sage: a = matrix(1, 1, [17])
sage: latex(a)
\left(\begin{array}{r}
17
\end{array}\right)
sage: latex.matrix_delimiters("[", "]")
sage: latex(a)
\left[\begin{array}{r}
17
\end{array}\right]
sage: latex.matrix_delimiters(left="\\{")
sage: latex(a)
\left\{\begin{array}{r}
17
\end{array}\right]
sage: latex.matrix_delimiters()
['\\{', ']']

Restore defaults:

sage: latex.matrix_delimiters("(", ")")
pdflatex(t=None)

This is deprecated. Use engine(“pdflatex”) instead.

Controls whether Sage uses PDFLaTeX or LaTeX when typesetting with view(), in %latex cells, etc.

INPUT:

  • t – boolean or None

OUTPUT: if t is None, return the current setting (True or False).

If t == True, use PDFLaTeX; otherwise use LaTeX.

EXAMPLES:

sage: latex.pdflatex()               
doctest:...: DeprecationWarning: Use engine() instead.
False
sage: latex.pdflatex(True)
doctest:...: DeprecationWarning: Use engine("pdflatex") instead.
sage: latex.pdflatex()
True
sage: latex.pdflatex(False) 
doctest:...: DeprecationWarning: Use engine("latex") instead.
vector_delimiters(left=None, right=None)

Change the left and right delimiters for the LaTeX representation of vectors

INPUT:

  • left, right - strings or None

If both left and right are None, then return the current delimiters. Otherwise, set the left and/or right delimiters, whichever are specified.

Good choices for left and right are any delimiters which LaTeX understands and knows how to resize; some examples are:

  • parentheses: ‘(‘, ‘)’
  • brackets: ‘[‘, ‘]’
  • braces: ‘\{‘, ‘\}’
  • vertical lines: ‘|’
  • angle brackets: ‘\langle’, ‘\rangle’

Note

Putting aside aesthetics, you may combine these in any way imaginable; for example, you could set left to be a right-hand bracket ‘]’ and right to be a right-hand brace ‘\}’, and it will be typeset correctly.

EXAMPLES:

sage: a = vector(QQ, [1,2,3])
sage: latex(a)
\left(1,2,3\right)
sage: latex.vector_delimiters("[", "]")
sage: latex(a)
\left[1,2,3\right]
sage: latex.vector_delimiters(right="\\}")
sage: latex(a)
\left[1,2,3\right\}
sage: latex.vector_delimiters()
['[', '\\}']

Restore defaults:

sage: latex.vector_delimiters("(", ")")
class sage.misc.latex.LatexExamples

A catalogue of Sage objects with complicated _latex_ methods. Use these for testing latex(), view(), the Typeset button in the notebook, etc.

The classes here only have __init__, _repr_, and _latex_ methods.

EXAMPLES:

sage: from sage.misc.latex import latex_examples
sage: K = latex_examples.knot()
sage: K
LaTeX example for testing display of a knot produced by xypic...
sage: latex(K)
\vtop{\vbox{\xygraph{!{0;/r1.5pc/:}
[u] !{\vloop<(-.005)\khole||\vcrossneg \vunder- }
[] !{\ar @{-}@'{p-(1,0)@+}+(-1,1)}
[ul] !{\vcap[3]>\khole}
[rrr] !{\ar @{-}@'{p-(0,1)@+}-(1,1)}
}}}
class diagram

Bases: sage.structure.sage_object.SageObject

LaTeX example for testing display of commutative diagrams. See its string representation for details.

EXAMPLES:

sage: from sage.misc.latex import latex_examples
sage: CD = latex_examples.diagram()
sage: CD
LaTeX example for testing display of a commutative diagram...
class LatexExamples.graph

Bases: sage.structure.sage_object.SageObject

LaTeX example for testing display of graphs. See its string representation for details.

EXAMPLES:

sage: from sage.misc.latex import latex_examples
sage: G = latex_examples.graph()
sage: G
LaTeX example for testing display of graphs...
class LatexExamples.knot

Bases: sage.structure.sage_object.SageObject

LaTeX example for testing display of knots. See its string representation for details.

EXAMPLES:

sage: from sage.misc.latex import latex_examples
sage: K = latex_examples.knot()
sage: K
LaTeX example for testing display of a knot...
class LatexExamples.pstricks

Bases: sage.structure.sage_object.SageObject

LaTeX example for testing display of pstricks output. See its string representation for details.

EXAMPLES:

sage: from sage.misc.latex import latex_examples
sage: PS = latex_examples.pstricks()
sage: PS
LaTeX example for testing display of pstricks...
class sage.misc.latex.LatexExpr

Bases: str

LaTeX expression. This is a string.

EXAMPLES:

sage: from sage.misc.latex import LatexExpr
sage: LatexExpr(3)
3
sage: LatexExpr(False)
False
sage: LatexExpr(pi)
pi
sage: LatexExpr(3.14)
3.14000000000000
sage: LatexExpr("abc")
abc
sage.misc.latex.bool_function(x)

Returns the LaTeX code for a boolean x.

INPUT: x - boolean

EXAMPLES:

sage: from sage.misc.latex import bool_function
sage: bool_function(2==3)
'\\mbox{\\rm False}'
sage: bool_function(3==(2+1))
'\\mbox{\\rm True}'
sage.misc.latex.coeff_repr(c)

LaTeX string representing coefficients in a linear combination.

INPUT:

  • c - a coefficient (i.e., an element of a ring)

OUTPUT: string

EXAMPLES:

sage: from sage.misc.latex import coeff_repr
sage: coeff_repr(QQ(1/2))
'\\frac{1}{2}'
sage: coeff_repr(-x^2)
'\\left(-x^{2}\\right)'
sage.misc.latex.dict_function(x)

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: 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\}
sage.misc.latex.float_function(x)

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:

trac #7356 fixed:

sage: latex(float(2e-13))
2 \times 10^{-13}
sage.misc.latex.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_()
...
TypeError: descriptor '_latex_' of 'sage.matrix.matrix0.Matrix' object needs an argument
sage: has_latex_attr(T)
False
sage.misc.latex.have_convert()

Return True if this computer has the program convert.

The first time it is run, this function caches its result in the variable _have_convert, and any subsequent time, it just checks the value of the variable.

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
sage: sage.misc.latex._have_convert is None
False
sage: sage.misc.latex._have_convert == have_convert()
True
sage.misc.latex.have_dvipng()

Return True if this computer has the program dvipng.

The first time it is run, this function caches its result in the variable _have_dvipng, and any subsequent time, it just checks the value of the variable.

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
sage: sage.misc.latex._have_dvipng is None
False
sage: sage.misc.latex._have_dvipng == have_dvipng()
True
sage.misc.latex.have_latex()

Return True if this computer has the program latex.

The first time it is run, this function caches its result in the variable _have_latex, and any subsequent time, it just checks the value of the variable.

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
sage: sage.misc.latex._have_latex is None
False
sage: sage.misc.latex._have_latex == have_latex()
True
sage.misc.latex.have_pdflatex()

Return True if this computer has the program pdflatex.

The first time it is run, this function caches its result in the variable _have_pdflatex, and any subsequent time, it just checks the value of the variable.

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
sage: sage.misc.latex._have_pdflatex is None
False
sage: sage.misc.latex._have_pdflatex == have_pdflatex()
True
sage.misc.latex.have_xelatex()

Return True if this computer has the program xelatex.

The first time it is run, this function caches its result in the variable _have_xelatex, and any subsequent time, it just checks the value of the variable.

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
sage: sage.misc.latex._have_xelatex is None
False
sage: sage.misc.latex._have_xelatex == have_xelatex()
True
sage.misc.latex.jsmath(x, mode='display')

Attempt to nicely render an arbitrary Sage object with jsMath typesetting. Tries to call ._latex_() on x. If that fails, it will render a string representation of x.

Warning

2009-04: This function is deprecated; use html() instead: replace jsmath('MATH', mode='display') with html('$$MATH$$'), and replace jsmath('MATH', mode='inline') with html('$MATH$').

INPUT:
x – the object to render mode – ‘display’ for displaymath or ‘inline’ for inline math
OUTPUT:
A string of html that contains the LaTeX representation of x. In the notebook this gets embedded into the cell.

EXAMPLES:

sage: from sage.misc.latex import jsmath
sage: f = maxima('1/(x^2+1)')
sage: g = f.integrate()
sage: jsmath(f)
doctest:1: DeprecationWarning: The jsmath function is deprecated.  Use html('$math$') for inline mode or html('$$math$$') for display mode.
<html><font color='black'><div class="math">{{1}\over{x^2+1}}</div></font></html>
sage: jsmath(g, 'inline')
<html><font color='black'><span class="math">\tan^{-1} x</span></font></html>
sage: jsmath('\int' + latex(f) + '\ dx=' + latex(g))
<html><font color='black'><div class="math">\int{{1}\over{x^2+1}}\ dx=\tan^{-1} x</div></font></html>

AUTHORS:

  • William Stein (2006-10): general layout (2006-10)
  • Bobby Moretti (2006-10): improvements, comments, documentation
sage.misc.latex.latex_extra_preamble()

Return the string containing the user-configured preamble, sage_latex_macros, and any user-configured macros. This is used in the eval() method for the Latex class, and in _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: latex_extra_preamble()
'\n\\newcommand{\\ZZ}{\\Bold{Z}}\n\\newcommand{\\RR}{\\Bold{R}}\n\\newcommand{\\CC}{\\Bold{C}}\n\\newcommand{\\QQ}{\\Bold{Q}}\n\\newcommand{\\QQbar}{\\overline{\\QQ}}\n\\newcommand{\\GF}[1]{\\Bold{F}_{#1}}\n\\newcommand{\\Zp}[1]{\\ZZ_{#1}}\n\\newcommand{\\Qp}[1]{\\QQ_{#1}}\n\\newcommand{\\Zmod}[1]{\\ZZ/#1\\ZZ}\n\\newcommand{\\CDF}{\\texttt{Complex Double Field}}\n\\newcommand{\\CIF}{\\Bold{C}}\n\\newcommand{\\CLF}{\\Bold{C}}\n\\newcommand{\\RDF}{\\Bold{R}}\n\\newcommand{\\RIF}{\\Bold{I} \\Bold{R}}\n\\newcommand{\\RLF}{\\Bold{R}}\n\\newcommand{\\CFF}{\\Bold{CFF}}\n\\newcommand{\\Bold}[1]{\\mathbf{#1}}\n'
sage.misc.latex.latex_variable_name(x, is_fname=False)

Return latex version of a variable name.

Here are some guiding principles for usage of this function:

  1. If the variable is a single letter, that is the latex version.
  2. If the variable name is suffixed by a number, we put the number in the subscript.
  3. If the variable name contains an ‘_’ we start the subscript at the underscore. Note that #3 trumps rule #2.
  4. If a component of the variable is a Greek letter, escape it properly.
  5. Recurse nicely with subscripts.

Refer to the examples section for how these rules might play out in practice.

EXAMPLES:

sage: from sage.misc.latex import latex_variable_name
sage: latex_variable_name('a')
'a'
sage: latex_variable_name('abc')
'\\mbox{abc}'
sage: latex_variable_name('sigma')
'\\sigma'
sage: latex_variable_name('sigma_k')
'\\sigma_{k}'
sage: latex_variable_name('sigma389')
'\\sigma_{389}'
sage: latex_variable_name('beta_00')
'\\beta_{00}'
sage: latex_variable_name('Omega84')
'\\Omega_{84}'
sage: latex_variable_name('sigma_alpha')
'\\sigma_{\\alpha}'
sage: latex_variable_name('nothing1')
'\\mbox{nothing}_{1}'
sage: latex_variable_name('nothing1', is_fname=True)
'{\\rm nothing}_{1}'
sage: latex_variable_name('nothing_abc')
'\\mbox{nothing}_{\\mbox{abc}}'
sage: latex_variable_name('nothing_abc', is_fname=True)
'{\\rm nothing}_{{\\rm abc}}'
sage: latex_variable_name('alpha_beta_gamma12')
'\\alpha_{\\beta_{\\gamma_{12}}}'

AUTHORS:

  • Joel B. Mohler: drastic rewrite and many doc-tests
sage.misc.latex.latex_varify(a, is_fname=False)

Convert a string a to a LaTeX string: if it’s an element of common_varnames, then prepend a backslash. If a consists of a single letter, then return it. Otherwise, return either “{\rm a}” or “\mbox{a}” if “is_fname” flag is True or False.

INPUT:

  • a - string

OUTPUT: string

EXAMPLES:

sage: from sage.misc.latex import latex_varify
sage: latex_varify('w')
'w'
sage: latex_varify('aleph')
'\\mbox{aleph}'
sage: latex_varify('aleph', is_fname=True)
'{\\rm aleph}'
sage: latex_varify('alpha')
'\\alpha'
sage.misc.latex.list_function(x)

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]
sage.misc.latex.png(x, filename, density=150, debug=False, do_in_background=False, tiny=False, pdflatex=True, engine='pdflatex')

Create a png image representation of x and save to the given filename.

INPUT:

  • x - object to be displayed
  • filename - file in which to save the image
  • density - integer (default: 150)
  • debug - bool (default: False): print verbose output
  • do_in_background - bool (default: False): create the file in the background.
  • tiny - bool (default: False): use ‘tiny’ font
  • pdflatex - bool (default: True): use pdflatex. This option is deprecated. Use engine option instead. See below.
  • engine - ‘latex’, ‘pdflatex’, or ‘xelatex’ (default: ‘pdflatex’)

EXAMPLES:

sage: from sage.misc.latex import png
sage: png(ZZ[x], SAGE_TMP + "zz.png", do_in_background=False) # random - error if no latex
sage.misc.latex.pretty_print(object)

Try to pretty print an object in an intelligent way. For graphics objects, this returns their default representation. For other objects, in the notebook, this calls the view() command, while from the command line, this produces an html string suitable for processing by jsMath.

INPUT:

  • object - a Sage object

This function is used in the notebook when the Typeset button is checked.

EXAMPLES:

sage: from sage.misc.latex import pretty_print
sage: pretty_print(ZZ)  # indirect doctest
<html><span class="math">\newcommand{\Bold}[1]{\mathbf{#1}}\Bold{Z}</span></html>
sage.misc.latex.pretty_print_default(enable=True)

Enable or disable default pretty printing. Pretty printing means rendering things so that jsMath or some other latex-aware front end can render real math.

INPUT:

  • enable - bool (optional, default True). If True, turn on pretty printing; if False, turn it off.

EXAMPLES:

sage: pretty_print_default(True)
sage: sys.displayhook
<html><span class="math">...\hbox{ < function pretty_print at ... > }</span></html>
sage: pretty_print_default(False)
sage: sys.displayhook == sys.__displayhook__
True
sage.misc.latex.print_or_typeset(object)

‘view’ or ‘print’ the object depending on the situation.

In particular, if in notebook mode with the typeset box checked, view the object. Otherwise, print the object.

INPUT: object: anything

EXAMPLES:

sage: sage.misc.latex.print_or_typeset(3)
3
sage: sage.misc.latex.EMBEDDED_MODE=True
sage: sage.misc.latex.print_or_typeset(3)
3
sage: TEMP = sys.displayhook
sage: sys.displayhook = sage.misc.latex.pretty_print
sage: sage.misc.latex.print_or_typeset(3)
<html><span class="math">\newcommand{\Bold}[1]{\mathbf{#1}}3</span></html>
sage: sage.misc.latex.EMBEDDED_MODE=False
sage: sys.displayhook = TEMP
sage.misc.latex.repr_lincomb(symbols, coeffs)

Compute a latex representation of a linear combination of some formal symbols.

INPUT:

  • symbols - list of symbols
  • coeffs - list of coefficients of the symbols

OUTPUT: a string

EXAMPLES:

sage: t = PolynomialRing(QQ, 't').0
sage: from sage.misc.latex import repr_lincomb
sage: repr_lincomb(['a', 's', ''], [-t, t - 2, t^12 + 2])
'-t\\texttt{a} + \\left(t - 2\\right)\\texttt{s} + \\left(t^{12} + 2\\right)'
sage: repr_lincomb(['a', 'b'], [1,1])
'\\texttt{a} + \\texttt{b}'

Verify that a certain corner case works (see trac 5707 and 5766):

sage: repr_lincomb([1,5,-3],[2,8/9,7]) 
'2\\cdot 1 + \\frac{8}{9}\\cdot 5 + 7\\cdot -3' 
sage.misc.latex.str_function(x, escape_underscores=False)

Returns the LaTeX code for a string x. If x contains only digits, then return x itself. Otherwise, enclose x in “texttt{}” and return that.

If optional argument escape_underscores is True, replace “_” with “\_”.

INPUT:

  • x - a string
  • escape_underscores - boolean (optional, default False)

OUTPUT:

  • a string

EXAMPLES:

sage: from sage.misc.latex import str_function
sage: str_function('34')
'34'
sage: str_function('abc')
'\\texttt{abc}'
sage: str_function('hello_world')  # note that this produces invalid LaTeX
'\\texttt{hello_world}'
sage: str_function('hello_world', escape_underscores=True)  # valid LaTeX
'\\texttt{hello\\_world}'
sage.misc.latex.tuple_function(x)

Returns the LaTeX code for a tuple x.

INPUT: x - a tuple

EXAMPLES:

sage: from sage.misc.latex import tuple_function
sage: tuple_function((1,2,3))
'\\left(1, 2, 3\\right)'
sage.misc.latex.view(objects, title='SAGE', debug=False, sep='', tiny=False, pdflatex=None, engine=None, viewer=None, tightpage=None, mode='inline', **kwds)

Compute a latex representation of each object in objects, compile, and display typeset. If used from the command line, this requires that latex be installed.

INPUT:

  • objects - list (or object)
  • title - string (default: ‘Sage’): title for the document
  • debug - bool (default: False): print verbose output
  • sep - string (default: ‘’): separator between math objects
  • tiny - bool (default: False): use tiny font.
  • pdflatex - bool (default: False): use pdflatex. This is deprecated. Use ‘engine’ option instead.
  • engine - ‘latex’, ‘pdflatex’, or ‘xelatex’
  • viewer – string or None (default: None): specify a viewer to use; currently the only options are None and ‘pdf’.
  • tightpage - bool (default: False): use the LaTeX package ‘preview’ with the ‘tightpage’ option.
  • mode – string (default: ‘inline’): ‘display’ for displaymath or ‘inline’ for inline math

OUTPUT: Display typeset objects.

This function behaves differently depending on whether in notebook mode or not.

If not in notebook mode, the output is displayed in a separate viewer displaying a dvi (or pdf) file, with the following: the title string is printed, centered, at the top. Beneath that, each object in objects is typeset on its own line, with the string sep inserted between these lines.

The value of sep is inserted between each element of the list objects; you can, for example, add vertical space between objects with sep='\\vspace{15mm}', while sep='\\hrule' adds a horizontal line between objects, and sep='\\newpage' inserts a page break between objects.

If pdflatex is True, then the latex engine is set to pdflatex. If the engine is either pdflatex or xelatex, it produces a pdf file. Otherwise, it produces a dvi file, and if the program dvipng is installed, it checks the dvi file by trying to convert it to a png file. If this conversion fails, the dvi file probably contains some postscript special commands or it has other issues which might make displaying it a problem; in this case, the file is converted to a pdf file, which is then displayed.

Setting viewer to 'pdf' forces the use of a separate viewer, even in notebook mode. This also sets the latex engine to be pdflatex if the current engine is latex.

Setting the option tightpage to True tells LaTeX to use the package ‘preview’ with the ‘tightpage’ option. Then, each object is typeset in its own page, and that page is cropped to exactly the size of the object. This is typically useful for very large pictures (like graphs) generated with tikz. This only works when using a separate viewer. Note that the object are currently typeset in plain math mode rather than displaymath, because the latter imposes a limit on the width of the picture. Technically, tightpage adds

\\usepackage[tightpage,active]{preview}
\\PreviewEnvironment{page}

to the LaTeX preamble, and replaces the \\[ and \\] around each object by \\begin{page}$ and $\\end{page}.

If in notebook mode with viewer equal to None, this usually uses jsMath – see the next paragraph for the exception – to display the output in the notebook. Only the first argument, objects, is relevant; the others are ignored. If objects is a list, each object is printed on its own line.

In the notebook, this does not use jsMath if the LaTeX code for objects contains a string in latex.jsmath_avoid_list(). In this case, it creates and displays a png file.

EXAMPLES:

sage: sage.misc.latex.EMBEDDED_MODE = True
sage: view(3)
<html><span class="math">\newcommand{\Bold}[1]{\mathbf{#1}}3</span></html>
sage: view(3, mode='display')
<html><div class="math">\newcommand{\Bold}[1]{\mathbf{#1}}3</div></html>
sage: sage.misc.latex.EMBEDDED_MODE = False

Previous topic

Functional notation

Next topic

LaTeX macros

This Page