Ticket #9774: trac_9774-mathjax-try5.patch

File trac_9774-mathjax-try5.patch, 62.0 KB (added by ppurka, 8 years ago)

Apply to devel/sage

  • doc/common/builder.py

    # HG changeset patch
    # User J. H. Palmieri <palmieri@math.washington.edu>
    # Date 1326533960 -28800
    # Node ID 61753be3b18106c11184c4922108624a7793e0f7
    # Parent  e5bd429887d6498d54981862e9a25fa21289b9a0
    #9774: switch Sage library from jsMath to MathJax.
    
    Many people helped in this patch, including: Rob Beezer, Davide Cervone,
    John Palmieri, Rado Kirov, Nathan Carter, and Jason Grout
    
    diff --git a/doc/common/builder.py b/doc/common/builder.py
    a b  
    791791    s += "    sage -docbuild -FDC all\n"
    792792    s += "    sage -docbuild constructions pdf\n"
    793793    s += "    sage -docbuild reference html -jv3\n"
    794     s += "    sage -docbuild --jsmath tutorial html\n"
     794    s += "    sage -docbuild --mathjax tutorial html\n"
    795795    s += "    sage -docbuild reference print_unincluded_modules\n"
    796796    s += "    sage -docbuild developer -j html --sphinx-opts -q,-aE --verbose 2"
    797797    return s
     
    964964                        default=False, action="store_true",
    965965                        help="include variables prefixed with '_' in reference manual; may be slow, may fail for PDF output")
    966966
    967     standard.add_option("-j", "--jsmath", dest="jsmath",
     967    standard.add_option("-j", "--mathjax", "--jsmath", dest="mathjax",
    968968                        action="store_true",
    969                         help="render math using jsMath; FORMATs: html, json, pickle, web")
     969                        help="render math using MathJax; FORMATs: html, json, pickle, web")
    970970    standard.add_option("--no-pdf-links", dest="no_pdf_links",
    971971                        action="store_true",
    972972                        help="do not include PDF links in DOCUMENT 'website'; FORMATs: html, json, pickle, web")
     
    10741074    logger = setup_logger(options.verbose, options.color)
    10751075
    10761076    # Process selected options.
    1077     if options.jsmath:
    1078         os.environ['SAGE_DOC_JSMATH'] = "True"
     1077    if (options.mathjax or (os.environ.get('SAGE_DOC_MATHJAX', False))
     1078        or (os.environ.get('SAGE_DOC_JSMATH', False))):
     1079        os.environ['SAGE_DOC_MATHJAX'] = "True"
    10791080
    10801081    if options.check_nested:
    10811082        os.environ['SAGE_CHECK_NESTED'] = 'True'
  • doc/common/conf.py

    diff --git a/doc/common/conf.py b/doc/common/conf.py
    a b  
    2727#, 'sphinx.ext.intersphinx']
    2828
    2929
    30 if 'SAGE_DOC_JSMATH' in os.environ:
    31     extensions.append('sphinx.ext.jsmath')
    32 else:
    33     extensions.append('sphinx.ext.pngmath')
    34 jsmath_path = 'jsmath_sage.js'
    35 
    3630# Add any paths that contain templates here, relative to this directory.
    3731templates_path = [os.path.join(SAGE_DOC, 'common/templates'), 'templates']
    3832
     
    134128# -----------------------
    135129
    136130# HTML theme (e.g., 'default', 'sphinxdoc').  We use a custom Sage
    137 # theme to set a Pygments style, stylesheet, and insert jsMath macros. See
     131# theme to set a Pygments style, stylesheet, and insert MathJax macros. See
    138132# the directory doc/common/themes/sage/ for files comprising the custom Sage
    139133# theme.
    140134html_theme = 'sage'
     
    144138# see the documentation.
    145139html_theme_options = {}
    146140
    147 if 'SAGE_DOC_JSMATH' in os.environ:
    148     from sage.misc.latex_macros import sage_jsmath_macros_easy
    149     html_theme_options['jsmath_macros'] = sage_jsmath_macros_easy
    150 
    151     from sage.misc.package import is_package_installed
    152     html_theme_options['jsmath_image_fonts'] = is_package_installed('jsmath-image-fonts')
    153 
    154141# Add any paths that contain custom themes here, relative to this directory.
    155142html_theme_path = [os.path.join(SAGE_DOC, 'common/themes')]
    156143
     
    179166# so a file named "default.css" will overwrite the builtin "default.css".
    180167html_static_path = [os.path.join(SAGE_DOC, 'common/static'), 'static']
    181168
    182 # If we're using jsMath, we prepend its location to the static path
    183 # array.  We can override / overwrite selected files by putting them
    184 # in the remaining paths.
    185 if 'SAGE_DOC_JSMATH' in os.environ:
     169# The environment variable SAGE_DOC_MATHJAX may be set by the user or
     170# by the file "builder.py".  If it's set, or if SAGE_DOC_JSMATH is set
     171# (for backwards compatibility), use MathJax.
     172if (os.environ.get('SAGE_DOC_MATHJAX', False)
     173    or os.environ.get('SAGE_DOC_JSMATH', False)):
     174
     175    extensions.append('sphinx.ext.mathjax')
     176    mathjax_path = 'MathJax.js?config=TeX-AMS_HTML-full,../mathjax_sage.js'
     177
     178    from sage.misc.latex_macros import sage_mathjax_macros
     179    html_theme_options['mathjax_macros'] = sage_mathjax_macros
     180
    186181    from pkg_resources import Requirement, working_set
    187182    sagenb_path = working_set.find(Requirement.parse('sagenb')).location
    188     jsmath_static = os.path.join(sagenb_path, 'sagenb', 'data', 'jsmath')
    189     html_static_path.insert(0, jsmath_static)
     183    mathjax_relative = os.path.join('sagenb','data','mathjax')
     184
     185    # It would be really nice if sphinx would copy the entire mathjax directory,
     186    # (so we could have a _static/mathjax directory), rather than the contents of the directory
     187
     188    mathjax_static = os.path.join(sagenb_path, mathjax_relative)
     189    html_static_path.append(mathjax_static)
     190    exclude_patterns=['**/'+os.path.join(mathjax_relative, i) for i in ('docs', 'README*', 'test',
     191                                                                        'unpacked', 'LICENSE')]
     192else:
     193     extensions.append('sphinx.ext.pngmath')
     194
    190195
    191196# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
    192197# using the given strftime format.
     
    428433        for i in range(len(lines)):
    429434            docstringlines[i] = lines[i]
    430435
    431 def process_mathtt(app, what, name, obj, options, docstringlines):
    432     r"""
    433     Replace \mathtt{BLAH} with \verb|BLAH| if using jsMath.
    434     See sage.misc.sagedoc.process_mathtt for more information
    435     """
    436     if (len(docstringlines) > 0 and 'SAGE_DOC_JSMATH' in os.environ
    437         and name.find("process_mathtt") == -1):
    438         from sage.misc.sagedoc import process_mathtt as sagedoc_mathtt
    439         s = sagedoc_mathtt("\n".join(docstringlines), True)
    440         lines = s.split("\n")
    441         for i in range(len(lines)):
    442             docstringlines[i] = lines[i]
    443 
    444436def process_inherited(app, what, name, obj, options, docstringlines):
    445437    """
    446438    If we're including inherited members, omit their docstrings.
     
    604596    app.connect('autodoc-process-docstring', process_directives)
    605597    app.connect('autodoc-process-docstring', process_docstring_module_title)
    606598    app.connect('autodoc-process-docstring', process_dollars)
    607     app.connect('autodoc-process-docstring', process_mathtt)
    608599    app.connect('autodoc-process-docstring', process_inherited)
    609600    app.connect('autodoc-skip-member', skip_member)
    610601
  • .js_t

    diff --git a/doc/common/themes/sage/static/jsmath_sage.js_t b/doc/common/themes/sage/static/mathjax_sage.js_t
    rename from doc/common/themes/sage/static/jsmath_sage.js_t
    rename to doc/common/themes/sage/static/mathjax_sage.js_t
    old new  
    1 /**********************************************************************
    2  *
    3  *   Customize the values given below to suit your needs.
    4  *   You can make additional copies of this file with
    5  *   different customizated settings if you need to load
    6  *   jsMath with different parameters.
    7  *
    8  *   Load this page via:
    9  *
    10  *   <SCRIPT SRC="path-to-jsMath/easy/load.js"></SCRIPT>
    11  *
    12  *   (If you are including this file into your page via Server-Side
    13  *   Includes, you should remove line above.)
    14  *
    15  *   You can make copies of this file with different settings
    16  *   if you need to have several different configurations.
    17  *
    18  **********************************************************************/
     1MathJax.Hub.Config({
     2  imageFont: null,
     3  tex2jax: {
     4    inlineMath: [['$','$'],['\\(','\\)']],
     5    processEscapes: true,
     6  },
     7  styles: {
     8    ".MathJax .mo, .MathJax .mi": {
     9      color: "inherit ! important"
     10    }
     11  },
     12  TeX: {
     13    Macros: {
     14     {{ theme_mathjax_macros|join(',\n') }}
     15    }
     16  }
     17});
    1918
    20     if (!window.jsMath) {window.jsMath = {}}
    21 
    22 //  Move the jsMath button 20 pixels from the right edge (apparently
    23 //  in some browsers, it covers up the scroll bar)
    24 jsMath.styles = {
    25     '#jsMath_button' : 'position:fixed; bottom:1px; right:20px; '
    26         + 'background-color:white; border: solid 1px #959595; margin:0px; '
    27         + 'padding: 0px 3px 1px 3px; z-index:102; color:black; '
    28         + 'text-decoration:none; font-size:x-small; width:auto; cursor:hand;'
    29 }
    30 
    31 jsMath.Easy = {
    32     //
    33     //  The URL of the root jsMath directory on your server
    34     //  (it must be in the same domain as the HTML page).
    35     //  It should include "http://yoursite.com/", or should
    36     //  be relative to the root of your server.  It is possible
    37     //  to be a relative URL, but it will be relative to the
    38     //  HTML page loading this file.
    39     //
    40     //  If you leave this blank, jsMath will try to look it up from
    41     //  the URL where it loaded this file, but that may not work.
    42     //
    43     root: "",
    44 
    45     //
    46     //  The default scaling factor for mathematics compared to the
    47     //  surrounding text.
    48     //
    49     scale: 115,
    50 
    51     //
    52     //  1 means use the autoload plug-in to decide if jsMath should be loaded
    53     //  0 means always load jsMath
    54     //
    55     autoload: 1,
    56 
    57     //
    58     //  Setting any of these will cause the tex2math plugin to be used
    59     //  to add the <DIV> and <SPAN> tags that jsMath needs.  See the
    60     //  documentation for the tex2math plugin for more information.
    61     //
    62     processSlashParens: 0,       // process \(...\) in text?
    63     processSlashBrackets: 0,     // process \[...\] in text?
    64     processDoubleDollars: 0,     // process $$...$$ in text?
    65     processSingleDollars: 0,     // process $...$ in text?
    66     processLaTeXenvironments: 0, // process \begin{xxx}...\end{xxx} outside math mode?
    67     fixEscapedDollars: 0,        // convert \$ to $ outside of math mode?
    68     doubleDollarsAreInLine: 0,   // make $$...$$ be in-line math?
    69     allowDisableTag: 0,          // allow ID="tex2math_off" to disable tex2math?
    70     //
    71     //  If you want to use your own custom delimiters for math instead
    72     //  of the usual ones, then uncomment the following four lines and
    73     //  insert your own delimiters within the quotes.  You may want to
    74     //  turn off processing of the dollars and other delimiters above
    75     //  as well, though you can use them in combination with the
    76     //  custom delimiters if you wish.  See the tex2math documentation
    77     //  for more details.
    78     //
    79     //customDelimiters: [
    80     //  '[math]','[/math]',        // to begin and end in-line math
    81     //  '[display]','[/display]'   // to begin and end display math
    82     //],
    83 
    84     //
    85     //  Disallow the use of the @(...) mechanism for including raw HTML
    86     //  in the contents of \hbox{}?  (If used in a content-management system
    87     //  where users are allowed to enter mathematics, setting this to 0
    88     //  would allow them to enter arbitrary HTML code within their
    89     //  math formulas, and that poses a security risk.)
    90     //
    91     safeHBoxes: 1,
    92 
    93     //
    94     //  Show TeX source when mathematics is double-clicked?
    95     //
    96     allowDoubleClicks: 1,
    97 
    98     //
    99     //  Show jsMath font warning messages?  (Disabling this prevents yours
    100     //  users from finding out that they can have a better experience on your
    101     //  site by installing some fonts, so don't disable this).
    102     //
    103     showFontWarnings: 0,
    104 
    105     //
    106     //  Use "Process" or "ProcessBeforeShowing".  See the jsMath
    107     //  author's documentation for the difference between these
    108     //  two routines.
    109     //
    110     method: "Process",
    111 
    112     //
    113     //  List of plug-ins and extensions that you want to be
    114     //  loaded automatically.  E.g.
    115     //      ["plugins/mimeTeX.js","extensions/AMSsymbols.js"]
    116     //
    117     loadFiles: [
    118         "extensions/verb.js",
    119         "extensions/moreArrows.js",
    120         "extensions/AMSmath.js",
    121         "extensions/AMSsymbols.js"
    122     ],
    123 
    124     //
    125     //  List of fonts to load automatically.  E.g.
    126     //      ["cmmib10"]
    127     //
    128     loadFonts: [],
    129 
    130     //
    131     //  List of macros to define.  These are of the form
    132     //      name: value
    133     //  where 'value' is the replacement text for the macro \name.
    134     //  The 'value' can also be [value,n] where 'value' is the replacement
    135     //  text and 'n' is the number of parameters for the macro.
    136     //  Note that backslashes must be doubled in the replacement string.
    137     //  E.g.,
    138     //      {
    139     //        RR: '{\\bf R}',
    140     //        bold: ['{\\bf #1}', 1]
    141     //      }
    142     //
    143     // Sage-specific jsMath macros.
    144     macros: {
    145     {{ theme_jsmath_macros|join(',\n') }}
    146     },
    147 
    148     //
    149     //  Allow jsMath to enter global mode?
    150     //  (Uses frames, so may not always work with complex web sites)
    151     //
    152     allowGlobal: 1,
    153 
    154     //
    155     //  Disable image fonts?  (In case you don't load them on your server.)
    156     //
    157     // If we set this to 1, we do not need to load plugins/noImageFonts.js
    158     {% if theme_jsmath_image_fonts %}
    159     noImageFonts: 0
    160     {% else %}
    161     noImageFonts: 1
    162     {% endif %}
    163 };
    164 
    165 /****************************************************************/
    166 /****************************************************************/
    167 //
    168 //            DO NOT MAKE CHANGES BELOW THIS
    169 //
    170 /****************************************************************/
    171 /****************************************************************/
    172 
    173 jsMath.Easy.find_root = function () {
    174     if (jsMath.Easy.root == "") {
    175         jsMath.Easy.root = document.getElementsByTagName("script");
    176         for (var i = 0; i < jsMath.Easy.root.length; i++) {
    177             if (jsMath.Easy.root[i].src.match(/doctools.js$/)) {
    178                 jsMath.Easy.root = jsMath.Easy.root[i].src.replace(/doctools.js$/, "");
    179                 return;
    180             }
    181         }
    182         jsMath.Easy.root = jsMath.Easy.root[jsMath.Easy.root.length-1].src
    183         if (jsMath.Easy.root.match(/\/easy\/[^\/]*$/)) {
    184             jsMath.Easy.root = jsMath.Easy.root.replace(/\/easy\/[^\/]*$/,"");
    185         } else {
    186             jsMath.Easy.root = jsMath.Easy.root.replace(/\/(jsMath\/(easy\/)?)?[^\/]*$/,"/jsMath");
    187         }
    188     }
    189 };
    190 
    191 jsMath.Easy.find_root();
    192 
    193 jsMath.Easy.root = jsMath.Easy.root.replace(/\/$/,""); // trim trailing "/" if any
    194 
    195 document.write('<SCRIPT SRC="'+jsMath.Easy.root+'/jsMath-easy-load.js"><'+'/SCRIPT>');
     19// This path is a little funny because we have to load our local
     20// config file as '../mathjax_sage' in the theme conf.py
     21MathJax.Ajax.loadComplete("[MathJax]/config/../mathjax_sage.js")
  • doc/common/themes/sage/theme.conf

    diff --git a/doc/common/themes/sage/theme.conf b/doc/common/themes/sage/theme.conf
    a b  
    66[options]
    77# Custom Sage theme options
    88
    9 # jsMath settings filled in by conf.py
    10 jsmath_macros =
    11 jsmath_image_fonts =
     9# MathJax settings filled in by conf.py
     10mathjax_macros =
    1211
    1312# Sphinx default theme options
    1413
  • doc/en/introspect/conf.py

    diff --git a/doc/en/introspect/conf.py b/doc/en/introspect/conf.py
    a b  
    66sys.path.append(os.environ['SAGE_DOC'])
    77from common.conf import *
    88
    9 extensions = ['sphinx.ext.autodoc', 'sphinx.ext.jsmath', 'sphinx.ext.todo']
     9extensions = ['sphinx.ext.autodoc', 'sphinx.ext.mathjax', 'sphinx.ext.todo']
    1010
    1111templates_path = ['templates']
    1212html_static_path = ['static']
  • doc/en/thematic_tutorials/conf.py

    diff --git a/doc/en/thematic_tutorials/conf.py b/doc/en/thematic_tutorials/conf.py
    a b  
    2828# Output file base name for HTML help builder.
    2929htmlhelp_basename = "thematic_tutorials"
    3030
    31 # mathfrak isn't defined in jsMath, so using it gives errors.  The
    32 # following line turns it into bold face only when using jsMath, thus
    33 # avoiding the errors, while keeping the nice mathfrak fonts when not
    34 # using jsMath.
    35 try:
    36     html_theme_options['jsmath_macros'].append("mathfrak : ['\\\\mathbf{#1}', 1]")
    37 except KeyError:
    38     html_theme_options['jsmath_macros'] = ["mathfrak : ['\\\\mathbf{#1}', 1]"]
    39 
    4031# Grouping the document tree into LaTeX files. List of tuples
    4132# (source start file, target name, title, author,
    4233# document class [howto/manual]).
  • sage/all_notebook.py

    diff --git a/sage/all_notebook.py b/sage/all_notebook.py
    a b  
    1111
    1212sage_mode = 'notebook'
    1313
    14 from sage.misc.latex import Latex, pretty_print_default, JSMath
     14from sage.misc.latex import Latex, pretty_print_default, MathJax
    1515latex = Latex(density=130)
    1616latex_debug = Latex(debug=True, density=130)
    1717slide = Latex(slide=True, density=256)
    1818slide_debug = Latex(slide=True, debug=True, density=256)
    1919pdflatex = Latex(density=130, pdflatex=True)
    2020pdflatex_debug = Latex(density=130, pdflatex=True, debug=True)
    21 # we need a global instance of this in order to get %jsmath to work...
    22 jsmath = JSMath()
    2321
    2422from sage.misc.python import python
    2523
  • sage/graphs/generic_graph.py

    diff --git a/sage/graphs/generic_graph.py b/sage/graphs/generic_graph.py
    a b  
    336336        here to ``None``.  Some options are added to the global
    337337        :data:`sage.misc.latex.latex` instance which will insure
    338338        that if `\mbox{\rm\LaTeX}` is used to render the graph,
    339         then the right packages are loaded and jsMath reacts
     339        then the right packages are loaded and MathJax reacts
    340340        properly.
    341341
    342342        Most other initialization is done in the directed
  • sage/graphs/graph_latex.py

    diff --git a/sage/graphs/graph_latex.py b/sage/graphs/graph_latex.py
    a b  
    4848
    4949Customizing the output is accomplished in several ways.  Suppose ``g`` is a graph, then ``g.set_latex_options()`` can be used to efficiently set or modify various options.  Setting individual options, or querying options, can be accomplished by first using a command like ``opts = g.latex_options()`` to obtain a :class:`sage.graphs.graph_latex.GraphLatex` object which has several methods to set and retrieve options.
    5050
    51 Here is a minimal session demonstrating how to use these features. The following setup should work in the notebook or at the command-line, though the call to :meth:`~sage.misc.latex.Latex.jsmath_avoid_list` is only needed in the notebook. ::
     51Here is a minimal session demonstrating how to use these features. The following setup should work in the notebook or at the command-line, though the call to :meth:`~sage.misc.latex.Latex.mathjax_avoid_list` is only needed in the notebook. ::
     52
    5253
    5354    sage: from sage.graphs.graph_latex import setup_latex_preamble
    5455    sage: setup_latex_preamble()
     
    5859    \usepackage{tkz-berge}
    5960    \usetikzlibrary{arrows,shapes}
    6061    sage: latex.engine('pdflatex')
    61     sage: latex.jsmath_avoid_list('tikzpicture')
     62    sage: latex.mathjax_avoid_list('tikzpicture')
    6263    sage: H=graphs.HeawoodGraph()
    6364    sage: H.set_latex_options(
    6465    ...   graphic_size=(5,5),
  • sage/matrix/matrix0.pyx

    diff --git a/sage/matrix/matrix0.pyx b/sage/matrix/matrix0.pyx
    a b  
    19521952       
    19531953        row_divs, col_divs = self.subdivisions()
    19541954       
    1955         from sage.server.support import EMBEDDED_MODE
    1956 
    1957         # jsmath doesn't know the command \hline, so have to do things
    1958         # differently (and not as attractively) in embedded mode:
    1959         # construct an array with a subarray for each block.
    1960         if len(row_divs) + len(col_divs) > 0 and EMBEDDED_MODE:
    1961             for r in range(len(row_divs)+1):
    1962                 s = ""
    1963                 for c in range(len(col_divs)+1):
    1964                     if c == len(col_divs):
    1965                         sep=""
    1966                     else:
    1967                         sep=" & "
    1968                     sub = self.subdivision(r,c)
    1969                     if sub.nrows() > 0 and sub.ncols() > 0:
    1970                         entry = latex(self.subdivision(r,c))
    1971                         s = s + entry + sep
    1972                 rows.append(s)
    1973                
    1974             # Put brackets around in a single string
    1975             tmp = []
    1976             for row in rows:
    1977                 tmp.append(str(row))
    1978 
    1979             s = " \\\\\n".join(tmp)
    1980             format = 'r'*len(row_divs)
    1981             return "\\left" + matrix_delimiters[0] + "\\begin{array}{%s}\n"%format + s + "\n\\end{array}\\right" + matrix_delimiters[1]
    1982 
    1983         # not in EMBEDDED_MODE, or in EMBEDDED_MODE with just a single
    1984         # block: construct one large array, using \hline and vertical
     1955        # construct one large array, using \hline and vertical
    19851956        # bars | in the array descriptor to indicate subdivisions.
    19861957        for r from 0 <= r < nr:
    19871958            if r in row_divs:
  • sage/misc/html.py

    diff --git a/sage/misc/html.py b/sage/misc/html.py
    a b  
    3030    Do the following:
    3131
    3232    * Replace all ``\$ text \$``\'s by
    33       ``<span class='math'> text </span>``
     33      ``<script type="math/tex"> text </script>``
    3434    * Replace all ``\$\$ text \$\$``\'s by
    35       ``<div class='math'> text </div>``
     35      ``<script type="math/tex; mode=display"> text </script>``
    3636    * Replace all ``\ \$``\'s by ``\$``\'s.  Note that in
    3737      the above two cases nothing is done if the ``\$``
    3838      is preceeded by a backslash.
    3939    * Replace all ``\[ text \]``\'s by
    40       ``<div class='math'> text </div>``
     40      ``<script type="math/tex; mode=display"> text </script>``
    4141
    4242    EXAMPLES::
    4343
    4444        sage: sage.misc.html.math_parse('This is $2+2$.')
    45         'This is <span class="math">2+2</span>.'
     45        'This is <script type="math/tex">2+2</script>.'
    4646        sage: sage.misc.html.math_parse('This is $$2+2$$.')
    47         'This is <div class="math">2+2</div>.'
     47        'This is <script type="math/tex; mode=display">2+2</script>.'
    4848        sage: sage.misc.html.math_parse('This is \\[2+2\\].')
    49         'This is <div class="math">2+2</div>.'
     49        'This is <script type="math/tex; mode=display">2+2</script>.'
    5050        sage: sage.misc.html.math_parse(r'This is \[2+2\].')
    51         'This is <div class="math">2+2</div>.'
     51        'This is <script type="math/tex; mode=display">2+2</script>.'
    5252
    5353    TESTS::
    5454
    5555        sage: sage.misc.html.math_parse(r'This \$\$is $2+2$.')
    56         'This $$is <span class="math">2+2</span>.'
     56        'This $$is <script type="math/tex">2+2</script>.'
    5757    """
    58     # first replace \\[ and \\] by <div class="math"> and </div>, respectively.
     58    # first replace \\[ and \\] by <script type="math/tex; mode=display">
     59    # and </script>, respectively.
    5960    while True:
    6061        i = s.find('\\[')
    6162        if i == -1:
    6263            break
    6364        else:
    64             s = s[:i] + '<div class="math">' + s[i+2:]
     65            s = s[:i] + '<script type="math/tex; mode=display">' + s[i+2:]
    6566            j = s.find('\\]')
    6667            if j == -1:  # missing right-hand delimiter, so add one
    67                 s = s + '</div>'
     68                s = s + '</script>'
    6869            else:
    69                 s = s[:j] + '</div>' + s[j+2:]
     70                s = s[:j] + '</script>' + s[j+2:]
    7071   
    7172    # Below t always has the "parsed so far" version of s, and s is
    7273    # just the part of the original input s that hasn't been parsed.
     
    8485            s = s[i+1:]
    8586            continue
    8687        elif i+1 < len(s) and s[i+1] == '$':
    87             # Found a math environment. Double dollar sign so div mode.
    88             typ = 'div'
     88            # Found a math environment. Double dollar sign so display mode.
     89            disp = '; mode=display'
    8990        else:
    90             # Found math environment. Single dollar sign so span mode.
    91             typ = 'span'
     91            # Found math environment. Single dollar sign so default mode.
     92            disp = ''
    9293
    93         # Now find the matching $ sign and form the span or div.
    94         j = s[i+2:].find('$')
    95         if j == -1:
    96             j = len(s)
    97             s += '$'
    98             if typ == 'div':
     94        # Now find the matching $ sign and form the html string.
     95
     96        if len(disp) > 0:
     97            j = s[i+2:].find('$$')
     98            if j == -1:
     99                j = len(s)
    99100                s += '$$'
    100         else:
    101             j += i + 2
    102         if typ == 'div':
     101            else:
     102                j += i + 2
    103103            txt = s[i+2:j]
    104104        else:
     105            j = s[i+2:].find('$')
     106            if j == -1:
     107                j = len(s)
     108                s += '$'
     109            else:
     110                j += i + 2
    105111            txt = s[i+1:j]
    106         t += s[:i] + '<%s class="math">%s</%s>'%(typ,
    107                       ' '.join(txt.splitlines()), typ)
     112
     113        t += s[:i] + '<script type="math/tex%s">%s</script>'%(disp,
     114                      ' '.join(txt.splitlines()))
    108115        s = s[j+1:]
    109         if typ == 'div':
     116        if len(disp) > 0:
    110117            s = s[1:]
    111118    return t
    112119
     
    168175            if j == -1:
    169176                 t += s
    170177                 break
    171             t += s[:i] + '<span class="math">%s</span>'%\
     178            t += s[:i] + '<script type="math/tex">%s</script>'%\
    172179                     latex(sage_eval(s[6+i:j], locals=locals))
    173180            s = s[j+7:]
    174181        print "<html><font color='black'>%s</font></html>"%t
     
    196203            <table class="table_form">
    197204            <tbody>
    198205            <tr class ="row-a">
    199             <td><span class="math">0</span></td>
    200             <td><span class="math">0</span></td>
    201             <td><span class="math">\mathrm{True}</span></td>
     206            <td><script type="math/tex">0</script></td>
     207            <td><script type="math/tex">0</script></td>
     208            <td><script type="math/tex">\mathrm{True}</script></td>
    202209            </tr>
    203210            <tr class ="row-b">
    204             <td><span class="math">0</span></td>
    205             <td><span class="math">1</span></td>
    206             <td><span class="math">\mathrm{False}</span></td>
     211            <td><script type="math/tex">0</script></td>
     212            <td><script type="math/tex">1</script></td>
     213            <td><script type="math/tex">\mathrm{False}</script></td>
    207214            </tr>
    208215            <tr class ="row-a">
    209             <td><span class="math">1</span></td>
    210             <td><span class="math">0</span></td>
    211             <td><span class="math">\mathrm{False}</span></td>
     216            <td><script type="math/tex">1</script></td>
     217            <td><script type="math/tex">0</script></td>
     218            <td><script type="math/tex">\mathrm{False}</script></td>
    212219            </tr>
    213220            <tr class ="row-b">
    214             <td><span class="math">1</span></td>
    215             <td><span class="math">1</span></td>
    216             <td><span class="math">\mathrm{True}</span></td>
     221            <td><script type="math/tex">1</script></td>
     222            <td><script type="math/tex">1</script></td>
     223            <td><script type="math/tex">\mathrm{True}</script></td>
    217224            </tr>
    218225            </tbody>
    219226            </table>
     
    226233            <table class="table_form">
    227234            <tbody>
    228235            <tr>
    229             <th>Functions <span class="math">f(x)</span></th>
     236            <th>Functions <script type="math/tex">f(x)</script></th>
    230237            </tr>
    231238            <tr class ="row-a">
    232             <td><span class="math">\sin\left(x\right)</span></td>
     239            <td><script type="math/tex">\sin\left(x\right)</script></td>
    233240            </tr>
    234241            <tr class ="row-b">
    235             <td><span class="math">\cos\left(x\right)</span></td>
     242            <td><script type="math/tex">\cos\left(x\right)</script></td>
    236243            </tr>
    237244            </tbody>
    238245            </table>
     
    245252            <table class="table_form">
    246253            <tbody>
    247254            <tr>
    248             <th><span class="math">x</span></th>
    249             <th><span class="math">\sin(x)</span></th>
     255            <th><script type="math/tex">x</script></th>
     256            <th><script type="math/tex">\sin(x)</script></th>
    250257            </tr>
    251258            <tr class ="row-a">
    252             <td><span class="math">0</span></td>
    253             <td><span class="math">0.00</span></td>
     259            <td><script type="math/tex">0</script></td>
     260            <td><script type="math/tex">0.00</script></td>
    254261            </tr>
    255262            <tr class ="row-b">
    256             <td><span class="math">1</span></td>
    257             <td><span class="math">0.84</span></td>
     263            <td><script type="math/tex">1</script></td>
     264            <td><script type="math/tex">0.84</script></td>
    258265            </tr>
    259266            <tr class ="row-a">
    260             <td><span class="math">2</span></td>
    261             <td><span class="math">0.91</span></td>
     267            <td><script type="math/tex">2</script></td>
     268            <td><script type="math/tex">0.91</script></td>
    262269            </tr>
    263270            <tr class ="row-b">
    264             <td><span class="math">3</span></td>
    265             <td><span class="math">0.14</span></td>
     271            <td><script type="math/tex">3</script></td>
     272            <td><script type="math/tex">0.14</script></td>
    266273            </tr>
    267274            </tbody>
    268275            </table>
     
    306313        TESTS::
    307314       
    308315            sage: html._table_columns(["a $x^2$",1, sin(x)])
    309             <td>a <span class="math">x^2</span></td>
    310             <td><span class="math">1</span></td>
    311             <td><span class="math">\sin\left(x\right)</span></td>
     316            <td>a <script type="math/tex">x^2</script></td>
     317            <td><script type="math/tex">1</script></td>
     318            <td><script type="math/tex">\sin\left(x\right)</script></td>
    312319            sage: html._table_columns("a", header=True)
    313320            <th>a</th>
    314321        """       
     
    326333            elif isinstance(row[column], str):
    327334                print column_tag % math_parse(row[column])
    328335            else:
    329                 print column_tag % ('<span class="math">%s</span>' % latex(row[column]))
     336                print column_tag % ('<script type="math/tex">%s</script>' % latex(row[column]))
    330337
    331338    def iframe(self, url, height=400, width=800):
    332339        r"""
  • sage/misc/latex.py

    diff --git a/sage/misc/latex.py b/sage/misc/latex.py
    a b  
    310310    # 2) wrap each line into \verb;
    311311    # 3) assemble lines into a left-justified array.
    312312   
    313     # There is a bug in verb-space treatment in jsMath...
    314     spacer = "\\phantom{%s}"
    315     # \phantom{\verb!%s!} is more accurate and it works, but it is not a valid
    316     # LaTeX and may cause problems, so let's live with the above variant until
    317     # spaces are properly treated in jsMath/MathJax and we don't need to worry.
     313    spacer = r"\phantom{\verb!%s!}"
    318314    lines = []
    319315    for line in x.split("\n"):
    320316        parts = []
     
    570566        self._option["preamble"] = ""
    571567        self._option["engine"] = "latex"
    572568        self._option["engine_name"] = "LaTeX"
    573         self._option["jsmath_avoid"] = []
     569        self._option["mathjax_avoid"] = []
    574570
    575571_Latex_prefs = _Latex_prefs_object()
    576572
     
    10651061        """
    10661062        if t is None:
    10671063            return _Latex_prefs._option["blackboard_bold"]
    1068         from latex_macros import sage_latex_macros, sage_jsmath_macros, sage_configurable_latex_macros, convert_latex_macro_to_jsmath
     1064        from latex_macros import sage_latex_macros, sage_mathjax_macros, sage_configurable_latex_macros, convert_latex_macro_to_mathjax
    10691065        global sage_latex_macros
    1070         global sage_jsmath_macros
     1066        global sage_mathjax_macros
    10711067        old = _Latex_prefs._option["blackboard_bold"]
    10721068        _Latex_prefs._option["blackboard_bold"] = bool(t)
    10731069        if bool(old) != bool(t):
     
    10831079            sage_configurable_latex_macros.remove(old_macro)
    10841080            sage_latex_macros.append(macro)
    10851081            sage_configurable_latex_macros.append(macro)
    1086             sage_jsmath_macros.remove(convert_latex_macro_to_jsmath(old_macro))
    1087             sage_jsmath_macros.append(convert_latex_macro_to_jsmath(macro))
     1082            sage_mathjax_macros.remove(convert_latex_macro_to_mathjax(old_macro))
     1083            sage_mathjax_macros.append(convert_latex_macro_to_mathjax(macro))
    10881084
    10891085    def matrix_delimiters(self, left=None, right=None):
    10901086        r"""nodetex
     
    12621258    def extra_macros(self, macros=None):
    12631259        r"""nodetex
    12641260        String containing extra LaTeX macros to use with %latex,
    1265         %html, and %jsmath.
     1261        %html, and %mathjax.
    12661262
    12671263        INPUT: ``macros`` - string
    12681264
     
    12871283    def add_macro(self, macro):
    12881284        r"""nodetex
    12891285        Append to the string of extra LaTeX macros, for use with
    1290         %latex, %html, and %jsmath.
     1286        %latex, %html, and %mathjax.
    12911287
    12921288        INPUT: ``macro`` - string
    12931289
     
    13071303    def extra_preamble(self, s=None):
    13081304        r"""nodetex
    13091305        String containing extra preamble to be used with %latex.
    1310         Anything in this string won't be processed by %jsmath.
     1306        Anything in this string won't be processed by %mathjax.
    13111307
    13121308        INPUT: ``s`` - string or ``None``
    13131309
     
    13411337        r"""nodetex
    13421338        Append to the string of extra LaTeX macros, for use with
    13431339        %latex.  Anything in this string won't be processed by
    1344         %jsmath.
     1340        %mathjax.
    13451341
    13461342        EXAMPLES::
    13471343
     
    14071403        if self.has_file(package_name+".sty"):
    14081404            self.add_to_preamble("\\usepackage{%s}\n"%package_name)
    14091405
    1410     def jsmath_avoid_list(self, L=None):
     1406    def mathjax_avoid_list(self, L=None):
    14111407        r"""nodetex
    1412         List of strings which signal that jsMath should not
     1408        List of strings which signal that MathJax should not
    14131409        be used when 'view'ing.
    14141410
    14151411        INPUT: ``L`` - list or ``None``
     
    14171413        If ``L`` is ``None``, then return the current list.
    14181414        Otherwise, set it to ``L``.  If you want to *append* to the
    14191415        current list instead of replacing it, use
    1420         :meth:`latex.add_to_jsmath_avoid_list <Latex.add_to_jsmath_avoid_list>`.
     1416        :meth:`latex.add_to_mathjax_avoid_list <Latex.add_to_mathjax_avoid_list>`.
    14211417
    14221418        EXAMPLES::
    14231419
    1424             sage: latex.jsmath_avoid_list(["\\mathsf", "pspicture"])
    1425             sage: latex.jsmath_avoid_list()  # display current setting
     1420            sage: latex.mathjax_avoid_list(["\\mathsf", "pspicture"])
     1421            sage: latex.mathjax_avoid_list()  # display current setting
    14261422            ['\\mathsf', 'pspicture']
    1427             sage: latex.jsmath_avoid_list([])  # reset to default
    1428             sage: latex.jsmath_avoid_list()
     1423            sage: latex.mathjax_avoid_list([])  # reset to default
     1424            sage: latex.mathjax_avoid_list()
    14291425            []
    14301426        """
    14311427        if L is None:
    1432             return _Latex_prefs._option['jsmath_avoid']
     1428            return _Latex_prefs._option['mathjax_avoid']
    14331429        else:
    1434             _Latex_prefs._option['jsmath_avoid'] = L
    1435 
    1436     def add_to_jsmath_avoid_list(self, s):
     1430            _Latex_prefs._option['mathjax_avoid'] = L
     1431
     1432    def add_to_mathjax_avoid_list(self, s):
    14371433        r"""nodetex
    1438         Add to the list of strings which signal that jsMath should not
     1434        Add to the list of strings which signal that MathJax should not
    14391435        be used when 'view'ing.
    14401436
    1441         INPUT: ``s`` - string -- add ``s`` to the list of 'jsMath avoid' strings
     1437        INPUT: ``s`` - string -- add ``s`` to the list of 'MathJax avoid' strings
    14421438
    14431439        If you want to replace the current list instead of adding to
    1444         it, use :meth:`latex.jsmath_avoid_list <Latex.jsmath_avoid_list>`.
     1440        it, use :meth:`latex.mathjax_avoid_list <Latex.mathjax_avoid_list>`.
    14451441
    14461442        EXAMPLES::
    14471443
    1448             sage: latex.add_to_jsmath_avoid_list("\\mathsf")
    1449             sage: latex.jsmath_avoid_list()  # display current setting
     1444            sage: latex.add_to_mathjax_avoid_list("\\mathsf")
     1445            sage: latex.mathjax_avoid_list()  # display current setting
    14501446            ['\\mathsf']
    1451             sage: latex.add_to_jsmath_avoid_list("tkz-graph")
    1452             sage: latex.jsmath_avoid_list()  # display current setting
     1447            sage: latex.add_to_mathjax_avoid_list("tkz-graph")
     1448            sage: latex.mathjax_avoid_list()  # display current setting
    14531449            ['\\mathsf', 'tkz-graph']
    1454             sage: latex.jsmath_avoid_list([])  # reset to default
    1455             sage: latex.jsmath_avoid_list()
     1450            sage: latex.mathjax_avoid_list([])  # reset to default
     1451            sage: latex.mathjax_avoid_list()
    14561452            []
    14571453        """
    1458         current = latex.jsmath_avoid_list()
     1454        current = latex.mathjax_avoid_list()
    14591455        if s not in current:
    1460             _Latex_prefs._option['jsmath_avoid'].append(s)
     1456            _Latex_prefs._option['mathjax_avoid'].append(s)
    14611457
    14621458    def pdflatex(self, t = None):  # this is deprecated since 4.3.3
    14631459        """
     
    16741670
    16751671    return s
    16761672
    1677 class JSMathExpr:
     1673class MathJaxExpr:
    16781674    """
    1679     An arbitrary JSMath expression that can be nicely concatenated.
     1675    An arbitrary MathJax expression that can be nicely concatenated.
    16801676
    16811677    EXAMPLES::
    16821678
    1683         sage: from sage.misc.latex import JSMathExpr
    1684         sage: JSMathExpr("a^{2}") + JSMathExpr("x^{-1}")
     1679        sage: from sage.misc.latex import MathJaxExpr
     1680        sage: MathJaxExpr("a^{2}") + MathJaxExpr("x^{-1}")
    16851681        a^{2}x^{-1}
    16861682    """
    16871683    def __init__(self, y):
    16881684        """
    1689         Initialize a JSMath expression.
     1685        Initialize a MathJax expression.
    16901686
    16911687        INPUT:
    16921688
     
    16961692
    16971693        EXAMPLES::
    16981694
    1699             sage: from sage.misc.latex import JSMathExpr
    1700             sage: js = JSMathExpr(3); js  # indirect doctest
     1695            sage: from sage.misc.latex import MathJaxExpr
     1696            sage: jax = MathJaxExpr(3); jax  # indirect doctest
    17011697            3
    17021698        """
    17031699        self.__y = y
     
    17081704
    17091705        EXAMPLES::
    17101706
    1711             sage: from sage.misc.latex import JSMathExpr
    1712             sage: js = JSMathExpr('3')
    1713             sage: js.__repr__()
     1707            sage: from sage.misc.latex import MathJaxExpr
     1708            sage: jax = MathJaxExpr('3')
     1709            sage: jax.__repr__()
    17141710            '3'
    17151711        """
    17161712        return str(self.__y)
    17171713
    17181714    def __add__(self, y):
    17191715        """
    1720         'Add' JSMathExpr ``self`` to ``y``.  This concatenates them
     1716        'Add' MathJaxExpr ``self`` to ``y``.  This concatenates them
    17211717        (assuming that they're strings).
    17221718
    17231719        EXAMPLES::
    17241720
    1725             sage: from sage.misc.latex import JSMathExpr
    1726             sage: j3 = JSMathExpr('3')
    1727             sage: jx = JSMathExpr('x')
     1721            sage: from sage.misc.latex import MathJaxExpr
     1722            sage: j3 = MathJaxExpr('3')
     1723            sage: jx = MathJaxExpr('x')
    17281724            sage: j3 + jx
    17291725            3x
    17301726        """
    1731         return JSMathExpr(self.__y + y)
     1727        return MathJaxExpr(self.__y + y)
    17321728
    17331729    def __radd__(self, y):
    17341730        """
    1735         'Add' JSMathExpr ``y`` to ``self``.  This concatenates them
     1731        'Add' MathJaxExpr ``y`` to ``self``.  This concatenates them
    17361732        (assuming that they're strings).
    17371733
    17381734        EXAMPLES::
    17391735
    1740             sage: from sage.misc.latex import JSMathExpr
    1741             sage: j3 = JSMathExpr('3')
    1742             sage: jx = JSMathExpr('x')
     1736            sage: from sage.misc.latex import MathJaxExpr
     1737            sage: j3 = MathJaxExpr('3')
     1738            sage: jx = MathJaxExpr('x')
    17431739            sage: j3.__radd__(jx)
    17441740            x3
    17451741        """
    1746         return JSMathExpr(y + self.__y)
    1747 
    1748 class JSMath:
     1742        return MathJaxExpr(y + self.__y)
     1743
     1744class MathJax:
    17491745    r"""
    1750     Render LaTeX input using JSMath.  This returns a :class:`JSMathExpr`.
     1746    Render LaTeX input using MathJax.  This returns a :class:`MathJaxExpr`.
    17511747
    17521748    EXAMPLES::
    17531749
    1754         sage: from sage.misc.latex import JSMath
    1755         sage: JSMath()(3)
    1756         <html><div class="math">\newcommand{\Bold}[1]{\mathbf{#1}}3</div></html>
    1757         sage: JSMath()(ZZ)
    1758         <html><div class="math">\newcommand{\Bold}[1]{\mathbf{#1}}\Bold{Z}</div></html>
     1750        sage: from sage.misc.latex import MathJax
     1751        sage: MathJax()(3)
     1752        <html><script type="math/tex; mode=display">\newcommand{\Bold}[1]{\mathbf{#1}}3</script></html>
     1753        sage: MathJax()(ZZ)
     1754        <html><script type="math/tex; mode=display">\newcommand{\Bold}[1]{\mathbf{#1}}\Bold{Z}</script></html>
    17591755    """
    17601756
    17611757    def __call__(self, x):
    17621758        r"""
    1763         Render LaTeX input using JSMath.  This returns a :class:`JSMathExpr`.
     1759        Render LaTeX input using MathJax.  This returns a :class:`MathJaxExpr`.
    17641760
    17651761        INPUT:
    17661762
    17671763        - ``x`` - a Sage object
    17681764
    1769         OUTPUT: a JSMathExpr
     1765        OUTPUT: a MathJaxExpr
    17701766
    17711767        EXAMPLES::
    17721768
    1773             sage: from sage.misc.latex import JSMath
    1774             sage: JSMath()(3)
    1775             <html><div class="math">\newcommand{\Bold}[1]{\mathbf{#1}}3</div></html>
    1776             sage: str(JSMath().eval(ZZ[x], mode='display')) == str(JSMath()(ZZ[x]))
     1769            sage: from sage.misc.latex import MathJax
     1770            sage: MathJax()(3)
     1771            <html><script type="math/tex; mode=display">\newcommand{\Bold}[1]{\mathbf{#1}}3</script></html>
     1772            sage: str(MathJax().eval(ZZ[x], mode='display')) == str(MathJax()(ZZ[x]))
    17771773            True
    17781774        """
    17791775        return self.eval(x)
    17801776
    17811777    def eval(self, x, globals=None, locals=None, mode='display'):
    17821778        r"""
    1783         Render LaTeX input using JSMath.  This returns a :class:`JSMathExpr`.
     1779        Render LaTeX input using MathJax.  This returns a :class:`MathJaxExpr`.
    17841780
    17851781        INPUT:
    17861782
     
    17941790        -  ``mode`` - string (optional, default 'display): 'display'
    17951791           for displaymath or 'inline' for inline math
    17961792
    1797         OUTPUT: a JSMathExpr
     1793        OUTPUT: a MathJaxExpr
    17981794
    17991795        EXAMPLES::
    18001796
    1801             sage: from sage.misc.latex import JSMath
    1802             sage: JSMath().eval(3, mode='display')
    1803             <html><div class="math">\newcommand{\Bold}[1]{\mathbf{#1}}3</div></html>
    1804             sage: JSMath().eval(3, mode='inline')
    1805             <html><span class="math">\newcommand{\Bold}[1]{\mathbf{#1}}3</span></html>
    1806             sage: JSMath().eval(type(3), mode='inline')
    1807             <html>...\verb|&lt;type|\phantom{x}\verb|'sage.rings.integer.Integer'&gt;|</span></html>
     1797            sage: from sage.misc.latex import MathJax
     1798            sage: MathJax().eval(3, mode='display')
     1799            <html><script type="math/tex; mode=display">\newcommand{\Bold}[1]{\mathbf{#1}}3</script></html>
     1800            sage: MathJax().eval(3, mode='inline')
     1801            <html><script type="math/tex">\newcommand{\Bold}[1]{\mathbf{#1}}3</script></html>
     1802            sage: MathJax().eval(type(3), mode='inline')
     1803            <html><script type="math/tex">\newcommand{\Bold}[1]{\mathbf{#1}}\verb|&lt;type|\phantom{\verb!x!}\verb|'sage.rings.integer.Integer'&gt;|</script></html>
    18081804        """
    18091805        # Get a regular LaTeX representation of x...
    18101806        x = latex(x)
    1811         # ... and make it suitable for jsMath, which has issues with < and >.
     1807        # ... and make it suitable for MathJax and html
    18121808        x = x.replace('<', '&lt;').replace('>', '&gt;')
    1813         # In jsMath:
    1814         #   inline math: <span class="math">...</span>
    1815         #   displaymath: <div class="math">...</div>
     1809        # In MathJax:
     1810        #   inline math: <script type="math/tex">...</script>
     1811        #   displaymath: <script type="math/tex; mode=display">...</script>
    18161812        from sage.misc.latex_macros import sage_configurable_latex_macros
    1817         if 'display' == mode:
    1818             return JSMathExpr('<html><div class="math">'
    1819                               + ''.join(sage_configurable_latex_macros)
    1820                               + _Latex_prefs._option['macros']
    1821                               + '%s</div></html>'%x)
    1822         elif 'inline' == mode:
    1823             return JSMathExpr('<html><span class="math">'
    1824                               + ''.join(sage_configurable_latex_macros)
    1825                               + _Latex_prefs._option['macros']
    1826                               + '%s</span></html>'%x)
     1813        if mode == 'display':
     1814            modecode = '; mode=display'
     1815        elif mode == 'inline':
     1816            modecode = ''
    18271817        else:
    18281818            # what happened here?
    1829             raise ValueError, "mode must be either 'display' or 'inline'"
    1830 
    1831 def jsmath(x, mode='display'):
    1832     r"""
    1833     Attempt to nicely render an arbitrary Sage object with jsMath typesetting.
    1834     Tries to call ._latex_() on x. If that fails, it will render a string
    1835     representation of x.
    1836 
    1837     .. warning::
    1838 
    1839         2009-04: This function is deprecated; use :func:`~.html.html`
    1840         instead: replace ``jsmath('MATH', mode='display')`` with
    1841         ``html('$$MATH$$')``, and replace ``jsmath('MATH',
    1842         mode='inline')`` with ``html('$MATH$')``.
    1843 
    1844     INPUT:
    1845         x -- the object to render
    1846         mode -- 'display' for displaymath or 'inline' for inline math
    1847 
    1848     OUTPUT:
    1849         A string of html that contains the LaTeX representation of x. In the
    1850         notebook this gets embedded into the cell.
    1851 
    1852     EXAMPLES::
    1853 
    1854         sage: from sage.misc.latex import jsmath
    1855         sage: f = maxima('1/(x^2+1)')
    1856         sage: g = f.integrate()
    1857         sage: jsmath(f)
    1858         doctest:1: DeprecationWarning: The jsmath function is deprecated.  Use html('$math$') for inline mode or html('$$math$$') for display mode.
    1859         <html><font color='black'><div class="math">{{1}\over{x^2+1}}</div></font></html>
    1860         sage: jsmath(g, 'inline')
    1861         <html><font color='black'><span class="math">\tan^{-1} x</span></font></html>
    1862         sage: jsmath('\int' + latex(f) + '\ dx=' + latex(g))
    1863         <html><font color='black'><div class="math">\int {{1}\over{x^2+1}} \ dx= \tan^{-1} x</div></font></html>
    1864 
    1865     AUTHORS:
    1866 
    1867     - William Stein (2006-10): general layout (2006-10)
    1868 
    1869     - Bobby Moretti (2006-10): improvements, comments, documentation
    1870     """
    1871     from sage.misc.misc import deprecation
    1872     from sage.misc.html import html
    1873     deprecation("The jsmath function is deprecated.  Use html('$math$') for inline mode or html('$$math$$') for display mode.")
    1874     if mode == 'display':
    1875         delimiter = '$$'
    1876     elif mode == 'inline':
    1877         delimiter = '$'
    1878     else:
    1879         raise ValueError, "mode must be either 'display' or 'inline'"
    1880     try:
    1881         # try to get a latex representation of the object
    1882         x = x._latex_()
    1883     except AttributeError:
    1884         # otherwise just get the string representation
    1885         x = str(x)
    1886     return html(delimiter + x + delimiter)
     1819            raise ValueError("mode must be either 'display' or 'inline'")
     1820
     1821        return MathJaxExpr('<html><script type="math/tex{0}">'.format(modecode)
     1822                         + ''.join(sage_configurable_latex_macros)
     1823                         + _Latex_prefs._option['macros']
     1824                         + '{0}</script></html>'.format(x))
    18871825
    18881826def view(objects, title='SAGE', debug=False, sep='', tiny=False, pdflatex=None, engine=None, viewer = None, tightpage = None, mode='inline', **kwds):
    18891827    r"""nodetex
     
    19681906    each object by ``\\begin{page}$`` and ``$\\end{page}``.
    19691907
    19701908    If in notebook mode with ``viewer`` equal to ``None``, this
    1971     usually uses jsMath -- see the next paragraph for the exception --
     1909    usually uses MathJax -- see the next paragraph for the exception --
    19721910    to display the output in the notebook. Only the first argument,
    19731911    ``objects``, is relevant; the others are ignored. If ``objects``
    19741912    is a list, each object is printed on its own line.
    19751913
    1976     In the notebook, this *does* *not* use jsMath if the LaTeX code
     1914    In the notebook, this *does* *not* use MathJax if the LaTeX code
    19771915    for ``objects`` contains a string in
    1978     :meth:`latex.jsmath_avoid_list() <Latex.jsmath_avoid_list>`.  In
     1916    :meth:`latex.mathjax_avoid_list() <Latex.mathjax_avoid_list>`.  In
    19791917    this case, it creates and displays a png file.
    19801918
    19811919    EXAMPLES::
    19821920
    19831921        sage: sage.misc.latex.EMBEDDED_MODE = True
    19841922        sage: view(3)
    1985         <html><span class="math">\newcommand{\Bold}[1]{\mathbf{#1}}3</span></html>
     1923        <html><script type="math/tex">\newcommand{\Bold}[1]{\mathbf{#1}}3</script></html>
    19861924        sage: view(3, mode='display')
    1987         <html><div class="math">\newcommand{\Bold}[1]{\mathbf{#1}}3</div></html>
     1925        <html><script type="math/tex; mode=display">\newcommand{\Bold}[1]{\mathbf{#1}}3</script></html>
    19881926        sage: sage.misc.latex.EMBEDDED_MODE = False
    19891927
    19901928    TESTS::
     
    20061944    s = _latex_file_(objects, title=title, sep=sep, tiny=tiny, debug=debug, **latex_options)
    20071945    # notebook
    20081946    if EMBEDDED_MODE and viewer is None:
    2009         jsMath_okay = True
    2010         for t in latex.jsmath_avoid_list():
     1947        MathJax_okay = True
     1948        for t in latex.mathjax_avoid_list():
    20111949            if s.find(t) != -1:
    2012                 jsMath_okay = False
    2013             if not jsMath_okay:
     1950                MathJax_okay = False
     1951            if not MathJax_okay:
    20141952                break
    2015         if jsMath_okay:
    2016             print JSMath().eval(objects, mode=mode)  # put comma at end of line?
     1953        if MathJax_okay:
     1954            print MathJax().eval(objects, mode=mode)  # put comma at end of line?
    20171955        else:
    20181956            if pdflatex is True:
    20191957                engine = "pdflatex"
     
    22302168        sage: TEMP = sys.displayhook
    22312169        sage: sys.displayhook = sage.misc.latex.pretty_print
    22322170        sage: sage.misc.latex.print_or_typeset(3)
    2233         <html><span class="math">\newcommand{\Bold}[1]{\mathbf{#1}}3</span></html>
     2171        <html><script type="math/tex">\newcommand{\Bold}[1]{\mathbf{#1}}3</script></html>
    22342172        sage: sage.misc.latex.EMBEDDED_MODE=False
    22352173        sage: sys.displayhook = TEMP
    22362174    """
     
    22462184    objects, this returns their default representation.  For other
    22472185    objects, in the notebook, this calls the :func:`view` command,
    22482186    while from the command line, this produces an html string suitable
    2249     for processing by jsMath.
     2187    for processing by MathJax.
    22502188
    22512189    INPUT:
    22522190
     
    22582196    EXAMPLES::
    22592197
    22602198        sage: pretty_print(ZZ)  # indirect doctest
    2261         <html><span class="math">\newcommand{\Bold}[1]{\mathbf{#1}}\Bold{Z}</span></html>
     2199        <html><script type="math/tex">\newcommand{\Bold}[1]{\mathbf{#1}}\Bold{Z}</script></html>
    22622200
    22632201    To typeset LaTeX code as-is, use :class:`LatexExpr`::
    22642202
    22652203        sage: pretty_print(LatexExpr(r"\frac{x^2 + 1}{x - 2}"))
    2266         <html><span class="math">\newcommand{\Bold}[1]{\mathbf{#1}}\frac{x^2 + 1}{x - 2}</span></html>
     2204        <html><script type="math/tex">\newcommand{\Bold}[1]{\mathbf{#1}}\frac{x^2 + 1}{x - 2}</script></html>
    22672205    """
    22682206    if object is None:
    22692207        return
     
    22792217        if EMBEDDED_MODE:
    22802218            view(object)
    22812219        else:
    2282             print JSMath().eval(object, mode='inline')
     2220            print MathJax().eval(object, mode='inline')
    22832221        return
    22842222
    22852223def pretty_print_default(enable=True):
    22862224    r"""
    22872225    Enable or disable default pretty printing. Pretty printing means
    2288     rendering things so that jsMath or some other latex-aware front end
     2226    rendering things so that MathJax or some other latex-aware front end
    22892227    can render real math.
    22902228
    22912229    INPUT:
     
    22972235
    22982236        sage: pretty_print_default(True)
    22992237        sage: sys.displayhook
    2300         <html>...\verb|&lt;function|\phantom{x}\verb|pretty_print|...</html>
     2238        <html><script type="math/tex">\newcommand{\Bold}[1]{\mathbf{#1}}\verb|&lt;function|\phantom{\verb!x!}\verb|pretty_print|\phantom{\verb!x!}\verb|at|\phantom{\verb!x!}\verb|...|</script></html>
    23012239        sage: pretty_print_default(False)
    23022240        sage: sys.displayhook == sys.__displayhook__
    23032241        True
     
    25232461the TeX package pgf installed, along with the LaTeX package tkz-graph.
    25242462Run 'latex.add_to_preamble("\\usepackage{tkz-graph}")', and try viewing
    25252463it again.  From the command line, this should pop open a nice window
    2526 with a picture of a graph.  In the notebook, you should get a jsMath
    2527 error.  Finally, run 'latex.add_to_jsmath_avoid_list("tikzpicture")'
     2464with a picture of a graph.  In the notebook, you should get a MathJax
     2465error.  Finally, run 'latex.add_to_mathjax_avoid_list("tikzpicture")'
    25282466and try again from the notebook -- you should get a nice picture.
    25292467
    25302468(LaTeX code taken from http://altermundus.com/pages/graph.html)
     
    26062544open a nice window with a picture of forces acting on a mass
    26072545on a pendulum. In the notebook, you should get an error.
    26082546Finally, run
    2609 'latex.add_to_jsmath_avoid_list("pspicture")' and try again
     2547'latex.add_to_mathjax_avoid_list("pspicture")' and try again
    26102548-- you should get a nice picture."""
    26112549
    26122550        def _latex_(self):
     
    26732611'latex.add_to_preamble("\\usepackage[graph,knot,poly,curve]{xypic}")',
    26742612and try viewing again -- it should work in the command line but not
    26752613from the notebook.  In the notebook, run
    2676 'latex.add_to_jsmath_avoid_list("xygraph")' and try again -- you
     2614'latex.add_to_mathjax_avoid_list("xygraph")' and try again -- you
    26772615should get a nice picture.
    26782616
    26792617(LaTeX code taken from the xypic manual)
     
    27372675'latex.add_to_preamble("\\usepackage[matrix,arrow,curve,cmtip]{xy}")',
    27382676and try viewing again -- it should work in the command line but not
    27392677from the notebook.  In the notebook, run
    2740 'latex.add_to_jsmath_avoid_list("xymatrix")' and try again -- you
     2678'latex.add_to_mathjax_avoid_list("xymatrix")' and try again -- you
    27412679should get a picture (a part of the diagram arising from a filtered
    27422680chain complex)."""
    27432681
  • sage/misc/latex_macros.py

    diff --git a/sage/misc/latex_macros.py b/sage/misc/latex_macros.py
    a b  
    99documentation. To add a macro, modify the list ``macros``, near the
    1010end of this file, and then run 'sage -b'. The entries in this list are
    1111used to produce ``sage_latex_macros``, a list of strings of the form
    12 '\\newcommand...', and ``sage_js_macros``, a list of strings of the
    13 form 'jsMath.Macro...'.  The LaTeX macros are produced using the
    14 ``_latex_`` method for each Sage object listed in ``macros``, and the
    15 jsMath macros are produced from the LaTeX macros.  The list of LaTeX
    16 macros is used in the file ``SAGE_ROOT/devel/sage/doc/common/conf.py``
    17 to add to the preambles of both the LaTeX file used to build the PDF
    18 version of the documentation and the LaTeX file used to build the HTML
    19 version.  The list of jsMath macros is used in the file
    20 ``sage/server/notebook/notebook.py`` to define jsMath macros for use
     12'\\newcommand...', and ``sage_mathjax_macros``, a list of strings
     13suitable for parsing by MathJax.  The LaTeX macros are produced using
     14the ``_latex_`` method for each Sage object listed in ``macros``, and
     15the MathJax macros are produced from the LaTeX macros.  The list of
     16LaTeX macros is used in the file
     17``SAGE_ROOT/devel/sage/doc/common/conf.py`` to add to the preambles of
     18both the LaTeX file used to build the PDF version of the documentation
     19and the LaTeX file used to build the HTML version.  The list of
     20MathJax macros is used in the file
     21``sage/server/notebook/notebook.py`` to define MathJax macros for use
    2122in the live documentation (and also in the notebook).
    2223
    2324Any macro defined here may be used in docstrings or in the tutorial
     
    101102        defn = defn.replace(str(x), "#" + str(count))
    102103    return newcommand + defn
    103104
    104 def convert_latex_macro_to_jsmath(macro):
     105def convert_latex_macro_to_mathjax(macro):
    105106    r"""
    106107    This converts a LaTeX macro definition (\newcommand...) to a
    107     jsMath macro definition (jsMath.Macro...).
     108    MathJax macro definition (MathJax.Macro...).
    108109
    109110    INPUT:
    110111
    111112    -  ``macro`` - LaTeX macro definition
    112113
    113114    See the web page
    114     http://www.math.union.edu/~dpvc/jsMath/authors/macros.html for a
    115     description of the format for jsMath macros.
     115    http://www.mathjax.org/docs/1.1/options/TeX.html for a
     116    description of the format for MathJax macros.
    116117
    117118    EXAMPLES::
    118119
    119         sage: from sage.misc.latex_macros import convert_latex_macro_to_jsmath
    120         sage: convert_latex_macro_to_jsmath('\\newcommand{\\ZZ}{\\Bold{Z}}')
    121         "jsMath.Macro('ZZ','\\\\Bold{Z}');"
    122         sage: convert_latex_macro_to_jsmath('\\newcommand{\\GF}[1]{\\Bold{F}_{#1}}')
    123         "jsMath.Macro('GF','\\\\Bold{F}_{#1}',1);"
     120        sage: from sage.misc.latex_macros import convert_latex_macro_to_mathjax
     121        sage: convert_latex_macro_to_mathjax('\\newcommand{\\ZZ}{\\Bold{Z}}')
     122        'ZZ: "\\\\Bold{Z}"'
     123        sage: convert_latex_macro_to_mathjax('\\newcommand{\\GF}[1]{\\Bold{F}_{#1}}')
     124        'GF: ["\\\\Bold{F}_{#1}",1]'
    124125    """
    125126    left_bracket = macro.find('[')
    126127    right_bracket = macro.find('[')
     
    135136    start_defn = macro.find('{', end_name)
    136137    end_defn = macro.rfind('}')
    137138    defn = macro[start_defn+1: end_defn].replace('\\', '\\\\')
    138     if num_args > 0:
    139         args_str = "," + str(num_args)
     139    if num_args == 0:
     140        return name + ': "' + defn + '"'
    140141    else:
    141         args_str = ""
    142     return "jsMath.Macro('" + name + "','" + defn + "'" + args_str + ");"
    143 
    144 def convert_latex_macro_to_jsmath_easy(macro):
    145     r"""
    146     This converts a LaTeX macro definition (\newcommand...) to a
    147     definition for jsMath's easy/load.js macro array.
    148 
    149     INPUT:
    150 
    151     -  ``macro`` - LaTeX macro definition
    152 
    153     EXAMPLES::
    154 
    155         sage: from sage.misc.latex_macros import convert_latex_macro_to_jsmath_easy
    156         sage: convert_latex_macro_to_jsmath_easy('\\newcommand{\\ZZ}{\\Bold{Z}}')
    157         "ZZ : '{\\\\Bold{Z}}'"
    158         sage: convert_latex_macro_to_jsmath_easy('\\newcommand{\\GF}[1]{\\Bold{F}_{#1}}')
    159         "GF : ['{\\\\Bold{F}_{#1}}', 1]"
    160     """
    161     left_bracket = macro.find('[')
    162     right_bracket = macro.find('[')
    163     if left_bracket >= 0:
    164         right_bracket = macro.find(']')
    165         num_args = macro[left_bracket+1:right_bracket]
    166     else:
    167         num_args = 0
    168     start_name = macro.find('{') + 1  # add one to go past the backslash
    169     end_name = macro.find('}')
    170     name = macro[start_name+1:end_name]
    171     start_defn = macro.find('{', end_name)
    172     end_defn = macro.rfind('}')
    173     defn = macro[start_defn+1: end_defn].replace('\\', '\\\\')
    174     if num_args > 0:
    175         args_str = "," + str(num_args)
    176         return name + " : ['{" + defn + "}', " + str(num_args) + ']'
    177     else:
    178         return name + " : '{" + defn + "}'"
     142        return name + ': ["' + defn + '",' + str(num_args) + ']'
    179143
    180144# To add a new macro for use in the Sage documentation, add a list or
    181145# tuple to the following list.  Each list (or tuple) should have the
     
    213177
    214178sage_latex_macros += sage_configurable_latex_macros
    215179
    216 # jsMath macro definitions as JavaScript, e.g., to include in HTML
     180# MathJax macro definitions as JavaScript, e.g., to include in HTML
    217181# script elements.
    218 sage_jsmath_macros = [convert_latex_macro_to_jsmath(m) for m in sage_latex_macros]
    219 
    220 # jsMath macro definitions for an easy/load.js file's "macros" array.
    221 sage_jsmath_macros_easy = [convert_latex_macro_to_jsmath_easy(m) for m in sage_latex_macros]
     182sage_mathjax_macros = [convert_latex_macro_to_mathjax(m) for m in sage_latex_macros]
  • sage/misc/sagedoc.py

    diff --git a/sage/misc/sagedoc.py b/sage/misc/sagedoc.py
    a b  
    4242
    4343# two kinds of substitutions: math, which should only be done on the
    4444# command line -- in the notebook, these should instead by taken care
    45 # of by jsMath -- and nonmath, which should be done always.
     45# of by MathJax -- and nonmath, which should be done always.
    4646math_substitutes = [ # don't forget leading backslash '\\'
    4747    ('\\to', '-->'),
    4848    ('\\leq', '<='),
     
    296296            s = s[:m.start()] + "$" + s[m.end():]
    297297    return s
    298298
    299 def process_mathtt(s, embedded=False):
     299def process_mathtt(s):
    300300    r"""nodetex
    301     Replace \\mathtt{BLAH} with either \\verb|BLAH| (in the notebook) or
    302     BLAH (from the command line).
     301    Replace \\mathtt{BLAH} with BLAH in the command line.
    303302
    304303    INPUT:
    305304
    306305    - ``s`` - string, in practice a docstring
    307     - ``embedded`` - boolean (optional, default False)
    308306
    309     This function is called by :func:`format`, and if in the notebook,
    310     it sets ``embedded`` to be ``True``, otherwise ``False``.
     307    This function is called by :func:`format`.
    311308
    312309    EXAMPLES::
    313310
    314311        sage: from sage.misc.sagedoc import process_mathtt
    315312        sage: process_mathtt(r'e^\mathtt{self}')
    316313        'e^self'
    317         sage: process_mathtt(r'e^\mathtt{self}', embedded=True)
    318         'e^{\\verb|self|}'
    319314    """
    320     replaced = False
    321315    while True:
    322316        start = s.find("\\mathtt{")
    323317        end = s.find("}", start)
    324318        if start == -1 or end == -1:
    325319            break
    326         if embedded:
    327             left = "{\\verb|"
    328             right = "|}"
    329         else:
    330             left = ""
    331             right = ""
    332         s = s[:start] + left + s[start+8:end] + right + s[end+1:]
     320        s = s[:start] + s[start+8:end] + s[end+1:]
    333321    return s
    334322
    335323def format(s, embedded=False):
     
    518506
    519507    if 'nodetex' not in directives:
    520508        s = process_dollars(s)
    521         s = process_mathtt(s, embedded=embedded)
     509        if not embedded:
     510            s = process_mathtt(s)
    522511        s = detex(s, embedded=embedded)
    523512    return embedding_info+s
    524513
     
    12791268    </script>
    12801269    <script type="text/javascript" src="%(static_path)s/jquery.js"></script>
    12811270    <script type="text/javascript" src="%(static_path)s/doctools.js"></script>
    1282     <script type="text/javascript" src="%(static_path)s/jsmath_sage.js"></script>
     1271    <script type="text/javascript" src="%(static_path)s/mathjax_sage.js"></script>
    12831272    <link rel="shortcut icon" href="%(static_path)s/favicon.ico" />
    12841273    <link rel="icon" href="%(static_path)s/sageicon.png" type="image/x-icon" />
    12851274  </head>
     
    13371326        path = os.path.join(self._base_path, name, "index.html")
    13381327        if not os.path.exists(path):
    13391328            raise OSError, """The document '%s' does not exist.  Please build it
    1340 with 'sage -docbuild %s html --jsmath' and try again.""" %(name, name)
     1329with 'sage -docbuild %s html --mathjax' and try again.""" %(name, name)
    13411330
    13421331        if testing:
    13431332            return (url, path)
  • sage/modules/vector_callable_symbolic_dense.py

    diff --git a/sage/modules/vector_callable_symbolic_dense.py b/sage/modules/vector_callable_symbolic_dense.py
    a b  
    104104            return r"%s \ {\mapsto}\ %s" % (args[0], latex_x)
    105105        else:
    106106            vars = ", ".join(args)
    107             # the weird TeX is to workaround an apparent JsMath bug
    108107            return r"\left( %s \right) \ {\mapsto} \ %s" % (vars, latex_x)
  • sage/symbolic/callable.py

    diff --git a/sage/symbolic/callable.py b/sage/symbolic/callable.py
    a b  
    435435            return r"%s \ {\mapsto}\ %s" % (args[0], latex_x)
    436436        else:
    437437            vars = ", ".join(args)
    438             # the weird TeX is to workaround an apparent JsMath bug
    439438            return r"\left( %s \right) \ {\mapsto} \ %s" % (vars, latex_x)
    440439
    441440    def _call_element_(self, _the_element, *args, **kwds):