Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit811a1ad

Browse files
DOC: Dynamically resize mathtext symbol tables (#26143)
1 parentde229cd commit811a1ad

File tree

1 file changed

+94
-141
lines changed

1 file changed

+94
-141
lines changed

‎doc/sphinxext/math_symbol_table.py‎

Lines changed: 94 additions & 141 deletions
Original file line numberDiff line numberDiff line change
@@ -1,152 +1,105 @@
1-
importre
2-
fromdocutils.parsers.rstimportDirective
1+
"""
2+
Sphinx extension that generates the math symbol table documentation
3+
for Matplotlib.
4+
"""
35

4-
frommatplotlibimport_mathtext,_mathtext_data
6+
from __future__importannotations
7+
fromtextwrapimportdedent
8+
fromdocutils.statemachineimportStringList
9+
fromdocutilsimportnodes
10+
fromsphinx.util.docutilsimportSphinxDirective
11+
frommatplotlibimport_mathtext
512

6-
bb_pattern=re.compile("Bbb[A-Z]")
7-
scr_pattern=re.compile("scr[a-zA-Z]")
8-
frak_pattern=re.compile("frak[A-Z]")
913

10-
symbols= [
11-
["Lower-case Greek",
12-
4,
13-
(r"\alpha",r"\beta",r"\gamma",r"\chi",r"\delta",r"\epsilon",
14-
r"\eta",r"\iota",r"\kappa",r"\lambda",r"\mu",r"\nu",r"\omega",
15-
r"\phi",r"\pi",r"\psi",r"\rho",r"\sigma",r"\tau",r"\theta",
16-
r"\upsilon",r"\xi",r"\zeta",r"\digamma",r"\varepsilon",r"\varkappa",
17-
r"\varphi",r"\varpi",r"\varrho",r"\varsigma",r"\vartheta")],
18-
["Upper-case Greek",
19-
4,
20-
(r"\Delta",r"\Gamma",r"\Lambda",r"\Omega",r"\Phi",r"\Pi",r"\Psi",
21-
r"\Sigma",r"\Theta",r"\Upsilon",r"\Xi")],
22-
["Hebrew",
23-
6,
24-
(r"\aleph",r"\beth",r"\gimel",r"\daleth")],
25-
["Latin named characters",
26-
6,
27-
r"""\aa \AA \ae \AE \oe \OE \O \o \thorn \Thorn \ss \eth \dh \DH""".split()],
28-
["Delimiters",
29-
5,
30-
_mathtext.Parser._delims],
31-
["Big symbols",
32-
5,
33-
_mathtext.Parser._overunder_symbols|_mathtext.Parser._dropsub_symbols],
34-
["Standard function names",
35-
5,
36-
{fr"\{fn}"forfnin_mathtext.Parser._function_names}],
37-
["Binary operation symbols",
38-
4,
39-
_mathtext.Parser._binary_operators],
40-
["Relation symbols",
41-
4,
42-
_mathtext.Parser._relation_symbols],
43-
["Arrow symbols",
44-
4,
45-
_mathtext.Parser._arrow_symbols],
46-
["Dot symbols",
47-
4,
48-
r"""\cdots \vdots \ldots \ddots \adots \Colon \therefore \because""".split()],
49-
["Black-board characters",
50-
6,
51-
[fr"\{symbol}"forsymbolin_mathtext_data.tex2uni
52-
ifre.match(bb_pattern,symbol)]],
53-
["Script characters",
54-
6,
55-
[fr"\{symbol}"forsymbolin_mathtext_data.tex2uni
56-
ifre.match(scr_pattern,symbol)]],
57-
["Fraktur characters",
58-
6,
59-
[fr"\{symbol}"forsymbolin_mathtext_data.tex2uni
60-
ifre.match(frak_pattern,symbol)]],
61-
["Miscellaneous symbols",
62-
4,
63-
r"""\neg \infty \forall \wp \exists \bigstar \angle \partial
64-
\nexists \measuredangle \emptyset \sphericalangle \clubsuit
65-
\varnothing \complement \diamondsuit \imath \Finv \triangledown
66-
\heartsuit \jmath \Game \spadesuit \ell \hbar \vartriangle
67-
\hslash \blacksquare \blacktriangle \sharp \increment
68-
\prime \blacktriangledown \Im \flat \backprime \Re \natural
69-
\circledS \P \copyright \circledR \S \yen \checkmark \$
70-
\cent \triangle \QED \sinewave \dag \ddag \perthousand \ac
71-
\lambdabar \L \l \degree \danger \maltese \clubsuitopen
72-
\i \hermitmatrix \sterling \nabla \mho""".split()],
73-
]
14+
classMathSymbolTableDirective(SphinxDirective):
15+
"""Generate tables of math symbols grouped by category."""
7416

75-
76-
defrun(state_machine):
77-
78-
defrender_symbol(sym,ignore_variant=False):
79-
ifignore_variantandsymnotin (r"\varnothing",r"\varlrtriangle"):
80-
sym=sym.replace(r"\var","\\")
81-
ifsym.startswith("\\"):
82-
sym=sym.lstrip("\\")
83-
ifsymnotin (_mathtext.Parser._overunder_functions|
84-
_mathtext.Parser._function_names):
85-
sym=chr(_mathtext_data.tex2uni[sym])
86-
returnf'\\{sym}'ifsymin ('\\','|','+','-','*')elsesym
87-
88-
lines= []
89-
forcategory,columns,symsinsymbols:
90-
syms=sorted(syms,
91-
# Sort by Unicode and place variants immediately
92-
# after standard versions.
93-
key=lambdasym: (render_symbol(sym,ignore_variant=True),
94-
sym.startswith(r"\var")),
95-
reverse=(category=="Hebrew"))# Hebrew is rtl
96-
rendered_syms= [f"{render_symbol(sym)} ``{sym}``"forsyminsyms]
97-
columns=min(columns,len(syms))
98-
lines.append("**%s**"%category)
99-
lines.append('')
100-
max_width=max(map(len,rendered_syms))
101-
header= (('='*max_width)+' ')*columns
102-
lines.append(header.rstrip())
103-
forpartinrange(0,len(rendered_syms),columns):
104-
row=" ".join(
105-
sym.rjust(max_width)forsyminrendered_syms[part:part+columns])
106-
lines.append(row)
107-
lines.append(header.rstrip())
108-
lines.append('')
109-
110-
state_machine.insert_input(lines,"Symbol table")
111-
return []
112-
113-
114-
classMathSymbolTableDirective(Directive):
11517
has_content=False
116-
required_arguments=0
117-
optional_arguments=0
118-
final_argument_whitespace=False
119-
option_spec= {}
12018

12119
defrun(self):
122-
returnrun(self.state_machine)
20+
# Build RST lines to be parsed. We include a small CSS style and
21+
# simple HTML wrappers so the result is responsive in the browser.
22+
lines:list[str]= []
23+
24+
style=dedent(
25+
"\n".join(
26+
[
27+
"<style>",
28+
".mpl-symbol-table { margin: 0 0 1rem 0; }",
29+
".mpl-symbol-grid {",
30+
" display: grid;",
31+
" grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));",
32+
" gap: 0.5rem 1rem;",
33+
" align-items: center;",
34+
"}",
35+
".mpl-symbol-cell {",
36+
" display: flex;",
37+
" align-items: center;",
38+
" gap: 0.6rem;",
39+
" padding: 0.2rem 0.1rem;",
40+
" white-space: nowrap;",
41+
"}",
42+
".mpl-symbol-cell .label {",
43+
" font-family: monospace;",
44+
" font-size: 0.9em;",
45+
" color: #333;",
46+
"}",
47+
".mpl-symbol-cell .math {",
48+
" font-size: 1.05em;",
49+
"}",
50+
"</style>",
51+
]
52+
)
53+
)
54+
55+
# Insert the style as raw HTML block
56+
lines.append(".. raw:: html")
57+
lines.append("")
58+
forstyle_lineinstyle.splitlines():
59+
lines.append(" "+style_line)
60+
lines.append("")
61+
62+
# Get symbol categories from matplotlib mathtext internals.
63+
try:
64+
categories=_mathtext._get_sphinx_symbol_table()
65+
exceptException:
66+
categories= []
67+
68+
forcategory,_,symsincategories:
69+
# Ensure consistent ordering for reproducible output.
70+
syms_list=sorted(list(syms),key=lambdas:str(s))
71+
72+
lines.append(f"**{category}**")
73+
lines.append("")
74+
lines.append(".. raw:: html")
75+
lines.append("")
76+
lines.append(' <div class="mpl-symbol-table">')
77+
lines.append(' <div class="mpl-symbol-grid">')
78+
79+
forsyminsyms_list:
80+
s=str(sym)
81+
# Use raw TeX inside \( ... \) so MathJax (Sphinx) renders it.
82+
tex=s
83+
html_line= (
84+
" <div class=\"mpl-symbol-cell\">"
85+
f"<span class=\"math\">\\({tex}\\)</span>"
86+
f"<span class=\"label\">`{s}`</span>"
87+
"</div>"
88+
)
89+
lines.append(html_line)
90+
91+
lines.append(" </div>")
92+
lines.append(" </div>")
93+
lines.append("")
94+
95+
# Let Sphinx parse the lines so roles and references work.
96+
text="\n".join(lines)
97+
node=nodes.paragraph()
98+
self.state.nested_parse(StringList(text.splitlines()),0,node)
99+
return [node]
123100

124101

125102
defsetup(app):
103+
"""Register the Sphinx directive."""
126104
app.add_directive("math_symbol_table",MathSymbolTableDirective)
127-
128-
metadata= {'parallel_read_safe':True,'parallel_write_safe':True}
129-
returnmetadata
130-
131-
132-
if__name__=="__main__":
133-
# Do some verification of the tables
134-
135-
print("SYMBOLS NOT IN STIX:")
136-
all_symbols= {}
137-
forcategory,columns,symsinsymbols:
138-
ifcategory=="Standard Function Names":
139-
continue
140-
forsyminsyms:
141-
iflen(sym)>1:
142-
all_symbols[sym[1:]]=None
143-
ifsym[1:]notin_mathtext_data.tex2uni:
144-
print(sym)
145-
146-
# Add accents
147-
all_symbols.update({v[1:]:kfork,vin_mathtext.Parser._accent_map.items()})
148-
all_symbols.update({v:vforvin_mathtext.Parser._wide_accents})
149-
print("SYMBOLS NOT IN TABLE:")
150-
forsym,valin_mathtext_data.tex2uni.items():
151-
ifsymnotinall_symbols:
152-
print(f"{sym} ={chr(val)}")
105+
return {"parallel_read_safe":True,"parallel_write_safe":True}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp