在Sphinx中创建LaTeX数学宏

ara*_*hev 10 python macros latex python-sphinx

我正在用Python编写一些数学代码,并使用Sphinx生成文档.我知道Sphinx可以在Python文档字符串中处理LaTeX代码; 请参阅http://sphinx.pocoo.org/latest/ext/math.html#module-sphinx.ext.mathbase.如何创建LaTeX宏,例如\newcommand{\cG}{\mathcal{G}},在Python文档字符串中使用?

ara*_*hev 5

啊哈,我找到了一个适用于 Sphinx pngmath 扩展的解决方案。这是 Sage(开源数学软件)使用的技巧;灵感来自http://www.sagemath.org/doc/reference/sage/misc/latex_macros.html

要将您自己的 Latex 宏添加到 Sphinx 文档:

1)创建一个文件,比如“latex_macros.sty”,包含你的宏(每行一个),然后把它放在与你的 Sphinx conf.py 文件相同的目录中;

2) 将以下代码添加到您的 Sphinx conf.py 文件中:

# 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'

#####################################################
Run Code Online (Sandbox Code Playgroud)


小智 5

如果您使用MathJax,这是一个可能的解决方案.我仍在寻找更好的解决方案,但如果您需要快速入侵,它可能会有所帮助.

  1. 比如在html_static_path配置选项中指定的目录下创建一个文件(通常_static)mathconf.js.这将包含MathJax的JS配置.例如(来自MathJax文档):

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

    您可以按照上面的语法添加更多命令.所示的内容限定了宏\RR\bold{#1},这最后一个接受一个参数.

  2. layout.html_templates目录中添加文件.我们的想法是扩展当前主题,因此它会搜索以前的MathJax配置文件.因此,内容是:

    {% extends "!layout.html" %}
    {% set script_files = script_files + ["_static/mathconf.js"] %}
    
    Run Code Online (Sandbox Code Playgroud)

    请注意,在这种情况下,它_static目录,因为在这种情况下,它指的是搜索的版本.Sphinx会将文件移动html_static_path_staticbuild目录下的目录中.