在reStructuredText和Sphinx中进行替换的Math Latex宏

6 投票
1 回答
2734 浏览
提问于 2025-04-20 12:22

使用SphinxreStructuredText,能否定义数学宏来在数学的LaTeX公式中进行替换呢?

简单来说,我想要的效果是这样的:

.. |bnabla| replace:: :math:`\boldsymbol{\nabla}`
.. |vv| replace:: :math:`\textbf{v}`

.. math:: \rho \mbox{D}_t |vv| = - |bnabla| p + \rho \textbf{g} + \eta |bnabla|^2 |vv|,

where |vv| is the velocity and |bnabla| is the nabla operator.

Then follow many other equations with |vv| and |bnabla|...

但是这个方法完全不行。首先,标志在数学模式下没有被替换,其次,即使它们被替换了,:math:语句在.. math::块中也不管用。要不要考虑在Sphinx中改变这两种行为,让它们更好用呢?

另外一个解决方案是使用LaTeX宏,像这个问题中提到的在Sphinx中创建LaTeX数学宏,但我觉得用本地的rst替换,最终的代码会更容易阅读。这样我可以得到清晰的公式,同时也能在文本模式下阅读。

而且,我正在使用MathJax扩展,所以我不能使用变量pngmath_latex_preamble。我可以参考这个解决方案给MathJaxhttps://stackoverflow.com/a/19268549/1779806,但看起来有点复杂,再说一次,用“本地”的rst替换代码会更清晰。

编辑:

我意识到,直接在reStructuredText中实现一个mathmacro替换指令,对很多人来说会非常方便和有用。这个新指令应该这样工作:

定义:

.. |bnabla| mathmacro:: \boldsymbol{\nabla}
.. |vv| mathmacro:: \textbf{v}

这些数学宏可以直接在文本中包含,比如:

|bnabla| is the nabla operator,

这应该会生成一个这样的行内公式:

:math:`\boldsymbol{\nabla}` is the nabla operator.

这些宏也可以包含在行内公式中:

This is an inline equation :math:`\vv = \bnabla f`, 

这应该等同于:

:math:`\textbf{v} = \boldsymbol{\nabla}f`

它们也可以包含在块公式中:

.. math:: \vv = \bnabla f

这应该等同于:

.. math:: \textbf{v} = \boldsymbol{\nabla}f.

不过,我对docutils的内部工作原理并不太熟悉。我特别注意到,MathBlock指令(在docutils/parsers/rst/directives/body.py中定义)并没有对其输入进行任何解析,所以在数学模式下没有替换。

我不知道是否可以改变替换指令的行为,让替换能够聪明地适应调用的上下文,无论是在文本中、行内数学中还是块数学中。

有没有人能给我一些关于如何实现这个有用的新功能的线索呢?

1 个回答

9

因为我真的需要一个好的解决方案,所以我自己动手做了...这花了我一段时间,虽然这个解决方案可能不是完美的,但至少它运行得不错。我把这个结果分享出来,因为它可能对其他人有帮助。

我还把这个解决方案做成了一个Sphinx的扩展,可以在这里找到。

我需要定义一个新的替换指令,并重新定义math指令和角色。所有这些都在一个名为mathmacro.py的文件中完成:

"""
'Proof of concept' for a new reStructuredText directive *mathmacro*.

Use for example with::

  python mathmacro.py example.rst example.html

"""

import re

from docutils.parsers.rst.directives.misc import Replace

from docutils.parsers.rst.directives.body import MathBlock
from docutils.parsers.rst.roles import math_role

def multiple_replacer(replace_dict):
    """Return a function replacing doing multiple replacements.

    The produced function replace `replace_dict.keys()` by
    `replace_dict.values`, respectively.

    """
    def replacement_function(match):
        s = match.group(0)
        end = s[-1]
        if re.match(r'[\W_]', end):
            return replace_dict[s[:-1]]+end
        else:
            return replace_dict[s]

    pattern = re.compile("|".join([re.escape(k)+r'[\W_\Z]|'+re.escape(k)+r'\Z'
                                   for k in replace_dict.keys()]), 
                         re.M)
    return lambda string: pattern.sub(replacement_function, string)


class MathMacro(Replace):
    """Directive defining a math macro."""
    def run(self):
        if not hasattr(self.state.document, 'math_macros'):
            self.state.document.math_macros = {}

        latex_key = '\\'+self.state.parent.rawsource.split('|')[1]
        self.state.document.math_macros[latex_key] = ''.join(self.content)

        self.state.document.math_macros_replace = \
            multiple_replacer(self.state.document.math_macros)

        self.content[0] = ':math:`'+self.content[0]
        self.content[-1] = self.content[-1]+'`'

        return super(MathMacro, self).run()


class NewMathBlock(MathBlock):
    """New math block directive parsing the latex code."""
    def run(self):
        try:
            multiple_replace = self.state.document.math_macros_replace
        except AttributeError:
            pass
        else:
            if self.state.document.math_macros:
                for i, c in enumerate(self.content):
                    self.content[i] = multiple_replace(c)
        return super(NewMathBlock, self).run()


def new_math_role(role, rawtext, text, lineno, inliner, 
                  options={}, content=[]):
    """New math role parsing the latex code."""
    try:
        multiple_replace = inliner.document.math_macros_replace
    except AttributeError:
        pass
    else:
        if inliner.document.math_macros:
            rawtext = multiple_replace(rawtext)

    return math_role(role, rawtext, text, lineno, inliner,
                     options=options, content=content)


if __name__ == '__main__':

    from docutils.parsers.rst.directives import register_directive
    from docutils.parsers.rst.roles import register_canonical_role

    register_directive('mathmacro', MathMacro)
    register_directive('math', NewMathBlock)
    register_canonical_role('math', new_math_role)



    from docutils.core import publish_cmdline, default_description
    description = ('Generates (X)HTML documents '
                   'from standalone reStructuredText sources. '
                   +default_description)
    publish_cmdline(writer_name='html', description=description)

文件example.rst的内容:

Here, I show how to use a new mathmacro substitution directive in
reStructuredText. I think even this small example demonstrates that it
is useful.


First some math without math macros.  Let's take the example of the
incompressible Navier-Stokes equation:

.. math:: \mbox{D}_t \textbf{v} = 
   -\boldsymbol{\nabla} p + \nu \boldsymbol{\nabla} ^2 \textbf{v}.

where :math:`\mbox{D}_t` is the convective derivative,
:math:`\textbf{v}` the velocity, :math:`\boldsymbol{\nabla}` the
nabla operator, :math:`\nu` the viscosity and
:math:`\boldsymbol{\nabla}^2` the Laplacian operator.


.. |Dt| mathmacro:: \mbox{D}_t
.. |bnabla| mathmacro:: \boldsymbol{\nabla}
.. |vv| mathmacro:: \textbf{v}

Now, let's use some math macros and try to get the same result...  The
Navier-Stokes equation can now be written like this:

.. math:: \Dt \vv = - \bnabla p + \nu \bnabla^2 \vv

where |Dt| is the convective derivative, |vv| the velocity, |bnabla|
the nabla operator, :math:`\nu` the viscosity and :math:`\bnabla^2`
the Laplacian operator.

撰写回答