数式入りのmarkdownをSphinxを使ってhtml/pdfにする

2017-01-22 08:11:24 -08:00·
Aki Ariga
Aki Ariga
· 2 min read
post

Sphinxでmarkdown拡張を扱うためのrecommonmarkというライブラリがあります。 これを使うとreSTではなく、markdownを書いてhtmlやPDFが吐けるようになります。

詳細は以下のエントリにやり方がまとまっています。

tech.3rd-p-zombie.net

実は、このrecommonmarkはconfigに設定を書くだけで、数式をmarkdownの中に埋め込めるのでした。

conf.pyの上の方に以下をimportし、

import recommonmark from recommonmark.parser
import CommonMarkParser from recommonmark.transform
import AutoStructify

source_suffixの修正、source_parsersの追加

source_suffix = [".rst", ".md"]
#source_suffix = ".rst"
source_parsers = { ".md" : "recommonmark.parser.CommonMarkParser" }

最後尾に以下を追加します。

def setup(app):
    app.add_config_value(
        "recommonmark_config",
        { "enable_math": True, "enable_inline_math": True, },
        True)
    app.add_transform(AutoStructify)

すると、

$$ (a + b)^2 = a^2 + 2ab + b^2 $$

とかくと、以下の数式の部分のようになります。(document)

また、inlineの数式も以下のように書けます。 (document)

This formula `$ y=\sum_{i=1}^n g(x_i) $`

ただ、残念ながら式番号を出す方法はわかりませんでした。

[追記]

conf.pyにmath_number_all = Trueを足せば数式がでました。ですが、参照はできないと思うので参照が必要な場合はreSTで書く必要があると思います。

math_number_all=True

[/追記]

$ make latexpdfja

とすれば、PDFが、

$ make html

とすればhtmlが生成されます。

さくっと書くときにはmarkdownで行けるのはありがたいですね。

Sphinxとlatex環境を用意するのが面倒な人向けに、docker imageも作りましたので活用してみてください。

https://hub.docker.com/r/chezou/sphinx-recommonmark/

参考

Aki Ariga
Authors
Staff Software Engineer
AI Product Engineer. Interested in Machine Learning, MLOps, and Data driven business. If you like my blog post, I’m glad if you can buy me a tea 😉

Related