Drop support for Python 2.3.
[docutils.git] / docutils / math / latex2mathml.py
blob8b10ce1ea2575acc79f5106711079fdaee5c24ad
1 #!/usr/bin/env python
2 # -*- coding: utf8 -*-
4 # :Id: $Id$
5 # :Copyright: © 2010 Günter Milde.
6 # Based on rst2mathml.py from the latex_math sandbox project
7 # © 2005 Jens Jørgen Mortensen
8 # :License: Released under the terms of the `2-Clause BSD license`_, in short:
9 #
10 # Copying and distribution of this file, with or without modification,
11 # are permitted in any medium without royalty provided the copyright
12 # notice and this notice are preserved.
13 # This file is offered as-is, without any warranty.
15 # .. _2-Clause BSD license: http://www.spdx.org/licenses/BSD-2-Clause
18 """Convert LaTex math code into presentational MathML"""
20 # Based on the `latex_math` sandbox project by Jens Jørgen Mortensen
22 import docutils.math.tex2unichar as tex2unichar
24 # TeX spacing combining
25 over = {'acute': u'\u00B4', # u'\u0301',
26 'bar': u'\u00AF', # u'\u0304',
27 'breve': u'\u02D8', # u'\u0306',
28 'check': u'\u02C7', # u'\u030C',
29 'dot': u'\u02D9', # u'\u0307',
30 'ddot': u'\u00A8', # u'\u0308',
31 'dddot': u'\u20DB',
32 'grave': u'`', # u'\u0300',
33 'hat': u'^', # u'\u0302',
34 'mathring': u'\u02DA', # u'\u030A',
35 'overleftrightarrow': u'\u20e1',
36 # 'overline': # u'\u0305',
37 'tilde': u'\u02DC', # u'\u0303',
38 'vec': u'\u20D7'}
40 Greek = { # Capital Greek letters: (upright in TeX style)
41 'Phi':u'\u03a6', 'Xi':u'\u039e', 'Sigma':u'\u03a3',
42 'Psi':u'\u03a8', 'Delta':u'\u0394', 'Theta':u'\u0398',
43 'Upsilon':u'\u03d2', 'Pi':u'\u03a0', 'Omega':u'\u03a9',
44 'Gamma':u'\u0393', 'Lambda':u'\u039b'}
46 letters = tex2unichar.mathalpha
48 special = tex2unichar.mathbin # Binary symbols
49 special.update(tex2unichar.mathrel) # Relation symbols, arrow symbols
50 special.update(tex2unichar.mathord) # Miscellaneous symbols
51 special.update(tex2unichar.mathop) # Variable-sized symbols
52 special.update(tex2unichar.mathopen) # Braces
53 special.update(tex2unichar.mathclose) # Braces
54 special.update(tex2unichar.mathfence)
56 sumintprod = ''.join([special[symbol] for symbol in
57 ['sum', 'int', 'oint', 'prod']])
59 functions = ['arccos', 'arcsin', 'arctan', 'arg', 'cos', 'cosh',
60 'cot', 'coth', 'csc', 'deg', 'det', 'dim',
61 'exp', 'gcd', 'hom', 'inf', 'ker', 'lg',
62 'lim', 'liminf', 'limsup', 'ln', 'log', 'max',
63 'min', 'Pr', 'sec', 'sin', 'sinh', 'sup',
64 'tan', 'tanh',
65 'injlim', 'varinjlim', 'varlimsup',
66 'projlim', 'varliminf', 'varprojlim']
69 mathbb = {
70 'A': u'\U0001D538',
71 'B': u'\U0001D539',
72 'C': u'\u2102',
73 'D': u'\U0001D53B',
74 'E': u'\U0001D53C',
75 'F': u'\U0001D53D',
76 'G': u'\U0001D53E',
77 'H': u'\u210D',
78 'I': u'\U0001D540',
79 'J': u'\U0001D541',
80 'K': u'\U0001D542',
81 'L': u'\U0001D543',
82 'M': u'\U0001D544',
83 'N': u'\u2115',
84 'O': u'\U0001D546',
85 'P': u'\u2119',
86 'Q': u'\u211A',
87 'R': u'\u211D',
88 'S': u'\U0001D54A',
89 'T': u'\U0001D54B',
90 'U': u'\U0001D54C',
91 'V': u'\U0001D54D',
92 'W': u'\U0001D54E',
93 'X': u'\U0001D54F',
94 'Y': u'\U0001D550',
95 'Z': u'\u2124',
98 mathscr = {
99 'A': u'\U0001D49C',
100 'B': u'\u212C', # bernoulli function
101 'C': u'\U0001D49E',
102 'D': u'\U0001D49F',
103 'E': u'\u2130',
104 'F': u'\u2131',
105 'G': u'\U0001D4A2',
106 'H': u'\u210B', # hamiltonian
107 'I': u'\u2110',
108 'J': u'\U0001D4A5',
109 'K': u'\U0001D4A6',
110 'L': u'\u2112', # lagrangian
111 'M': u'\u2133', # physics m-matrix
112 'N': u'\U0001D4A9',
113 'O': u'\U0001D4AA',
114 'P': u'\U0001D4AB',
115 'Q': u'\U0001D4AC',
116 'R': u'\u211B',
117 'S': u'\U0001D4AE',
118 'T': u'\U0001D4AF',
119 'U': u'\U0001D4B0',
120 'V': u'\U0001D4B1',
121 'W': u'\U0001D4B2',
122 'X': u'\U0001D4B3',
123 'Y': u'\U0001D4B4',
124 'Z': u'\U0001D4B5',
125 'a': u'\U0001D4B6',
126 'b': u'\U0001D4B7',
127 'c': u'\U0001D4B8',
128 'd': u'\U0001D4B9',
129 'e': u'\u212F',
130 'f': u'\U0001D4BB',
131 'g': u'\u210A',
132 'h': u'\U0001D4BD',
133 'i': u'\U0001D4BE',
134 'j': u'\U0001D4BF',
135 'k': u'\U0001D4C0',
136 'l': u'\U0001D4C1',
137 'm': u'\U0001D4C2',
138 'n': u'\U0001D4C3',
139 'o': u'\u2134', # order of
140 'p': u'\U0001D4C5',
141 'q': u'\U0001D4C6',
142 'r': u'\U0001D4C7',
143 's': u'\U0001D4C8',
144 't': u'\U0001D4C9',
145 'u': u'\U0001D4CA',
146 'v': u'\U0001D4CB',
147 'w': u'\U0001D4CC',
148 'x': u'\U0001D4CD',
149 'y': u'\U0001D4CE',
150 'z': u'\U0001D4CF',
153 negatables = {'=': u'\u2260',
154 '\in': u'\u2209',
155 '\equiv': u'\u2262'}
157 # LaTeX to MathML translation stuff:
158 class math:
159 """Base class for MathML elements."""
161 nchildren = 1000000
162 """Required number of children"""
164 def __init__(self, children=None, inline=None):
165 """math([children]) -> MathML element
167 children can be one child or a list of children."""
169 self.children = []
170 if children is not None:
171 if type(children) is list:
172 for child in children:
173 self.append(child)
174 else:
175 # Only one child:
176 self.append(children)
178 if inline is not None:
179 self.inline = inline
181 def __repr__(self):
182 if hasattr(self, 'children'):
183 return self.__class__.__name__ + '(%s)' % \
184 ','.join([repr(child) for child in self.children])
185 else:
186 return self.__class__.__name__
188 def full(self):
189 """Room for more children?"""
191 return len(self.children) >= self.nchildren
193 def append(self, child):
194 """append(child) -> element
196 Appends child and returns self if self is not full or first
197 non-full parent."""
199 assert not self.full()
200 self.children.append(child)
201 child.parent = self
202 node = self
203 while node.full():
204 node = node.parent
205 return node
207 def delete_child(self):
208 """delete_child() -> child
210 Delete last child and return it."""
212 child = self.children[-1]
213 del self.children[-1]
214 return child
216 def close(self):
217 """close() -> parent
219 Close element and return first non-full element."""
221 parent = self.parent
222 while parent.full():
223 parent = parent.parent
224 return parent
226 def xml(self):
227 """xml() -> xml-string"""
229 return self.xml_start() + self.xml_body() + self.xml_end()
231 def xml_start(self):
232 if not hasattr(self, 'inline'):
233 return ['<%s>' % self.__class__.__name__]
234 xmlns = 'http://www.w3.org/1998/Math/MathML'
235 if self.inline:
236 return ['<math xmlns="%s">' % xmlns]
237 else:
238 return ['<math xmlns="%s" mode="display">' % xmlns]
240 def xml_end(self):
241 return ['</%s>' % self.__class__.__name__]
243 def xml_body(self):
244 xml = []
245 for child in self.children:
246 xml.extend(child.xml())
247 return xml
249 class mrow(math):
250 def xml_start(self):
251 return ['\n<%s>' % self.__class__.__name__]
253 class mtable(math):
254 def xml_start(self):
255 return ['\n<%s>' % self.__class__.__name__]
257 class mtr(mrow): pass
258 class mtd(mrow): pass
260 class mx(math):
261 """Base class for mo, mi, and mn"""
263 nchildren = 0
264 def __init__(self, data):
265 self.data = data
267 def xml_body(self):
268 return [self.data]
270 class mo(mx):
271 translation = {'<': '&lt;', '>': '&gt;'}
272 def xml_body(self):
273 return [self.translation.get(self.data, self.data)]
275 class mi(mx): pass
276 class mn(mx): pass
278 class msub(math):
279 nchildren = 2
281 class msup(math):
282 nchildren = 2
284 class msqrt(math):
285 nchildren = 1
287 class mroot(math):
288 nchildren = 2
290 class mfrac(math):
291 nchildren = 2
293 class msubsup(math):
294 nchildren = 3
295 def __init__(self, children=None, reversed=False):
296 self.reversed = reversed
297 math.__init__(self, children)
299 def xml(self):
300 if self.reversed:
301 ## self.children[1:3] = self.children[2:0:-1]
302 self.children[1:3] = [self.children[2], self.children[1]]
303 self.reversed = False
304 return math.xml(self)
306 class mfenced(math):
307 translation = {'\\{': '{', '\\langle': u'\u2329',
308 '\\}': '}', '\\rangle': u'\u232A',
309 '.': ''}
310 def __init__(self, par):
311 self.openpar = par
312 math.__init__(self)
314 def xml_start(self):
315 open = self.translation.get(self.openpar, self.openpar)
316 close = self.translation.get(self.closepar, self.closepar)
317 return ['<mfenced open="%s" close="%s">' % (open, close)]
319 class mspace(math):
320 nchildren = 0
322 class mstyle(math):
323 def __init__(self, children=None, nchildren=None, **kwargs):
324 if nchildren is not None:
325 self.nchildren = nchildren
326 math.__init__(self, children)
327 self.attrs = kwargs
329 def xml_start(self):
330 return ['<mstyle '] + ['%s="%s"' % item
331 for item in self.attrs.items()] + ['>']
333 class mover(math):
334 nchildren = 2
335 def __init__(self, children=None, reversed=False):
336 self.reversed = reversed
337 math.__init__(self, children)
339 def xml(self):
340 if self.reversed:
341 self.children.reverse()
342 self.reversed = False
343 return math.xml(self)
345 class munder(math):
346 nchildren = 2
348 class munderover(math):
349 nchildren = 3
350 def __init__(self, children=None):
351 math.__init__(self, children)
353 class mtext(math):
354 nchildren = 0
355 def __init__(self, text):
356 self.text = text
358 def xml_body(self):
359 return [self.text]
361 def parse_latex_math(string, inline=True):
362 """parse_latex_math(string [,inline]) -> MathML-tree
364 Returns a MathML-tree parsed from string. inline=True is for
365 inline math and inline=False is for displayed math.
367 tree is the whole tree and node is the current element."""
369 # Normalize white-space:
370 string = ' '.join(string.split())
372 if inline:
373 node = mrow()
374 tree = math(node, inline=True)
375 else:
376 node = mtd()
377 tree = math(mtable(mtr(node)), inline=False)
379 while len(string) > 0:
380 n = len(string)
381 c = string[0]
382 skip = 1 # number of characters consumed
383 if n > 1:
384 c2 = string[1]
385 else:
386 c2 = ''
387 ## print n, string, c, c2, node.__class__.__name__
388 if c == ' ':
389 pass
390 elif c == '\\':
391 if c2 in '{}':
392 node = node.append(mo(c2))
393 skip = 2
394 elif c2 == ' ':
395 node = node.append(mspace())
396 skip = 2
397 elif c2 == ',': # TODO: small space
398 node = node.append(mspace())
399 skip = 2
400 elif c2.isalpha():
401 # We have a LaTeX-name:
402 i = 2
403 while i < n and string[i].isalpha():
404 i += 1
405 name = string[1:i]
406 node, skip = handle_keyword(name, node, string[i:])
407 skip += i
408 elif c2 == '\\':
409 # End of a row:
410 entry = mtd()
411 row = mtr(entry)
412 node.close().close().append(row)
413 node = entry
414 skip = 2
415 else:
416 raise SyntaxError(ur'Syntax error: "%s%s"' % (c, c2))
417 elif c.isalpha():
418 node = node.append(mi(c))
419 elif c.isdigit():
420 node = node.append(mn(c))
421 elif c in "+-*/=()[]|<>,.!?':;@":
422 node = node.append(mo(c))
423 elif c == '_':
424 child = node.delete_child()
425 if isinstance(child, msup):
426 sub = msubsup(child.children, reversed=True)
427 elif isinstance(child, mo) and child.data in sumintprod:
428 sub = munder(child)
429 else:
430 sub = msub(child)
431 node.append(sub)
432 node = sub
433 elif c == '^':
434 child = node.delete_child()
435 if isinstance(child, msub):
436 sup = msubsup(child.children)
437 elif isinstance(child, mo) and child.data in sumintprod:
438 sup = mover(child)
439 elif (isinstance(child, munder) and
440 child.children[0].data in sumintprod):
441 sup = munderover(child.children)
442 else:
443 sup = msup(child)
444 node.append(sup)
445 node = sup
446 elif c == '{':
447 row = mrow()
448 node.append(row)
449 node = row
450 elif c == '}':
451 node = node.close()
452 elif c == '&':
453 entry = mtd()
454 node.close().append(entry)
455 node = entry
456 else:
457 raise SyntaxError(ur'Illegal character: "%s"' % c)
458 string = string[skip:]
459 return tree
462 def handle_keyword(name, node, string):
463 skip = 0
464 if len(string) > 0 and string[0] == ' ':
465 string = string[1:]
466 skip = 1
467 if name == 'begin':
468 if not string.startswith('{matrix}'):
469 raise SyntaxError(u'Environment not supported! '
470 u'Supported environment: "matrix".')
471 skip += 8
472 entry = mtd()
473 table = mtable(mtr(entry))
474 node.append(table)
475 node = entry
476 elif name == 'end':
477 if not string.startswith('{matrix}'):
478 raise SyntaxError(ur'Expected "\end{matrix}"!')
479 skip += 8
480 node = node.close().close().close()
481 elif name in ('text', 'mathrm'):
482 if string[0] != '{':
483 raise SyntaxError(ur'Expected "\text{...}"!')
484 i = string.find('}')
485 if i == -1:
486 raise SyntaxError(ur'Expected "\text{...}"!')
487 node = node.append(mtext(string[1:i]))
488 skip += i + 1
489 elif name == 'sqrt':
490 sqrt = msqrt()
491 node.append(sqrt)
492 node = sqrt
493 elif name == 'frac':
494 frac = mfrac()
495 node.append(frac)
496 node = frac
497 elif name == 'left':
498 for par in ['(', '[', '|', '\\{', '\\langle', '.']:
499 if string.startswith(par):
500 break
501 else:
502 raise SyntaxError(u'Missing left-brace!')
503 fenced = mfenced(par)
504 node.append(fenced)
505 row = mrow()
506 fenced.append(row)
507 node = row
508 skip += len(par)
509 elif name == 'right':
510 for par in [')', ']', '|', '\\}', '\\rangle', '.']:
511 if string.startswith(par):
512 break
513 else:
514 raise SyntaxError(u'Missing right-brace!')
515 node = node.close()
516 node.closepar = par
517 node = node.close()
518 skip += len(par)
519 elif name == 'not':
520 for operator in negatables:
521 if string.startswith(operator):
522 break
523 else:
524 raise SyntaxError(ur'Expected something to negate: "\not ..."!')
525 node = node.append(mo(negatables[operator]))
526 skip += len(operator)
527 elif name == 'mathbf':
528 style = mstyle(nchildren=1, fontweight='bold')
529 node.append(style)
530 node = style
531 elif name == 'mathbb':
532 if string[0] != '{' or not string[1].isupper() or string[2] != '}':
533 raise SyntaxError(ur'Expected something like "\mathbb{A}"!')
534 node = node.append(mi(mathbb[string[1]]))
535 skip += 3
536 elif name in ('mathscr', 'mathcal'):
537 if string[0] != '{' or string[2] != '}':
538 raise SyntaxError(ur'Expected something like "\mathscr{A}"!')
539 node = node.append(mi(mathscr[string[1]]))
540 skip += 3
541 elif name == 'colon': # "normal" colon, not binary operator
542 node = node.append(mo(':')) # TODO: add ``lspace="0pt"``
543 elif name in Greek: # Greek capitals (upright in "TeX style")
544 node = node.append(mo(Greek[name]))
545 # TODO: "ISO style" sets them italic. Could we use a class argument
546 # to enable styling via CSS?
547 elif name in letters:
548 node = node.append(mi(letters[name]))
549 elif name in special:
550 node = node.append(mo(special[name]))
551 elif name in functions:
552 node = node.append(mo(name))
553 elif name in over:
554 ovr = mover(mo(over[name]), reversed=True)
555 node.append(ovr)
556 node = ovr
557 else:
558 raise SyntaxError(u'Unknown LaTeX command: ' + name)
560 return node, skip