Debian Codegraph @

docutils/utils/math/tex2mathml_extern.py

raw symbols SCIP
1 # :Id: $Id: tex2mathml_extern.py 10136 2025-05-20 15:48:27Z milde $
2 # :Copyright: © 2015 Günter Milde.
3 # :License: Released under the terms of the `2-Clause BSD license`__, in short:
4 #
5 # Copying and distribution of this file, with or without modification,
6 # are permitted in any medium without royalty provided the copyright
7 # notice and this notice are preserved.
8 # This file is offered as-is, without any warranty.
9 #
10 # __ https://opensource.org/licenses/BSD-2-Clause
11
12 """Wrappers for TeX->MathML conversion by external tools
13
14 This module is provisional:
15 the API is not settled and may change with any minor Docutils version.
16 """
17
18 from __future__ import annotations
19
20 __docformat__ = 'reStructuredText'
21
22 import subprocess
23
24 from docutils import nodes
25 from docutils.utils.math import MathError, wrap_math_code
26
27 # `latexml` expects a complete document:
28 document_template = r"""\documentclass{article}
29 \begin{document}
30 %s
31 \end{document}
32 """
33
34
35 def _check_result(result, details=[]):
36 # raise MathError if the conversion went wrong
37 # :details: list of doctree nodes with additional info
38 msg = ''
39 if not details and result.stderr:
40 details = [nodes.paragraph('', result.stderr, classes=['pre-wrap'])]
41 if details:
42 msg = f'TeX to MathML converter `{result.args[0]}` failed:'
43 elif result.returncode:
44 msg = (f'TeX to MathMl converter `{result.args[0]}` '
45 f'exited with Errno {result.returncode}.')
46 elif not result.stdout:
47 msg = f'TeX to MathML converter `{result.args[0]}` returned no MathML.'
48 if msg:
49 raise MathError(msg, details=details)
50
51
52 def blahtexml(math_code, as_block=False) -> str:
53 """Convert LaTeX math code to MathML with blahtexml__.
54
55 __ http://gva.noekeon.org/blahtexml/
56 """
57 args = ['blahtexml',
58 '--mathml',
59 '--indented',
60 '--spacing', 'moderate',
61 '--mathml-encoding', 'raw',
62 '--other-encoding', 'raw',
63 '--doctype-xhtml+mathml',
64 '--annotate-TeX',
65 ]
66 # "blahtexml" expects LaTeX code without math-mode-switch.
67 # We still need to tell it about displayed equation(s).
68 mathml_args = ' display="block"' if as_block else ''
69 _wrapped = wrap_math_code(math_code, as_block)
70 if '{align*}' in _wrapped:
71 math_code = _wrapped.replace('{align*}', '{aligned}')
72
73 result = subprocess.run(args, input=math_code,
74 capture_output=True, text=True)
75
76 # blahtexml writes <error> messages to stdout
77 if '<error>' in result.stdout:
78 result.stderr = result.stdout[result.stdout.find('<message>')+9:
79 result.stdout.find('</message>')]
80 else:
81 result.stdout = result.stdout[result.stdout.find('<markup>')+9:
82 result.stdout.find('</markup>')]
83 _check_result(result)
84 return (f'<math xmlns="http://www.w3.org/1998/Math/MathML"{mathml_args}>'
85 f'\n{result.stdout}</math>')
86
87
88 def latexml(math_code, as_block=False):
89 """Convert LaTeX math code to MathML with LaTeXML__.
90
91 Comprehensive macro support but **very** slow.
92
93 __ http://dlmf.nist.gov/LaTeXML/
94 """
95
96 # LaTeXML works in 2 stages, expects complete documents.
97 #
98 # The `latexmlmath`__ convenience wrapper does not support block-level
99 # (displayed) equations.
100 #
101 # __ https://metacpan.org/dist/LaTeXML/view/bin/latexmlmath
102 args1 = ['latexml',
103 '-', # read from stdin
104 '--preload=amsmath',
105 '--preload=amssymb', # also loads amsfonts
106 '--inputencoding=utf8',
107 '--',
108 ]
109 math_code = document_template % wrap_math_code(math_code, as_block)
110 error_tags = ('Error:', 'Warning:', 'Fatal:')
111
112 result1 = subprocess.run(args1, input=math_code,
113 capture_output=True, text=True)
114 if result1.stderr:
115 result1.stderr = '\n'.join(line for line in result1.stderr.splitlines()
116 if line.startswith(error_tags))
117 _check_result(result1)
118
119 args2 = ['latexmlpost',
120 '-',
121 '--nonumbersections',
122 '--format=html5', # maths included as MathML
123 '--omitdoctype', # Make it simple, we only need the maths.
124 '--noscan', # ...
125 '--nocrossref',
126 '--nographicimages',
127 '--nopictureimages',
128 '--nodefaultresources', # do not copy *.css files to output dir
129 '--'
130 ]
131 result2 = subprocess.run(args2, input=result1.stdout,
132 capture_output=True, text=True)
133 # Extract MathML from HTML document:
134 # <table> with <math> in cells for "align", <math> element else.
135 start = result2.stdout.find('<table class="ltx_equationgroup')
136 if start != -1:
137 stop = result2.stdout.find('</table>', start)+8
138 result2.stdout = result2.stdout[start:stop].replace(
139 'ltx_equationgroup', 'borderless align-center')
140 else:
141 result2.stdout = result2.stdout[result2.stdout.find('<math'):
142 result2.stdout.find('</math>')+7]
143 # Search for error messages
144 if result2.stdout:
145 _msg_source = result2.stdout # latexmlpost reports errors in output
146 else:
147 _msg_source = result2.stderr # just in case
148 result2.stderr = '\n'.join(line for line in _msg_source.splitlines()
149 if line.startswith(error_tags))
150 _check_result(result2)
151 return result2.stdout
152
153
154 def pandoc(math_code, as_block=False):
155 """Convert LaTeX math code to MathML with pandoc__.
156
157 __ https://pandoc.org/
158 """
159 args = ['pandoc',
160 '--mathml',
161 '--from=latex',
162 ]
163 result = subprocess.run(args, input=wrap_math_code(math_code, as_block),
164 capture_output=True, text=True)
165
166 result.stdout = result.stdout[result.stdout.find('<math'):
167 result.stdout.find('</math>')+7]
168 # Pandoc (2.9.2.1) messages are pre-formatted for the terminal:
169 # 1. summary
170 # 2. math source (part)
171 # 3. error spot indicator '^' (works only in a literal block)
172 # 4. assumed problem
173 # 5. assumed solution (may be wrong or confusing)
174 # Construct a "details" list:
175 details = []
176 if result.stderr:
177 lines = result.stderr.splitlines()
178 details += [nodes.paragraph('', lines[0]),
179 nodes.literal_block('', '\n'.join(lines[1:3])),
180 nodes.paragraph('', '\n'.join(lines[3:]),
181 classes=['pre-wrap']),
182 ]
183 _check_result(result, details=details)
184 return result.stdout
185
186
187 def ttm(math_code, as_block=False):
188 """Convert LaTeX math code to MathML with TtM__.
189
190 Aged, limited, but fast.
191
192 __ http://silas.psfc.mit.edu/tth/mml/
193 """
194 args = ['ttm',
195 '-L', # source is LaTeX snippet
196 '-r'] # output MathML snippet
197 math_code = wrap_math_code(math_code, as_block)
198
199 # "ttm" does not support UTF-8 input. (Docutils converts most math
200 # characters to LaTeX commands before calling this function.)
201 try:
202 result = subprocess.run(args, input=math_code,
203 capture_output=True, text=True,
204 encoding='ISO-8859-1')
205 except UnicodeEncodeError as err:
206 raise MathError(err)
207
208 result.stdout = result.stdout[result.stdout.find('<math'):
209 result.stdout.find('</math>')+7]
210 if as_block:
211 result.stdout = result.stdout.replace('<math xmlns=',
212 '<math display="block" xmlns=')
213 result.stderr = '\n'.join(line[5:] + '.'
214 for line in result.stderr.splitlines()
215 if line.startswith('**** '))
216 _check_result(result)
217 return result.stdout
218
219
220 # self-test
221
222 if __name__ == "__main__":
223 example = (r'\frac{\partial \sin^2(\alpha)}{\partial \vec r}'
224 r'\varpi \mathbb{R} \, \text{Grüße}')
225
226 print("""<!DOCTYPE html>
227 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
228 <head>
229 <title>test external mathml converters</title>
230 </head>
231 <body>
232 <p>Test external converters</p>
233 <p>
234 """)
235 print(f'latexml: {latexml(example)},')
236 print(f'ttm: {ttm(example.replace("mathbb", "mathbf"))},')
237 print(f'blahtexml: {blahtexml(example)},')
238 print(f'pandoc: {pandoc(example)}.')
239 print('</p>')
240
241 print('<p>latexml:</p>')
242 print(latexml(example, as_block=True))
243 print('<p>ttm:</p>')
244 print(ttm(example.replace('mathbb', 'mathbf'), as_block=True))
245 print('<p>blahtexml:</p>')
246 print(blahtexml(example, as_block=True))
247 print('<p>pandoc:</p>')
248 print(pandoc(example, as_block=True))
249
250 print('</main>\n</body>\n</html>')
251
252 buggy = r'\sinc \phy'
253 # buggy = '\sqrt[e]'
254 try:
255 # print(blahtexml(buggy))
256 # print(latexml(f'${buggy}$'))
257 print(pandoc(f'${buggy}$'))
258 # print(ttm(f'${buggy}$'))
259 except MathError as err:
260 print(err)
261 print(err.details)
262 for node in err.details:
263 print(node.astext())