@@ -95,30 +95,43 @@ def install_mathjax(
9595
9696 builder = cast ('StandaloneHTMLBuilder' , app .builder )
9797 page_has_equations = context .get ('has_maths_elements' , False )
98+
99+ # Enable mathjax only if equations exists
98100 if app .registry .html_assets_policy == 'always' or page_has_equations :
99- # Enable mathjax only if equations exists
100101 if app .config .mathjax2_config :
101102 if app .config .mathjax_path == MATHJAX_URL :
102103 logger .warning (
103104 'mathjax_config/mathjax2_config does not work '
104105 'for the current MathJax version, use mathjax3_config instead'
105106 )
106- body = 'MathJax.Hub.Config(%s)' % json .dumps (app .config .mathjax2_config )
107+ body = f 'MathJax.Hub.Config({ json .dumps (app .config .mathjax2_config )} )'
107108 builder .add_js_file ('' , type = 'text/x-mathjax-config' , body = body )
109+
108110 if app .config .mathjax3_config :
109- body = 'window.MathJax = %s' % json .dumps (app .config .mathjax3_config )
111+ body = f'window.MathJax = { json .dumps (app .config .mathjax3_config )} '
112+ builder .add_js_file ('' , body = body )
113+
114+ if app .config .mathjax_config_path :
115+ config_path = app .confdir / app .config .mathjax_config_path
116+ if not config_path .exists ():
117+ msg = f'mathjax_config_path file not found: { config_path } '
118+ raise ExtensionError (msg )
119+ if not config_path .is_file () or config_path .suffix != '.js' :
120+ msg = f'mathjax_config_path: expected a .js file, but got { config_path } '
121+ raise ExtensionError (msg )
122+ body = config_path .read_text (encoding = 'utf-8' )
110123 builder .add_js_file ('' , body = body )
111124
112125 options = {}
113126 if app .config .mathjax_options :
114127 options .update (app .config .mathjax_options )
115128 if 'async' not in options and 'defer' not in options :
116- if app .config .mathjax3_config :
117- # Load MathJax v3 via "defer" method
118- options ['defer' ] = 'defer'
119- else :
120- # Load other MathJax via "async" method
129+ if app .config .mathjax2_config or app .config .mathjax_config :
130+ # Load old MathJax versions via the 'async' method
121131 options ['async' ] = 'async'
132+ else :
133+ # Load MathJax v3+ via the 'defer' method
134+ options ['defer' ] = 'defer'
122135 builder .add_js_file (app .config .mathjax_path , ** options )
123136
124137
@@ -149,6 +162,7 @@ def setup(app: Sphinx) -> ExtensionMetadata:
149162 app .add_config_value (
150163 'mathjax3_config' , None , 'html' , types = frozenset ({dict , NoneType })
151164 )
165+ app .add_config_value ('mathjax_config_path' , '' , 'html' , types = frozenset ({str }))
152166 app .connect ('html-page-context' , install_mathjax )
153167
154168 return {
0 commit comments