Debian Codegraph @

doc/sphinx/_extensions/dollarmath.py

raw
1 # This program is public domain
2 # Author: Paul Kienzle
3 r"""
4 Allow $math$ markup in text and docstrings, ignoring \$.
5
6 The $math$ markup should be separated from the surrounding text by spaces.
7 To embed markup within a word, place backslash-space before and after. For
8 convenience, the final $ can be followed by punctuation (period, comma or
9 semicolon).
10 """
11
12 import re
13
14 _DOLLAR = re.compile(
15 r"(?:^|(?<=\s|[-(]))[$]([^\n]*?)(?<![\\])[$](?:$|(?=\s|[-.,;:?\\)]))")
16 _NOTDOLLAR = re.compile(r"\\[$]")
17
18 def replace_dollar(content):
19 #original = content
20 content = _DOLLAR.sub(r":math:`\1`", content)
21 content = _NOTDOLLAR.sub("$", content)
22 #if '$' in content:
23 # import sys
24 # sys.stdout.write("\n========> not converted\n")
25 # sys.stdout.write(content)
26 # sys.stdout.write("\n")
27 #elif '$' in original:
28 # import sys
29 # sys.stdout.write("\n========> converted\n")
30 # sys.stdout.write(content)
31 # sys.stdout.write("\n")
32 return content
33
34 def rewrite_rst(app, docname, source):
35 source[0] = replace_dollar(source[0])
36
37 def rewrite_autodoc(app, what, name, obj, options, lines):
38 lines[:] = [replace_dollar(L) for L in lines]
39
40 def setup(app):
41 app.connect('source-read', rewrite_rst)
42 app.connect('autodoc-process-docstring', rewrite_autodoc)
43
44
45 def test_dollar():
46 assert replace_dollar(u"no dollar") == u"no dollar"
47 assert replace_dollar(u"$only$") == u":math:`only`"
48 assert replace_dollar(u"$first$ is good") == u":math:`first` is good"
49 assert replace_dollar(u"so is $last$") == u"so is :math:`last`"
50 assert replace_dollar(u"and $mid$ too") == u"and :math:`mid` too"
51 assert (replace_dollar(u"$first$, $mid$, $last$")
52 == u":math:`first`, :math:`mid`, :math:`last`")
53 assert replace_dollar(u"dollar\\$ escape") == u"dollar$ escape"
54 assert replace_dollar(u"dollar \\$escape\\$ too") == u"dollar $escape$ too"
55 assert (replace_dollar(u"spaces $in the$ math")
56 == u"spaces :math:`in the` math")
57 assert replace_dollar(u"emb\\ $ed$\\ ed") == u"emb\\ :math:`ed`\\ ed"
58 assert replace_dollar(u"$first$a") == u"$first$a"
59 assert replace_dollar(u"a$last$") == u"a$last$"
60 assert replace_dollar(u"$37") == u"$37"
61 assert replace_dollar(u"($37)") == u"($37)"
62 assert replace_dollar(u"$37 - $43") == u"$37 - $43"
63 assert replace_dollar(u"($37, $38)") == u"($37, $38)"
64 assert replace_dollar(u"a $mid$dle a") == u"a $mid$dle a"
65 assert replace_dollar(u"a ($in parens$) a") == u"a (:math:`in parens`) a"
66 assert (replace_dollar(u"a (again $in parens$) a")
67 == u"a (again :math:`in parens`) a")
68
69 if __name__ == "__main__":
70 test_dollar()