Creating LaTeX math macros within Sphinx
Asked Answered
T

6

16

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?

Trematode answered 15/3, 2012 at 21:16 Comment(0)
T
6

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'

#####################################################
Trematode answered 16/3, 2012 at 20:41 Comment(0)
G
8

If you are using MathJax, here's a possible solution. I'm still looking for a nicer solution, but it might help if you need a quick hack.

  1. Create a file under the directory specified in the html_static_path configuration option (typically _static), say mathconf.js. This will contain the JS configuration for MathJax. For instance (from the MathJax documentation):

    MathJax.Hub.Config({
      TeX: {
        Macros: {
          RR: '{\\bf R}',
          bold: ['{\\bf #1}', 1]
        }
      }
    });
    

    You can add more commands following the syntax above. The contents shown define the macros \RR and \bold{#1}, this last one accepting one argument.

  2. Add a layout.html file at the _templates directory. The idea is to extend the current theme, so it searches the previous MathJax configuration file. Thus, the contents are:

    {% extends "!layout.html" %}
    {% set script_files = script_files + ["_static/mathconf.js"] %}
    

    Note that in this case it is the _static directory, because in this case it refers to where to search after the build. Sphinx will have moved the file from html_static_path to the _static directory under the build directory.

Gains answered 9/10, 2013 at 9:47 Comment(1)
Didn't work for me (sphinx=1.3.1) probably because I can't set the script type correctly to <script type="text/x-mathjax-config"> src="_static/mathconf.js"></script> (see docs.mathjax.org/en/latest/…).Peculiarity
T
6

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'

#####################################################
Trematode answered 16/3, 2012 at 20:41 Comment(0)
R
2

To add to @Keta's answer since Aug 2018 and this commit (https://github.com/sphinx-doc/sphinx/pull/5230/files) you can use mathjax_config in the conf.py according to the documentation (http://www.sphinx-doc.org/en/master/usage/extensions/math.html?#confval-mathjax_config)

So for example the following can be added,

mathjax_config = {                  
    "TeX": {                        
        "Macros": {                 
            "RR": '{\\bf R}',       
            "bold": ['{\\bf #1}',1] 
            }                       
        }                           
    }                               
Rapscallion answered 28/6, 2019 at 18:19 Comment(0)
F
1

If you're using the pngmath extension, you can put that in the preamble by inserting this into the conf.py script:

pngmath_latex_preamble = r"\newcommand{\cG}{\mathcal{G}}"
Frankly answered 16/3, 2012 at 16:9 Comment(0)
G
1

The proposed solution tested on sphinx-doc 2.4.3 (e.g., sphinx-quickstart --version)

Sphinx-doc allows additional tweak with MathJax through mathjax_config. The end goal is we want to implement the following in conf.py:

mathjax_config = {
    'TeX': {
        'Macros': {
            # Math notation
            "Z": "\\mathbb{Z}",                                    # set of integers
            # MoA notations
            "minus": "{}^{\\boldsymbol{\\mbox{-}}\\!}",            # scalar negation operator
        }
   }
}

We can do so manually like above. However, we can do better by automatically populate mathjax_config via parsing a separate .tex file that contains all the macro commands.

For example, I have mathsymbols.tex sits in the same level as conf.py with content looks like below:

\DeclareRobustCommand{\ojoin}{\rule[-0.12ex]{.3em}{.4pt}\llap{\rule[1.2ex]{.3em}{.4pt}}}
\newcommand{\leftouterjoin}{\mathrel{\ojoin\mkern-6.5mu\Join}}
\newcommand{\rightouterjoin}{\mathrel{\Join\mkern-6.5mu\ojoin}}
\newcommand{\fullouterjoin}{\mathrel{\ojoin\mkern-6.5mu\Join\mkern-6.5mu\ojoin}}

Then, inside conf.py, we can write:

mathjax_config = { 'TeX': {'Macros': {}}}

with open('mathsymbols.tex', 'r') as f:
    for line in f:
        macros = re.findall(r'\\(DeclareRobustCommand|newcommand){\\(.*?)}(\[(\d)\])?{(.+)}', line)
        for macro in macros:
            if len(macro[2]) == 0:
                mathjax_config['TeX']['Macros'][macro[1]] = "{"+macro[4]+"}"
            else:
                mathjax_config['TeX']['Macros'][macro[1]] = ["{"+macro[4]+"}", int(macro[3])]

to automatically populate mathjax_config and we're done.

With the above example, we can use \leftouterjoin LaTeX macro inside sphinx-doc.

Guileful answered 2/3, 2020 at 23:1 Comment(2)
This answer is great! however, I needed the following modifications to make it work for me: (1) change mathjax_config to mathjax3_config; (2) lowercase the config dict keys: {'tex': {'macros': {}}}. In addition, I also added renewcommand to the regex.Kentish
Thank you so much for the great modifications for mathjax!Quittance
H
0

If HTML+MathJax is the only output format, the following works in plain Docutils out-of-the-box:

.. math:: \newcommand{\half}{\frac{1}{2}}
          0.5 = \half

With MathJax, we can use the macro later: :math:`\half+\half=1`.

With LaTeX, the \newcommand definition is local to the first equation.

Hautbois answered 1/2 at 14:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.