77
88import matplotlib as mpl
99from matplotlib import _api , mathtext
10+ from matplotlib .rcsetup import validate_float_or_None
1011
1112
1213# Define LaTeX math node:
@@ -25,32 +26,37 @@ def math_role(role, rawtext, text, lineno, inliner,
2526 node = latex_math (rawtext )
2627 node ['latex' ] = latex
2728 node ['fontset' ] = options .get ('fontset' , 'cm' )
29+ node ['fontsize' ] = options .get ('fontsize' ,
30+ setup .app .config .mathmpl_fontsize )
2831 return [node ], []
29- math_role .options = {'fontset' : fontset_choice }
32+ math_role .options = {'fontset' : fontset_choice ,
33+ 'fontsize' : validate_float_or_None }
3034
3135
3236class MathDirective (Directive ):
3337 has_content = True
3438 required_arguments = 0
3539 optional_arguments = 0
3640 final_argument_whitespace = False
37- option_spec = {'fontset' : fontset_choice }
41+ option_spec = {'fontset' : fontset_choice ,
42+ 'fontsize' : validate_float_or_None }
3843
3944 def run (self ):
4045 latex = '' .join (self .content )
4146 node = latex_math (self .block_text )
4247 node ['latex' ] = latex
4348 node ['fontset' ] = self .options .get ('fontset' , 'cm' )
49+ node ['fontsize' ] = self .options .get ('fontsize' ,
50+ setup .app .config .mathmpl_fontsize )
4451 return [node ]
4552
4653
4754# This uses mathtext to render the expression
48- def latex2png (latex , filename , fontset = 'cm' ):
49- latex = "$%s$" % latex
50- with mpl .rc_context ({'mathtext.fontset' : fontset }):
55+ def latex2png (latex , filename , fontset = 'cm' , fontsize = 10 ):
56+ with mpl .rc_context ({'mathtext.fontset' : fontset , 'font.size' : fontsize }):
5157 try :
5258 depth = mathtext .math_to_image (
53- latex , filename , dpi = 100 , format = "png" )
59+ f"$ { latex } $" , filename , dpi = 100 , format = "png" )
5460 except Exception :
5561 _api .warn_external (f"Could not render math expression { latex } " )
5662 depth = 0
@@ -62,14 +68,15 @@ def latex2html(node, source):
6268 inline = isinstance (node .parent , nodes .TextElement )
6369 latex = node ['latex' ]
6470 fontset = node ['fontset' ]
71+ fontsize = node ['fontsize' ]
6572 name = 'math-{}' .format (
66- hashlib .md5 (( latex + fontset ) .encode ()).hexdigest ()[- 10 :])
73+ hashlib .md5 (f' { latex } { fontset } { fontsize } ' .encode ()).hexdigest ()[- 10 :])
6774
6875 destdir = Path (setup .app .builder .outdir , '_images' , 'mathmpl' )
6976 destdir .mkdir (parents = True , exist_ok = True )
7077 dest = destdir / f'{ name } .png'
7178
72- depth = latex2png (latex , dest , fontset )
79+ depth = latex2png (latex , dest , fontset , fontsize = fontsize )
7380
7481 if inline :
7582 cls = ''
@@ -86,6 +93,7 @@ def latex2html(node, source):
8693
8794def setup (app ):
8895 setup .app = app
96+ app .add_config_value ('mathmpl_fontsize' , 10.0 , True )
8997
9098 # Add visit/depart methods to HTML-Translator:
9199 def visit_latex_math_html (self , node ):
0 commit comments