使用 Sphinx 和 reStructuredText,是否可以定义数学宏来在数学 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 中的这两种行为是一个好主意而不是让事情变得复杂吗?
另一个解决方案是使用乳胶宏,如本问题在 Sphinx 中创建乳胶数学宏,但我认为最终的代码会更容易阅读,如我的示例中所示,使用本地第一次替换。我想要有清晰的公式,也可以在文本模式下阅读。
此外,我正在使用 MathJax 扩展,因此我无法使用变量 pngmath_latex_preamble。我可以将此解决方案用于 MathJax https://stackoverflow.com/a/19268549/1779806 但它看起来相当复杂,并且通过“本地”第一次替换,代码会更清晰。
我意识到,对于很多人来说,直接在 reStructuredText 中(即在 Python 包 docutils 中)实现
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 中定义)不会调用其输入的任何解析,因此数学模式下没有替换。
我不知道是否可以更改替换指令的行为,以便替换更加清晰并适应调用它的上下文(在文本中、内联数学中或块数学中)。
有人可以给我一些关于如何实现这个有用的新功能的线索吗?
由于我确实需要一个好的解决方案来满足这个需求,所以我自己解决了......我花了一段时间,解决方案可能并不完美,但至少它运作良好。我呈现结果是因为它对其他人有用。
我还将该解决方案改编为 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.