Ticket #9774: trac_9774-mathjax-try4.patch

File trac_9774-mathjax-try4.patch, 61.5 KB (added by kini, 8 years ago)

apply to $SAGE_ROOT/devel/sage

  • doc/common/builder.py

    # HG changeset patch
    # User J. H. Palmieri <palmieri@math.washington.edu>
    # Date 1326533960 -28800
    # Node ID f7ec280b8b87459a578859bac0df68db0a922e03
    # Parent 92c93226b64f933e0af00bbcbd1a8a79c444f43f
    #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  
    758758    s += "    sage -docbuild -FDC all\n"
    759759    s += "    sage -docbuild constructions pdf\n"
    760760    s += "    sage -docbuild reference html -jv3\n"
    761     s += "    sage -docbuild --jsmath tutorial html\n"
     761    s += "    sage -docbuild --mathjax tutorial html\n"
    762762    s += "    sage -docbuild reference print_unincluded_modules\n"
    763763    s += "    sage -docbuild developer -j html --sphinx-opts -q,-aE --verbose 2"
    764764    return s
     
    931931                        default=False, action="store_true",
    932932                        help="include variables prefixed with '_' in reference manual; may be slow, may fail for PDF output")
    933933
    934     standard.add_option("-j", "--jsmath", dest="jsmath",
     934    standard.add_option("-j", "--mathjax", "--jsmath", dest="mathjax",
    935935                        action="store_true",
    936                         help="render math using jsMath; FORMATs: html, json, pickle, web")
     936                        help="render math using MathJax; FORMATs: html, json, pickle, web")
    937937    standard.add_option("--no-pdf-links", dest="no_pdf_links",
    938938                        action="store_true",
    939939                        help="do not include PDF links in DOCUMENT 'website'; FORMATs: html, json, pickle, web")
     
    10381038    logger = setup_logger(options.verbose, options.color)
    10391039
    10401040    # Process selected options.
    1041     if options.jsmath:
    1042         os.environ['SAGE_DOC_JSMATH'] = "True"
     1041    if (options.mathjax or (os.environ.get('SAGE_DOC_MATHJAX', False))
     1042        or (os.environ.get('SAGE_DOC_JSMATH', False))):
     1043        os.environ['SAGE_DOC_MATHJAX'] = "True"
    10431044
    10441045    if options.check_nested:
    10451046        os.environ['SAGE_CHECK_NESTED'] = 'True'
  • doc/common/conf.py

    diff --git a/doc/common/conf.py b/doc/common/conf.py
    a b  
    1717              'sphinx.ext.inheritance_diagram', 'sphinx.ext.todo']
    1818#, 'sphinx.ext.intersphinx', 'sphinx.ext.extlinks']
    1919
    20 if 'SAGE_DOC_JSMATH' in os.environ:
    21     extensions.append('sphinx.ext.jsmath')
    22 else:
    23     extensions.append('sphinx.ext.pngmath')
    24 jsmath_path = 'jsmath_sage.js'
    25 
    2620# Add any paths that contain templates here, relative to this directory.
    2721templates_path = [os.path.join(SAGE_DOC, 'common/templates'), 'templates']
    2822
     
    10397# -----------------------
    10498
    10599# HTML theme (e.g., 'default', 'sphinxdoc').  We use a custom Sage
    106 # theme to set a Pygments style, stylesheet, and insert jsMath macros. See
     100# theme to set a Pygments style, stylesheet, and insert MathJax macros. See
    107101# the directory doc/common/themes/sage/ for files comprising the custom Sage
    108102# theme.
    109103html_theme = 'sage'
     
    113107# see the documentation.
    114108html_theme_options = {}
    115109
    116 if 'SAGE_DOC_JSMATH' in os.environ:
    117     from sage.misc.latex_macros import sage_jsmath_macros_easy
    118     html_theme_options['jsmath_macros'] = sage_jsmath_macros_easy
    119 
    120     from sage.misc.package import is_package_installed
    121     html_theme_options['jsmath_image_fonts'] = is_package_installed('jsmath-image-fonts')
    122 
    123110# Add any paths that contain custom themes here, relative to this directory.
    124111html_theme_path = [os.path.join(SAGE_DOC, 'common/themes')]
    125112
     
    148135# so a file named "default.css" will overwrite the builtin "default.css".
    149136html_static_path = [os.path.join(SAGE_DOC, 'common/static'), 'static']
    150137
    151 # If we're using jsMath, we prepend its location to the static path
    152 # array.  We can override / overwrite selected files by putting them
    153 # in the remaining paths.
    154 if 'SAGE_DOC_JSMATH' in os.environ:
     138# The environment variable SAGE_DOC_MATHJAX may be set by the user or
     139# by the file "builder.py".  If it's set, or if SAGE_DOC_JSMATH is set
     140# (for backwards compatibility), use MathJax.
     141if (os.environ.get('SAGE_DOC_MATHJAX', False)
     142    or os.environ.get('SAGE_DOC_JSMATH', False)):
     143
     144    extensions.append('sphinx.ext.mathjax')
     145    mathjax_path = 'MathJax.js?config=TeX-AMS_HTML-full,../mathjax_sage.js'
     146
     147    from sage.misc.latex_macros import sage_mathjax_macros
     148    html_theme_options['mathjax_macros'] = sage_mathjax_macros
     149
    155150    from pkg_resources import Requirement, working_set
    156151    sagenb_path = working_set.find(Requirement.parse('sagenb')).location
    157     jsmath_static = os.path.join(sagenb_path, 'sagenb', 'data', 'jsmath')
    158     html_static_path.insert(0, jsmath_static)
     152    mathjax_relative = os.path.join('sagenb','data','mathjax')
     153
     154    # It would be really nice if sphinx would copy the entire mathjax directory,
     155    # (so we could have a _static/mathjax directory), rather than the contents of the directory
     156
     157    mathjax_static = os.path.join(sagenb_path, mathjax_relative)
     158    html_static_path.append(mathjax_static)
     159    exclude_patterns=['**/'+os.path.join(mathjax_relative, i) for i in ('docs', 'README*', 'test',
     160                                                                        'unpacked', 'LICENSE')]
     161else:
     162     extensions.append('sphinx.ext.pngmath')
     163
    159164
    160165# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
    161166# using the given strftime format.
     
    400405        for i in range(len(lines)):
    401406            docstringlines[i] = lines[i]
    402407
    403 def process_mathtt(app, what, name, obj, options, docstringlines):
    404     r"""
    405     Replace \mathtt{BLAH} with \verb|BLAH| if using jsMath.
    406     See sage.misc.sagedoc.process_mathtt for more information
    407     """
    408     if (len(docstringlines) > 0 and 'SAGE_DOC_JSMATH' in os.environ
    409         and name.find("process_mathtt") == -1):
    410         from sage.misc.sagedoc import process_mathtt as sagedoc_mathtt
    411         s = sagedoc_mathtt("\n".join(docstringlines), True)
    412         lines = s.split("\n")
    413         for i in range(len(lines)):
    414             docstringlines[i] = lines[i]
    415 
    416408def process_inherited(app, what, name, obj, options, docstringlines):
    417409    """
    418410    If we're including inherited members, omit their docstrings.
     
    444436    app.connect('autodoc-process-docstring', process_directives)
    445437    app.connect('autodoc-process-docstring', process_docstring_module_title)
    446438    app.connect('autodoc-process-docstring', process_dollars)
    447     app.connect('autodoc-process-docstring', process_mathtt)
    448439    app.connect('autodoc-process-docstring', process_inherited)
    449440    app.connect('autodoc-skip-member', skip_member)
  • .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  
    2828        here to ``None``.  Some options are added to the global
    2929        :data:`sage.misc.latex.latex` instance which will insure
    3030        that if `\mbox{\rm\LaTeX}` is used to render the graph,
    31         then the right packages are loaded and jsMath reacts
     31        then the right packages are loaded and MathJax reacts
    3232        properly.
    3333
    3434        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  
    18501850       
    18511851        row_divs, col_divs = self.subdivisions()
    18521852       
    1853         from sage.server.support import EMBEDDED_MODE
    1854 
    1855         # jsmath doesn't know the command \hline, so have to do things
    1856         # differently (and not as attractively) in embedded mode:
    1857         # construct an array with a subarray for each block.
    1858         if len(row_divs) + len(col_divs) > 0 and EMBEDDED_MODE:
    1859             for r in range(len(row_divs)+1):
    1860                 s = ""
    1861                 for c in range(len(col_divs)+1):
    1862                     if c == len(col_divs):
    1863                         sep=""
    1864                     else:
    1865                         sep=" & "
    1866                     sub = self.subdivision(r,c)
    1867                     if sub.nrows() > 0 and sub.ncols() > 0:
    1868                         entry = latex(self.subdivision(r,c))
    1869                         s = s + entry + sep
    1870                 rows.append(s)
    1871                
    1872             # Put brackets around in a single string
    1873             tmp = []
    1874             for row in rows:
    1875                 tmp.append(str(row))
    1876 
    1877             s = " \\\\\n".join(tmp)
    1878             format = 'r'*len(row_divs)
    1879             return "\\left" + matrix_delimiters[0] + "\\begin{array}{%s}\n"%format + s + "\n\\end{array}\\right" + matrix_delimiters[1]
    1880 
    1881         # not in EMBEDDED_MODE, or in EMBEDDED_MODE with just a single
    1882         # block: construct one large array, using \hline and vertical
     1853        # construct one large array, using \hline and vertical
    18831854        # bars | in the array descriptor to indicate subdivisions.
    18841855        for r from 0 <= r < nr:
    18851856            if r in row_divs:
  • sage/misc/html.py

    diff --git a/sage/misc/html.py b/sage/misc/html.py
    a b  
    2727    Do the following:
    2828    \begin{verbatim}
    2929       * Replace all $ text $'s by
    30          <span class='math'> text </span>
     30         <script type="math/tex"> text </script>
    3131       * Replace all $$ text $$'s by
    32          <div class='math'> text </div>
     32         <script type="math/tex; mode=display"> text </script>
    3333       * Replace all \$'s by $'s.  Note that in
    3434         the above two cases nothing is done if the $
    3535         is preceeded by a backslash.
    3636       * Replace all \[ text \]'s by
    37          <div class='math'> text </div>
     37         <script type="math/tex; mode=display"> text </script>
    3838    \end{verbatim}
    3939
    4040    EXAMPLES:
    4141        sage: sage.misc.html.math_parse('This is $2+2$.')
    42         'This is <span class="math">2+2</span>.'
     42        'This is <script type="math/tex">2+2</script>.'
    4343        sage: sage.misc.html.math_parse('This is $$2+2$$.')
    44         'This is <div class="math">2+2</div>.'
     44        'This is <script type="math/tex; mode=display">2+2</script>.'
    4545        sage: sage.misc.html.math_parse('This is \\[2+2\\].')
    46         'This is <div class="math">2+2</div>.'
     46        'This is <script type="math/tex; mode=display">2+2</script>.'
    4747        sage: sage.misc.html.math_parse(r'This is \[2+2\].')
    48         'This is <div class="math">2+2</div>.'
     48        'This is <script type="math/tex; mode=display">2+2</script>.'
    4949
    5050    TESTS:
    5151        sage: sage.misc.html.math_parse(r'This \$\$is $2+2$.')
    52         'This $$is <span class="math">2+2</span>.'   
     52        'This $$is <script type="math/tex">2+2</script>.'
    5353    """
    54     # first replace \\[ and \\] by <div class="math"> and </div>, respectively.
     54    # first replace \\[ and \\] by <script type="math/tex; mode=display"> and
     55    # </script>, respectively.
    5556    while True:
    5657        i = s.find('\\[')
    5758        if i == -1:
    5859            break
    5960        else:
    60             s = s[:i] + '<div class="math">' + s[i+2:]
     61            s = s[:i] + '<script type="math/tex; mode=display">' + s[i+2:]
    6162            j = s.find('\\]')
    6263            if j == -1:  # missing right-hand delimiter, so add one
    63                 s = s + '</div>'
     64                s = s + '</script>'
    6465            else:
    65                 s = s[:j] + '</div>' + s[j+2:]
     66                s = s[:j] + '</script>' + s[j+2:]
    6667   
    6768    # Below t always has the "parsed so far" version of s, and s is
    6869    # just the part of the original input s that hasn't been parsed.
     
    8081            s = s[i+1:]
    8182            continue
    8283        elif i+1 < len(s) and s[i+1] == '$':
    83             # Found a math environment. Double dollar sign so div mode.
    84             typ = 'div'
     84            # Found a math environment. Double dollar sign so display mode.
     85            disp = '; mode=display'
    8586        else:
    86             # Found math environment. Single dollar sign so span mode.
    87             typ = 'span'
     87            # Found math environment. Single dollar sign so default mode.
     88            disp = ''
    8889
    89         # Now find the matching $ sign and form the span or div.
    90         j = s[i+2:].find('$')
    91         if j == -1:
    92             j = len(s)
    93             s += '$'
    94             if typ == 'div':
     90        # Now find the matching $ sign and form the html string.
     91
     92        if len(disp) > 0:
     93            j = s[i+2:].find('$$')
     94            if j == -1:
     95                j = len(s)
    9596                s += '$$'
    96         else:
    97             j += i + 2
    98         if typ == 'div':
     97            else:
     98                j += i + 2
    9999            txt = s[i+2:j]
    100100        else:
     101            j = s[i+2:].find('$')
     102            if j == -1:
     103                j = len(s)
     104                s += '$'
     105            else:
     106                j += i + 2
    101107            txt = s[i+1:j]
    102         t += s[:i] + '<%s class="math">%s</%s>'%(typ,
    103                       ' '.join(txt.splitlines()), typ)
     108
     109        t += s[:i] + '<script type="math/tex%s">%s</script>'%(disp,
     110                      ' '.join(txt.splitlines()))
    104111        s = s[j+1:]
    105         if typ == 'div':
     112        if len(disp) > 0:
    106113            s = s[1:]
    107114    return t
    108115
     
    163170            if j == -1:
    164171                 t += s
    165172                 break
    166             t += s[:i] + '<span class="math">%s</span>'%\
     173            t += s[:i] + '<script type="math/tex">%s</script>'%\
    167174                     latex(sage_eval(s[6+i:j], locals=locals))
    168175            s = s[j+7:]
    169176        print "<html><font color='black'>%s</font></html>"%t
     
    191198            <table class="table_form">
    192199            <tbody>
    193200            <tr class ="row-a">
    194             <td><span class="math">0</span></td>
    195             <td><span class="math">0</span></td>
    196             <td><span class="math">\mathrm{True}</span></td>
     201            <td><script type="math/tex">0</script></td>
     202            <td><script type="math/tex">0</script></td>
     203            <td><script type="math/tex">\mathrm{True}</script></td>
    197204            </tr>
    198205            <tr class ="row-b">
    199             <td><span class="math">0</span></td>
    200             <td><span class="math">1</span></td>
    201             <td><span class="math">\mathrm{False}</span></td>
     206            <td><script type="math/tex">0</script></td>
     207            <td><script type="math/tex">1</script></td>
     208            <td><script type="math/tex">\mathrm{False}</script></td>
    202209            </tr>
    203210            <tr class ="row-a">
    204             <td><span class="math">1</span></td>
    205             <td><span class="math">0</span></td>
    206             <td><span class="math">\mathrm{False}</span></td>
     211            <td><script type="math/tex">1</script></td>
     212            <td><script type="math/tex">0</script></td>
     213            <td><script type="math/tex">\mathrm{False}</script></td>
    207214            </tr>
    208215            <tr class ="row-b">
    209             <td><span class="math">1</span></td>
    210             <td><span class="math">1</span></td>
    211             <td><span class="math">\mathrm{True}</span></td>
     216            <td><script type="math/tex">1</script></td>
     217            <td><script type="math/tex">1</script></td>
     218            <td><script type="math/tex">\mathrm{True}</script></td>
    212219            </tr>
    213220            </tbody>
    214221            </table>
     
    221228            <table class="table_form">
    222229            <tbody>
    223230            <tr>
    224             <th>Functions <span class="math">f(x)</span></th>
     231            <th>Functions <script type="math/tex">f(x)</script></th>
    225232            </tr>
    226233            <tr class ="row-a">
    227             <td><span class="math">\sin\left(x\right)</span></td>
     234            <td><script type="math/tex">\sin\left(x\right)</script></td>
    228235            </tr>
    229236            <tr class ="row-b">
    230             <td><span class="math">\cos\left(x\right)</span></td>
     237            <td><script type="math/tex">\cos\left(x\right)</script></td>
    231238            </tr>
    232239            </tbody>
    233240            </table>
     
    240247            <table class="table_form">
    241248            <tbody>
    242249            <tr>
    243             <th><span class="math">x</span></th>
    244             <th><span class="math">\sin(x)</span></th>
     250            <th><script type="math/tex">x</script></th>
     251            <th><script type="math/tex">\sin(x)</script></th>
    245252            </tr>
    246253            <tr class ="row-a">
    247             <td><span class="math">0</span></td>
    248             <td><span class="math">0.00</span></td>
     254            <td><script type="math/tex">0</script></td>
     255            <td><script type="math/tex">0.00</script></td>
    249256            </tr>
    250257            <tr class ="row-b">
    251             <td><span class="math">1</span></td>
    252             <td><span class="math">0.84</span></td>
     258            <td><script type="math/tex">1</script></td>
     259            <td><script type="math/tex">0.84</script></td>
    253260            </tr>
    254261            <tr class ="row-a">
    255             <td><span class="math">2</span></td>
    256             <td><span class="math">0.91</span></td>
     262            <td><script type="math/tex">2</script></td>
     263            <td><script type="math/tex">0.91</script></td>
    257264            </tr>
    258265            <tr class ="row-b">
    259             <td><span class="math">3</span></td>
    260             <td><span class="math">0.14</span></td>
     266            <td><script type="math/tex">3</script></td>
     267            <td><script type="math/tex">0.14</script></td>
    261268            </tr>
    262269            </tbody>
    263270            </table>
     
    301308        TESTS::
    302309       
    303310            sage: html._table_columns(["a $x^2$",1, sin(x)])
    304             <td>a <span class="math">x^2</span></td>
    305             <td><span class="math">1</span></td>
    306             <td><span class="math">\sin\left(x\right)</span></td>
     311            <td>a <script type="math/tex">x^2</script></td>
     312            <td><script type="math/tex">1</script></td>
     313            <td><script type="math/tex">\sin\left(x\right)</script></td>
    307314            sage: html._table_columns("a", header=True)
    308315            <th>a</th>
    309316        """       
     
    321328            elif isinstance(row[column], str):
    322329                print column_tag % math_parse(row[column])
    323330            else:
    324                 print column_tag % ('<span class="math">%s</span>' % latex(row[column]))
     331                print column_tag % ('<script type="math/tex">%s</script>' % latex(row[column]))
    325332
    326333    def iframe(self, url, height=400, width=800):
    327334        r"""
  • sage/misc/latex.py

    diff --git a/sage/misc/latex.py b/sage/misc/latex.py
    a b  
    280280    # 2) wrap each line into \verb;
    281281    # 3) assemble lines into a left-justified array.
    282282   
    283     # There is a bug in verb-space treatment in jsMath...
    284     spacer = "\\phantom{%s}"
    285     # \phantom{\verb!%s!} is more accurate and it works, but it is not a valid
    286     # LaTeX and may cause problems, so let's live with the above variant until
    287     # spaces are properly treated in jsMath/MathJax and we don't need to worry.
     283    spacer = r"\phantom{\verb!%s!}"
    288284    lines = []
    289285    for line in x.split("\n"):
    290286        parts = []
     
    537533        self._option["preamble"] = ""
    538534        self._option["engine"] = "latex"
    539535        self._option["engine_name"] = "LaTeX"
    540         self._option["jsmath_avoid"] = []
     536        self._option["mathjax_avoid"] = []
    541537
    542538_Latex_prefs = _Latex_prefs_object()
    543539
     
    10311027        """
    10321028        if t is None:
    10331029            return _Latex_prefs._option["blackboard_bold"]
    1034         from latex_macros import sage_latex_macros, sage_jsmath_macros, sage_configurable_latex_macros, convert_latex_macro_to_jsmath
     1030        from latex_macros import sage_latex_macros, sage_mathjax_macros, sage_configurable_latex_macros, convert_latex_macro_to_mathjax
    10351031        global sage_latex_macros
    1036         global sage_jsmath_macros
     1032        global sage_mathjax_macros
    10371033        old = _Latex_prefs._option["blackboard_bold"]
    10381034        _Latex_prefs._option["blackboard_bold"] = bool(t)
    10391035        if bool(old) != bool(t):
     
    10491045            sage_configurable_latex_macros.remove(old_macro)
    10501046            sage_latex_macros.append(macro)
    10511047            sage_configurable_latex_macros.append(macro)
    1052             sage_jsmath_macros.remove(convert_latex_macro_to_jsmath(old_macro))
    1053             sage_jsmath_macros.append(convert_latex_macro_to_jsmath(macro))
     1048            sage_mathjax_macros.remove(convert_latex_macro_to_mathjax(old_macro))
     1049            sage_mathjax_macros.append(convert_latex_macro_to_mathjax(macro))
    10541050
    10551051    def matrix_delimiters(self, left=None, right=None):
    10561052        r"""nodetex
     
    12281224    def extra_macros(self, macros=None):
    12291225        r"""nodetex
    12301226        String containing extra LaTeX macros to use with %latex,
    1231         %html, and %jsmath.
     1227        %html, and %mathjax.
    12321228
    12331229        INPUT: ``macros`` - string
    12341230
     
    12531249    def add_macro(self, macro):
    12541250        r"""nodetex
    12551251        Append to the string of extra LaTeX macros, for use with
    1256         %latex, %html, and %jsmath.
     1252        %latex, %html, and %mathjax.
    12571253
    12581254        INPUT: ``macro`` - string
    12591255
     
    12731269    def extra_preamble(self, s=None):
    12741270        r"""nodetex
    12751271        String containing extra preamble to be used with %latex.
    1276         Anything in this string won't be processed by %jsmath.
     1272        Anything in this string won't be processed by %mathjax.
    12771273
    12781274        INPUT: ``s`` - string or ``None``
    12791275
     
    13071303        r"""nodetex
    13081304        Append to the string of extra LaTeX macros, for use with
    13091305        %latex.  Anything in this string won't be processed by
    1310         %jsmath.
     1306        %mathjax.
    13111307
    13121308        EXAMPLES::
    13131309
     
    13731369        if self.has_file(package_name+".sty"):
    13741370            self.add_to_preamble("\\usepackage{%s}\n"%package_name)
    13751371
    1376     def jsmath_avoid_list(self, L=None):
     1372    def mathjax_avoid_list(self, L=None):
    13771373        r"""nodetex
    1378         List of strings which signal that jsMath should not
     1374        List of strings which signal that MathJax should not
    13791375        be used when 'view'ing.
    13801376
    13811377        INPUT: ``L`` - list or ``None``
     
    13831379        If ``L`` is ``None``, then return the current list.
    13841380        Otherwise, set it to ``L``.  If you want to *append* to the
    13851381        current list instead of replacing it, use
    1386         :meth:`latex.add_to_jsmath_avoid_list <Latex.add_to_jsmath_avoid_list>`.
     1382        :meth:`latex.add_to_mathjax_avoid_list <Latex.add_to_mathjax_avoid_list>`.
    13871383
    13881384        EXAMPLES::
    13891385
    1390             sage: latex.jsmath_avoid_list(["\\mathsf", "pspicture"])
    1391             sage: latex.jsmath_avoid_list()  # display current setting
     1386            sage: latex.mathjax_avoid_list(["\\mathsf", "pspicture"])
     1387            sage: latex.mathjax_avoid_list()  # display current setting
    13921388            ['\\mathsf', 'pspicture']
    1393             sage: latex.jsmath_avoid_list([])  # reset to default
    1394             sage: latex.jsmath_avoid_list()
     1389            sage: latex.mathjax_avoid_list([])  # reset to default
     1390            sage: latex.mathjax_avoid_list()
    13951391            []
    13961392        """
    13971393        if L is None:
    1398             return _Latex_prefs._option['jsmath_avoid']
     1394            return _Latex_prefs._option['mathjax_avoid']
    13991395        else:
    1400             _Latex_prefs._option['jsmath_avoid'] = L
    1401 
    1402     def add_to_jsmath_avoid_list(self, s):
     1396            _Latex_prefs._option['mathjax_avoid'] = L
     1397
     1398    def add_to_mathjax_avoid_list(self, s):
    14031399        r"""nodetex
    1404         Add to the list of strings which signal that jsMath should not
     1400        Add to the list of strings which signal that MathJax should not
    14051401        be used when 'view'ing.
    14061402
    1407         INPUT: ``s`` - string -- add ``s`` to the list of 'jsMath avoid' strings
     1403        INPUT: ``s`` - string -- add ``s`` to the list of 'MathJax avoid' strings
    14081404
    14091405        If you want to replace the current list instead of adding to
    1410         it, use :meth:`latex.jsmath_avoid_list <Latex.jsmath_avoid_list>`.
     1406        it, use :meth:`latex.mathjax_avoid_list <Latex.mathjax_avoid_list>`.
    14111407
    14121408        EXAMPLES::
    14131409
    1414             sage: latex.add_to_jsmath_avoid_list("\\mathsf")
    1415             sage: latex.jsmath_avoid_list()  # display current setting
     1410            sage: latex.add_to_mathjax_avoid_list("\\mathsf")
     1411            sage: latex.mathjax_avoid_list()  # display current setting
    14161412            ['\\mathsf']
    1417             sage: latex.add_to_jsmath_avoid_list("tkz-graph")
    1418             sage: latex.jsmath_avoid_list()  # display current setting
     1413            sage: latex.add_to_mathjax_avoid_list("tkz-graph")
     1414            sage: latex.mathjax_avoid_list()  # display current setting
    14191415            ['\\mathsf', 'tkz-graph']
    1420             sage: latex.jsmath_avoid_list([])  # reset to default
    1421             sage: latex.jsmath_avoid_list()
     1416            sage: latex.mathjax_avoid_list([])  # reset to default
     1417            sage: latex.mathjax_avoid_list()
    14221418            []
    14231419        """
    1424         current = latex.jsmath_avoid_list()
     1420        current = latex.mathjax_avoid_list()
    14251421        if s not in current:
    1426             _Latex_prefs._option['jsmath_avoid'].append(s)
     1422            _Latex_prefs._option['mathjax_avoid'].append(s)
    14271423
    14281424    def pdflatex(self, t = None):  # this is deprecated since 4.3.3
    14291425        """
     
    16371633
    16381634    return s
    16391635
    1640 class JSMathExpr:
     1636class MathJaxExpr:
    16411637    """
    1642     An arbitrary JSMath expression that can be nicely concatenated.
     1638    An arbitrary MathJax expression that can be nicely concatenated.
    16431639
    16441640    EXAMPLES::
    16451641
    1646         sage: from sage.misc.latex import JSMathExpr
    1647         sage: JSMathExpr("a^{2}") + JSMathExpr("x^{-1}")
     1642        sage: from sage.misc.latex import MathJaxExpr
     1643        sage: MathJaxExpr("a^{2}") + MathJaxExpr("x^{-1}")
    16481644        a^{2}x^{-1}
    16491645    """
    16501646    def __init__(self, y):
    16511647        """
    1652         Initialize a JSMath expression.
     1648        Initialize a MathJax expression.
    16531649
    16541650        INPUT:
    16551651
     
    16591655
    16601656        EXAMPLES::
    16611657
    1662             sage: from sage.misc.latex import JSMathExpr
    1663             sage: js = JSMathExpr(3); js  # indirect doctest
     1658            sage: from sage.misc.latex import MathJaxExpr
     1659            sage: jax = MathJaxExpr(3); jax  # indirect doctest
    16641660            3
    16651661        """
    16661662        self.__y = y
     
    16711667
    16721668        EXAMPLES::
    16731669
    1674             sage: from sage.misc.latex import JSMathExpr
    1675             sage: js = JSMathExpr('3')
    1676             sage: js.__repr__()
     1670            sage: from sage.misc.latex import MathJaxExpr
     1671            sage: jax = MathJaxExpr('3')
     1672            sage: jax.__repr__()
    16771673            '3'
    16781674        """
    16791675        return str(self.__y)
    16801676
    16811677    def __add__(self, y):
    16821678        """
    1683         'Add' JSMathExpr ``self`` to ``y``.  This concatenates them
     1679        'Add' MathJaxExpr ``self`` to ``y``.  This concatenates them
    16841680        (assuming that they're strings).
    16851681
    16861682        EXAMPLES::
    16871683
    1688             sage: from sage.misc.latex import JSMathExpr
    1689             sage: j3 = JSMathExpr('3')
    1690             sage: jx = JSMathExpr('x')
     1684            sage: from sage.misc.latex import MathJaxExpr
     1685            sage: j3 = MathJaxExpr('3')
     1686            sage: jx = MathJaxExpr('x')
    16911687            sage: j3 + jx
    16921688            3x
    16931689        """
    1694         return JSMathExpr(self.__y + y)
     1690        return MathJaxExpr(self.__y + y)
    16951691
    16961692    def __radd__(self, y):
    16971693        """
    1698         'Add' JSMathExpr ``y`` to ``self``.  This concatenates them
     1694        'Add' MathJaxExpr ``y`` to ``self``.  This concatenates them
    16991695        (assuming that they're strings).
    17001696
    17011697        EXAMPLES::
    17021698
    1703             sage: from sage.misc.latex import JSMathExpr
    1704             sage: j3 = JSMathExpr('3')
    1705             sage: jx = JSMathExpr('x')
     1699            sage: from sage.misc.latex import MathJaxExpr
     1700            sage: j3 = MathJaxExpr('3')
     1701            sage: jx = MathJaxExpr('x')
    17061702            sage: j3.__radd__(jx)
    17071703            x3
    17081704        """
    1709         return JSMathExpr(y + self.__y)
    1710 
    1711 class JSMath:
     1705        return MathJaxExpr(y + self.__y)
     1706
     1707class MathJax:
    17121708    r"""
    1713     Render LaTeX input using JSMath.  This returns a :class:`JSMathExpr`.
     1709    Render LaTeX input using MathJax.  This returns a :class:`MathJaxExpr`.
    17141710
    17151711    EXAMPLES::
    17161712
    1717         sage: from sage.misc.latex import JSMath
    1718         sage: JSMath()(3)
    1719         <html><div class="math">\newcommand{\Bold}[1]{\mathbf{#1}}3</div></html>
    1720         sage: JSMath()(ZZ)
    1721         <html><div class="math">\newcommand{\Bold}[1]{\mathbf{#1}}\Bold{Z}</div></html>
     1713        sage: from sage.misc.latex import MathJax
     1714        sage: MathJax()(3)
     1715        <html><script type="math/tex; mode=display">\newcommand{\Bold}[1]{\mathbf{#1}}3</script></html>
     1716        sage: MathJax()(ZZ)
     1717        <html><script type="math/tex; mode=display">\newcommand{\Bold}[1]{\mathbf{#1}}\Bold{Z}</script></html>
    17221718    """
    17231719
    17241720    def __call__(self, x):
    17251721        r"""
    1726         Render LaTeX input using JSMath.  This returns a :class:`JSMathExpr`.
     1722        Render LaTeX input using MathJax.  This returns a :class:`MathJaxExpr`.
    17271723
    17281724        INPUT:
    17291725
    17301726        - ``x`` - a Sage object
    17311727
    1732         OUTPUT: a JSMathExpr
     1728        OUTPUT: a MathJaxExpr
    17331729
    17341730        EXAMPLES::
    17351731
    1736             sage: from sage.misc.latex import JSMath
    1737             sage: JSMath()(3)
    1738             <html><div class="math">\newcommand{\Bold}[1]{\mathbf{#1}}3</div></html>
    1739             sage: str(JSMath().eval(ZZ[x], mode='display')) == str(JSMath()(ZZ[x]))
     1732            sage: from sage.misc.latex import MathJax
     1733            sage: MathJax()(3)
     1734            <html><script type="math/tex; mode=display">\newcommand{\Bold}[1]{\mathbf{#1}}3</script></html>
     1735            sage: str(MathJax().eval(ZZ[x], mode='display')) == str(MathJax()(ZZ[x]))
    17401736            True
    17411737        """
    17421738        return self.eval(x)
    17431739
    17441740    def eval(self, x, globals=None, locals=None, mode='display'):
    17451741        r"""
    1746         Render LaTeX input using JSMath.  This returns a :class:`JSMathExpr`.
     1742        Render LaTeX input using MathJax.  This returns a :class:`MathJaxExpr`.
    17471743
    17481744        INPUT:
    17491745
     
    17571753        -  ``mode`` - string (optional, default 'display): 'display'
    17581754           for displaymath or 'inline' for inline math
    17591755
    1760         OUTPUT: a JSMathExpr
     1756        OUTPUT: a MathJaxExpr
    17611757
    17621758        EXAMPLES::
    17631759
    1764             sage: from sage.misc.latex import JSMath
    1765             sage: JSMath().eval(3, mode='display')
    1766             <html><div class="math">\newcommand{\Bold}[1]{\mathbf{#1}}3</div></html>
    1767             sage: JSMath().eval(3, mode='inline')
    1768             <html><span class="math">\newcommand{\Bold}[1]{\mathbf{#1}}3</span></html>
    1769             sage: JSMath().eval(type(3), mode='inline')
    1770             <html>...\verb|&lt;type|\phantom{x}\verb|'sage.rings.integer.Integer'&gt;|</span></html>
     1760            sage: from sage.misc.latex import MathJax
     1761            sage: MathJax().eval(3, mode='display')
     1762            <html><script type="math/tex; mode=display">\newcommand{\Bold}[1]{\mathbf{#1}}3</script></html>
     1763            sage: MathJax().eval(3, mode='inline')
     1764            <html><script type="math/tex">\newcommand{\Bold}[1]{\mathbf{#1}}3</script></html>
     1765            sage: MathJax().eval(type(3), mode='inline')
     1766            <html><script type="math/tex">\newcommand{\Bold}[1]{\mathbf{#1}}\hbox{ < type 'sage.rings.integer.Integer' > }</script></html>
    17711767        """
    17721768        # Get a regular LaTeX representation of x...
    17731769        x = latex(x)
    1774         # ... and make it suitable for jsMath, which has issues with < and >.
     1770        # ... and make it suitable for MathJax and html
    17751771        x = x.replace('<', '&lt;').replace('>', '&gt;')
    1776         # In jsMath:
    1777         #   inline math: <span class="math">...</span>
    1778         #   displaymath: <div class="math">...</div>
     1772        # In MathJax:
     1773        #   inline math: <script type="math/tex">...</script>
     1774        #   displaymath: <script type="math/tex; mode=display">...</script>
    17791775        from sage.misc.latex_macros import sage_configurable_latex_macros
    1780         if 'display' == mode:
    1781             return JSMathExpr('<html><div class="math">'
    1782                               + ''.join(sage_configurable_latex_macros)
    1783                               + _Latex_prefs._option['macros']
    1784                               + '%s</div></html>'%x)
    1785         elif 'inline' == mode:
    1786             return JSMathExpr('<html><span class="math">'
    1787                               + ''.join(sage_configurable_latex_macros)
    1788                               + _Latex_prefs._option['macros']
    1789                               + '%s</span></html>'%x)
     1776        if mode == 'display':
     1777            modecode = '; mode=display'
     1778        elif mode == 'inline':
     1779            modecode = ''
    17901780        else:
    17911781            # what happened here?
    17921782            raise ValueError, "mode must be either 'display' or 'inline'"
    1793 
    1794 def jsmath(x, mode='display'):
    1795     r"""
    1796     Attempt to nicely render an arbitrary Sage object with jsMath typesetting.
    1797     Tries to call ._latex_() on x. If that fails, it will render a string
    1798     representation of x.
    1799 
    1800     .. warning::
    1801 
    1802         2009-04: This function is deprecated; use :func:`html`
    1803         instead: replace ``jsmath('MATH', mode='display')`` with
    1804         ``html('$$MATH$$')``, and replace ``jsmath('MATH',
    1805         mode='inline')`` with ``html('$MATH$')``.
    1806 
    1807     INPUT:
    1808         x -- the object to render
    1809         mode -- 'display' for displaymath or 'inline' for inline math
    1810 
    1811     OUTPUT:
    1812         A string of html that contains the LaTeX representation of x. In the
    1813         notebook this gets embedded into the cell.
    1814 
    1815     EXAMPLES::
    1816 
    1817         sage: from sage.misc.latex import jsmath
    1818         sage: f = maxima('1/(x^2+1)')
    1819         sage: g = f.integrate()
    1820         sage: jsmath(f)
    1821         doctest:1: DeprecationWarning: The jsmath function is deprecated.  Use html('$math$') for inline mode or html('$$math$$') for display mode.
    1822         <html><font color='black'><div class="math">{{1}\over{x^2+1}}</div></font></html>
    1823         sage: jsmath(g, 'inline')
    1824         <html><font color='black'><span class="math">\tan^{-1} x</span></font></html>
    1825         sage: jsmath('\int' + latex(f) + '\ dx=' + latex(g))
    1826         <html><font color='black'><div class="math">\int {{1}\over{x^2+1}} \ dx= \tan^{-1} x</div></font></html>
    1827 
    1828     AUTHORS:
    1829 
    1830     - William Stein (2006-10): general layout (2006-10)
    1831 
    1832     - Bobby Moretti (2006-10): improvements, comments, documentation
    1833     """
    1834     from sage.misc.misc import deprecation
    1835     from sage.misc.html import html
    1836     deprecation("The jsmath function is deprecated.  Use html('$math$') for inline mode or html('$$math$$') for display mode.")
    1837     if mode == 'display':
    1838         delimiter = '$$'
    1839     elif mode == 'inline':
    1840         delimiter = '$'
    1841     else:
    1842         raise ValueError, "mode must be either 'display' or 'inline'"
    1843     try:
    1844         # try to get a latex representation of the object
    1845         x = x._latex_()
    1846     except AttributeError:
    1847         # otherwise just get the string representation
    1848         x = str(x)
    1849     return html(delimiter + x + delimiter)
     1783        return MathJaxExpr('<html><script type="math/tex%s">'%modecode
     1784                         + ''.join(sage_configurable_latex_macros)
     1785                         + _Latex_prefs._option['macros']
     1786                         + '%s</script></html>'%x)
    18501787
    18511788def view(objects, title='SAGE', debug=False, sep='', tiny=False, pdflatex=None, engine=None, viewer = None, tightpage = None, mode='inline', **kwds):
    18521789    r"""nodetex
     
    19311868    each object by ``\\begin{page}$`` and ``$\\end{page}``.
    19321869
    19331870    If in notebook mode with ``viewer`` equal to ``None``, this
    1934     usually uses jsMath -- see the next paragraph for the exception --
     1871    usually uses MathJax -- see the next paragraph for the exception --
    19351872    to display the output in the notebook. Only the first argument,
    19361873    ``objects``, is relevant; the others are ignored. If ``objects``
    19371874    is a list, each object is printed on its own line.
    19381875
    1939     In the notebook, this *does* *not* use jsMath if the LaTeX code
     1876    In the notebook, this *does* *not* use MathJax if the LaTeX code
    19401877    for ``objects`` contains a string in
    1941     :meth:`latex.jsmath_avoid_list() <Latex.jsmath_avoid_list>`.  In
     1878    :meth:`latex.mathjax_avoid_list() <Latex.mathjax_avoid_list>`.  In
    19421879    this case, it creates and displays a png file.
    19431880
    19441881    EXAMPLES::
    19451882
    19461883        sage: sage.misc.latex.EMBEDDED_MODE = True
    19471884        sage: view(3)
    1948         <html><span class="math">\newcommand{\Bold}[1]{\mathbf{#1}}3</span></html>
     1885        <html><script type="math/tex">\newcommand{\Bold}[1]{\mathbf{#1}}3</script></html>
    19491886        sage: view(3, mode='display')
    1950         <html><div class="math">\newcommand{\Bold}[1]{\mathbf{#1}}3</div></html>
     1887        <html><script type="math/tex; mode=display">\newcommand{\Bold}[1]{\mathbf{#1}}3</script></html>
    19511888        sage: sage.misc.latex.EMBEDDED_MODE = False
    19521889
    19531890    TESTS::
     
    19691906    s = _latex_file_(objects, title=title, sep=sep, tiny=tiny, debug=debug, **latex_options)
    19701907    # notebook
    19711908    if EMBEDDED_MODE and viewer is None:
    1972         jsMath_okay = True
    1973         for t in latex.jsmath_avoid_list():
     1909        MathJax_okay = True
     1910        for t in latex.mathjax_avoid_list():
    19741911            if s.find(t) != -1:
    1975                 jsMath_okay = False
    1976             if not jsMath_okay:
     1912                MathJax_okay = False
     1913            if not MathJax_okay:
    19771914                break
    1978         if jsMath_okay:
    1979             print JSMath().eval(objects, mode=mode)  # put comma at end of line?
     1915        if MathJax_okay:
     1916            print MathJax().eval(objects, mode=mode)  # put comma at end of line?
    19801917        else:
    19811918            if pdflatex is True:
    19821919                engine = "pdflatex"
     
    21932130        sage: TEMP = sys.displayhook
    21942131        sage: sys.displayhook = sage.misc.latex.pretty_print
    21952132        sage: sage.misc.latex.print_or_typeset(3)
    2196         <html><span class="math">\newcommand{\Bold}[1]{\mathbf{#1}}3</span></html>
     2133        <html><script type="math/tex">\newcommand{\Bold}[1]{\mathbf{#1}}3</script></html>
    21972134        sage: sage.misc.latex.EMBEDDED_MODE=False
    21982135        sage: sys.displayhook = TEMP
    21992136    """
     
    22092146    objects, this returns their default representation.  For other
    22102147    objects, in the notebook, this calls the :func:`view` command,
    22112148    while from the command line, this produces an html string suitable
    2212     for processing by jsMath.
     2149    for processing by MathJax.
    22132150
    22142151    INPUT:
    22152152
     
    22212158    EXAMPLES::
    22222159
    22232160        sage: pretty_print(ZZ)  # indirect doctest
    2224         <html><span class="math">\newcommand{\Bold}[1]{\mathbf{#1}}\Bold{Z}</span></html>
     2161        <html><script type="math/tex">\newcommand{\Bold}[1]{\mathbf{#1}}\Bold{Z}</script></html>
    22252162
    22262163    To typeset LaTeX code as-is, use :class:`LatexExpr`::
    22272164
    22282165        sage: pretty_print(LatexExpr(r"\frac{x^2 + 1}{x - 2}"))
    2229         <html><span class="math">\newcommand{\Bold}[1]{\mathbf{#1}}\frac{x^2 + 1}{x - 2}</span></html>
     2166        <html><script type="math/tex">\newcommand{\Bold}[1]{\mathbf{#1}}\frac{x^2 + 1}{x - 2}</script></html>
    22302167    """
    22312168    if object is None:
    22322169        return
     
    22422179        if EMBEDDED_MODE:
    22432180            view(object)
    22442181        else:
    2245             print JSMath().eval(object, mode='inline')
     2182            print MathJax().eval(object, mode='inline')
    22462183        return
    22472184
    22482185def pretty_print_default(enable=True):
    22492186    r"""
    22502187    Enable or disable default pretty printing. Pretty printing means
    2251     rendering things so that jsMath or some other latex-aware front end
     2188    rendering things so that MathJax or some other latex-aware front end
    22522189    can render real math.
    22532190
    22542191    INPUT:
     
    24862423the TeX package pgf installed, along with the LaTeX package tkz-graph.
    24872424Run 'latex.add_to_preamble("\\usepackage{tkz-graph}")', and try viewing
    24882425it again.  From the command line, this should pop open a nice window
    2489 with a picture of a graph.  In the notebook, you should get a jsMath
    2490 error.  Finally, run 'latex.add_to_jsmath_avoid_list("tikzpicture")'
     2426with a picture of a graph.  In the notebook, you should get a MathJax
     2427error.  Finally, run 'latex.add_to_mathjax_avoid_list("tikzpicture")'
    24912428and try again from the notebook -- you should get a nice picture.
    24922429
    24932430(LaTeX code taken from http://altermundus.com/pages/graph.html)
     
    25692506open a nice window with a picture of forces acting on a mass
    25702507on a pendulum. In the notebook, you should get an error.
    25712508Finally, run
    2572 'latex.add_to_jsmath_avoid_list("pspicture")' and try again
     2509'latex.add_to_mathjax_avoid_list("pspicture")' and try again
    25732510-- you should get a nice picture."""
    25742511
    25752512        def _latex_(self):
     
    26362573'latex.add_to_preamble("\\usepackage[graph,knot,poly,curve]{xypic}")',
    26372574and try viewing again -- it should work in the command line but not
    26382575from the notebook.  In the notebook, run
    2639 'latex.add_to_jsmath_avoid_list("xygraph")' and try again -- you
     2576'latex.add_to_mathjax_avoid_list("xygraph")' and try again -- you
    26402577should get a nice picture.
    26412578
    26422579(LaTeX code taken from the xypic manual)
     
    27002637'latex.add_to_preamble("\\usepackage[matrix,arrow,curve,cmtip]{xy}")',
    27012638and try viewing again -- it should work in the command line but not
    27022639from the notebook.  In the notebook, run
    2703 'latex.add_to_jsmath_avoid_list("xymatrix")' and try again -- you
     2640'latex.add_to_mathjax_avoid_list("xymatrix")' and try again -- you
    27042641should get a picture (a part of the diagram arising from a filtered
    27052642chain complex)."""
    27062643
  • 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
     
    212176
    213177sage_latex_macros += sage_configurable_latex_macros
    214178
    215 # jsMath macro definitions as JavaScript, e.g., to include in HTML
     179# MathJax macro definitions as JavaScript, e.g., to include in HTML
    216180# script elements.
    217 sage_jsmath_macros = [convert_latex_macro_to_jsmath(m) for m in sage_latex_macros]
    218 
    219 # jsMath macro definitions for an easy/load.js file's "macros" array.
    220 sage_jsmath_macros_easy = [convert_latex_macro_to_jsmath_easy(m) for m in sage_latex_macros]
     181sage_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  
    3131
    3232# two kinds of substitutions: math, which should only be done on the
    3333# command line -- in the notebook, these should instead by taken care
    34 # of by jsMath -- and nonmath, which should be done always.
     34# of by MathJax -- and nonmath, which should be done always.
    3535math_substitutes = [ # don't forget leading backslash '\\'
    3636    ('\\to', '-->'),
    3737    ('\\leq', '<='),
     
    283283            s = s[:m.start()] + "$" + s[m.end():]
    284284    return s
    285285
    286 def process_mathtt(s, embedded=False):
     286def process_mathtt(s):
    287287    r"""nodetex
    288     Replace \\mathtt{BLAH} with either \\verb|BLAH| (in the notebook) or
    289     BLAH (from the command line).
     288    Replace \\mathtt{BLAH} with BLAH in the command line.
    290289
    291290    INPUT:
    292291
    293292    - ``s`` - string, in practice a docstring
    294     - ``embedded`` - boolean (optional, default False)
    295293
    296     This function is called by :func:`format`, and if in the notebook,
    297     it sets ``embedded`` to be ``True``, otherwise ``False``.
     294    This function is called by :func:`format`.
    298295
    299296    EXAMPLES::
    300297
    301298        sage: from sage.misc.sagedoc import process_mathtt
    302299        sage: process_mathtt(r'e^\mathtt{self}')
    303300        'e^self'
    304         sage: process_mathtt(r'e^\mathtt{self}', embedded=True)
    305         'e^{\\verb|self|}'
    306301    """
    307     replaced = False
    308302    while True:
    309303        start = s.find("\\mathtt{")
    310304        end = s.find("}", start)
    311305        if start == -1 or end == -1:
    312306            break
    313         if embedded:
    314             left = "{\\verb|"
    315             right = "|}"
    316         else:
    317             left = ""
    318             right = ""
    319         s = s[:start] + left + s[start+8:end] + right + s[end+1:]
     307        s = s[:start] + s[start+8:end] + s[end+1:]
    320308    return s
    321309
    322310def format(s, embedded=False):
     
    464452
    465453    if 'nodetex' not in directives:
    466454        s = process_dollars(s)
    467         s = process_mathtt(s, embedded=embedded)
     455        if not embedded:
     456            s = process_mathtt(s)
    468457        s = detex(s, embedded=embedded)
    469458    else:
    470459        # strip the 'nodetex' directive from s
     
    12501239    </script>
    12511240    <script type="text/javascript" src="%(static_path)s/jquery.js"></script>
    12521241    <script type="text/javascript" src="%(static_path)s/doctools.js"></script>
    1253     <script type="text/javascript" src="%(static_path)s/jsmath_sage.js"></script>
     1242    <script type="text/javascript" src="%(static_path)s/mathjax_sage.js"></script>
    12541243    <link rel="shortcut icon" href="%(static_path)s/favicon.ico" />
    12551244    <link rel="icon" href="%(static_path)s/sageicon.png" type="image/x-icon" />
    12561245  </head>
     
    13111300
    13121301        if not os.path.exists(path):
    13131302            raise OSError, """The document '%s' does not exist.  Please build it
    1314 with 'sage -docbuild %s html --jsmath' and try again.""" %(name, name)
     1303with 'sage -docbuild %s html --mathjax' and try again.""" %(name, name)
    13151304
    13161305        from sage.server.support import EMBEDDED_MODE
    13171306        if EMBEDDED_MODE:
  • 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):