File: extension.py

package info (click to toggle)
sympy 1.7.1-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, sid
  • size: 37,052 kB
  • sloc: python: 426,614; xml: 359; sh: 318; makefile: 138; lisp: 4
file content (62 lines) | stat: -rw-r--r-- 2,333 bytes parent folder | download
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
61
62
from __future__ import print_function
import os
import sys

from .math_dollar import split_dollars

from docutils.nodes import GenericNodeVisitor, Text, math, FixedTextElement, literal
from docutils.transforms import Transform

NODE_BLACKLIST = node_blacklist = (FixedTextElement, literal, math)

DEBUG = bool(os.environ.get("MATH_DOLLAR_DEBUG", False))

class MathDollarReplacer(GenericNodeVisitor):
    def default_visit(self, node):
        return node

    def visit_Text(self, node):
        parent = node.parent
        while parent:
            if isinstance(parent, node_blacklist):
                if DEBUG and any(i == 'math' for i, _ in split_dollars(node.rawsource)):
                    print("sphinx-math-dollar: Skipping", node, "(node_blacklist = %s)" % (node_blacklist,), file=sys.stderr)
                return
            parent = parent.parent
        data = split_dollars(node.rawsource)
        nodes = []
        has_math = False
        for typ, text in data:
            if typ == "math":
                has_math = True
                nodes.append(math(text, Text(text)))
            elif typ == "text":
                nodes.append(Text(text))
            else:
                raise ValueError("Unrecognized type from split_dollars %r" % typ)
        if has_math:
            node.parent.replace(node, nodes)

class TransformMath(Transform):
    # See http://docutils.sourceforge.net/docs/ref/transforms.html. We want it
    # to apply before things that change rawsource, since we have to use that
    # to get the version of the text with backslashes. I'm not sure which all
    # transforms are relevant here, other than SmartQuotes, so this may need
    # to be adjusted.
    default_priority = 500
    def apply(self, **kwargs):
        self.document.walk(MathDollarReplacer(self.document))

def config_inited(app, config):
    global node_blacklist, DEBUG
    node_blacklist = config.math_dollar_node_blacklist
    DEBUG = config.math_dollar_debug

def setup(app):
    app.add_transform(TransformMath)
    # We can't force a rebuild here because it will always appear different
    # since the tuple contains classes
    app.add_config_value('math_dollar_node_blacklist', NODE_BLACKLIST, '')
    app.add_config_value('math_dollar_debug', DEBUG, '')

    app.connect('config-inited', config_inited)