| 1 |
|
| 2 |
]_ |
| 3 |
e. |
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 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 |
|
| 23 |
|
| 24 |
|
| 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 |
|
| 38 |
|
| 39 |
|
| 40 |
|
| 41 |
|
| 42 |
|
| 43 |
|
| 44 |
|
| 45 |
letters = {'hbar': 'ℏ'} ħ |
| 46 |
ℏ. |
| 47 |
letters.update(tex2unichar.mathalpha) |
| 48 |
|
| 49 |
ordinary = tex2unichar.mathord |
| 50 |
|
| 51 |
|
| 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 |
|
| 59 |
functions = { |
| 60 |
|
| 61 |
'liminf': 'lim\u202finf', |
| 62 |
'limsup': 'lim\u202fsup', |
| 63 |
'injlim': 'inj\u202flim', |
| 64 |
'projlim': 'proj\u202flim', |
| 65 |
|
| 66 |
'varlimsup': 'lim', |
| 67 |
'varliminf': 'lim', |
| 68 |
'varprojlim': 'lim', |
| 69 |
'varinjlim': 'lim', |
| 70 |
|
| 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 |
|
| 80 |
|
| 81 |
|
| 82 |
|
| 83 |
modulo_functions = { |
| 84 |
|
| 85 |
'bmod': (True, True, False, '0.278em'), |
| 86 |
'pmod': (False, True, True, '0.444em'), |
| 87 |
'mod': (False, True, False, '0.667em'), |
| 88 |
'pod': (False, False, True, '0.444em'), |
| 89 |
} |
| 90 |
|
| 91 |
|
| 92 |
|
| 93 |
|
| 94 |
math_alphabets = { |
| 95 |
|
| 96 |
'mathbb': 'double-struck', |
| 97 |
'mathbf': 'bold', |
| 98 |
'mathbfit': 'bold-italic', |
| 99 |
'mathcal': 'script', |
| 100 |
'mathfrak': 'fraktur', |
| 101 |
'mathit': 'italic', |
| 102 |
'mathrm': 'normal', |
| 103 |
'mathscr': 'script', |
| 104 |
'mathsf': 'sans-serif', |
| 105 |
'mathbfsfit': 'sans-serif-bold-italic', |
| 106 |
'mathsfbfit': 'sans-serif-bold-italic', |
| 107 |
'mathsfit': 'sans-serif-italic', |
| 108 |
'mathtt': 'monospace', |
| 109 |
|
| 110 |
|
| 111 |
|
| 112 |
} |
| 113 |
|
| 114 |
|
| 115 |
|
| 116 |
stretchables = { |
| 117 |
|
| 118 |
'backslash': '\\', |
| 119 |
'uparrow': '\u2191', OW |
| 120 |
'downarrow': '\u2193', OW |
| 121 |
'updownarrow': '\u2195', OW |
| 122 |
'Uparrow': '\u21d1', OW |
| 123 |
'Downarrow': '\u21d3', OW |
| 124 |
'Updownarrow': '\u21d5', OW |
| 125 |
'lmoustache': '\u23b0', TION |
| 126 |
'rmoustache': '\u23b1', TION |
| 127 |
'arrowvert': '\u23d0', ON |
| 128 |
'bracevert': '\u23aa', ON |
| 129 |
'lvert': '|', |
| 130 |
'lVert': '\u2016', ‖ |
| 131 |
'rvert': '|', |
| 132 |
'rVert': '\u2016', ‖ |
| 133 |
'Arrowvert': '\u2016', ‖ |
| 134 |
} |
| 135 |
stretchables.update(tex2unichar.mathfence) |
| 136 |
stretchables.update(tex2unichar.mathopen) |
| 137 |
stretchables.update(tex2unichar.mathclose) |
| 138 |
|
| 139 |
|
| 140 |
⌟ ⎪ ⎰ ⎱ ⏐ ⟅ ⟆ ⟦ ⟧ ⟨ ⟩ ⟮ ⟯ ⦇ ⦈ |
| 141 |
|
| 142 |
operators = { |
| 143 |
|
| 144 |
'nleqq': '\u2266\u0338', ≦̸ |
| 145 |
'ngeqq': '\u2267\u0338', ≧̸ |
| 146 |
'nleqslant': '\u2a7d\u0338', ⩽̸ |
| 147 |
'ngeqslant': '\u2a7e\u0338', ⩾̸ |
| 148 |
'ngtrless': '\u2277\u0338', |
| 149 |
'nlessgtr': '\u2276\u0338', |
| 150 |
'nsubseteqq': '\u2AC5\u0338', ⫅̸ |
| 151 |
'nsupseteqq': '\u2AC6\u0338', ⫆̸ |
| 152 |
|
| 153 |
'centerdot': '\u2B1D', |
| 154 |
'varnothing': '\u2300', et |
| 155 |
'varpropto': '\u221d', if |
| 156 |
'triangle': '\u25B3', |
| 157 |
'triangledown': '\u25BD', |
| 158 |
|
| 159 |
'dotsb': '\u22ef', ns |
| 160 |
'dotsc': '\u2026', as |
| 161 |
'dotsi': '\u22ef', ls |
| 162 |
'dotsm': '\u22ef', ts |
| 163 |
'dotso': '\u2026', ts |
| 164 |
|
| 165 |
'lim': 'lim', |
| 166 |
'sup': 'sup', |
| 167 |
'inf': 'inf', |
| 168 |
'max': 'max', |
| 169 |
'min': 'min', |
| 170 |
} |
| 171 |
operators.update(tex2unichar.mathbin) |
| 172 |
operators.update(tex2unichar.mathrel) |
| 173 |
operators.update(tex2unichar.mathpunct) |
| 174 |
operators.update(tex2unichar.mathop) |
| 175 |
operators.update(stretchables) |
| 176 |
|
| 177 |
|
| 178 |
|
| 179 |
|
| 180 |
thick_operators = { |
| 181 |
|
| 182 |
'thicksim': '\u223C', ∼ |
| 183 |
'thickapprox': '\u2248', ≈ |
| 184 |
} |
| 185 |
|
| 186 |
small_operators = { |
| 187 |
|
| 188 |
'shortmid': '\u2223', ∣ |
| 189 |
'shortparallel': '\u2225', ∥ |
| 190 |
'nshortmid': '\u2224', ∤ |
| 191 |
'nshortparallel': '\u2226', ∦ |
| 192 |
'smallfrown': '\u2322', WN |
| 193 |
'smallsmile': '\u2323', LE |
| 194 |
'smallint': '\u222b', AL |
| 195 |
} |
| 196 |
|
| 197 |
|
| 198 |
|
| 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 |
|
| 204 |
|
| 205 |
|
| 206 |
|
| 207 |
|
| 208 |
|
| 209 |
|
| 210 |
|
| 211 |
|
| 212 |
spaces = {'qquad': '2em', |
| 213 |
'quad': '1em', |
| 214 |
'thickspace': '0.2778em', |
| 215 |
';': '0.2778em', |
| 216 |
' ': '0.25em', |
| 217 |
'\n': '0.25em', |
| 218 |
'medspace': '0.2222em', |
| 219 |
':': '0.2222em', |
| 220 |
'thinspace': '0.1667em', |
| 221 |
',': '0.1667em', |
| 222 |
'negthinspace': '-0.1667em', |
| 223 |
'!': '-0.1667em', |
| 224 |
'negmedspace': '-0.2222em', |
| 225 |
'negthickspace': '-0.2778em', |
| 226 |
} |
| 227 |
|
| 228 |
|
| 229 |
accents = { |
| 230 |
|
| 231 |
'acute': '´', ' |
| 232 |
'bar': 'ˉ', ' |
| 233 |
'breve': '˘', ' |
| 234 |
'check': 'ˇ', ' |
| 235 |
'dot': '˙', ' |
| 236 |
'ddot': '¨', ' |
| 237 |
'dddot': '˙˙˙',… ? |
| 238 |
'ddddot': '˙˙˙˙¨¨ ? |
| 239 |
'grave': '`', |
| 240 |
'hat': 'ˆ', ' |
| 241 |
'mathring': '˚', ' |
| 242 |
'tilde': '~', ? |
| 243 |
'vec': '→', "+1" |
| 244 |
} |
| 245 |
|
| 246 |
|
| 247 |
over = { |
| 248 |
|
| 249 |
'overbrace': ('\u23DE', -0.2), |
| 250 |
'overleftarrow': ('\u2190', -0.2), |
| 251 |
'overleftrightarrow': ('\u2194', -0.2), |
| 252 |
'overline': ('_', -0.2), |
| 253 |
'overrightarrow': ('\u2192', -0.2), |
| 254 |
'widehat': ('^', -0.5), |
| 255 |
'widetilde': ('~', -0.3), |
| 256 |
} |
| 257 |
under = {'underbrace': ('\u23DF', 0.1), |
| 258 |
'underleftarrow': ('\u2190', -0.2), |
| 259 |
'underleftrightarrow': ('\u2194', -0.2), |
| 260 |
'underline': ('_', -0.8), |
| 261 |
'underrightarrow': ('\u2192', -0.2), |
| 262 |
} |
| 263 |
|
| 264 |
|
| 265 |
|
| 266 |
|
| 267 |
|
| 268 |
anomalous_chars = {'-': '\u2212', |
| 269 |
':': '\u2236', |
| 270 |
'~': '\u00a0', |
| 271 |
} |
| 272 |
|
| 273 |
|
| 274 |
mathbb = {'Γ': '\u213E', ℾ |
| 275 |
'Π': '\u213F', ℿ |
| 276 |
'Σ': '\u2140', ⅀ |
| 277 |
'γ': '\u213D', ℽ |
| 278 |
'π': '\u213C', ℼ |
| 279 |
} |
| 280 |
|
| 281 |
|
| 282 |
matrices = { |
| 283 |
|
| 284 |
'matrix': ('', ''), |
| 285 |
'smallmatrix': ('', ''), |
| 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 |
|
| 302 |
|
| 303 |
fractions = { |
| 304 |
|
| 305 |
'frac': {}, |
| 306 |
'cfrac': {'displaystyle': True, 'scriptlevel': 0, |
| 307 |
'class': 'cfrac'}, |
| 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 |
|
| 330 |
|
| 331 |
|
| 332 |
|
| 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 |
|
| 353 |
|
| 354 |
|
| 355 |
|
| 356 |
|
| 357 |
|
| 358 |
|
| 359 |
|
| 360 |
|
| 361 |
|
| 362 |
|
| 363 |
|
| 364 |
|
| 365 |
|
| 366 |
|
| 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 |
|
| 384 |
|
| 385 |
|
| 386 |
|
| 387 |
|
| 388 |
|
| 389 |
|
| 390 |
|
| 391 |
|
| 392 |
|
| 393 |
|
| 394 |
|
| 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 |
|
| 415 |
|
| 416 |
|
| 417 |
|
| 418 |
|
| 419 |
|
| 420 |
|
| 421 |
|
| 422 |
|
| 423 |
|
| 424 |
|
| 425 |
|
| 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 |
| 437 |
escape = False |
| 438 |
|
| 439 |
if not string.startswith('{'): |
| 440 |
|
| 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 |
|
| 460 |
|
| 461 |
|
| 462 |
|
| 463 |
|
| 464 |
|
| 465 |
|
| 466 |
|
| 467 |
|
| 468 |
|
| 469 |
|
| 470 |
|
| 471 |
|
| 472 |
|
| 473 |
|
| 474 |
|
| 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 |
|
| 496 |
|
| 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 |
|
| 520 |
|
| 521 |
|
| 522 |
|
| 523 |
|
| 524 |
|
| 525 |
|
| 526 |
|
| 527 |
|
| 528 |
|
| 529 |
|
| 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 |
|
| 542 |
string = source |
| 543 |
node = root |
| 544 |
|
| 545 |
|
| 546 |
while len(string) > 0: |
| 547 |
|
| 548 |
c, string = string[0], string[1:] |
| 549 |
|
| 550 |
if c in ' \n': |
| 551 |
continue |
| 552 |
if c == '\\': |
| 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 |
|
| 560 |
node.nchildren = None |
| 561 |
else: |
| 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 |
|
| 578 |
|
| 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 |
|
| 593 |
if node is None: |
| 594 |
if not string: |
| 595 |
return root |
| 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 |
|
| 603 |
|
| 604 |
|
| 605 |
|
| 606 |
|
| 607 |
) |
| 608 |
|
| 609 |
|
| 610 |
|
| 611 |
)) |
| 612 |
|
| 613 |
|
| 614 |
|
| 615 |
|
| 616 |
|
| 617 |
|
| 618 |
|
| 619 |
|
| 620 |
|
| 621 |
)) |
| 622 |
|
| 623 |
) |
| 624 |
|
| 625 |
|
| 626 |
') |
| 627 |
|
| 628 |
"! |
| 629 |
|
| 630 |
|
| 631 |
|
| 632 |
|
| 633 |
|
| 634 |
|
| 635 |
|
| 636 |
|
| 637 |
|
| 638 |
|
| 639 |
def handle_cmd(name, node, string): |
| 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 |
|
| 654 |
|
| 655 |
|
| 656 |
|
| 657 |
|
| 658 |
if name in letters: |
| 659 |
new_node = mi(letters[name]) |
| 660 |
if name in greek_capitals: |
| 661 |
|
| 662 |
|
| 663 |
|
| 664 |
new_node.set('class', 'capital-greek') |
| 665 |
node = node.append(new_node) |
| 666 |
return node, string |
| 667 |
|
| 668 |
if name in ordinary: |
| 669 |
|
| 670 |
|
| 671 |
t ∂t |
| 672 |
|
| 673 |
return node.append(mi(ordinary[name])), string |
| 674 |
|
| 675 |
if name in functions: |
| 676 |
|
| 677 |
|
| 678 |
if name == 'operatorname': |
| 679 |
|
| 680 |
|
| 681 |
arg, string = tex_token_or_group(string) |
| 682 |
new_node = mi(arg, mathvariant='normal') |
| 683 |
else: |
| 684 |
new_node = mi(functions[name]) |
| 685 |
|
| 686 |
if name == 'varliminf': |
| 687 |
new_node = munder(new_node, mo('_')) |
| 688 |
elif name == 'varlimsup': |
| 689 |
new_node = mover(new_node, mo('¯'), accent=False) |
| 690 |
elif name == 'varprojlim': |
| 691 |
new_node = munder(new_node, mo('\u2190')) |
| 692 |
elif name == 'varinjlim': |
| 693 |
new_node = munder(new_node, mo('\u2192')) |
| 694 |
|
| 695 |
node = node.append(new_node) |
| 696 |
|
| 697 |
|
| 698 |
if string and string[0] not in ('^', '_'): |
| 699 |
node = node.append(mo('\u2061')) |
| 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 |
|
| 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 |
|
| 723 |
|
| 724 |
if name in ('boldsymbol', 'pmb'): |
| 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 |
|
| 733 |
|
| 734 |
if name == 'colon': |
| 735 |
node = node.append(mo(':', form='postfix', lspace='0', rspace='0.28em')) |
| 736 |
return node, string |
| 737 |
|
| 738 |
if name == 'idotsint': ···∫︀ |
| 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 != '.': |
| 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 |
|
| 785 |
arg, string = tex_token(string) |
| 786 |
if arg == '{': |
| 787 |
return node, '{\\not ' + string |
| 788 |
if arg.startswith('\\'): |
| 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 |
|
| 798 |
if name in ('text', 'mbox', 'textrm'): |
| 799 |
arg, string = tex_token_or_group(string) |
| 800 |
parts = arg.split('$') |
| 801 |
for i, part in enumerate(parts): |
| 802 |
if i % 2 == 0: |
| 803 |
|
| 804 |
|
| 805 |
SP |
| 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 |
|
| 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 |
|
| 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 |
|
| 832 |
|
| 833 |
new_node = menclose(notation='box', CLASS='boxed') |
| 834 |
node.append(new_node) |
| 835 |
return new_node, string |
| 836 |
|
| 837 |
|
| 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] |
| 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 == '\\': |
| 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 |
|
| 877 |
|
| 878 |
if name == 'vec': |
| 879 |
accent_node.set('scriptlevel', '+1') |
| 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 |
|
| 886 |
|
| 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: |
| 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 '_^': |
| 932 |
string = remainder |
| 933 |
node = handle_script_or_limit(node, arg, limits=name) |
| 934 |
return node, string |
| 935 |
|
| 936 |
|
| 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 |
|
| 947 |
|
| 948 |
|
| 949 |
|
| 950 |
|
| 951 |
') |
| 952 |
|
| 953 |
') |
| 954 |
|
| 955 |
|
| 956 |
|
| 957 |
|
| 958 |
|
| 959 |
|
| 960 |
|
| 961 |
|
| 962 |
|
| 963 |
|
| 964 |
|
| 965 |
|
| 966 |
|
| 967 |
|
| 968 |
|
| 969 |
|
| 970 |
|
| 971 |
|
| 972 |
|
| 973 |
|
| 974 |
|
| 975 |
) |
| 976 |
|
| 977 |
}') |
| 978 |
|
| 979 |
}') |
| 980 |
|
| 981 |
|
| 982 |
|
| 983 |
|
| 984 |
|
| 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 |
|
| 993 |
if name == 'mathrm' and arg.isalpha() and len(arg) > 1: |
| 994 |
node = node.append(mi(arg)) |
| 995 |
return node, string |
| 996 |
|
| 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 |
|
| 1005 |
subnode.text = ''.join(a2ch.get(ch, ch) for ch in subnode.text) |
| 1006 |
elif isinstance(subnode, mi): |
| 1007 |
|
| 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 |
|
| 1014 |
) |
| 1015 |
|
| 1016 |
') |
| 1017 |
|
| 1018 |
') |
| 1019 |
|
| 1020 |
|
| 1021 |
|
| 1022 |
|
| 1023 |
|
| 1024 |
|
| 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 |
|
| 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() |
| 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 |
|
| 1104 |
|
| 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 |
|
| 1112 |
|
| 1113 |
|
| 1114 |
|
| 1115 |
|
| 1116 |
|
| 1117 |
|
| 1118 |
|
| 1119 |
|
| 1120 |
|
| 1121 |
|
| 1122 |
|
| 1123 |
|
| 1124 |
def align_attributes(rows): |
| 1125 |
atts = {'class': 'ams-align', |
| 1126 |
'displaystyle': True} |
| 1127 |
|
| 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 |
|
| 1137 |
|
| 1138 |
|
| 1139 |
|
| 1140 |
|
| 1141 |
|
| 1142 |
|
| 1143 |
|
| 1144 |
|
| 1145 |
|
| 1146 |
|
| 1147 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 1171 |
|
| 1172 |
|
| 1173 |
|
| 1174 |
|
| 1175 |
|
| 1176 |
|
| 1177 |
|
| 1178 |
|
| 1179 |
|
| 1180 |
|
| 1181 |
|
| 1182 |
|
| 1183 |
|
| 1184 |
|
| 1185 |
|
| 1186 |
|
| 1187 |
|
| 1188 |
|
| 1189 |
|
| 1190 |
|
| 1191 |
|
| 1192 |
|
| 1193 |
|
| 1194 |
|
| 1195 |
|
| 1196 |
|
| 1197 |
|
| 1198 |
|
| 1199 |
|
| 1200 |
|
| 1201 |
|
| 1202 |
|
| 1203 |
|
| 1204 |
|
| 1205 |
|
| 1206 |
|
| 1207 |
|
| 1208 |
|
| 1209 |
|
| 1210 |
|
| 1211 |
|
| 1212 |
|
| 1213 |
|
| 1214 |
|
| 1215 |
|
| 1216 |
|
| 1217 |
|
| 1218 |
|
| 1219 |
|
| 1220 |
|
| 1221 |
|
| 1222 |
|
| 1223 |
|
| 1224 |
|
| 1225 |
|
| 1226 |
|
| 1227 |
|
| 1228 |
|
| 1229 |
|
| 1230 |
|
| 1231 |
|
| 1232 |
|
| 1233 |
|
| 1234 |
|
| 1235 |
|
| 1236 |
|
| 1237 |
|
| 1238 |
|
| 1239 |
|
| 1240 |
|
| 1241 |
|
| 1242 |
|
| 1243 |
|
| 1244 |
|
| 1245 |
|
| 1246 |
|
| 1247 |
|
| 1248 |
|
| 1249 |
|
| 1250 |
|
| 1251 |
|
| 1252 |
|