Debian Codegraph @

docutils/utils/math/mathml_elements.py

raw symbols SCIP
1 # :Id: $Id: mathml_elements.py 10136 2025-05-20 15:48:27Z milde $
2 # :Copyright: 2024 Günter Milde.
3 #
4 # :License: Released under the terms of the `2-Clause BSD license`_, in short:
5 #
6 # Copying and distribution of this file, with or without modification,
7 # are permitted in any medium without royalty provided the copyright
8 # notice and this notice are preserved.
9 # This file is offered as-is, without any warranty.
10 #
11 # .. _2-Clause BSD license: https://opensource.org/licenses/BSD-2-Clause
12
13 """MathML element classes based on `xml.etree`.
14
15 The module is intended for programmatic generation of MathML
16 and covers the part of `MathML Core`_ that is required by
17 Docutil's *TeX math to MathML* converter.
18
19 This module is PROVISIONAL:
20 the API is not settled and may change with any minor Docutils version.
21
22 .. _MathML Core: https://www.w3.org/TR/mathml-core/
23 """
24
25 from __future__ import annotations
26
27 __docformat__ = 'reStructuredText'
28
29 # Usage:
30 #
31 # >>> from mathml_elements import *
32
33 import numbers
34 import xml.etree.ElementTree as ET
35
36
37 GLOBAL_ATTRIBUTES = (
38 'class', # space-separated list of element classes
39 # 'data-*', # custom data attributes (see HTML)
40 'dir', # directionality ('ltr', 'rtl')
41 'displaystyle', # True: normal, False: compact
42 'id', # unique identifier
43 # 'mathbackground', # color definition, deprecated
44 # 'mathcolor', # color definition, deprecated
45 # 'mathsize', # font-size, deprecated
46 'nonce', # cryptographic nonce ("number used once")
47 'scriptlevel', # math-depth for the element
48 'style', # CSS styling declarations
49 'tabindex', # indicate if the element takes input focus
50 )
51 """Global MathML attributes
52
53 https://w3c.github.io/mathml-core/#global-attributes
54 """
55
56
57 # Base classes
58 # ------------
59
60 class MathElement(ET.Element):
61 """Base class for MathML elements."""
62
63 nchildren = None
64 """Expected number of children or None"""
65 # cf. https://www.w3.org/TR/MathML3/chapter3.html#id.3.1.3.2
66 parent = None
67 """Parent node in MathML element tree."""
68
69 def __init__(self, *children, **attributes) -> None:
70 """Set up node with `children` and `attributes`.
71
72 Attribute names are normalised to lowercase.
73 You may use "CLASS" to set a "class" attribute.
74 Attribute values are converted to strings
75 (with True -> "true" and False -> "false").
76
77 >>> math(CLASS='test', level=3, split=True)
78 math(class='test', level='3', split='true')
79 >>> math(CLASS='test', level=3, split=True).toxml()
80 '<math class="test" level="3" split="true"></math>'
81
82 """
83 attrib = {k.lower(): self.a_str(v) for k, v in attributes.items()}
84 super().__init__(self.__class__.__name__, **attrib)
85 self.extend(children)
86
87 @staticmethod
88 def a_str(v):
89 # Return string representation for attribute value `v`.
90 if isinstance(v, bool):
91 return str(v).lower()
92 return str(v)
93
94 def __repr__(self) -> str:
95 """Return full string representation."""
96 args = [repr(child) for child in self]
97 if self.text:
98 args.append(repr(self.text))
99 if self.nchildren != self.__class__.nchildren:
100 args.append(f'nchildren={self.nchildren}')
101 if getattr(self, 'switch', None):
102 args.append('switch=True')
103 args += [f'{k}={v!r}' for k, v in self.items() if v is not None]
104 return f'{self.tag}({", ".join(args)})'
105
106 def __str__(self) -> str:
107 """Return concise, informal string representation."""
108 if self.text:
109 args = repr(self.text)
110 else:
111 args = ', '.join(f'{child}' for child in self)
112 return f'{self.tag}({args})'
113
114 def set(self, key, value) -> None:
115 super().set(key, self.a_str(value))
116
117 def __setitem__(self, key, value) -> None:
118 if self.nchildren == 0:
119 raise TypeError(f'Element "{self}" does not take children.')
120 if isinstance(value, MathElement):
121 value.parent = self
122 else: # value may be an iterable
123 if self.nchildren and len(self) + len(value) > self.nchildren:
124 raise TypeError(f'Element "{self}" takes only {self.nchildren}'
125 ' children')
126 for e in value:
127 e.parent = self
128 super().__setitem__(key, value)
129
130 def is_full(self):
131 """Return boolean indicating whether children may be appended."""
132 return self.nchildren is not None and len(self) >= self.nchildren
133
134 def close(self):
135 """Close element and return first non-full anchestor or None."""
136 self.nchildren = len(self) # mark node as full
137 parent = self.parent
138 while parent is not None and parent.is_full():
139 parent = parent.parent
140 return parent
141
142 def append(self, element):
143 """Append `element` and return new "current node" (insertion point).
144
145 Append as child element and set the internal `parent` attribute.
146
147 If self is already full, raise TypeError.
148
149 If self is full after appending, call `self.close()`
150 (returns first non-full anchestor or None) else return `self`.
151 """
152 if self.is_full():
153 if self.nchildren:
154 status = f'takes only {self.nchildren} children'
155 else:
156 status = 'does not take children'
157 raise TypeError(f'Element "{self}" {status}.')
158 super().append(element)
159 element.parent = self
160 if self.is_full():
161 return self.close()
162 return self
163
164 def extend(self, elements):
165 """Sequentially append `elements`. Return new "current node".
166
167 Raise TypeError if overfull.
168 """
169 current_node = self
170 for element in elements:
171 current_node = self.append(element)
172 return current_node
173
174 def pop(self, index=-1):
175 element = self[index]
176 del self[index]
177 return element
178
179 def in_block(self):
180 """Return True, if `self` or an ancestor has ``display='block'``.
181
182 Used to find out whether we are in inline vs. displayed maths.
183 """
184 if self.get('display') is None:
185 try:
186 return self.parent.in_block()
187 except AttributeError:
188 return False
189 return self.get('display') == 'block'
190
191 # XML output:
192
193 def indent_xml(self, space=' ', level=0) -> None:
194 """Format XML output with indents.
195
196 Use with care:
197 Formatting whitespace is permanently added to the
198 `text` and `tail` attributes of `self` and anchestors!
199 """
200 ET.indent(self, space, level)
201
202 def unindent_xml(self) -> None:
203 """Strip whitespace at the end of `text` and `tail` attributes...
204
205 to revert changes made by the `indent_xml()` method.
206 Use with care, trailing whitespace from the original may be lost.
207 """
208 for e in self.iter():
209 if not isinstance(e, MathToken) and e.text:
210 e.text = e.text.rstrip()
211 if e.tail:
212 e.tail = e.tail.rstrip()
213
214 def toxml(self, encoding=None):
215 """Return an XML representation of the element.
216
217 By default, the return value is a `str` instance. With an explicit
218 `encoding` argument, the result is a `bytes` instance in the
219 specified encoding. The XML default encoding is UTF-8, any other
220 encoding must be specified in an XML document header.
221
222 Name and encoding handling match `xml.dom.minidom.Node.toxml()`
223 while `etree.Element.tostring()` returns `bytes` by default.
224 """
225 xml = ET.tostring(self, encoding or 'unicode',
226 short_empty_elements=False)
227 # Visible representation for "Apply Function" character:
228 try:
229 xml = xml.replace('\u2061', '&ApplyFunction;')
230 except TypeError:
231 xml = xml.replace('\u2061'.encode(encoding), b'&ApplyFunction;')
232 return xml
233
234
235 # Group sub-expressions in a horizontal row
236 #
237 # The elements <msqrt>, <mstyle>, <merror>, <mpadded>, <mphantom>,
238 # <menclose>, <mtd>, <mscarry>, and <math> treat their contents
239 # as a single inferred mrow formed from all their children.
240 # (https://www.w3.org/TR/mathml4/#presm_inferredmrow)
241 #
242 # MathML Core uses the term "anonymous mrow element".
243
244 class MathRow(MathElement):
245 """Base class for elements treating content as a single mrow."""
246
247
248 # 2d Schemata
249
250 class MathSchema(MathElement):
251 """Base class for schemata expecting 2 or more children.
252
253 The special attribute `switch` indicates that the last two child
254 elements are in reversed order and must be switched before XML-export.
255 See `msub` for an example.
256 """
257 nchildren = 2
258
259 def __init__(self, *children, **kwargs) -> None:
260 self.switch = kwargs.pop('switch', False)
261 super().__init__(*children, **kwargs)
262
263 def append(self, element):
264 """Append element. Normalize order and close if full."""
265 current_node = super().append(element)
266 if self.switch and self.is_full():
267 self[-1], self[-2] = self[-2], self[-1]
268 self.switch = False
269 return current_node
270
271
272 # Token elements represent the smallest units of mathematical notation which
273 # carry meaning.
274
275 class MathToken(MathElement):
276 """Token Element: contains textual data instead of children.
277
278 Expect text data on initialisation.
279 """
280 nchildren = 0
281
282 def __init__(self, text, **attributes) -> None:
283 super().__init__(**attributes)
284 if not isinstance(text, (str, numbers.Number)):
285 raise ValueError('MathToken element expects `str` or number,'
286 f' not "{text}".')
287 self.text = str(text)
288
289
290 # MathML element classes
291 # ----------------------
292
293 class math(MathRow):
294 """Top-level MathML element, a single mathematical formula."""
295
296
297 # Token elements
298 # ~~~~~~~~~~~~~~
299
300 class mtext(MathToken):
301 """Arbitrary text with no notational meaning."""
302
303
304 class mi(MathToken):
305 """Identifier, such as a function name, variable or symbolic constant."""
306
307
308 class mn(MathToken):
309 """Numeric literal.
310
311 >>> mn(3.41).toxml()
312 '<mn>3.41</mn>'
313
314 Normally a sequence of digits with a possible separator (a dot or a comma).
315 (Values with comma must be specified as `str`.)
316 """
317
318
319 class mo(MathToken):
320 """Operator, Fence, Separator, or Accent.
321
322 >>> mo('<').toxml()
323 '<mo>&lt;</mo>'
324
325 Besides operators in strict mathematical meaning, this element also
326 includes "operators" like parentheses, separators like comma and
327 semicolon, or "absolute value" bars.
328 """
329
330
331 class mspace(MathElement):
332 """Blank space, whose size is set by its attributes.
333
334 Takes additional attributes `depth`, `height`, `width`.
335 Takes no children and no text.
336
337 See also `mphantom`.
338 """
339 nchildren = 0
340
341
342 # General Layout Schemata
343 # ~~~~~~~~~~~~~~~~~~~~~~~
344
345 class mrow(MathRow):
346 """Generic element to group children as a horizontal row.
347
348 Removed on closing if not required (see `mrow.close()`).
349 """
350
351 def transfer_attributes(self, other) -> None:
352 """Transfer attributes from self to other.
353
354 "List values" (class, style) are appended to existing values,
355 other values replace existing values.
356 """
357 delimiters = {'class': ' ', 'style': '; '}
358 for k, v in self.items():
359 if k in ('class', 'style') and v:
360 if other.get(k):
361 v = delimiters[k].join(
362 (other.get(k).rstrip(delimiters[k]), v))
363 other.set(k, v)
364
365 def close(self):
366 """Close element and return first non-full anchestor or None.
367
368 Remove <mrow> if it has only one child element.
369 """
370 parent = self.parent
371 # replace `self` with single child
372 if parent is not None and len(self) == 1:
373 child = self[0]
374 try:
375 parent[list(parent).index(self)] = child
376 child.parent = parent
377 except (AttributeError, ValueError):
378 return None
379 self.transfer_attributes(child)
380 return super().close()
381
382
383 class mfrac(MathSchema):
384 """Fractions or fraction-like objects such as binomial coefficients."""
385
386
387 class msqrt(MathRow):
388 """Square root. See also `mroot`."""
389 nchildren = 1 # \sqrt expects one argument or a group
390
391
392 class mroot(MathSchema):
393 """Roots with an explicit index. See also `msqrt`."""
394
395
396 class mstyle(MathRow):
397 """Style Change.
398
399 In modern browsers, <mstyle> is equivalent to an <mrow> element.
400 However, <mstyle> may still be relevant for compatibility with
401 MathML implementations outside browsers.
402 """
403
404
405 class merror(MathRow):
406 """Display contents as error messages."""
407
408
409 class menclose(MathRow):
410 """Renders content inside an enclosing notation...
411
412 ... specified by the notation attribute.
413
414 Non-standard but still required by Firefox for boxed expressions.
415 """
416 nchildren = 1 # \boxed expects one argument or a group
417
418
419 class mpadded(MathRow):
420 """Adjust space around content."""
421 # nchildren = 1 # currently not used by latex2mathml
422
423
424 class mphantom(MathRow):
425 """Placeholder: Rendered invisibly but dimensions are kept."""
426 nchildren = 1 # \phantom expects one argument or a group
427
428
429 # Script and Limit Schemata
430 # ~~~~~~~~~~~~~~~~~~~~~~~~~
431
432 class msub(MathSchema):
433 """Attach a subscript to an expression."""
434
435
436 class msup(MathSchema):
437 """Attach a superscript to an expression."""
438
439
440 class msubsup(MathSchema):
441 """Attach both a subscript and a superscript to an expression."""
442 nchildren = 3
443
444 # Examples:
445 #
446 # The `switch` attribute reverses the order of the last two children:
447 # >>> msub(mn(1), mn(2)).toxml()
448 # '<msub><mn>1</mn><mn>2</mn></msub>'
449 # >>> msub(mn(1), mn(2), switch=True).toxml()
450 # '<msub><mn>2</mn><mn>1</mn></msub>'
451 #
452 # >>> msubsup(mi('base'), mn(1), mn(2)).toxml()
453 # '<msubsup><mi>base</mi><mn>1</mn><mn>2</mn></msubsup>'
454 # >>> msubsup(mi('base'), mn(1), mn(2), switch=True).toxml()
455 # '<msubsup><mi>base</mi><mn>2</mn><mn>1</mn></msubsup>'
456
457
458 class munder(msub):
459 """Attach an accent or a limit under an expression."""
460
461
462 class mover(msup):
463 """Attach an accent or a limit over an expression."""
464
465
466 class munderover(msubsup):
467 """Attach accents or limits both under and over an expression."""
468
469
470 # Tabular Math
471 # ~~~~~~~~~~~~
472
473 class mtable(MathElement):
474 """Table or matrix element."""
475
476
477 class mtr(MathRow):
478 """Row in a table or a matrix."""
479
480
481 class mtd(MathRow):
482 """Cell in a table or a matrix"""