Debian Codegraph @

docutils/utils/math/__init__.py

raw symbols SCIP
1 # :Id: $Id: __init__.py 10136 2025-05-20 15:48:27Z milde $
2 # :Author: Guenter 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 # .. _2-Clause BSD license: https://opensource.org/licenses/BSD-2-Clause
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 # helpers for Docutils math support
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 # Wrap math-code in mode-switching TeX command/environment.
73 # If `as_block` is True, use environment for displayed equation(s).
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