Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write math formulas for Rust documentation?

I'd like to write a math formula in Rust documentation for my crate. Looks like there is basic support of LaTeX as at least power works:

/// $ 2^8 $

Is rendered like:

enter image description here

I'd like to use a fraction in my formula, but unfortunately, this does not work:

/// $ \frac{x}y $
like image 630
Sergey Potapov Avatar asked Sep 29 '17 18:09

Sergey Potapov


1 Answers

Similar to Steve's answer, using katex you could follow the approaches from:

  • https://docs.rs/rustdoc-katex-demo/0.1.5/rustdoc_katex_demo/, see also the resources section. Kernfeld.
  • https://docs.rs/katex-doc/0.1.0/katex_doc/, Durham.

You need to put an html file in your crate in some place with the code to include with the --html-in-header option. Then execute:

Linux:

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

Windows cmd:

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 is not strictly necessary, but convenient if you do not want to add the header to the doc of another external crates.

For use in http://docs.rs you must place this on Cargo.toml:

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

The content of the header html file could be (this is the solution of Kernfeld):

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.css" integrity="sha384-9eLZqc9ds8eNjO3TmqPeYcDj8n+Qfa4nuSiGYa6DjLNcv9BtN69ZIulL9+8CqC9Y" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.js"                  integrity="sha384-K3vbOmF2BtaVai+Qk37uypf7VrgBubhQreNQe9aGsz9lB63dIFiQVlJbr92dw2Lx" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/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 for another example (no LaTeX) of extending the possibilities of doc html pages.

UPDATE:

I made a minimal example repo showing all the above. The crate with associated documentation using LaTeX.

like image 198
victe Avatar answered Sep 23 '22 19:09

victe