Sub topic 2
Formatting documentation with Markdown
Rustdoc, the documentation tool that ships with Rust, reads the text of your doc comments as Markdown. This chapter covers which Markdown constructs work, how rustdoc treats them, and the formatting mistakes that produce warnings or broken output. It assumes you can already write /// comments, as covered in the previous chapter, and that you know basic Markdown.
How rustdoc reads a doc comment
Rustdoc removes the /// marker and one leading space from each line. It joins the remaining lines into one Markdown document and renders that document as HTML. It uses CommonMark, a precise specification of Markdown, and turns on several extensions.
The extensions are:
- Tables
- Footnotes
- Strikethrough, written
~~like this~~ - Task lists, written
- [x] done - Smart punctuation
Smart punctuation turns straight quotes into curly quotes, -- into an en dash, and ... into an ellipsis. It does not touch text inside code spans or code blocks.
The summary line
The first paragraph of a doc comment has a special role. Module pages and search results show only that paragraph, so it works as a summary. Keep it to one short sentence that stands alone, and separate it from the rest with a blank /// line.
/// Returns the larger of two values.
///
/// If the values compare equal, the second argument is returned. This
/// paragraph appears only on the item's own page, not in the module index.
pub fn larger<T: PartialOrd>(a: T, b: T) -> T {
if a > b { a } else { b }
}If the first paragraph is long, the module index shows a long, cluttered entry. This is the most common formatting mistake in real crates.
Text, emphasis, and line breaks
Standard inline formatting works as you would expect:
*emphasis*renders in italics.**strong**renders in bold.- `
code` renders as a code span.
Use code spans for every identifier, type name, and literal value. Writing Vec<T> without backticks is a mistake because the <T> looks like an HTML tag. Rustdoc then warns about it through the rustdoc::invalid_html_tags lint.
A single newline inside a paragraph is a soft break. The browser joins the two lines with a space. For a hard break, end the line with a backslash or with two trailing spaces. Editors often strip trailing spaces, so the backslash is safer. A list is usually a better choice than hard breaks.
Headings
You can use #, ##, and ### headings inside a doc comment. Rustdoc shifts them down when it renders them, so the item's own name stays the top heading on the page. The convention, which the standard library follows, is to write top-level # headings for sections:
/// Removes every element equal to `value` and returns how many were removed.
///
/// # Examples
///
/// See the crate documentation for a full walkthrough.
///
/// # Performance
///
/// Runs in linear time and allocates nothing.
pub fn remove_all(items: &mut Vec<i32>, value: i32) -> usize {
let before = items.len();
items.retain(|&x| x != value);
before - items.len()
}Rustdoc gives each heading an anchor, so you can link to #performance from elsewhere. Sections such as # Examples, # Panics, # Errors, and # Safety have conventional meanings, and a later chapter covers them. This chapter only needs you to know that they are ordinary Markdown headings.
Lists, tables, and task lists
Lists use - or 1. . Indent continuation lines under the list item so they stay part of it. Tables need a header row and a separator row. They work well for compact reference material such as the mapping between input and output.
/// Classifies a temperature in degrees Celsius.
///
/// | Range (inclusive) | Result |
/// |--------------------|------------|
/// | below `0` | `"freezing"` |
/// | `0` to `24` | `"mild"` |
/// | `25` and above | `"hot"` |
///
/// Notes on the boundaries:
///
/// - `0` counts as mild, not freezing.
/// - `25` counts as hot, not mild.
pub fn classify(celsius: i32) -> &'static str {
match celsius {
i32::MIN..=-1 => "freezing",
0..=24 => "mild",
_ => "hot",
}
}Table cells must stay on one line, so keep the content short. If a table needs long prose in its cells, use a list instead.
Code blocks and their language tags
Fenced code blocks are the Markdown feature that matters most in Rust docs, because rustdoc compiles and runs them. The tag after the opening fence decides what happens.
| Fence tag | Rendered as | Tested as a doc test? |
|---|---|---|
| none | Rust, highlighted | Yes |
| `rust` | Rust, highlighted | Yes |
| `text` | Plain text | No |
| `toml`, `json`, `sh`, `console` | Highlighted for that language | No |
The tag has to be right. If you paste a shell session or a configuration snippet into an untagged block, rustdoc tries to compile it as Rust and cargo test --doc fails. Always tag non-Rust blocks.
Be aware that an indented code block, which is a block indented by four spaces with no fence, is also treated as Rust and tested. This catches people who indent an example under a list item. Rustdoc then sees the indentation as a code block and tries to compile ordinary prose or output. Prefer fenced blocks everywhere, and tag them.
The tag position also accepts Rust-specific attributes such as no_run and should_panic. A later chapter covers them. The point for now is that the text after the fence is not free-form.
A doc comment cannot show a fenced block inside another fenced block when you write documentation about documentation. When you need to display a literal fence, use a longer fence on the outside. Use four backticks to wrap a block that contains three.
Links in Markdown
Ordinary Markdown links work in doc comments:
- Inline links:
[Rust book](https://doc.rust-lang.org/book/). - Reference links:
[text][ref], with[ref]: https://example.comdefined elsewhere in the same comment. - Autolinks:
<https://example.com>.
A bare URL pasted into the text triggers the rustdoc::bare_urls lint. Wrap it in angle brackets or give it link text.
Rustdoc has an extra feature on top of this. A bracketed name such as [Vec] or [crate::parse_port] is resolved as a link to a Rust item. A later chapter covers these intra-doc links in full. For formatting, the consequence is that square brackets in prose are not neutral. Writing see items[0] for the first one makes rustdoc try to resolve 0 as an item and emit a rustdoc::broken_intra_doc_links warning. Put such text in a code span, as in ` items[0] , or escape the bracket as \[0]`.
HTML in doc comments
CommonMark allows raw HTML, so tags like <kbd>Ctrl</kbd> or <sup>2</sup> pass through to the page. Use it sparingly. Rustdoc warns about unclosed or unknown tags, and other tools that display your docs, such as an IDE hover, may not render HTML at all. Prefer Markdown equivalents where one exists.
Footnotes and strikethrough
Footnotes keep a long caveat out of the main text:
/// Computes the checksum of `data`.
///
/// The result is stable across platforms.[^endian]
///
/// [^endian]: Bytes are always read in little-endian order, regardless of
/// the host's native byte order.
pub fn checksum(data: &[u8]) -> u32 {
data.iter().fold(0u32, |acc, &b| acc.wrapping_mul(31).wrapping_add(b as u32))
}Rustdoc collects the footnotes at the bottom of the page. Strikethrough is rarely useful in API docs, but it is available for marking something as superseded.
Previewing your formatting
Formatting problems show up at build time and when you view the page. Build the docs for your own crate and open them:
cargo doc --no-deps --openLook at the module index to check the summary lines, then open individual items to check tables and lists. Warnings from rustdoc appear in the terminal during the build. Read them, because lints such as rustdoc::invalid_html_tags, rustdoc::bare_urls, and rustdoc::broken_intra_doc_links flag exactly the mistakes this chapter describes.
Common mistakes
- A long first paragraph. The module index shows all of it. Keep the first sentence short and self-contained.
- Untagged non-Rust code blocks. Rustdoc compiles them as Rust and the doc test fails. Tag them
text,toml,sh, or the right language. - Indented code blocks inside lists. They count as Rust code. Use fences.
- Types with angle brackets outside backticks.
Option<T>in plain text is read as an HTML tag. Wrap it in a code span. - Square brackets in prose. They may be parsed as intra-doc links. Use code spans or escape them.
- Bare URLs. Use
<https://...>or a named link.
Exercise
A doc comment for a function contains a block that shows the contents of a Cargo.toml file. The block opens with three backticks and no language tag. What happens when you run cargo test --doc, and how do you fix it?
Show answer
Rustdoc treats an untagged block as Rust, so it tries to compile the TOML as Rust code and the doc test fails. Fix it by adding the toml tag to the opening fence, so the block is highlighted as TOML and is not tested.
Exercise
You write the sentence "Index into the buffer with buf[0] to read the first byte." in a doc comment, and cargo doc prints a rustdoc::broken_intra_doc_links warning. Why, and what are two ways to fix it?
Show answer
Rustdoc reads [0] as an intra-doc link to an item named 0, which does not exist. Either put the expression in a code span, as in ` buf[0] , or escape the opening bracket with a backslash, as in buf\[0]`.