victe / rust-latex-doc-minimal-example

33 stars 0 forks source link

Minimal Rust project example for using Latex in docs

Crates.io docs.rs

Documenting code in Rust is straightforward and appealing, but you can not write mathematical expressions.

The solution is to include in the final HTML doc page a script to parse the mathematical expressions when rendering the page.

We use Latex for the mathematical syntax and Katex for parsing the expressions in the final HTML file. The parser script get Katex from CDN and configure escape characters to use in documentation code.

Now you can do this:

/// $$E = mc^2 $$
/// $$m = \frac{m_0}{\sqrt{1-\frac{v^2}{c^2}}}$$
fn energy(v: Velocity) -> Energy {...}

As a result, see the documentation page of this repo example at docs.rs.

Including the parser script in the final doc

rustdoc has command-line arguments for including HTML in the header, before the content and after the content. We use --html-in-header because we need to link to the CDN for getting Katex.

For passing --html-in-header to cargo doc command there are two options:

1) Using the environmental variable RUSTDOCFLAGS (see cargo rustdoc)

Linux

RUSTDOCFLAGS="--html-in-header src/docs-header.html" cargo doc

Windows cmd

set RUSTDOCFLAGS=--html-in-header src\docs-header.html
cargo doc

Windows PowerShell

$env:RUSTDOCFLAGS="--html-in-header .\src\docs-header.html"
cargo doc

2) Setting the build.rustdocflags config value in .cargo\config.toml (in this Repo is configured)

[build]
rustdocflags = [ "--html-in-header", "./src/docs-header.html" ]

Publish the crate and showing documentation in docs.rs

The crate must be a lib. If it is only a bin, docs.rs do not build the documentation.

We need to add the header file ubication in the cargo manifest:

[package.metadata.docs.rs]
rustdoc-args = [ "--html-in-header", "./src/docs-header.html" ]

Publish the doc in your hosting

If your crate is a bin or you don't want to publish your crate at crates.io, you can always publish the target/doc directory at your convenience.

In this repo, we use github pages in the docs directory. In this case, just use:

rm -rf docs/ && cargo clean --doc && cargo doc && cp -r target/doc/ docs/

If you publish your crate to crates.io set the documentation entry in the cargo manifest to your final URL destination. In this crate, this entry should look like this:

# Cargo.toml
[package]
...
documentation = "https://victe.github.io/rust-latex-doc-minimal-example/rust_latex_doc_minimal_example/"
...

License

CC0
To the extent possible under law, Vicente Ramírez Perea has waived all copyright and related or neighboring rights to Minimal Rust project example for using Latex in docs. This work is published from: Belgium.