summaryrefslogtreecommitdiffstats
path: root/sphinx/util/math.py
blob: 97b8440b67e9f22a63366e25dc3e06a29061fe59 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
"""Utility functions for math."""

from __future__ import annotations

from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from docutils import nodes

    from sphinx.builders.html import HTML5Translator


def get_node_equation_number(writer: HTML5Translator, node: nodes.math_block) -> str:
    if writer.builder.config.math_numfig and writer.builder.config.numfig:
        figtype = 'displaymath'
        if writer.builder.name == 'singlehtml':
            key = f"{writer.docnames[-1]}/{figtype}"  # type: ignore[has-type]
        else:
            key = figtype

        id = node['ids'][0]
        number = writer.builder.fignumbers.get(key, {}).get(id, ())
        return '.'.join(map(str, number))
    else:
        return node['number']


def wrap_displaymath(text: str, label: str | None, numbering: bool) -> str:
    def is_equation(part: str) -> str:
        return part.strip()

    if label is None:
        labeldef = ''
    else:
        labeldef = r'\label{%s}' % label
        numbering = True

    parts = list(filter(is_equation, text.split('\n\n')))
    equations = []
    if len(parts) == 0:
        return ''
    elif len(parts) == 1:
        if numbering:
            begin = r'\begin{equation}' + labeldef
            end = r'\end{equation}'
        else:
            begin = r'\begin{equation*}' + labeldef
            end = r'\end{equation*}'
        equations.append('\\begin{split}%s\\end{split}\n' % parts[0])
    else:
        if numbering:
            begin = r'\begin{align}%s\!\begin{aligned}' % labeldef
            end = r'\end{aligned}\end{align}'
        else:
            begin = r'\begin{align*}%s\!\begin{aligned}' % labeldef
            end = r'\end{aligned}\end{align*}'
        equations.extend('%s\\\\\n' % part.strip() for part in parts)

    concatenated_equations = ''.join(equations)
    return f'{begin}\n{concatenated_equations}{end}'