Skip to content

Instantly share code, notes, and snippets.

@newville
Last active February 13, 2023 12:59
Show Gist options
  • Save newville/8c1759a295e93fef984f to your computer and use it in GitHub Desktop.
Save newville/8c1759a295e93fef984f to your computer and use it in GitHub Desktop.
rendering Angstrom Symbol with Mathjax and sphinx
MathJax doesn't directly support the Angstrom symbol, TeX's \AA. This is painful in many
fields, notably those that work with X-rays.
To use mathjax with the Sphinx documentation system, one would put
extensions = ['sphinx.ext.mathjax', ...]
in conf.py. But this will not understand \AA as the Angstrom symbol.
The solution is to add a Mathjax configuration script to each HTML file produced by sphinx.
To do this, put the following code in _templates/layout.html:
{% extends "default/layout.html" %}
{%- block extrahead %}
<script type="text/x-mathjax-config"> MathJax.Hub.Config({
"TeX": {Macros: {AA : "{\\unicode{x212B}}"}}, "HTML-CSS": {scale: 90}});
</script>
{% endblock %}
This will tell mathjax to use the unicode (version 6.0? ISO Latin?) symbol for Angstrom.
@bskinn
Copy link

bskinn commented Nov 16, 2015

Looks elegant, but this completely munged my docs using sphinx_rtd_theme.

@briantoby
Copy link

briantoby commented Feb 16, 2020

I found that MathJax can be "instructed" to use the Angstrom (Å) symbol using this instruction \require{mediawiki-texvc} but LaTeX does not like that, so it needs to be defined conditionally. If I put this code into the docstring for my .py file prior to the first use of \AA, MathJax now has Å in the HTML output:

.. only:: html

   :math:`\\require{mediawiki-texvc}`

then later

wavelength in :math:`\\AA`

works fine.

The next problem is that \AA is defined for regular LaTeX processing, but not in math mode, where I want it, but \text{\AA} would work fine in math mode. Adding this code to conf.py fixes that problem:

latex_elements = {
#this allows \AA to be used in equations 
'preamble': '\\global\\renewcommand{\\AA}{\\text{\\r{A}}}',
}

(I suspect the \\global is not needed.) Now I have Å symbols in my RTD HTML and PDFs.

@newville
Copy link
Author

@briantoby Hm, this trick still works for me for HTML docs build on my own machine. I sort of gave up trying to build tex/pdf from sphinx. But I guess I have not tried this with a simple test case and RTD.

@m3lab-zzl
Copy link

If I put this code into the docstring for my .py file prior to the first use of \AA, MathJax now has Å in the HTML output:

Did you mean that we should write in conf.py the following snippet?

extensions = [ 'sphinx.ext.mathjax', ...]

rst_prolog = u"""\

.. only:: html

   :math:`\\require{mediawiki-texvc}`

"""    

I tried it, but the $\AA$ symbol was not rendered as expected, it was red \AA.
image

Meanwhile, there was a warning:
image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment