Ticket #9774: mathjax.v2.patch

File mathjax.v2.patch, 59.8 KB (added by jhpalmieri, 9 years ago)

(experimental) patch for Sage library, alternate version

  • doc/common/builder.py

    # HG changeset patch
    # User J. H. Palmieri <palmieri@math.washington.edu>
    # Date 1308085809 25200
    # Node ID da46561d068f21213d8873861f820d99fb0d2ffe
    # Parent  6ca08864b80c1e04599ba23ba295bfcf6a61f19b
    #9774: switch Sage library from jsMath to MathJax.
    This patch adds the file mathjax.py
    (from https://bitbucket.org/kevindunn/sphinx-extension-mathjax)
    to sage/doc/common.  Once we upgrade to Sphinx 1.1 (or later),
    we can remove this file.
    
    TO DO:
    - don't include MathJax in all_notebook.py?
    - in latex.py, make "jsmath" an alias to "mathjax"?
    - in scripts repo, there are a few references to jsmath which
      need to be fixed
    - command to load mathjax extension in introspect/conf.py:
      extensions = ['sphinx.ext.autodoc', 'mathjax'] or
      extensions = ['sphinx.ext.autodoc', 'common.mathjax']??
    
    diff --git a/doc/common/builder.py b/doc/common/builder.py
    a b def help_examples(s=u""): 
    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
    def setup_parser(): 
    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")
    if __name__ == '__main__': 
    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 extensions = ['sage_autodoc', 'sphinx.e 
    1717              'sphinx.ext.inheritance_diagram']
    1818#, 'sphinx.ext.intersphinx', 'sphinx.ext.extlinks']
    1919
    20 if 'SAGE_DOC_JSMATH' in os.environ:
    21     extensions.append('sphinx.ext.jsmath')
     20# The environment variable SAGE_DOC_MATHJAX may be set by the user or
     21# by the file "builder.py".  If it's set, or if SAGE_DOC_JSMATH is set
     22# (for backwards compatibility), use MathJax.
     23if (os.environ.get('SAGE_DOC_MATHJAX', False)
     24    or os.environ.get('SAGE_DOC_JSMATH', False)):
     25    extensions.append('mathjax')
     26    # This setting for mathjax_path requires that mathjax_sage.js be
     27    # created in the right directory.  See below (search this file for
     28    # "mathjax_sage") for details.
     29    mathjax_path = 'MathJax.js?config=TeX-AMS_HTML-full,local/mathjax_sage.js'
    2230else:
    2331    extensions.append('sphinx.ext.pngmath')
    24 jsmath_path = 'jsmath_sage.js'
    2532
    2633# Add any paths that contain templates here, relative to this directory.
    2734templates_path = [os.path.join(SAGE_DOC, 'common/templates'), 'templates']
    inheritance_edge_attrs = {} 
    96103# -----------------------
    97104
    98105# HTML theme (e.g., 'default', 'sphinxdoc').  We use a custom Sage
    99 # theme to set a Pygments style, stylesheet, and insert jsMath macros. See
    100 # the directory doc/common/themes/sage/ for files comprising the custom Sage
    101 # theme.
     106# theme to set a Pygments style and stylesheet. See the directory
     107# doc/common/themes/sage/ for files comprising the custom Sage theme.
    102108html_theme = 'sage'
    103109
    104110# Theme options are theme-specific and customize the look and feel of
    html_theme = 'sage' 
    106112# see the documentation.
    107113html_theme_options = {}
    108114
    109 if 'SAGE_DOC_JSMATH' in os.environ:
    110     from sage.misc.latex_macros import sage_jsmath_macros_easy
    111     html_theme_options['jsmath_macros'] = sage_jsmath_macros_easy
    112 
    113     from sage.misc.package import is_package_installed
    114     html_theme_options['jsmath_image_fonts'] = is_package_installed('jsmath-image-fonts')
    115 
    116115# Add any paths that contain custom themes here, relative to this directory.
    117116html_theme_path = [os.path.join(SAGE_DOC, 'common/themes')]
    118117
    html_favicon = 'favicon.ico' 
    141140# so a file named "default.css" will overwrite the builtin "default.css".
    142141html_static_path = [os.path.join(SAGE_DOC, 'common/static'), 'static']
    143142
    144 # If we're using jsMath, we prepend its location to the static path
     143# If we're using MathJax, we prepend its location to the static path
    145144# array.  We can override / overwrite selected files by putting them
    146 # in the remaining paths.
    147 if 'SAGE_DOC_JSMATH' in os.environ:
     145# in the remaining paths.  We also write the local config file,
     146# containing Sage-specific macros and allowing the use of dollar signs
     147# to delimit math.  We write the file to the directory
     148#    sagenb/data/mathjax/config/local/mathjax_sage.js,
     149# in the sagenb-... subdirectory of
     150#    SAGE_ROOT/local/lib/python/site-libraries.
     151# This is in the static path, so the file gets copied to the
     152# appropriate place, allowing us to use the above setting for
     153# mathjax_path.
     154if (os.environ.get('SAGE_DOC_MATHJAX', False)
     155    or os.environ.get('SAGE_DOC_JSMATH', False)):
    148156    from pkg_resources import Requirement, working_set
     157    from sage.misc.latex_macros import sage_mathjax_macros
    149158    sagenb_path = working_set.find(Requirement.parse('sagenb')).location
    150     jsmath_static = os.path.join(sagenb_path, 'sagenb', 'data', 'jsmath')
    151     html_static_path.insert(0, jsmath_static)
     159    mathjax_static = os.path.join(sagenb_path, 'sagenb', 'data', 'mathjax')
     160    # Write the local configuration file.  If it already exists,
     161    # overwrite it (in case the macros have been modified since it was
     162    # first created).
     163    mathjax_configuration_string = '''
     164MathJax.Hub.Config({
     165  tex2jax: {
     166    inlineMath: [['$','$'],['\\(','\\)']],
     167    processEscapes: true
     168  },
     169  styles: {
     170    ".MathJax .mo, .MathJax .mi": {
     171      color: "inherit ! important"
     172    }
     173  },
     174  TeX: {
     175    Macros: {
     176     %s
     177    }
     178  }
     179});
     180
     181MathJax.Ajax.loadComplete("[MathJax]/local/mathjax_sage.js")
     182''' % ',\n'.join(sage_mathjax_macros)
     183    config_file = os.path.join(mathjax_static, 'config', 'local',
     184                               'mathjax_sage.js')
     185    F = open(config_file, 'w')
     186    F.write(mathjax_configuration_string)
     187    F.close()
     188    html_static_path.insert(0, mathjax_static)
    152189
    153190# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
    154191# using the given strftime format.
    def process_dollars(app, what, name, obj 
    395432
    396433def process_mathtt(app, what, name, obj, options, docstringlines):
    397434    r"""
    398     Replace \mathtt{BLAH} with \verb|BLAH| if using jsMath.
     435    Replace \mathtt{BLAH} with \verb|BLAH| if using MathJax.
    399436    See sage.misc.sagedoc.process_mathtt for more information
    400437    """
    401     if (len(docstringlines) > 0 and 'SAGE_DOC_JSMATH' in os.environ
     438    if (len(docstringlines) > 0 and
     439        (os.environ.get('SAGE_DOC_MATHJAX', False)
     440         or os.environ.get('SAGE_DOC_JSMATH', False))
    402441        and name.find("process_mathtt") == -1):
    403442        from sage.misc.sagedoc import process_mathtt as sagedoc_mathtt
    404443        s = sagedoc_mathtt("\n".join(docstringlines), True)
  • new file doc/common/mathjax.py

    diff --git a/doc/common/mathjax.py b/doc/common/mathjax.py
    new file mode 100644
    - +  
     1# -*- coding: utf-8 -*-
     2"""
     3    sphinx.ext.mathjax
     4    ~~~~~~~~~~~~~~~~~~
     5
     6    Allow `MathJax <http://mathjax.org/>`_ to be used to display math
     7    in Sphinx's HTML writer - requires the MathJax JavaScript library
     8    on your webserver/computer.
     9
     10    Kevin Dunn, kgdunn@gmail.com, 3-clause BSD license.
     11   
     12
     13    For background, installation details and support:
     14   
     15        https://bitbucket.org/kevindunn/sphinx-extension-mathjax
     16
     17"""
     18from docutils import nodes
     19from sphinx.application import ExtensionError
     20from sphinx.ext.mathbase import setup_math as mathbase_setup
     21
     22def html_visit_math(self, node):
     23    self.body.append(self.starttag(node, 'span', '', CLASS='math'))
     24    self.body.append(self.builder.config.mathjax_inline[0] + \
     25                     self.encode(node['latex']) +\
     26                     self.builder.config.mathjax_inline[1] + '</span>')
     27    raise nodes.SkipNode
     28
     29def html_visit_displaymath(self, node):
     30    self.body.append(self.starttag(node, 'div', CLASS='math'))
     31    if node['nowrap']:
     32        self.body.append(self.builder.config.mathjax_display[0] + \
     33                         node['latex'] +\
     34                         self.builder.config.mathjax_display[1])
     35        self.body.append('</div>')
     36        raise nodes.SkipNode
     37
     38    parts = [prt for prt in node['latex'].split('\n\n') if prt.strip() != '']
     39    for i, part in enumerate(parts):
     40        part = self.encode(part)
     41        if i == 0:
     42            # necessary to e.g. set the id property correctly
     43            if node['number']:
     44                self.body.append('<span class="eqno">(%s)</span>' %
     45                                 node['number'])
     46        if '&' in part or '\\\\' in part:
     47            self.body.append(self.builder.config.mathjax_display[0] + \
     48                             '\\begin{split}' + part + '\\end{split}' + \
     49                             self.builder.config.mathjax_display[1])
     50        else:
     51            self.body.append(self.builder.config.mathjax_display[0] + part + \
     52                             self.builder.config.mathjax_display[1])
     53    self.body.append('</div>\n')
     54    raise nodes.SkipNode
     55
     56def builder_inited(app):
     57    if not app.config.mathjax_path:
     58        raise ExtensionError('mathjax_path config value must be set for the '
     59                             'mathjax extension to work')
     60    app.add_javascript(app.config.mathjax_path)
     61
     62def setup(app):
     63    mathbase_setup(app, (html_visit_math, None), (html_visit_displaymath, None))
     64    app.add_config_value('mathjax_path', '', False)
     65    app.add_config_value('mathjax_inline', [r'\(', r'\)'], 'html')
     66    app.add_config_value('mathjax_display', [r'\[', r'\]'], 'html')
     67    app.connect('builder-inited', builder_inited)
     68
  • deleted file doc/common/themes/sage/static/jsmath_sage.js_t

    diff --git a/doc/common/themes/sage/static/jsmath_sage.js_t b/doc/common/themes/sage/static/jsmath_sage.js_t
    deleted file mode 100644
    + -  
    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  **********************************************************************/
    19 
    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>');
  • doc/common/themes/sage/theme.conf

    diff --git a/doc/common/themes/sage/theme.conf b/doc/common/themes/sage/theme.conf
    a b stylesheet = sage.css 
    44pygments_style = sphinx
    55
    66[options]
    7 # Custom Sage theme options
    8 
    9 # jsMath settings filled in by conf.py
    10 jsmath_macros =
    11 jsmath_image_fonts =
    12 
    137# Sphinx default theme options
    148
    159#nosidebar = false
  • doc/en/introspect/conf.py

    diff --git a/doc/en/introspect/conf.py b/doc/en/introspect/conf.py
    a b import sys, os 
    66sys.path.append(os.environ['SAGE_DOC'])
    77from common.conf import *
    88
    9 extensions = ['sphinx.ext.autodoc', 'sphinx.ext.jsmath']
     9extensions = ['sphinx.ext.autodoc', 'mathjax']
    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 html_title = project + " v" + release 
    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 html_theme_options['jsmath_macros'] = ["mathfrak : ['\\\\mathbf{#1}', 1]"]
    36 
    3731# Grouping the document tree into LaTeX files. List of tuples
    3832# (source start file, target name, title, author,
    3933# document class [howto/manual]).
  • sage/all_notebook.py

    diff --git a/sage/all_notebook.py b/sage/all_notebook.py
    a b from sage.calculus.predefined import x 
    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()
     21# we need a global instance of this in order to get %mathjax to work...
     22mathjax = MathJax()
    2323
    2424from sage.misc.python import python
    2525
  • sage/misc/html.py

    diff --git a/sage/misc/html.py b/sage/misc/html.py
    a b def math_parse(s): 
    2424    Do the following:
    2525    \begin{verbatim}
    2626       * Replace all $ text $'s by
    27          <span class='math'> text </span>
     27         <script type="math/tex"> text </script>
    2828       * Replace all $$ text $$'s by
    29          <div class='math'> text </div>
     29         <script type="math/tex; mode=display"> text </script>
    3030       * Replace all \$'s by $'s.  Note that in
    3131         the above two cases nothing is done if the $
    3232         is preceeded by a backslash.
    3333       * Replace all \[ text \]'s by
    34          <div class='math'> text </div>
     34         <script type="math/tex; mode=display"> text </script>
    3535    \end{verbatim}
    3636
    3737    EXAMPLES:
    3838        sage: sage.misc.html.math_parse('This is $2+2$.')
    39         'This is <span class="math">2+2</span>.'
     39        'This is <script type="math/tex">2+2</script>.'
    4040        sage: sage.misc.html.math_parse('This is $$2+2$$.')
    41         'This is <div class="math">2+2</div>.'
     41        'This is <script type="math/tex; mode=display">2+2</script>.'
    4242        sage: sage.misc.html.math_parse('This is \\[2+2\\].')
    43         'This is <div class="math">2+2</div>.'
     43        'This is <script type="math/tex; mode=display">2+2</script>.'
    4444        sage: sage.misc.html.math_parse(r'This is \[2+2\].')
    45         'This is <div class="math">2+2</div>.'
     45        'This is <script type="math/tex; mode=display">2+2</script>.'
    4646
    4747    TESTS:
    4848        sage: sage.misc.html.math_parse(r'This \$\$is $2+2$.')
    49         'This $$is <span class="math">2+2</span>.'   
     49        'This $$is <script type="math/tex">2+2</script>.'
    5050    """
    5151    # first replace \\[ and \\] by <div class="math"> and </div>, respectively.
    5252    while True:
    def math_parse(s): 
    5454        if i == -1:
    5555            break
    5656        else:
    57             s = s[:i] + '<div class="math">' + s[i+2:]
     57            s = s[:i] + '<script type="math/tex; mode=display">' + s[i+2:]
    5858            j = s.find('\\]')
    5959            if j == -1:  # missing right-hand delimiter, so add one
    60                 s = s + '</div>'
     60                s = s + '</script>'
    6161            else:
    62                 s = s[:j] + '</div>' + s[j+2:]
     62                s = s[:j] + '</script>' + s[j+2:]
    6363   
    6464    # Below t always has the "parsed so far" version of s, and s is
    6565    # just the part of the original input s that hasn't been parsed.
    def math_parse(s): 
    7777            s = s[i+1:]
    7878            continue
    7979        elif i+1 < len(s) and s[i+1] == '$':
    80             # Found a math environment. Double dollar sign so div mode.
    81             typ = 'div'
     80            # Found a math environment. Double dollar sign so display mode.
     81            disp = '; mode=display'
    8282        else:
    83             # Found math environment. Single dollar sign so span mode.
    84             typ = 'span'
     83            # Found math environment. Single dollar sign so default mode.
     84            disp = ''
    8585
    86         # Now find the matching $ sign and form the span or div.
    87         j = s[i+2:].find('$')
    88         if j == -1:
    89             j = len(s)
    90             s += '$'
    91             if typ == 'div':
     86        # Now find the matching $ sign and form the html string.
     87
     88        if len(disp) > 0:
     89            j = s[i+2:].find('$$')
     90            if j == -1:
     91                j = len(s)
    9292                s += '$$'
    93         else:
    94             j += i + 2
    95         if typ == 'div':
     93            else:
     94                j += i + 2
    9695            txt = s[i+2:j]
    9796        else:
     97            j = s[i+2:].find('$')
     98            if j == -1:
     99                j = len(s)
     100                s += '$'
     101            else:
     102                j += i + 2
    98103            txt = s[i+1:j]
    99         t += s[:i] + '<%s class="math">%s</%s>'%(typ,
    100                       ' '.join(txt.splitlines()), typ)
     104
     105        t += s[:i] + '<script type="math/tex%s">%s</script>'%(disp,
     106                      ' '.join(txt.splitlines()))
    101107        s = s[j+1:]
    102         if typ == 'div':
     108        if len(disp) > 0:
    103109            s = s[1:]
    104110    return t
    105111
    class HTML: 
    143149            <html><font color='black'><hr></font></html>
    144150            ''
    145151
    146         We work around a limitation of jsmath (it can't typeset '\texttt')::
     152        We work around a limitation of MathJax (it can't typeset '\texttt')::
    147153
    148154            sage: html.eval('<sage>Primes</sage>')
    149             <html><font color='black'><span class="math">\hbox{<class 'sage.sets.primes.Primes'>}</span></font></html>
     155            <html><font color='black'><script type="math/tex">\hbox{<class 'sage.sets.primes.Primes'>}</script></font></html>
    150156            ''
    151157        """
    152158        if globals is None:
    class HTML: 
    165171            if j == -1:
    166172                 t += s
    167173                 break
    168             t += s[:i] + '<span class="math">%s</span>'%\
     174            t += s[:i] + '<script type="math/tex">%s</script>'%\
    169175                     latex(sage_eval(s[6+i:j], locals=locals)).replace('\\texttt','\\hbox')
    170176            s = s[j+7:]
    171177        print "<html><font color='black'>%s</font></html>"%t
    class HTML: 
    185191            <table class="table_form">
    186192            <tbody>
    187193            <tr class ="row-a">
    188             <td><span class="math">0</span></td>
    189             <td><span class="math">0</span></td>
    190             <td><span class="math">\mbox{\rm True}</span></td>
     194            <td><script type="math/tex">0</script></td>
     195            <td><script type="math/tex">0</script></td>
     196            <td><script type="math/tex">\mbox{\rm True}</script></td>
    191197            </tr>
    192198            <tr class ="row-b">
    193             <td><span class="math">0</span></td>
    194             <td><span class="math">1</span></td>
    195             <td><span class="math">\mbox{\rm False}</span></td>
     199            <td><script type="math/tex">0</script></td>
     200            <td><script type="math/tex">1</script></td>
     201            <td><script type="math/tex">\mbox{\rm False}</script></td>
    196202            </tr>
    197203            <tr class ="row-a">
    198             <td><span class="math">1</span></td>
    199             <td><span class="math">0</span></td>
    200             <td><span class="math">\mbox{\rm False}</span></td>
     204            <td><script type="math/tex">1</script></td>
     205            <td><script type="math/tex">0</script></td>
     206            <td><script type="math/tex">\mbox{\rm False}</script></td>
    201207            </tr>
    202208            <tr class ="row-b">
    203             <td><span class="math">1</span></td>
    204             <td><span class="math">1</span></td>
    205             <td><span class="math">\mbox{\rm True}</span></td>
     209            <td><script type="math/tex">1</script></td>
     210            <td><script type="math/tex">1</script></td>
     211            <td><script type="math/tex">\mbox{\rm True}</script></td>
    206212            </tr>
    207213            </tbody>
    208214            </table>
    class HTML: 
    215221            <table class="table_form">
    216222            <tbody>
    217223            <tr>
    218             <th>Functions <span class="math">f(x)</span></th>
     224            <th>Functions <script type="math/tex">f(x)</script></th>
    219225            </tr>
    220226            <tr class ="row-a">
    221             <td><span class="math">\sin\left(x\right)</span></td>
     227            <td><script type="math/tex">\sin\left(x\right)</script></td>
    222228            </tr>
    223229            <tr class ="row-b">
    224             <td><span class="math">\cos\left(x\right)</span></td>
     230            <td><script type="math/tex">\cos\left(x\right)</script></td>
    225231            </tr>
    226232            </tbody>
    227233            </table>
    class HTML: 
    260266
    261267        TESTS:
    262268            sage: html._table_columns(["a $x^2$",1, sin(x)])
    263             <td>a <span class="math">x^2</span></td>
    264             <td><span class="math">1</span></td>
    265             <td><span class="math">\sin\left(x\right)</span></td>
     269            <td>a <script type="math/tex">x^2</script></td>
     270            <td><script type="math/tex">1</script></td>
     271            <td><script type="math/tex">\sin\left(x\right)</script></td>
    266272            sage: html._table_columns("a", header = True)
    267273            <th>a</th>
    268274
    269         We work around a limitation of jsmath (it can't typeset '\texttt')::
     275        We work around a limitation of MathJax (it can't typeset '\texttt')::
    270276
    271277            sage: html._table_columns([Primes])
    272             <td><span class="math">\hbox{<class 'sage.sets.primes.Primes'>}</span></td>
     278            <td><script type="math/tex">\hbox{<class 'sage.sets.primes.Primes'>}</script></td>
    273279        """
    274280        if header == False:
    275281            column_tag = "<td>%s</td>"
    class HTML: 
    289295            elif isinstance(row[column], str):
    290296                print column_tag % math_parse(row[column])
    291297            else:
    292                 print column_tag % ('<span class="math">'
     298                print column_tag % ('<script type="math/tex">'
    293299                                    + latex(row[column]).replace('\\texttt','\\hbox')
    294                                     + '</span>')
     300                                    + '</script>')
    295301
    296302html = HTML()
  • sage/misc/latex.py

    diff --git a/sage/misc/latex.py b/sage/misc/latex.py
    a b class _Latex_prefs_object(SageObject): 
    420420        self._option["preamble"] = ""
    421421        self._option["engine"] = "latex"
    422422        self._option["engine_name"] = "LaTeX"
    423         self._option["jsmath_avoid"] = []
     423        self._option["mathjax_avoid"] = []
    424424
    425425_Latex_prefs = _Latex_prefs_object()
    426426
    class Latex: 
    885885        """
    886886        if t is None:
    887887            return _Latex_prefs._option["blackboard_bold"]
    888         from latex_macros import sage_latex_macros, sage_jsmath_macros, sage_configurable_latex_macros, convert_latex_macro_to_jsmath
     888        from latex_macros import sage_latex_macros, sage_mathjax_macros, sage_configurable_latex_macros, convert_latex_macro_to_mathjax
    889889        global sage_latex_macros
    890         global sage_jsmath_macros
     890        global sage_mathjax_macros
    891891        old = _Latex_prefs._option["blackboard_bold"]
    892892        _Latex_prefs._option["blackboard_bold"] = bool(t)
    893893        if bool(old) != bool(t):
    class Latex: 
    903903            sage_configurable_latex_macros.remove(old_macro)
    904904            sage_latex_macros.append(macro)
    905905            sage_configurable_latex_macros.append(macro)
    906             sage_jsmath_macros.remove(convert_latex_macro_to_jsmath(old_macro))
    907             sage_jsmath_macros.append(convert_latex_macro_to_jsmath(macro))
     906            sage_mathjax_macros.remove(convert_latex_macro_to_mathjax(old_macro))
     907            sage_mathjax_macros.append(convert_latex_macro_to_mathjax(macro))
    908908
    909909    def matrix_delimiters(self, left=None, right=None):
    910910        r"""nodetex
    Warning: `%s` is not part of this comput 
    10821082    def extra_macros(self, macros=None):
    10831083        r"""nodetex
    10841084        String containing extra LaTeX macros to use with %latex,
    1085         %html, and %jsmath.
     1085        %html, and %mathjax.
    10861086
    10871087        INPUT: ``macros`` - string
    10881088
    Warning: `%s` is not part of this comput 
    11071107    def add_macro(self, macro):
    11081108        r"""nodetex
    11091109        Append to the string of extra LaTeX macros, for use with
    1110         %latex, %html, and %jsmath.
     1110        %latex, %html, and %mathjax.
    11111111
    11121112        INPUT: ``macro`` - string
    11131113
    Warning: `%s` is not part of this comput 
    11271127    def extra_preamble(self, s=None):
    11281128        r"""nodetex
    11291129        String containing extra preamble to be used with %latex.
    1130         Anything in this string won't be processed by %jsmath.
     1130        Anything in this string won't be processed by %mathjax.
    11311131
    11321132        INPUT: ``s`` - string or ``None``
    11331133
    Warning: `%s` is not part of this comput 
    11611161        r"""nodetex
    11621162        Append to the string of extra LaTeX macros, for use with
    11631163        %latex.  Anything in this string won't be processed by
    1164         %jsmath.
     1164        %mathjax.
    11651165
    11661166        EXAMPLES::
    11671167
    Warning: `%s` is not part of this comput 
    12271227        if self.has_file(package_name+".sty"):
    12281228            self.add_to_preamble("\\usepackage{%s}\n"%package_name)
    12291229
    1230     def jsmath_avoid_list(self, L=None):
     1230    def mathjax_avoid_list(self, L=None):
    12311231        r"""nodetex
    1232         List of strings which signal that jsMath should not
     1232        List of strings which signal that MathJax should not
    12331233        be used when 'view'ing.
    12341234
    12351235        INPUT: ``L`` - list or ``None``
    Warning: `%s` is not part of this comput 
    12371237        If ``L`` is ``None``, then return the current list.
    12381238        Otherwise, set it to ``L``.  If you want to *append* to the
    12391239        current list instead of replacing it, use
    1240         :meth:`latex.add_to_jsmath_avoid_list <Latex.add_to_jsmath_avoid_list>`.
     1240        :meth:`latex.add_to_mathjax_avoid_list <Latex.add_to_mathjax_avoid_list>`.
    12411241
    12421242        EXAMPLES::
    12431243
    1244             sage: latex.jsmath_avoid_list(["\\mathsf", "pspicture"])
    1245             sage: latex.jsmath_avoid_list()  # display current setting
     1244            sage: latex.mathjax_avoid_list(["\\mathsf", "pspicture"])
     1245            sage: latex.mathjax_avoid_list()  # display current setting
    12461246            ['\\mathsf', 'pspicture']
    1247             sage: latex.jsmath_avoid_list([])  # reset to default
    1248             sage: latex.jsmath_avoid_list()
     1247            sage: latex.mathjax_avoid_list([])  # reset to default
     1248            sage: latex.mathjax_avoid_list()
    12491249            []
    12501250        """
    12511251        if L is None:
    1252             return _Latex_prefs._option['jsmath_avoid']
     1252            return _Latex_prefs._option['mathjax_avoid']
    12531253        else:
    1254             _Latex_prefs._option['jsmath_avoid'] = L
    1255 
    1256     def add_to_jsmath_avoid_list(self, s):
     1254            _Latex_prefs._option['mathjax_avoid'] = L
     1255
     1256    def add_to_mathjax_avoid_list(self, s):
    12571257        r"""nodetex
    1258         Add to the list of strings which signal that jsMath should not
     1258        Add to the list of strings which signal that MathJax should not
    12591259        be used when 'view'ing.
    12601260
    1261         INPUT: ``s`` - string -- add ``s`` to the list of 'jsMath avoid' strings
     1261        INPUT: ``s`` - string -- add ``s`` to the list of 'MathJax avoid' strings
    12621262
    12631263        If you want to replace the current list instead of adding to
    1264         it, use :meth:`latex.jsmath_avoid_list <Latex.jsmath_avoid_list>`.
     1264        it, use :meth:`latex.mathjax_avoid_list <Latex.mathjax_avoid_list>`.
    12651265
    12661266        EXAMPLES::
    12671267
    1268             sage: latex.add_to_jsmath_avoid_list("\\mathsf")
    1269             sage: latex.jsmath_avoid_list()  # display current setting
     1268            sage: latex.add_to_mathjax_avoid_list("\\mathsf")
     1269            sage: latex.mathjax_avoid_list()  # display current setting
    12701270            ['\\mathsf']
    1271             sage: latex.add_to_jsmath_avoid_list("tkz-graph")
    1272             sage: latex.jsmath_avoid_list()  # display current setting
     1271            sage: latex.add_to_mathjax_avoid_list("tkz-graph")
     1272            sage: latex.mathjax_avoid_list()  # display current setting
    12731273            ['\\mathsf', 'tkz-graph']
    1274             sage: latex.jsmath_avoid_list([])  # reset to default
    1275             sage: latex.jsmath_avoid_list()
     1274            sage: latex.mathjax_avoid_list([])  # reset to default
     1275            sage: latex.mathjax_avoid_list()
    12761276            []
    12771277        """
    1278         current = latex.jsmath_avoid_list()
     1278        current = latex.mathjax_avoid_list()
    12791279        if s not in current:
    1280             _Latex_prefs._option['jsmath_avoid'].append(s)
     1280            _Latex_prefs._option['mathjax_avoid'].append(s)
    12811281
    12821282    def pdflatex(self, t = None):  # this is deprecated since 4.3.3
    12831283        """
    def _latex_file_(objects, title='SAGE',  
    14911491
    14921492    return s
    14931493
    1494 class JSMathExpr:
     1494class MathJaxExpr:
    14951495    """
    1496     An arbitrary JSMath expression that can be nicely concatenated.
     1496    An arbitrary MathJax expression that can be nicely concatenated.
    14971497
    14981498    EXAMPLES::
    14991499
    1500         sage: from sage.misc.latex import JSMathExpr
    1501         sage: JSMathExpr("a^{2}") + JSMathExpr("x^{-1}")
     1500        sage: from sage.misc.latex import MathJaxExpr
     1501        sage: MathJaxExpr("a^{2}") + MathJaxExpr("x^{-1}")
    15021502        a^{2}x^{-1}
    15031503    """
    15041504    def __init__(self, y):
    15051505        """
    1506         Initialize a JSMath expression.
     1506        Initialize a MathJax expression.
    15071507
    15081508        INPUT:
    15091509
    class JSMathExpr: 
    15131513
    15141514        EXAMPLES::
    15151515
    1516             sage: from sage.misc.latex import JSMathExpr
    1517             sage: js = JSMathExpr(3); js  # indirect doctest
     1516            sage: from sage.misc.latex import MathJaxExpr
     1517            sage: jax = MathJaxExpr(3); jax  # indirect doctest
    15181518            3
    15191519        """
    15201520        self.__y = y
    class JSMathExpr: 
    15251525
    15261526        EXAMPLES::
    15271527
    1528             sage: from sage.misc.latex import JSMathExpr
    1529             sage: js = JSMathExpr('3')
    1530             sage: js.__repr__()
     1528            sage: from sage.misc.latex import MathJaxExpr
     1529            sage: jax = MathJaxExpr('3')
     1530            sage: jax.__repr__()
    15311531            '3'
    15321532        """
    15331533        return str(self.__y)
    15341534
    15351535    def __add__(self, y):
    15361536        """
    1537         'Add' JSMathExpr ``self`` to ``y``.  This concatenates them
     1537        'Add' MathJaxExpr ``self`` to ``y``.  This concatenates them
    15381538        (assuming that they're strings).
    15391539
    15401540        EXAMPLES::
    15411541
    1542             sage: from sage.misc.latex import JSMathExpr
    1543             sage: j3 = JSMathExpr('3')
    1544             sage: jx = JSMathExpr('x')
     1542            sage: from sage.misc.latex import MathJaxExpr
     1543            sage: j3 = MathJaxExpr('3')
     1544            sage: jx = MathJaxExpr('x')
    15451545            sage: j3 + jx
    15461546            3x
    15471547        """
    1548         return JSMathExpr(self.__y + y)
     1548        return MathJaxExpr(self.__y + y)
    15491549
    15501550    def __radd__(self, y):
    15511551        """
    1552         'Add' JSMathExpr ``y`` to ``self``.  This concatenates them
     1552        'Add' MathJaxExpr ``y`` to ``self``.  This concatenates them
    15531553        (assuming that they're strings).
    15541554
    15551555        EXAMPLES::
    15561556
    1557             sage: from sage.misc.latex import JSMathExpr
    1558             sage: j3 = JSMathExpr('3')
    1559             sage: jx = JSMathExpr('x')
     1557            sage: from sage.misc.latex import MathJaxExpr
     1558            sage: j3 = MathJaxExpr('3')
     1559            sage: jx = MathJaxExpr('x')
    15601560            sage: j3.__radd__(jx)
    15611561            x3
    15621562        """
    1563         return JSMathExpr(y + self.__y)
    1564 
    1565 class JSMath:
     1563        return MathJaxExpr(y + self.__y)
     1564
     1565class MathJax:
    15661566    r"""
    1567     Render LaTeX input using JSMath.  This returns a :class:`JSMathExpr`.
     1567    Render LaTeX input using MathJax.  This returns a :class:`MathJaxExpr`.
    15681568
    15691569    EXAMPLES::
    15701570
    1571         sage: from sage.misc.latex import JSMath
    1572         sage: JSMath()(3)
    1573         <html><div class="math">\newcommand{\Bold}[1]{\mathbf{#1}}3</div></html>
    1574         sage: JSMath()(ZZ)
    1575         <html><div class="math">\newcommand{\Bold}[1]{\mathbf{#1}}\Bold{Z}</div></html>
     1571        sage: from sage.misc.latex import MathJax
     1572        sage: MathJax()(3)
     1573        <html><script type="math/tex; mode=display">\newcommand{\Bold}[1]{\mathbf{#1}}3</script></html>
     1574        sage: MathJax()(ZZ)
     1575        <html><script type="math/tex; mode=display">\newcommand{\Bold}[1]{\mathbf{#1}}\Bold{Z}</script></html>
    15761576    """
    15771577
    15781578    def __call__(self, x):
    15791579        r"""
    1580         Render LaTeX input using JSMath.  This returns a :class:`JSMathExpr`.
     1580        Render LaTeX input using MathJax.  This returns a :class:`MathJaxExpr`.
    15811581
    15821582        INPUT:
    15831583
    15841584        - ``x`` - a Sage object
    15851585
    1586         OUTPUT: a JSMathExpr
     1586        OUTPUT: a MathJaxExpr
    15871587
    15881588        EXAMPLES::
    15891589
    1590             sage: from sage.misc.latex import JSMath
    1591             sage: JSMath()(3)
    1592             <html><div class="math">\newcommand{\Bold}[1]{\mathbf{#1}}3</div></html>
    1593             sage: str(JSMath().eval(ZZ[x], mode='display')) == str(JSMath()(ZZ[x]))
     1590            sage: from sage.misc.latex import MathJax
     1591            sage: MathJax()(3)
     1592            <html><script type="math/tex; mode=display">\newcommand{\Bold}[1]{\mathbf{#1}}3</script></html>
     1593            sage: str(MathJax().eval(ZZ[x], mode='display')) == str(MathJax()(ZZ[x]))
    15941594            True
    15951595        """
    15961596        return self.eval(x)
    15971597
    15981598    def eval(self, x, globals=None, locals=None, mode='display'):
    15991599        r"""
    1600         Render LaTeX input using JSMath.  This returns a :class:`JSMathExpr`.
     1600        Render LaTeX input using MathJax.  This returns a :class:`MathJaxExpr`.
    16011601
    16021602        INPUT:
    16031603
    class JSMath: 
    16111611        -  ``mode`` - string (optional, default 'display): 'display'
    16121612           for displaymath or 'inline' for inline math
    16131613
    1614         OUTPUT: a JSMathExpr
     1614        OUTPUT: a MathJaxExpr
    16151615
    16161616        EXAMPLES::
    16171617
    1618             sage: from sage.misc.latex import JSMath
    1619             sage: JSMath().eval(3, mode='display')
    1620             <html><div class="math">\newcommand{\Bold}[1]{\mathbf{#1}}3</div></html>
    1621             sage: JSMath().eval(3, mode='inline')
    1622             <html><span class="math">\newcommand{\Bold}[1]{\mathbf{#1}}3</span></html>
    1623             sage: JSMath().eval(type(3), mode='inline')
    1624             <html><span class="math">\newcommand{\Bold}[1]{\mathbf{#1}}\hbox{ < type 'sage.rings.integer.Integer' > }</span></html>
     1618            sage: from sage.misc.latex import MathJax
     1619            sage: MathJax().eval(3, mode='display')
     1620            <html><script type="math/tex; mode=display">\newcommand{\Bold}[1]{\mathbf{#1}}3</script></html>
     1621            sage: MathJax().eval(3, mode='inline')
     1622            <html><script type="math/tex">\newcommand{\Bold}[1]{\mathbf{#1}}3</script></html>
     1623            sage: MathJax().eval(type(3), mode='inline')
     1624            <html><script type="math/tex">\newcommand{\Bold}[1]{\mathbf{#1}}\hbox{ < type 'sage.rings.integer.Integer' > }</script></html>
    16251625        """
    16261626        # try to get a latex representation of the object
    16271627        if isinstance(x, LatexExpr):
    16281628            # already a latex expression, so the output of
    16291629            # latex(blah).  so treat as a string.
    16301630            x = "\\hbox{%s}"%str(x.replace('\\texttt','\\hbox'))
    1631             # add spaces around < and > to help jsMath to parse them
     1631            # add spaces around < and > to help MathJax to parse them
     1632            # (probably unnecessary with change from jsMath to MathJax)
    16321633            x = x.replace('<', ' < ')
    16331634            x = x.replace('>', ' > ')
    16341635        elif has_latex_attr(x):
    class JSMath: 
    16401641            except KeyError:
    16411642                # otherwise just get the string representation
    16421643                x = "\\hbox{%s}"%str(x)
    1643                 # add spaces around < and > to help jsMath to parse them
     1644                # add spaces around < and > to help MathJax to parse them
     1645                # (probably unnecessary with change from jsMath to MathJax)
    16441646                x = x.replace('<', ' < ')
    16451647                x = x.replace('>', ' > ')
    16461648
    1647         # in JSMath:
    1648         # inline math: <span class="math">...</span>
    1649         # displaymath: <div class="math">...</div>
     1649        # in MathJax:
     1650        # inline math: <script type="math/tex">...</script>
     1651        # displaymath: <script type="math/tex; mode=display">...</script>
    16501652        from sage.misc.latex_macros import sage_configurable_latex_macros
    16511653        if 'display' == mode:
    1652             return JSMathExpr('<html><div class="math">'
    1653                               + ''.join(sage_configurable_latex_macros)
    1654                               + _Latex_prefs._option['macros']
    1655                               + '%s</div></html>'%x)
     1654            display_str = '; mode=display'
    16561655        elif 'inline' == mode:
    1657             return JSMathExpr('<html><span class="math">'
    1658                               + ''.join(sage_configurable_latex_macros)
    1659                               + _Latex_prefs._option['macros']
    1660                               + '%s</span></html>'%x)
     1656            display_str = ''
    16611657        else:
    16621658            # what happened here?
    16631659            raise ValueError, "mode must be either 'display' or 'inline'"
    1664 
    1665 def jsmath(x, mode='display'):
    1666     r"""
    1667     Attempt to nicely render an arbitrary Sage object with jsMath typesetting.
    1668     Tries to call ._latex_() on x. If that fails, it will render a string
    1669     representation of x.
    1670 
    1671     .. warning::
    1672 
    1673         2009-04: This function is deprecated; use :func:`html`
    1674         instead: replace ``jsmath('MATH', mode='display')`` with
    1675         ``html('$$MATH$$')``, and replace ``jsmath('MATH',
    1676         mode='inline')`` with ``html('$MATH$')``.
    1677 
    1678     INPUT:
    1679         x -- the object to render
    1680         mode -- 'display' for displaymath or 'inline' for inline math
    1681 
    1682     OUTPUT:
    1683         A string of html that contains the LaTeX representation of x. In the
    1684         notebook this gets embedded into the cell.
    1685 
    1686     EXAMPLES::
    1687 
    1688         sage: from sage.misc.latex import jsmath
    1689         sage: f = maxima('1/(x^2+1)')
    1690         sage: g = f.integrate()
    1691         sage: jsmath(f)
    1692         doctest:1: DeprecationWarning: The jsmath function is deprecated.  Use html('$math$') for inline mode or html('$$math$$') for display mode.
    1693         <html><font color='black'><div class="math">{{1}\over{x^2+1}}</div></font></html>
    1694         sage: jsmath(g, 'inline')
    1695         <html><font color='black'><span class="math">\tan^{-1} x</span></font></html>
    1696         sage: jsmath('\int' + latex(f) + '\ dx=' + latex(g))
    1697         <html><font color='black'><div class="math">\int{{1}\over{x^2+1}}\ dx=\tan^{-1} x</div></font></html>
    1698 
    1699     AUTHORS:
    1700 
    1701     - William Stein (2006-10): general layout (2006-10)
    1702 
    1703     - Bobby Moretti (2006-10): improvements, comments, documentation
    1704     """
    1705     from sage.misc.misc import deprecation
    1706     from sage.misc.html import html
    1707     deprecation("The jsmath function is deprecated.  Use html('$math$') for inline mode or html('$$math$$') for display mode.")
    1708     if mode == 'display':
    1709         delimiter = '$$'
    1710     elif mode == 'inline':
    1711         delimiter = '$'
    1712     else:
    1713         raise ValueError, "mode must be either 'display' or 'inline'"
    1714     try:
    1715         # try to get a latex representation of the object
    1716         x = x._latex_()
    1717     except AttributeError:
    1718         # otherwise just get the string representation
    1719         x = str(x)
    1720     return html(delimiter + x + delimiter)
     1660        return MathJaxExpr('<html><script type="math/tex%s">'%display_str
     1661                              + ''.join(sage_configurable_latex_macros)
     1662                              + _Latex_prefs._option['macros']
     1663                              + '%s'%x
     1664                              + '</script></html>')
    17211665
    17221666def view(objects, title='SAGE', debug=False, sep='', tiny=False, pdflatex=None, engine=None, viewer = None, tightpage = None, mode='inline', **kwds):
    17231667    r"""nodetex
    def view(objects, title='SAGE', debug=Fa 
    18021746    each object by ``\\begin{page}$`` and ``$\\end{page}``.
    18031747
    18041748    If in notebook mode with ``viewer`` equal to ``None``, this
    1805     usually uses jsMath -- see the next paragraph for the exception --
     1749    usually uses MathJax -- see the next paragraph for the exception --
    18061750    to display the output in the notebook. Only the first argument,
    18071751    ``objects``, is relevant; the others are ignored. If ``objects``
    18081752    is a list, each object is printed on its own line.
    18091753
    1810     In the notebook, this *does* *not* use jsMath if the LaTeX code
     1754    In the notebook, this *does* *not* use MathJax if the LaTeX code
    18111755    for ``objects`` contains a string in
    1812     :meth:`latex.jsmath_avoid_list() <Latex.jsmath_avoid_list>`.  In
     1756    :meth:`latex.mathjax_avoid_list() <Latex.mathjax_avoid_list>`.  In
    18131757    this case, it creates and displays a png file.
    18141758
    18151759    EXAMPLES::
    18161760
    18171761        sage: sage.misc.latex.EMBEDDED_MODE = True
    18181762        sage: view(3)
    1819         <html><span class="math">\newcommand{\Bold}[1]{\mathbf{#1}}3</span></html>
     1763        <html><script type="math/tex">\newcommand{\Bold}[1]{\mathbf{#1}}3</script></html>
    18201764        sage: view(3, mode='display')
    1821         <html><div class="math">\newcommand{\Bold}[1]{\mathbf{#1}}3</div></html>
     1765        <html><script type="math/tex; mode=display">\newcommand{\Bold}[1]{\mathbf{#1}}3</script></html>
    18221766        sage: sage.misc.latex.EMBEDDED_MODE = False
    18231767
    18241768    TESTS::
    def view(objects, title='SAGE', debug=Fa 
    18431787        s = _latex_file_(objects, title=title, sep=sep, tiny=tiny, debug=debug, **latex_options)
    18441788    # notebook
    18451789    if EMBEDDED_MODE and viewer is None:
    1846         jsMath_okay = True
    1847         for t in latex.jsmath_avoid_list():
     1790        MathJax_okay = True
     1791        for t in latex.mathjax_avoid_list():
    18481792            if s.find(t) != -1:
    1849                 jsMath_okay = False
    1850             if not jsMath_okay:
     1793                MathJax_okay = False
     1794            if not MathJax_okay:
    18511795                break
    1852         if jsMath_okay:
    1853             print JSMath().eval(objects, mode=mode)  # put comma at end of line?
     1796        if MathJax_okay:
     1797            print MathJax().eval(objects, mode=mode)  # put comma at end of line?
    18541798        else:
    18551799            if pdflatex is True:
    18561800                engine = "pdflatex"
    def print_or_typeset(object): 
    20672011        sage: TEMP = sys.displayhook
    20682012        sage: sys.displayhook = sage.misc.latex.pretty_print
    20692013        sage: sage.misc.latex.print_or_typeset(3)
    2070         <html><span class="math">\newcommand{\Bold}[1]{\mathbf{#1}}3</span></html>
     2014        <html><script type="math/tex">\newcommand{\Bold}[1]{\mathbf{#1}}3</script></html>
    20712015        sage: sage.misc.latex.EMBEDDED_MODE=False
    20722016        sage: sys.displayhook = TEMP
    20732017    """
    def pretty_print (object): 
    20832027    objects, this returns their default representation.  For other
    20842028    objects, in the notebook, this calls the :func:`view` command,
    20852029    while from the command line, this produces an html string suitable
    2086     for processing by jsMath.
     2030    for processing by MathJax.
    20872031
    20882032    INPUT:
    20892033
    def pretty_print (object): 
    20962040
    20972041        sage: from sage.misc.latex import pretty_print
    20982042        sage: pretty_print(ZZ)  # indirect doctest
    2099         <html><span class="math">\newcommand{\Bold}[1]{\mathbf{#1}}\Bold{Z}</span></html>
     2043        <html><script type="math/tex">\newcommand{\Bold}[1]{\mathbf{#1}}\Bold{Z}</script></html>
    21002044    """
    21012045    if object is None:
    21022046        return
    def pretty_print (object): 
    21122056        if EMBEDDED_MODE:
    21132057            view(object)
    21142058        else:
    2115             print JSMath().eval(object, mode='inline')
     2059            print MathJax().eval(object, mode='inline')
    21162060        return
    21172061
    21182062def pretty_print_default(enable=True):
    21192063    r"""
    21202064    Enable or disable default pretty printing. Pretty printing means
    2121     rendering things so that jsMath or some other latex-aware front end
     2065    rendering things so that MathJax or some other latex-aware front end
    21222066    can render real math.
    21232067
    21242068    INPUT:
    def pretty_print_default(enable=True): 
    21302074
    21312075        sage: pretty_print_default(True)
    21322076        sage: sys.displayhook
    2133         <html><span class="math">...\hbox{ < function pretty_print at ... > }</span></html>
     2077        <html><script type="math/tex">...\hbox{ < function pretty_print at ... > }</script></html>
    21342078        sage: pretty_print_default(False)
    21352079        sage: sys.displayhook == sys.__displayhook__
    21362080        True
    gibberish. Now, make sure that you have 
    23562300the TeX package pgf installed, along with the LaTeX package tkz-graph.
    23572301Run 'latex.add_to_preamble("\\usepackage{tkz-graph}")', and try viewing
    23582302it again.  From the command line, this should pop open a nice window
    2359 with a picture of a graph.  In the notebook, you should get a jsMath
    2360 error.  Finally, run 'latex.add_to_jsmath_avoid_list("tikzpicture")'
     2303with a picture of a graph.  In the notebook, you should get a MathJax
     2304error.  Finally, run 'latex.add_to_mathjax_avoid_list("tikzpicture")'
    23612305and try again from the notebook -- you should get a nice picture.
    23622306
    23632307(LaTeX code taken from http://altermundus.com/pages/graph.html)
    viewing it again. From the command line, 
    24392383open a nice window with a picture of forces acting on a mass
    24402384on a pendulum. In the notebook, you should get an error.
    24412385Finally, run
    2442 'latex.add_to_jsmath_avoid_list("pspicture")' and try again
     2386'latex.add_to_mathjax_avoid_list("pspicture")' and try again
    24432387-- you should get a nice picture."""
    24442388
    24452389        def _latex_(self):
    To use, try to view this object -- it wo 
    25062450'latex.add_to_preamble("\\usepackage[graph,knot,poly,curve]{xypic}")',
    25072451and try viewing again -- it should work in the command line but not
    25082452from the notebook.  In the notebook, run
    2509 'latex.add_to_jsmath_avoid_list("xygraph")' and try again -- you
     2453'latex.add_to_mathjax_avoid_list("xygraph")' and try again -- you
    25102454should get a nice picture.
    25112455
    25122456(LaTeX code taken from the xypic manual)
    To use, try to view this object -- it wo 
    25702514'latex.add_to_preamble("\\usepackage[matrix,arrow,curve,cmtip]{xy}")',
    25712515and try viewing again -- it should work in the command line but not
    25722516from the notebook.  In the notebook, run
    2573 'latex.add_to_jsmath_avoid_list("xymatrix")' and try again -- you
     2517'latex.add_to_mathjax_avoid_list("xymatrix")' and try again -- you
    25742518should get a picture (a part of the diagram arising from a filtered
    25752519chain complex)."""
    25762520
  • sage/misc/latex_macros.py

    diff --git a/sage/misc/latex_macros.py b/sage/misc/latex_macros.py
    a b The code here sets up LaTeX macro defini 
    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
    def produce_latex_macro(name, *sample_ar 
    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('[')
    def convert_latex_macro_to_jsmath(macro) 
    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
    sage_configurable_latex_macros = ["\\new 
    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 import sage.version 
    3030
    3131# two kinds of substitutions: math, which should only be done on the
    3232# command line -- in the notebook, these should instead by taken care
    33 # of by jsMath -- and nonmath, which should be done always.
     33# of by MathJax -- and nonmath, which should be done always.
    3434math_substitutes = [('\\to', '-->'),
    3535                    ('\\leq', '<='),
    3636                    ('\\geq', '>='),
    class _sage_doc: 
    11761176    </script>
    11771177    <script type="text/javascript" src="%(static_path)s/jquery.js"></script>
    11781178    <script type="text/javascript" src="%(static_path)s/doctools.js"></script>
    1179     <script type="text/javascript" src="%(static_path)s/jsmath_sage.js"></script>
     1179    <script type="text/javascript" src="%(static_path)s/mathjax_sage.js"></script>
    11801180    <link rel="shortcut icon" href="%(static_path)s/favicon.ico" />
    11811181    <link rel="icon" href="%(static_path)s/sageicon.png" type="image/x-icon" />
    11821182  </head>
    class _sage_doc: 
    12371237
    12381238        if not os.path.exists(path):
    12391239            raise OSError, """The document '%s' does not exist.  Please build it
    1240 with 'sage -docbuild %s html --jsmath' and try again.""" %(name, name)
     1240with 'sage -docbuild %s html --mathjax' and try again.""" %(name, name)
    12411241
    12421242        from sage.server.support import EMBEDDED_MODE
    12431243        if EMBEDDED_MODE: