| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
""" |
| 13 |
This is the Docutils (Python Documentation Utilities) "math" sub-package. |
| 14 |
|
| 15 |
It contains various modules for conversion between different math formats |
| 16 |
(LaTeX, MathML, HTML). |
| 17 |
|
| 18 |
:math2html: LaTeX math -> HTML conversion from eLyXer |
| 19 |
:latex2mathml: LaTeX math -> presentational MathML |
| 20 |
:unichar2tex: Unicode character to LaTeX math translation table |
| 21 |
:tex2unichar: LaTeX math to Unicode character translation dictionaries |
| 22 |
:mathalphabet2unichar: LaTeX math alphabets to Unicode character translation |
| 23 |
:tex2mathml_extern: Wrapper for 3rd party TeX -> MathML converters |
| 24 |
""" |
| 25 |
|
| 26 |
from __future__ import annotations |
| 27 |
|
| 28 |
__docformat__ = 'reStructuredText' |
| 29 |
|
| 30 |
|
| 31 |
|
| 32 |
|
| 33 |
|
| 34 |
class MathError(ValueError): |
| 35 |
"""Exception for math syntax and math conversion errors. |
| 36 |
|
| 37 |
The additional attribute `details` may hold a list of Docutils |
| 38 |
nodes suitable as children for a ``<system_message>``. |
| 39 |
""" |
| 40 |
def __init__(self, msg, details=[]) -> None: |
| 41 |
super().__init__(msg) |
| 42 |
self.details = details |
| 43 |
|
| 44 |
|
| 45 |
def toplevel_code(code): |
| 46 |
"""Return string (LaTeX math) `code` with environments stripped out.""" |
| 47 |
chunks = code.split(r'\begin{') |
| 48 |
return r'\begin{'.join(chunk.split(r'\end{')[-1] |
| 49 |
for chunk in chunks) |
| 50 |
|
| 51 |
|
| 52 |
def pick_math_environment(code, numbered=False): |
| 53 |
"""Return the right math environment to display `code`. |
| 54 |
|
| 55 |
The test simply looks for line-breaks (``\\``) outside environments. |
| 56 |
Multi-line formulae are set with ``align``, one-liners with |
| 57 |
``equation``. |
| 58 |
|
| 59 |
If `numbered` evaluates to ``False``, the "starred" versions are used |
| 60 |
to suppress numbering. |
| 61 |
""" |
| 62 |
if toplevel_code(code).find(r'\\') >= 0: |
| 63 |
env = 'align' |
| 64 |
else: |
| 65 |
env = 'equation' |
| 66 |
if not numbered: |
| 67 |
env += '*' |
| 68 |
return env |
| 69 |
|
| 70 |
|
| 71 |
def wrap_math_code(code, as_block) -> str: |
| 72 |
|
| 73 |
|
| 74 |
if as_block: |
| 75 |
env = pick_math_environment(code) |
| 76 |
return '\\begin{%s}\n%s\n\\end{%s}' % (env, code, env) |
| 77 |
return '$%s$' % code |