Debian Codegraph @

docutils/utils/math/latex2mathml.py

raw symbols SCIP
1 # :Id: $Id: latex2mathml.py 9536 2024-02-01 13:04:22Z milde $
2 # :Copyright: © 2005 Jens Jørgen Mortensen [1]_
3 # © 2010, 2021, 2024 Günter Milde.
4 #
5 # :License: Released under the terms of the `2-Clause BSD license`_, in short:
6 #
7 # Copying and distribution of this file, with or without modification,
8 # are permitted in any medium without royalty provided the copyright
9 # notice and this notice are preserved.
10 # This file is offered as-is, without any warranty.
11 #
12 # .. _2-Clause BSD license: https://opensource.org/licenses/BSD-2-Clause
13 #
14 # .. [1] the original `rst2mathml.py` in `sandbox/jensj/latex_math`
15
16 """Convert LaTex maths code into presentational MathML.
17
18 This module is provisional:
19 the API is not settled and may change with any minor Docutils version.
20 """
21
22 # Usage:
23 #
24 # >>> from latex2mathml import *
25
26 import re
27 import unicodedata
28
29 from docutils.utils.math import (MathError, mathalphabet2unichar,
30 tex2unichar, toplevel_code)
31 from docutils.utils.math.mathml_elements import (
32 math, mtable, mrow, mtr, mtd, menclose, mphantom, msqrt, mi, mn, mo,
33 mtext, msub, msup, msubsup, munder, mover, munderover, mroot, mfrac,
34 mspace, MathRow)
35
36
37 # Character data
38 # --------------
39
40 # LaTeX math macro to Unicode mappings.
41 # Character categories.
42
43 # identifiers -> <mi>
44
45 letters = {'hbar': 'ℏ'} # Compatibility mapping: \hbar resembles italic ħ
46 # "unicode-math" unifies \hbar and \hslash to ℏ.
47 letters.update(tex2unichar.mathalpha)
48
49 ordinary = tex2unichar.mathord # Miscellaneous symbols
50
51 # special case: Capital Greek letters: (upright in TeX style)
52 greek_capitals = {
53 'Phi': '\u03a6', 'Xi': '\u039e', 'Sigma': '\u03a3',
54 'Psi': '\u03a8', 'Delta': '\u0394', 'Theta': '\u0398',
55 'Upsilon': '\u03d2', 'Pi': '\u03a0', 'Omega': '\u03a9',
56 'Gamma': '\u0393', 'Lambda': '\u039b'}
57
58 # functions -> <mi>
59 functions = {
60 # functions with a space in the name
61 'liminf': 'lim\u202finf',
62 'limsup': 'lim\u202fsup',
63 'injlim': 'inj\u202flim',
64 'projlim': 'proj\u202flim',
65 # embellished function names (see handle_cmd() below)
66 'varlimsup': 'lim',
67 'varliminf': 'lim',
68 'varprojlim': 'lim',
69 'varinjlim': 'lim',
70 # custom function name
71 'operatorname': None,
72 }
73 functions.update((name, name) for name in
74 ('arccos', 'arcsin', 'arctan', 'arg', 'cos',
75 'cosh', 'cot', 'coth', 'csc', 'deg',
76 'det', 'dim', 'exp', 'gcd', 'hom',
77 'ker', 'lg', 'ln', 'log', 'Pr',
78 'sec', 'sin', 'sinh', 'tan', 'tanh'))
79 # Function with limits: 'lim', 'sup', 'inf', 'max', 'min':
80 # use <mo> to allow "movablelimits" attribute (see below).
81
82 # modulo operator/arithmetic
83 modulo_functions = {
84 # cmdname: (binary, named, parentheses, padding)
85 'bmod': (True, True, False, '0.278em'), # a mod n
86 'pmod': (False, True, True, '0.444em'), # a (mod n)
87 'mod': (False, True, False, '0.667em'), # a mod n
88 'pod': (False, False, True, '0.444em'), # a (n)
89 }
90
91
92 # "mathematical alphabets": map identifiers to the corresponding
93 # characters from the "Mathematical Alphanumeric Symbols" block
94 math_alphabets = {
95 # 'cmdname': 'mathvariant value' # package
96 'mathbb': 'double-struck', # amssymb
97 'mathbf': 'bold',
98 'mathbfit': 'bold-italic', # isomath
99 'mathcal': 'script',
100 'mathfrak': 'fraktur', # amssymb
101 'mathit': 'italic',
102 'mathrm': 'normal',
103 'mathscr': 'script', # mathrsfs et al
104 'mathsf': 'sans-serif',
105 'mathbfsfit': 'sans-serif-bold-italic', # unicode-math
106 'mathsfbfit': 'sans-serif-bold-italic', # isomath
107 'mathsfit': 'sans-serif-italic', # isomath
108 'mathtt': 'monospace',
109 # unsupported: bold-fraktur
110 # bold-script
111 # bold-sans-serif
112 }
113
114 # operator, fence, or separator -> <mo>
115
116 stretchables = {
117 # extensible delimiters allowed in left/right cmds
118 'backslash': '\\',
119 'uparrow': '\u2191', # ↑ UPWARDS ARROW
120 'downarrow': '\u2193', # ↓ DOWNWARDS ARROW
121 'updownarrow': '\u2195', # ↕ UP DOWN ARROW
122 'Uparrow': '\u21d1', # ⇑ UPWARDS DOUBLE ARROW
123 'Downarrow': '\u21d3', # ⇓ DOWNWARDS DOUBLE ARROW
124 'Updownarrow': '\u21d5', # ⇕ UP DOWN DOUBLE ARROW
125 'lmoustache': '\u23b0', # ⎰ … CURLY BRACKET SECTION
126 'rmoustache': '\u23b1', # ⎱ … LEFT CURLY BRACKET SECTION
127 'arrowvert': '\u23d0', # ⏐ VERTICAL LINE EXTENSION
128 'bracevert': '\u23aa', # ⎪ CURLY BRACKET EXTENSION
129 'lvert': '|', # left |
130 'lVert': '\u2016', # left ‖
131 'rvert': '|', # right |
132 'rVert': '\u2016', # right ‖
133 'Arrowvert': '\u2016', # ‖
134 }
135 stretchables.update(tex2unichar.mathfence)
136 stretchables.update(tex2unichar.mathopen) # Braces
137 stretchables.update(tex2unichar.mathclose) # Braces
138
139 # >>> print(' '.join(sorted(set(stretchables.values()))))
140 # [ \ ] { | } ‖ ↑ ↓ ↕ ⇑ ⇓ ⇕ ⌈ ⌉ ⌊ ⌋ ⌜ ⌝ ⌞ ⌟ ⎪ ⎰ ⎱ ⏐ ⟅ ⟆ ⟦ ⟧ ⟨ ⟩ ⟮ ⟯ ⦇ ⦈
141
142 operators = {
143 # negated symbols without pre-composed Unicode character
144 'nleqq': '\u2266\u0338', # ≦̸
145 'ngeqq': '\u2267\u0338', # ≧̸
146 'nleqslant': '\u2a7d\u0338', # ⩽̸
147 'ngeqslant': '\u2a7e\u0338', # ⩾̸
148 'ngtrless': '\u2277\u0338', # txfonts
149 'nlessgtr': '\u2276\u0338', # txfonts
150 'nsubseteqq': '\u2AC5\u0338', # ⫅̸
151 'nsupseteqq': '\u2AC6\u0338', # ⫆̸
152 # compatibility definitions:
153 'centerdot': '\u2B1D', # BLACK VERY SMALL SQUARE | mathbin
154 'varnothing': '\u2300', # ⌀ DIAMETER SIGN | empty set
155 'varpropto': '\u221d', # ∝ PROPORTIONAL TO | sans serif
156 'triangle': '\u25B3', # WHITE UP-POINTING TRIANGLE | mathord
157 'triangledown': '\u25BD', # WHITE DOWN-POINTING TRIANGLE | mathord
158 # alias commands:
159 'dotsb': '\u22ef', # ⋯ with binary operators/relations
160 'dotsc': '\u2026', # … with commas
161 'dotsi': '\u22ef', # ⋯ with integrals
162 'dotsm': '\u22ef', # ⋯ multiplication dots
163 'dotso': '\u2026', # … other dots
164 # functions with movable limits (requires <mo>)
165 'lim': 'lim',
166 'sup': 'sup',
167 'inf': 'inf',
168 'max': 'max',
169 'min': 'min',
170 }
171 operators.update(tex2unichar.mathbin) # Binary symbols
172 operators.update(tex2unichar.mathrel) # Relation symbols, arrow symbols
173 operators.update(tex2unichar.mathpunct) # Punctuation
174 operators.update(tex2unichar.mathop) # Variable-sized symbols
175 operators.update(stretchables)
176
177
178 # special cases
179
180 thick_operators = {
181 # style='font-weight: bold;'
182 'thicksim': '\u223C', # ∼
183 'thickapprox': '\u2248', # ≈
184 }
185
186 small_operators = {
187 # mathsize='75%'
188 'shortmid': '\u2223', # ∣
189 'shortparallel': '\u2225', # ∥
190 'nshortmid': '\u2224', # ∤
191 'nshortparallel': '\u2226', # ∦
192 'smallfrown': '\u2322', # ⌢ FROWN
193 'smallsmile': '\u2323', # ⌣ SMILE
194 'smallint': '\u222b', # ∫ INTEGRAL
195 }
196
197 # Operators and functions with limits above/below in display formulas
198 # and in index position inline (movablelimits=True)
199 movablelimits = ('bigcap', 'bigcup', 'bigodot', 'bigoplus', 'bigotimes',
200 'bigsqcup', 'biguplus', 'bigvee', 'bigwedge',
201 'coprod', 'intop', 'ointop', 'prod', 'sum',
202 'lim', 'max', 'min', 'sup', 'inf')
203 # Depending on settings, integrals may also be in this category.
204 # (e.g. if "amsmath" is loaded with option "intlimits", see
205 # http://mirror.ctan.org/macros/latex/required/amsmath/amsldoc.pdf)
206 # movablelimits.extend(('fint', 'iiiint', 'iiint', 'iint', 'int', 'oiint',
207 # 'oint', 'ointctrclockwise', 'sqint',
208 # 'varointclockwise',))
209
210 # horizontal space -> <mspace>
211
212 spaces = {'qquad': '2em', # two \quad
213 'quad': '1em', # 18 mu
214 'thickspace': '0.2778em', # 5mu = 5/18em
215 ';': '0.2778em', # 5mu thickspace
216 ' ': '0.25em', # inter word space
217 '\n': '0.25em', # inter word space
218 'medspace': '0.2222em', # 4mu = 2/9em
219 ':': '0.2222em', # 4mu medspace
220 'thinspace': '0.1667em', # 3mu = 1/6em
221 ',': '0.1667em', # 3mu thinspace
222 'negthinspace': '-0.1667em', # -3mu = -1/6em
223 '!': '-0.1667em', # negthinspace
224 'negmedspace': '-0.2222em', # -4mu = -2/9em
225 'negthickspace': '-0.2778em', # -5mu = -5/18em
226 }
227
228 # accents: -> <mo stretchy="false"> in <mover>
229 accents = {
230 # TeX: spacing combining
231 'acute': '´', # '\u0301'
232 'bar': 'ˉ', # '\u0304'
233 'breve': '˘', # '\u0306'
234 'check': 'ˇ', # '\u030C'
235 'dot': '˙', # '\u0307'
236 'ddot': '¨', # '\u0308'
237 'dddot': '˙˙˙', # '\u20DB' # or … ?
238 'ddddot': '˙˙˙˙', # '\u20DC' # or ¨¨ ?
239 'grave': '`', # '\u0300'
240 'hat': 'ˆ', # '\u0302'
241 'mathring': '˚', # '\u030A'
242 'tilde': '~', # '\u0303' # tilde ~ or small tilde ˜?
243 'vec': '→', # '\u20d7' # → too heavy, use scriptlevel="+1"
244 }
245
246 # limits etc. -> <mo> in <mover> or <munder>
247 over = {
248 # TeX: (char, offset-correction/em)
249 'overbrace': ('\u23DE', -0.2), # DejaVu Math -0.6
250 'overleftarrow': ('\u2190', -0.2),
251 'overleftrightarrow': ('\u2194', -0.2),
252 'overline': ('_', -0.2), # \u2012 does not stretch
253 'overrightarrow': ('\u2192', -0.2),
254 'widehat': ('^', -0.5),
255 'widetilde': ('~', -0.3),
256 }
257 under = {'underbrace': ('\u23DF', 0.1), # DejaVu Math -0.7
258 'underleftarrow': ('\u2190', -0.2),
259 'underleftrightarrow': ('\u2194', -0.2),
260 'underline': ('_', -0.8),
261 'underrightarrow': ('\u2192', -0.2),
262 }
263
264 # Character translations
265 # ----------------------
266 # characters with preferred alternative in mathematical use
267 # cf. https://www.w3.org/TR/MathML3/chapter7.html#chars.anomalous
268 anomalous_chars = {'-': '\u2212', # HYPHEN-MINUS -> MINUS SIGN
269 ':': '\u2236', # COLON -> RATIO
270 '~': '\u00a0', # NO-BREAK SPACE
271 }
272
273 # blackboard bold (Greek characters not working with "mathvariant" (Firefox 78)
274 mathbb = {'Γ': '\u213E', # ℾ
275 'Π': '\u213F', # ℿ
276 'Σ': '\u2140', # ⅀
277 'γ': '\u213D', # ℽ
278 'π': '\u213C', # ℼ
279 }
280
281 # Matrix environments
282 matrices = {
283 # name: fences
284 'matrix': ('', ''),
285 'smallmatrix': ('', ''), # smaller, see begin_environment()!
286 'pmatrix': ('(', ')'),
287 'bmatrix': ('[', ']'),
288 'Bmatrix': ('{', '}'),
289 'vmatrix': ('|', '|'),
290 'Vmatrix': ('\u2016', '\u2016'), # ‖
291 'aligned': ('', ''),
292 'cases': ('{', ''),
293 }
294
295 layout_styles = {
296 'displaystyle': {'displaystyle': True, 'scriptlevel': 0},
297 'textstyle': {'displaystyle': False, 'scriptlevel': 0},
298 'scriptstyle': {'displaystyle': False, 'scriptlevel': 1},
299 'scriptscriptstyle': {'displaystyle': False, 'scriptlevel': 2},
300 }
301 # See also https://www.w3.org/TR/MathML3/chapter3.html#presm.scriptlevel
302
303 fractions = {
304 # name: attributes
305 'frac': {},
306 'cfrac': {'displaystyle': True, 'scriptlevel': 0,
307 'class': 'cfrac'}, # in LaTeX with padding
308 'dfrac': layout_styles['displaystyle'],
309 'tfrac': layout_styles['textstyle'],
310 'binom': {'linethickness': 0},
311 'dbinom': layout_styles['displaystyle'] | {'linethickness': 0},
312 'tbinom': layout_styles['textstyle'] | {'linethickness': 0},
313 }
314
315 delimiter_sizes = ['', '1.2em', '1.623em', '2.047em', '2.470em']
316 bigdelimiters = {'left': 0,
317 'right': 0,
318 'bigl': 1,
319 'bigr': 1,
320 'Bigl': 2,
321 'Bigr': 2,
322 'biggl': 3,
323 'biggr': 3,
324 'Biggl': 4,
325 'Biggr': 4,
326 }
327
328
329 # LaTeX to MathML translation
330 # ---------------------------
331
332 # auxiliary functions
333 # ~~~~~~~~~~~~~~~~~~~
334
335 def tex_cmdname(string):
336 """Return leading TeX command name and remainder of `string`.
337
338 >>> tex_cmdname('mymacro2') # up to first non-letter
339 ('mymacro', '2')
340 >>> tex_cmdname('name 2') # strip trailing whitespace
341 ('name', '2')
342 >>> tex_cmdname('_2') # single non-letter character
343 ('_', '2')
344
345 """
346 m = re.match(r'([a-zA-Z]+)[ \n]*(.*)', string, re.DOTALL)
347 if m is None:
348 m = re.match(r'(.?)(.*)', string, re.DOTALL)
349 return m.group(1), m.group(2)
350
351
352 # Test:
353 #
354 # >>> tex_cmdname('name\nnext') # strip trailing whitespace, also newlines
355 # ('name', 'next')
356 # >>> tex_cmdname('name_2') # first non-letter terminates
357 # ('name', '_2')
358 # >>> tex_cmdname('name_2\nnext line') # line-break allowed
359 # ('name', '_2\nnext line')
360 # >>> tex_cmdname(' next') # leading whitespace is returned
361 # (' ', 'next')
362 # >>> tex_cmdname('1 2') # whitespace after non-letter is kept
363 # ('1', ' 2')
364 # >>> tex_cmdname('1\n2\t3') # whitespace after non-letter is kept
365 # ('1', '\n2\t3')
366 # >>> tex_cmdname('') # empty string
367 # ('', '')
368
369
370 def tex_number(string):
371 """Return leading number literal and remainder of `string`.
372
373 >>> tex_number('123.4')
374 ('123.4', '')
375
376 """
377 m = re.match(r'([0-9.,]*[0-9]+)(.*)', string, re.DOTALL)
378 if m is None:
379 return '', string
380 return m.group(1), m.group(2)
381
382
383 # Test:
384 #
385 # >>> tex_number(' 23.4b') # leading whitespace -> no number
386 # ('', ' 23.4b')
387 # >>> tex_number('23,400/2') # comma separator included
388 # ('23,400', '/2')
389 # >>> tex_number('23. 4/2') # trailing separator not included
390 # ('23', '. 4/2')
391 # >>> tex_number('4, 2') # trailing separator not included
392 # ('4', ', 2')
393 # >>> tex_number('1 000.4')
394 # ('1', ' 000.4')
395
396
397 def tex_token(string):
398 """Return first simple TeX token and remainder of `string`.
399
400 >>> tex_token('\\command{without argument}')
401 ('\\command', '{without argument}')
402 >>> tex_token('or first character')
403 ('o', 'r first character')
404
405 """
406 m = re.match(r"""((?P<cmd>\\[a-zA-Z]+)\s* # TeX command, skip whitespace
407 |(?P<chcmd>\\.) # one-character TeX command
408 |(?P<ch>.?)) # first character (or empty)
409 (?P<remainder>.*$) # remaining part of string
410 """, string, re.VERBOSE | re.DOTALL)
411 cmd, chcmd, ch, remainder = m.group('cmd', 'chcmd', 'ch', 'remainder')
412 return cmd or chcmd or ch, remainder
413
414 # Test:
415 #
416 # >>> tex_token('{opening bracket of group}')
417 # ('{', 'opening bracket of group}')
418 # >>> tex_token('\\skip whitespace after macro name')
419 # ('\\skip', 'whitespace after macro name')
420 # >>> tex_token('. but not after single char')
421 # ('.', ' but not after single char')
422 # >>> tex_token('') # empty string.
423 # ('', '')
424 # >>> tex_token('\{escaped bracket')
425 # ('\\{', 'escaped bracket')
426
427
428 def tex_group(string):
429 """Return first TeX group or token and remainder of `string`.
430
431 >>> tex_group('{first group} returned without brackets')
432 ('first group', ' returned without brackets')
433
434 """
435 split_index = 0
436 nest_level = 0 # level of {{nested} groups}
437 escape = False # the next character is escaped (\)
438
439 if not string.startswith('{'):
440 # special case: there is no group, return first token and remainder
441 return string[:1], string[1:]
442 for c in string:
443 split_index += 1
444 if escape:
445 escape = False
446 elif c == '\\':
447 escape = True
448 elif c == '{':
449 nest_level += 1
450 elif c == '}':
451 nest_level -= 1
452 if nest_level == 0:
453 break
454 else:
455 raise MathError('Group without closing bracket!')
456 return string[1:split_index-1], string[split_index:]
457
458
459 # >>> tex_group('{} empty group')
460 # ('', ' empty group')
461 # >>> tex_group('{group with {nested} group} ')
462 # ('group with {nested} group', ' ')
463 # >>> tex_group('{group with {nested group}} at the end')
464 # ('group with {nested group}', ' at the end')
465 # >>> tex_group('{{group} {with {{complex }nesting}} constructs}')
466 # ('{group} {with {{complex }nesting}} constructs', '')
467 # >>> tex_group('{group with \\{escaped\\} brackets}')
468 # ('group with \\{escaped\\} brackets', '')
469 # >>> tex_group('{group followed by closing bracket}} from outer group')
470 # ('group followed by closing bracket', '} from outer group')
471 # >>> tex_group('No group? Return first character.')
472 # ('N', 'o group? Return first character.')
473 # >>> tex_group(' {also whitespace}')
474 # (' ', '{also whitespace}')
475
476
477 def tex_token_or_group(string):
478 """Return first TeX group or token and remainder of `string`.
479
480 >>> tex_token_or_group('\\command{without argument}')
481 ('\\command', '{without argument}')
482 >>> tex_token_or_group('first character')
483 ('f', 'irst character')
484 >>> tex_token_or_group(' also whitespace')
485 (' ', 'also whitespace')
486 >>> tex_token_or_group('{first group} keep rest')
487 ('first group', ' keep rest')
488
489 """
490 arg, remainder = tex_token(string)
491 if arg == '{':
492 arg, remainder = tex_group(string.lstrip())
493 return arg, remainder
494
495 # >>> tex_token_or_group('\{no group but left bracket')
496 # ('\\{', 'no group but left bracket')
497
498
499 def tex_optarg(string):
500 """Return optional argument and remainder.
501
502 >>> tex_optarg('[optional argument] returned without brackets')
503 ('optional argument', ' returned without brackets')
504 >>> tex_optarg('{empty string, if there is no optional arg}')
505 ('', '{empty string, if there is no optional arg}')
506
507 """
508 m = re.match(r"""\s* # leading whitespace
509 \[(?P<optarg>(\\]|[^\[\]]|\\])*)\] # [group] without nested groups
510 (?P<remainder>.*$)
511 """, string, re.VERBOSE | re.DOTALL)
512 if m is None and not string.startswith('['):
513 return '', string
514 try:
515 return m.group('optarg'), m.group('remainder')
516 except AttributeError:
517 raise MathError(f'Could not extract optional argument from "{string}"!')
518
519 # Test:
520 # >>> tex_optarg(' [optional argument] after whitespace')
521 # ('optional argument', ' after whitespace')
522 # >>> tex_optarg('[missing right bracket')
523 # Traceback (most recent call last):
524 # ...
525 # docutils.utils.math.MathError: Could not extract optional argument from "[missing right bracket"!
526 # >>> tex_optarg('[group with [nested group]]')
527 # Traceback (most recent call last):
528 # ...
529 # docutils.utils.math.MathError: Could not extract optional argument from "[group with [nested group]]"!
530
531
532 def parse_latex_math(root, source):
533 """Append MathML conversion of `string` to `node` and return it.
534
535 >>> parse_latex_math(math(), r'\alpha')
536 math(mi('α'))
537 >>> parse_latex_math(mrow(), r'x_{n}')
538 mrow(msub(mi('x'), mi('n')))
539
540 """
541 # Normalize white-space:
542 string = source # not-yet handled part of source
543 node = root # the current "insertion point"
544
545 # Loop over `string` while changing it.
546 while len(string) > 0:
547 # Take off first character:
548 c, string = string[0], string[1:]
549
550 if c in ' \n':
551 continue # whitespace is ignored in LaTeX math mode
552 if c == '\\': # start of a LaTeX macro
553 cmdname, string = tex_cmdname(string)
554 node, string = handle_cmd(cmdname, node, string)
555 elif c in "_^":
556 node = handle_script_or_limit(node, c)
557 elif c == '{':
558 if isinstance(node, MathRow) and node.nchildren == 1:
559 # LaTeX takes one arg, MathML node accepts a group
560 node.nchildren = None # allow appending until closed by '}'
561 else: # wrap group in an <mrow>
562 new_node = mrow()
563 node.append(new_node)
564 node = new_node
565 elif c == '}':
566 node = node.close()
567 elif c == '&':
568 new_node = mtd()
569 node.close().append(new_node)
570 node = new_node
571 elif c.isalpha():
572 node = node.append(mi(c))
573 elif c.isdigit():
574 number, string = tex_number(string)
575 node = node.append(mn(c+number))
576 elif c in anomalous_chars:
577 # characters with a special meaning in LaTeX math mode
578 # fix spacing before "unary" minus.
579 attributes = {}
580 if c == '-' and len(node):
581 previous_node = node[-1]
582 if (previous_node.text and previous_node.text in '([='
583 or previous_node.get('class') == 'mathopen'):
584 attributes['form'] = 'prefix'
585 node = node.append(mo(anomalous_chars[c], **attributes))
586 elif c in "/()[]|":
587 node = node.append(mo(c, stretchy=False))
588 elif c in "+*=<>,.!?`';@":
589 node = node.append(mo(c))
590 else:
591 raise MathError(f'Unsupported character: "{c}"!')
592 # TODO: append as <mi>?
593 if node is None:
594 if not string:
595 return root # ignore unbalanced braces
596 raise MathError(f'No insertion point for "{string}". '
597 f'Unbalanced braces in "{source[:-len(string)]}"?')
598 if node.nchildren and len(node) < node.nchildren:
599 raise MathError('Last node missing children. Source incomplete?')
600 return root
601
602 # Test:
603
604 # >>> parse_latex_math(math(), '')
605 # math()
606 # >>> parse_latex_math(math(), ' \\sqrt{ \\alpha}')
607 # math(msqrt(mi('α')))
608 # >>> parse_latex_math(math(), '23.4x')
609 # math(mn('23.4'), mi('x'))
610 # >>> parse_latex_math(math(), '\\sqrt 2 \\ne 3')
611 # math(msqrt(mn('2')), mo('≠'), mn('3'))
612 # >>> parse_latex_math(math(), '\\sqrt{2 + 3} < 10')
613 # math(msqrt(mn('2'), mo('+'), mn('3'), nchildren=3), mo('<'), mn('10'))
614 # >>> parse_latex_math(math(), '\\sqrt[3]{2 + 3}')
615 # math(mroot(mrow(mn('2'), mo('+'), mn('3'), nchildren=3), mn('3')))
616 # >>> parse_latex_math(math(), '\max_x') # function takes limits
617 # math(munder(mo('max', movablelimits='true'), mi('x')))
618 # >>> parse_latex_math(math(), 'x^j_i') # ensure correct order: base, sub, sup
619 # math(msubsup(mi('x'), mi('i'), mi('j')))
620 # >>> parse_latex_math(math(), '\int^j_i') # ensure correct order
621 # math(msubsup(mo('∫'), mi('i'), mi('j')))
622 # >>> parse_latex_math(math(), 'x_{\\alpha}')
623 # math(msub(mi('x'), mi('α')))
624 # >>> parse_latex_math(math(), 'x_\\text{in}')
625 # math(msub(mi('x'), mtext('in')))
626 # >>> parse_latex_math(math(), '2⌘')
627 # Traceback (most recent call last):
628 # docutils.utils.math.MathError: Unsupported character: "⌘"!
629 # >>> parse_latex_math(math(), '23}x') # doctest: +ELLIPSIS
630 # Traceback (most recent call last):
631 # ...
632 # docutils.utils.math.MathError: ... Unbalanced braces in "23}"?
633 # >>> parse_latex_math(math(), '\\frac{2}')
634 # Traceback (most recent call last):
635 # ...
636 # docutils.utils.math.MathError: Last node missing children. Source incomplete?
637
638
639 def handle_cmd(name, node, string): # noqa: C901 TODO make this less complex
640 """Process LaTeX command `name` followed by `string`.
641
642 Append result to `node`.
643 If needed, parse `string` for command argument.
644 Return new current node and remainder of `string`:
645
646 >>> handle_cmd('hbar', math(), r' \frac')
647 (math(mi('ℏ')), ' \\frac')
648 >>> handle_cmd('hspace', math(), r'{1ex} (x)')
649 (math(mspace(width='1ex')), ' (x)')
650
651 """
652
653 # Token elements
654 # ==============
655
656 # identifier -> <mi>
657
658 if name in letters:
659 new_node = mi(letters[name])
660 if name in greek_capitals:
661 # upright in "TeX style" but MathML sets them italic ("ISO style").
662 # CSS styling does not change the font style in Firefox 78.
663 # Use 'mathvariant="normal"'?
664 new_node.set('class', 'capital-greek')
665 node = node.append(new_node)
666 return node, string
667
668 if name in ordinary:
669 # <mi mathvariant="normal"> well supported by Chromium but
670 # Firefox 115.5.0 puts additional space around the symbol, e.g.
671 # <mi mathvariant="normal">∂</mi><mi>t</mi> looks like ∂ t, not ∂t
672 # return node.append(mi(ordinary[name], mathvariant='normal')), string
673 return node.append(mi(ordinary[name])), string
674
675 if name in functions:
676 # use <mi> followed by invisible function applicator character
677 # (see https://www.w3.org/TR/MathML3/chapter3.html#presm.mi)
678 if name == 'operatorname':
679 # custom function name, e.g. ``\operatorname{abs}(x)``
680 # TODO: \operatorname* -> with limits
681 arg, string = tex_token_or_group(string)
682 new_node = mi(arg, mathvariant='normal')
683 else:
684 new_node = mi(functions[name])
685 # embellished function names:
686 if name == 'varliminf': # \underline\lim
687 new_node = munder(new_node, mo('_'))
688 elif name == 'varlimsup': # \overline\lim
689 new_node = mover(new_node, mo('¯'), accent=False)
690 elif name == 'varprojlim': # \underleftarrow\lim
691 new_node = munder(new_node, mo('\u2190'))
692 elif name == 'varinjlim': # \underrightarrow\lim
693 new_node = munder(new_node, mo('\u2192'))
694
695 node = node.append(new_node)
696 # add ApplyFunction when appropriate (not \sin^2(x), say)
697 # cf. https://www.w3.org/TR/MathML3/chapter3.html#presm.mi
698 if string and string[0] not in ('^', '_'):
699 node = node.append(mo('\u2061')) # &ApplyFunction;
700 return node, string
701
702 if name in modulo_functions:
703 (binary, named, parentheses, padding) = modulo_functions[name]
704 if binary:
705 node = node.append(mo('mod', lspace=padding, rspace=padding))
706 return node, string
707 # left padding
708 if node.in_block():
709 padding = '1em'
710 node = node.append(mspace(width=padding))
711 if parentheses:
712 node = node.append(mo('(', stretchy=False))
713 if named:
714 node = node.append(mi('mod'))
715 node = node.append(mspace(width='0.333em'))
716 arg, string = tex_token_or_group(string)
717 node = parse_latex_math(node, arg)
718 if parentheses:
719 node = node.append(mo(')', stretchy=False))
720 return node, string
721
722 # font changes or mathematical alphanumeric characters
723
724 if name in ('boldsymbol', 'pmb'): # \pmb is "poor mans bold"
725 new_node = mrow(CLASS='boldsymbol')
726 node.append(new_node)
727 return new_node, string
728
729 if name in math_alphabets:
730 return handle_math_alphabet(name, node, string)
731
732 # operator, fence, or separator -> <mo>
733
734 if name == 'colon': # trailing punctuation, not binary relation
735 node = node.append(mo(':', form='postfix', lspace='0', rspace='0.28em'))
736 return node, string
737
738 if name == 'idotsint': # AMS shortcut for ∫︀···∫︀
739 node = parse_latex_math(node, r'\int\dotsi\int')
740 return node, string
741
742 if name in thick_operators:
743 node = node.append(mo(thick_operators[name], style='font-weight: bold'))
744 return node, string
745
746 if name in small_operators:
747 node = node.append(mo(small_operators[name], mathsize='75%'))
748 return node, string
749
750 if name in operators:
751 attributes = {}
752 if name in movablelimits and string and string[0] in ' _^':
753 attributes['movablelimits'] = True
754 elif name in ('lvert', 'lVert'):
755 attributes['class'] = 'mathopen'
756 node = node.append(mo(operators[name], **attributes))
757 return node, string
758
759 if name in bigdelimiters:
760 delimiter_attributes = {}
761 size = delimiter_sizes[bigdelimiters[name]]
762 delimiter, string = tex_token_or_group(string)
763 if delimiter not in '()[]/|.':
764 try:
765 delimiter = stretchables[delimiter.lstrip('\\')]
766 except KeyError:
767 raise MathError(f'Unsupported "\\{name}" delimiter '
768 f'"{delimiter}"!')
769 if size:
770 delimiter_attributes['maxsize'] = size
771 delimiter_attributes['minsize'] = size
772 delimiter_attributes['symmetric'] = True
773 if name == 'left' or name.endswith('l'):
774 row = mrow()
775 node.append(row)
776 node = row
777 if delimiter != '.': # '.' stands for "empty delimiter"
778 node.append(mo(delimiter, **delimiter_attributes))
779 if name == 'right' or name.endswith('r'):
780 node = node.close()
781 return node, string
782
783 if name == 'not':
784 # negation: LaTeX just overlays next symbol with "/".
785 arg, string = tex_token(string)
786 if arg == '{':
787 return node, '{\\not ' + string
788 if arg.startswith('\\'): # LaTeX macro
789 try:
790 arg = operators[arg[1:]]
791 except KeyError:
792 raise MathError(rf'"\not" cannot negate: "{arg}"!')
793 arg = unicodedata.normalize('NFC', arg+'\u0338')
794 node = node.append(mo(arg))
795 return node, string
796
797 # arbitrary text (usually comments) -> <mtext>
798 if name in ('text', 'mbox', 'textrm'):
799 arg, string = tex_token_or_group(string)
800 parts = arg.split('$') # extract inline math
801 for i, part in enumerate(parts):
802 if i % 2 == 0: # i is even
803 # LaTeX keeps whitespace in, e.g., ``\text{ foo }``,
804 # <mtext> displays only internal whitespace.
805 # → replace marginal whitespace with NBSP
806 part = re.sub('(^[ \n]|[ \n]$)', '\u00a0', part)
807 node = node.append(mtext(part))
808 else:
809 parse_latex_math(node, part)
810 return node, string
811
812 # horizontal space -> <mspace>
813 if name in spaces:
814 node = node.append(mspace(width='%s'%spaces[name]))
815 return node, string
816
817 if name in ('hspace', 'mspace'):
818 arg, string = tex_group(string)
819 if arg.endswith('mu'):
820 # unit "mu" (1mu=1/18em) not supported by MathML
821 arg = '%sem' % (float(arg[:-2])/18)
822 node = node.append(mspace(width='%s'%arg))
823 return node, string
824
825 if name == 'phantom':
826 new_node = mphantom()
827 node.append(new_node)
828 return new_node, string
829
830 if name == 'boxed':
831 # CSS padding is broken in Firefox 115.6.0esr
832 # therefore we still need the deprecated <menclose> element
833 new_node = menclose(notation='box', CLASS='boxed')
834 node.append(new_node)
835 return new_node, string
836
837 # Complex elements (Layout schemata)
838 # ==================================
839
840 if name == 'sqrt':
841 radix, string = tex_optarg(string)
842 if radix:
843 indexnode = mrow()
844 new_node = mroot(indexnode, switch=True)
845 parse_latex_math(indexnode, radix)
846 indexnode.close()
847 else:
848 new_node = msqrt()
849 node.append(new_node)
850 return new_node, string
851
852 if name in fractions:
853 attributes = fractions[name]
854 if name == 'cfrac':
855 optarg, string = tex_optarg(string)
856 optargs = {'l': 'left', 'r': 'right'}
857 if optarg in optargs:
858 attributes = attributes.copy()
859 attributes['numalign'] = optargs[optarg] # "numalign" is deprecated
860 attributes['class'] += ' numalign-' + optargs[optarg]
861 new_node = frac = mfrac(**attributes)
862 if name.endswith('binom'):
863 new_node = mrow(mo('('), new_node, mo(')'), CLASS='binom')
864 new_node.nchildren = 3
865 node.append(new_node)
866 return frac, string
867
868 if name == '\\': # end of a row
869 entry = mtd()
870 new_node = mtr(entry)
871 node.close().close().append(new_node)
872 return entry, string
873
874 if name in accents:
875 accent_node = mo(accents[name], stretchy=False)
876 # mi() would be simpler, but semantically wrong
877 # --- https://w3c.github.io/mathml-core/#operator-fence-separator-or-accent-mo
878 if name == 'vec':
879 accent_node.set('scriptlevel', '+1') # scale down arrow
880 new_node = mover(accent_node, accent=True, switch=True)
881 node.append(new_node)
882 return new_node, string
883
884 if name in over:
885 # set "accent" to False (otherwise dots on i and j are dropped)
886 # but to True on accent node get "textstyle" (full size) symbols on top
887 new_node = mover(mo(over[name][0], accent=True),
888 switch=True, accent=False)
889 node.append(new_node)
890 return new_node, string
891
892 if name == 'overset':
893 new_node = mover(switch=True)
894 node.append(new_node)
895 return new_node, string
896
897 if name in under:
898 new_node = munder(mo(under[name][0]), switch=True)
899 node.append(new_node)
900 return new_node, string
901
902 if name == 'underset':
903 new_node = munder(switch=True)
904 node.append(new_node)
905 return new_node, string
906
907 if name in ('xleftarrow', 'xrightarrow'):
908 subscript, string = tex_optarg(string)
909 base = mo(operators['long'+name[1:]])
910 if subscript:
911 new_node = munderover(base)
912 sub_node = parse_latex_math(mrow(), subscript)
913 if len(sub_node) == 1:
914 sub_node = sub_node[0]
915 new_node.append(sub_node)
916 else:
917 new_node = mover(base)
918 node.append(new_node)
919 return new_node, string
920
921 if name in layout_styles: # 'displaystyle', 'textstyle', ...
922 if len(node) > 0:
923 raise MathError(rf'Declaration "\{name}" must be first command '
924 'in a group!')
925 for k, v in layout_styles[name].items():
926 node.set(k, v)
927 return node, string
928
929 if name.endswith('limits'):
930 arg, remainder = tex_token(string)
931 if arg in '_^': # else ignore
932 string = remainder
933 node = handle_script_or_limit(node, arg, limits=name)
934 return node, string
935
936 # Environments
937
938 if name == 'begin':
939 return begin_environment(node, string)
940
941 if name == 'end':
942 return end_environment(node, string)
943
944 raise MathError(rf'Unknown LaTeX command "\{name}".')
945
946 # >>> handle_cmd('left', math(), '[a\\right]')
947 # (mrow(mo('[')), 'a\\right]')
948 # >>> handle_cmd('left', math(), '. a)') # empty \left
949 # (mrow(), ' a)')
950 # >>> handle_cmd('left', math(), '\\uparrow a)') # cmd
951 # (mrow(mo('↑')), 'a)')
952 # >>> handle_cmd('not', math(), '\\equiv \\alpha)') # cmd
953 # (math(mo('≢')), '\\alpha)')
954 # >>> handle_cmd('text', math(), '{ for } i>0') # group
955 # (math(mtext('\xa0for\xa0')), ' i>0')
956 # >>> handle_cmd('text', math(), '{B}T') # group
957 # (math(mtext('B')), 'T')
958 # >>> handle_cmd('text', math(), '{number of apples}}') # group
959 # (math(mtext('number of apples')), '}')
960 # >>> handle_cmd('text', math(), 'i \\sin(x)') # single char
961 # (math(mtext('i')), ' \\sin(x)')
962 # >>> handle_cmd(' ', math(), ' next') # inter word space
963 # (math(mspace(width='0.25em')), ' next')
964 # >>> handle_cmd('\n', math(), '\nnext') # inter word space
965 # (math(mspace(width='0.25em')), '\nnext')
966 # >>> handle_cmd('sin', math(), '(\\alpha)')
967 # (math(mi('sin'), mo('\u2061')), '(\\alpha)')
968 # >>> handle_cmd('sin', math(), ' \\alpha')
969 # (math(mi('sin'), mo('\u2061')), ' \\alpha')
970 # >>> handle_cmd('operatorname', math(), '{abs}(x)')
971 # (math(mi('abs', mathvariant='normal'), mo('\u2061')), '(x)')
972 # >>> handle_cmd('overline', math(), '{981}')
973 # (mover(mo('_', accent='true'), switch=True, accent='false'), '{981}')
974 # >>> handle_cmd('bar', math(), '{x}')
975 # (mover(mo('ˉ', stretchy='false'), switch=True, accent='true'), '{x}')
976 # >>> handle_cmd('xleftarrow', math(), r'[\alpha]{10}')
977 # (munderover(mo('⟵'), mi('α')), '{10}')
978 # >>> handle_cmd('xleftarrow', math(), r'[\alpha=5]{10}')
979 # (munderover(mo('⟵'), mrow(mi('α'), mo('='), mn('5'))), '{10}')
980 # >>> handle_cmd('left', math(), '< a)')
981 # Traceback (most recent call last):
982 # docutils.utils.math.MathError: Unsupported "\left" delimiter "<"!
983 # >>> handle_cmd('not', math(), '{< b} c') # LaTeX ignores the braces, too.
984 # (math(), '{\\not < b} c')
985
986
987 def handle_math_alphabet(name, node, string):
988 attributes = {}
989 if name == 'mathscr':
990 attributes['class'] = 'mathscr'
991 arg, string = tex_token_or_group(string)
992 # Shortcut for text arg like \mathrm{out} with more than one letter:
993 if name == 'mathrm' and arg.isalpha() and len(arg) > 1:
994 node = node.append(mi(arg)) # <mi> defaults to "normal" font
995 return node, string
996 # Parse into an <mrow>
997 container = mrow(**attributes)
998 node.append(container)
999 parse_latex_math(container, arg)
1000 key = name.replace('mathscr', 'mathcal').replace('mathbfsfit', 'mathsfbfit')
1001 a2ch = getattr(mathalphabet2unichar, key, {})
1002 for subnode in container.iter():
1003 if isinstance(subnode, mn):
1004 # a number may consist of more than one digit
1005 subnode.text = ''.join(a2ch.get(ch, ch) for ch in subnode.text)
1006 elif isinstance(subnode, mi):
1007 # don't convert multi-letter identifiers (functions)
1008 subnode.text = a2ch.get(subnode.text, subnode.text)
1009 if name == 'mathrm' and subnode.text.isalpha():
1010 subnode.set('mathvariant', 'normal')
1011 return container.close(), string
1012
1013 # >>> handle_math_alphabet('mathrm', math(), '\\alpha')
1014 # (math(mi('α', mathvariant='normal')), '')
1015 # >>> handle_math_alphabet('mathbb', math(), '{R} = 3')
1016 # (math(mi('ℝ')), ' = 3')
1017 # >>> handle_math_alphabet('mathcal', math(), '{F = 3}')
1018 # (math(mrow(mi('ℱ'), mo('='), mn('3'), nchildren=3)), '')
1019 # >>> handle_math_alphabet('mathrm', math(), '{out} = 3') # drop <mrow>
1020 # (math(mi('out')), ' = 3')
1021 #
1022 # Single letters in \mathrm require "mathvariant='normal'":
1023 # >>> handle_math_alphabet('mathrm', math(), '{V = 3}') # doctest: +ELLIPSIS
1024 # (math(mrow(mi('V', mathvariant='normal'), mo('='), mn('3'), ...)), '')
1025
1026
1027 def handle_script_or_limit(node, c, limits=''):
1028 """Append script or limit element to `node`."""
1029 child = node.pop()
1030 if limits == 'limits':
1031 child.set('movablelimits', 'false')
1032 elif (limits == 'movablelimits'
1033 or getattr(child, 'text', '') in movablelimits):
1034 child.set('movablelimits', 'true')
1035
1036 if c == '_':
1037 if isinstance(child, mover):
1038 new_node = munderover(*child, switch=True)
1039 elif isinstance(child, msup):
1040 new_node = msubsup(*child, switch=True)
1041 elif (limits in ('limits', 'movablelimits')
1042 or limits == '' and child.get('movablelimits', None)):
1043 new_node = munder(child)
1044 else:
1045 new_node = msub(child)
1046 elif c == '^':
1047 if isinstance(child, munder):
1048 new_node = munderover(*child)
1049 elif isinstance(child, msub):
1050 new_node = msubsup(*child)
1051 elif (limits in ('limits', 'movablelimits')
1052 or limits == '' and child.get('movablelimits', None)):
1053 new_node = mover(child)
1054 else:
1055 new_node = msup(child)
1056 node.append(new_node)
1057 return new_node
1058
1059
1060 def begin_environment(node, string):
1061 name, string = tex_group(string)
1062 if name in matrices:
1063 left_delimiter = matrices[name][0]
1064 attributes = {}
1065 if left_delimiter:
1066 wrapper = mrow(mo(left_delimiter))
1067 if name == 'cases':
1068 wrapper = mrow(mo(left_delimiter, rspace='0.17em'))
1069 attributes['columnalign'] = 'left'
1070 attributes['class'] = 'cases'
1071 node.append(wrapper)
1072 node = wrapper
1073 elif name == 'smallmatrix':
1074 attributes['rowspacing'] = '0.02em'
1075 attributes['columnspacing'] = '0.333em'
1076 attributes['scriptlevel'] = '1'
1077 elif name == 'aligned':
1078 attributes['class'] = 'ams-align'
1079 # TODO: array, aligned & alignedat take an optional [t], [b], or [c].
1080 entry = mtd()
1081 node.append(mtable(mtr(entry), **attributes))
1082 node = entry
1083 else:
1084 raise MathError(f'Environment "{name}" not supported!')
1085 return node, string
1086
1087
1088 def end_environment(node, string):
1089 name, string = tex_group(string)
1090 if name in matrices:
1091 node = node.close().close().close() # close: mtd, mdr, mtable
1092 right_delimiter = matrices[name][1]
1093 if right_delimiter:
1094 node = node.append(mo(right_delimiter))
1095 node = node.close()
1096 elif name == 'cases':
1097 node = node.close()
1098 else:
1099 raise MathError(f'Environment "{name}" not supported!')
1100 return node, string
1101
1102
1103 # Return the number of "equation_columns" in `code_lines`. cf. "alignat"
1104 # in http://mirror.ctan.org/macros/latex/required/amsmath/amsldoc.pdf
1105 def tex_equation_columns(rows):
1106 tabs = max(row.count('&') - row.count(r'\&') for row in rows)
1107 if tabs == 0:
1108 return 0
1109 return int(tabs/2 + 1)
1110
1111 # >>> tex_equation_columns(['a = b'])
1112 # 0
1113 # >>> tex_equation_columns(['a &= b'])
1114 # 1
1115 # >>> tex_equation_columns(['a &= b & a \in S'])
1116 # 2
1117 # >>> tex_equation_columns(['a &= b & c &= d'])
1118 # 2
1119
1120
1121 # Return dictionary with attributes to style an <mtable> as align environment:
1122 # Not used with HTML. Replaced by CSS rule for "mtable.ams-align" in
1123 # "minimal.css" as "columnalign" is disregarded by Chromium and webkit.
1124 def align_attributes(rows):
1125 atts = {'class': 'ams-align',
1126 'displaystyle': True}
1127 # get maximal number of non-escaped "next column" markup characters:
1128 tabs = max(row.count('&') - row.count(r'\&') for row in rows)
1129 if tabs:
1130 aligns = ['right', 'left'] * tabs
1131 spacing = ['0', '2em'] * tabs
1132 atts['columnalign'] = ' '.join(aligns[:tabs+1])
1133 atts['columnspacing'] = ' '.join(spacing[:tabs])
1134 return atts
1135
1136 # >>> align_attributes(['a = b'])
1137 # {'class': 'ams-align', 'displaystyle': True}
1138 # >>> align_attributes(['a &= b'])
1139 # {'class': 'ams-align', 'displaystyle': True, 'columnalign': 'right left', 'columnspacing': '0'}
1140 # >>> align_attributes(['a &= b & a \in S'])
1141 # {'class': 'ams-align', 'displaystyle': True, 'columnalign': 'right left right', 'columnspacing': '0 2em'}
1142 # >>> align_attributes(['a &= b & c &= d'])
1143 # {'class': 'ams-align', 'displaystyle': True, 'columnalign': 'right left right left', 'columnspacing': '0 2em 0'}
1144 # >>> align_attributes([r'a &= b & c &= d \& e'])
1145 # {'class': 'ams-align', 'displaystyle': True, 'columnalign': 'right left right left', 'columnspacing': '0 2em 0'}
1146 # >>> align_attributes([r'a &= b & c &= d & e'])
1147 # {'class': 'ams-align', 'displaystyle': True, 'columnalign': 'right left right left right', 'columnspacing': '0 2em 0 2em'}
1148
1149
1150 def tex2mathml(tex_math, as_block=False):
1151 """Return string with MathML code corresponding to `tex_math`.
1152
1153 Set `as_block` to ``True`` for displayed formulas.
1154 """
1155 # Set up tree
1156 math_tree = math(xmlns='http://www.w3.org/1998/Math/MathML')
1157 node = math_tree
1158 if as_block:
1159 math_tree.set('display', 'block')
1160 rows = toplevel_code(tex_math).split(r'\\')
1161 if len(rows) > 1:
1162 # emulate "align*" environment with a math table
1163 node = mtd()
1164 math_tree.append(mtable(mtr(node), CLASS='ams-align',
1165 displaystyle=True))
1166 parse_latex_math(node, tex_math)
1167 math_tree.indent_xml()
1168 return math_tree.toxml()
1169
1170 # >>> print(tex2mathml('3'))
1171 # <math xmlns="http://www.w3.org/1998/Math/MathML">
1172 # <mn>3</mn>
1173 # </math>
1174 # >>> print(tex2mathml('3', as_block=True))
1175 # <math xmlns="http://www.w3.org/1998/Math/MathML" display="block">
1176 # <mn>3</mn>
1177 # </math>
1178 # >>> print(tex2mathml(r'a & b \\ c & d', as_block=True))
1179 # <math xmlns="http://www.w3.org/1998/Math/MathML" display="block">
1180 # <mtable class="ams-align" displaystyle="true">
1181 # <mtr>
1182 # <mtd>
1183 # <mi>a</mi>
1184 # </mtd>
1185 # <mtd>
1186 # <mi>b</mi>
1187 # </mtd>
1188 # </mtr>
1189 # <mtr>
1190 # <mtd>
1191 # <mi>c</mi>
1192 # </mtd>
1193 # <mtd>
1194 # <mi>d</mi>
1195 # </mtd>
1196 # </mtr>
1197 # </mtable>
1198 # </math>
1199 # >>> print(tex2mathml(r'a \\ b', as_block=True))
1200 # <math xmlns="http://www.w3.org/1998/Math/MathML" display="block">
1201 # <mtable class="ams-align" displaystyle="true">
1202 # <mtr>
1203 # <mtd>
1204 # <mi>a</mi>
1205 # </mtd>
1206 # </mtr>
1207 # <mtr>
1208 # <mtd>
1209 # <mi>b</mi>
1210 # </mtd>
1211 # </mtr>
1212 # </mtable>
1213 # </math>
1214
1215
1216 # TODO: look up more symbols from tr25, e.g.
1217 #
1218 #
1219 # Table 2.8 Using Vertical Line or Solidus Overlay
1220 # some of the negated forms of mathematical relations that can only be
1221 # encoded by using either U+0338 COMBINING LONG SOLIDUS OVERLAY or U+20D2
1222 # COMBINING LONG VERTICAL LINE OVERLAY . (For issues with using 0338 in
1223 # MathML, see Section 3.2.7, Combining Marks.
1224 #
1225 # Table 2.9 Variants of Mathematical Symbols using VS1?
1226 #
1227 # Sequence Description
1228 # 0030 + VS1 DIGIT ZERO - short diagonal stroke form
1229 # 2205 + VS1 EMPTY SET - zero with long diagonal stroke overlay form
1230 # 2229 + VS1 INTERSECTION - with serifs
1231 # 222A + VS1 UNION - with serifs
1232 # 2268 + VS1 LESS-THAN BUT NOT EQUAL TO - with vertical stroke
1233 # 2269 + VS1 GREATER-THAN BUT NOT EQUAL TO - with vertical stroke
1234 # 2272 + VS1 LESS-THAN OR EQUIVALENT TO - following the slant of the lower leg
1235 # 2273 + VS1 GREATER-THAN OR EQUIVALENT TO - following the slant of the lower leg
1236 # 228A + VS1 SUBSET OF WITH NOT EQUAL TO - variant with stroke through bottom members
1237 # 228B + VS1 SUPERSET OF WITH NOT EQUAL TO - variant with stroke through bottom members
1238 # 2293 + VS1 SQUARE CAP - with serifs
1239 # 2294 + VS1 SQUARE CUP - with serifs
1240 # 2295 + VS1 CIRCLED PLUS - with white rim
1241 # 2297 + VS1 CIRCLED TIMES - with white rim
1242 # 229C + VS1 CIRCLED EQUALS - equal sign inside and touching the circle
1243 # 22DA + VS1 LESS-THAN slanted EQUAL TO OR GREATER-THAN
1244 # 22DB + VS1 GREATER-THAN slanted EQUAL TO OR LESS-THAN
1245 # 2A3C + VS1 INTERIOR PRODUCT - tall variant with narrow foot
1246 # 2A3D + VS1 RIGHTHAND INTERIOR PRODUCT - tall variant with narrow foot
1247 # 2A9D + VS1 SIMILAR OR LESS-THAN - following the slant of the upper leg
1248 # 2A9E + VS1 SIMILAR OR GREATER-THAN - following the slant of the upper leg
1249 # 2AAC + VS1 SMALLER THAN OR slanted EQUAL
1250 # 2AAD + VS1 LARGER THAN OR slanted EQUAL
1251 # 2ACB + VS1 SUBSET OF ABOVE NOT EQUAL TO - variant with stroke through bottom members
1252 # 2ACC + VS1 SUPERSET OF ABOVE NOT EQUAL TO - variant with stroke through bottom members