Search code examples
pythonmacroslatexpython-sphinx

Creating LaTeX math macros within Sphinx


I'm writing some mathematical code in Python and using Sphinx to produce the documentation. I know that Sphinx can handle LaTeX code in Python docstrings; see https://www.sphinx-doc.org/en/master/usage/extensions/math.html#module-sphinx.ext.mathbase. How can I create LaTeX macros, such as \newcommand{\cG}{\mathcal{G}}, to use in the Python docstrings?


Solution

  • Aha, i found a solution that works with the Sphinx pngmath extension. It's the trick that Sage (open source mathematics software) uses; inspiration from http://www.sagemath.org/doc/reference/sage/misc/latex_macros.html.

    To add your own Latex macros to a Sphinx document:

    1) Make a file, say 'latex_macros.sty', containing your macros (one per line), and put it in, say, the same directory as your Sphinx conf.py file;

    2) Add the following code to your Sphinx conf.py file:

    # Additional stuff for the LaTeX preamble.
    latex_elements['preamble'] = '\usepackage{amsmath}\n\usepackage{amssymb}\n'
    
    #####################################################
    # add LaTeX macros 
    
    f = file('latex_macros.sty')
    
    try:
        pngmath_latex_preamble  # check whether this is already defined
    except NameError:
        pngmath_latex_preamble = ""
    
    for macro in f:
        # used when building latex and pdf versions
        latex_elements['preamble'] += macro + '\n'
        # used when building html version
        pngmath_latex_preamble += macro + '\n'
    
    #####################################################