如何为 Rust 文档编写数学公式?

How to write math formulas for Rust documentation?

我想在 Rust 文档中为我的箱子写一个数学公式。 看起来有对 LaTeX 的基本支持,因为至少 power 有效:

/// $ 2^8 $

呈现如下:

我想在我的公式中使用分数,但不幸的是,这不起作用:

/// $ \frac{x}y $

Looks like there is basic support of LaTeX

不完全是。支持 Markdown,不支持 LaTeX。 Stack Overflow 也支持 Markdown,但风格不同。例如:a^b => a^b,但是 a<sup>b</sup> => ab。 Markdown 不支持任意的 LaTeX。的确,你的例子:

/// Hi
///
/// $ 2^8 $
pub fn what() {

}

生成仍然包含 $:

的内容

下一个最好的办法可能是生成预渲染图像,然后将它们包含在您的文档中,但 an open issue 似乎表明目前这是不可能的,除非您将图像托管在其他地方.

甚至还有 an issue to support MathJax in rustdoc,但那已经关闭了。

您可以让它与 MathJax 和 rustdoc--html-in-header 一起工作,以将 link 传递给它需要的脚本标签。这非常 hacky,不适用于 docs.rs,但如果您托管自己的文档,它可以工作。

类似于 Steve's answer,使用 katex 您可以遵循以下方法:

您需要将 html 文件放入您的包中的某个位置,其中包含要包含在 --html-in-header 选项中的代码。然后执行:

Linux:

RUSTDOCFLAGS="--html-in-header path-to-your-header-file.html" cargo doc --no-deps

Windows命令:

set RUSTDOCFLAGS=--html-in-header path-to-your-header-file.html
cargo doc --no-deps --open

Windows PowerShell:

$env:RUSTDOCFLAGS="--html-in-header .\path-to-your-header-file.html"
cargo doc --no-deps --open

--no-deps 不是绝对必要的,但如果您不想将 header 添加到另一个外部包的文档中,则很方便。

要在 http://docs.rs 中使用,您必须将其放在 Cargo.toml:

[package.metadata.docs.rs]
rustdoc-args = [ "--html-in-header", "path-to-your-header-file.html" ]

headerhtml文件的内容可以是(这是Kernfeld的解决方法):

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.10.0/dist/katex.min.css" integrity="sha384-9eLZqc9ds8eNjO3TmqPeYcDj8n+Qfa4nuSiGYa6DjLNcv9BtN69ZIulL9+8CqC9Y" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/katex@0.10.0/dist/katex.min.js"                  integrity="sha384-K3vbOmF2BtaVai+Qk37uypf7VrgBubhQreNQe9aGsz9lB63dIFiQVlJbr92dw2Lx" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/katex@0.10.0/dist/contrib/auto-render.min.js"    integrity="sha384-kmZOZB5ObwgQnS/DuDg6TScgOiWWBiVt0plIRkZCmE6rDZGrEOQeHM5PcHi+nyqe" crossorigin="anonymous"></script>
<script>
    document.addEventListener("DOMContentLoaded", function() {
        renderMathInElement(document.body, {
            delimiters: [
                {left: "$$", right: "$$", display: true},
                {left: "\(", right: "\)", display: false},
                {left: "$", right: "$", display: false},
                {left: "\[", right: "\]", display: true}
            ]
        });
    });
</script>

See pwnies 扩展 doc html 页的可能性的另一个例子(无 LaTeX)。

更新:

我用LaTeX做了一个minimal example repo showing all the above. The crate with associated documentation

我迭代了 victe's minimal example and created a crate providing a macro that embeds .tex in documentation as Markdown。此外,我使用了更新的 KaTeX 渲染器,这使我的说明更加易于复制粘贴。