MathJax icon indicating copy to clipboard operation
MathJax copied to clipboard

suppress errors about multiple sub/superscripts?

Open hbghlyj opened this issue 2 years ago • 1 comments

Is your feature request related to a problem? Please describe. Similar question to Is there a way to override LaTeX's errors about double subscripts and superscripts?

When one writes

a^b^c, a_b_c

or

a^b'

MathJax gives an error message complaining about multiple super/subscripts.

Is there a way to override the error and have MathJax output

a^{bc} a_{bc} {a^b}'  

Describe the solution you'd like Is there a way to redefine ^ and _ to append an empty {}? like in LaTeX:

\catcode`\^ = 13 \def^#1{\sp{#1}{}}
\catcode`\_ = 13 \def_#1{\sb{#1}{}}

hbghlyj avatar Feb 26 '24 21:02 hbghlyj

It can be done using the following configuration:

MathJax = {
  tex: {
    packages: {'[+]': ['my-scripts']}
  },
  startup: {
    ready() {
      const {Configuration} = MathJax._.input.tex.Configuration;
      const {CommandMap, MacroMap} = MathJax._.input.tex.SymbolMap;
      const BaseMethods = MathJax._.input.tex.base.BaseMethods.default;
      
      new MacroMap('my-script-chars', {
        '^': ['Macro', '\\sp{#1}{}', 1],
        '_': ['Macro', '\\sb{#1}{}', 1],
        '\'': 'Prime',
      }, {
        Macro: BaseMethods.Macro,
        Prime(parser, c) {
          const top = parser.stack.Top()
          const [base, atom] = top?.Peek(2) || [];
          if (base && atom && 
              base.isKind('msubsup') && !base.isKind('msup') && !!base.childNodes[base.sup] &&
              atom.isKind('TeXAtom') && atom.childNodes[0].childNodes.length === 0) {
            top.Pop(); top.Pop();
            const msup = parser.create('node', 'msup', [base.childNodes[0], base.childNodes[base.sup]]);
            parser.stack.Push(msup);
          }
          BaseMethods.Prime(parser, c);
        }
      });
      
      new CommandMap('my-script-cs', {
        sp: 'Superscript',
        sb: 'Subscript'
      }, BaseMethods);
      
      Configuration.create('my-scripts', {
        handler: {
          macro: ['my-script-cs'],
          character: ['my-script-chars']
        }
      });
      MathJax.startup.defaultReady();
    }
  }
}

Note, however, that a^b^c doesn't actually give a^{bc} but rather a^{b}{}^{c}{}, which is semantically different, though visually similar, so people with screen readers will get a strange result from this. Similarly for a_b_c, which gives a_{b}{}_{c}.

In actual TeX, these do not render quite the same:

tex

(note the extra space in the second form). MathJax v3 gets this wrong and both appear identical, but v4 fixes the error and produces the result shown above. There is a similar extra space for the subscripts (in LaTeX and v4), and in the result for {a^b}' that is missing in v3.

dpvc avatar Mar 03 '24 13:03 dpvc