Rustdoc for Syntax Highlighting

Before starting, you'll need:

  1. rustup
  2. rust nightly installed via rustup

If anything fails, prefer rustc 1.14.0-nightly (cae6ab1c4 2016-11-05).

So, here how we do it. First, we need to write our syntax highlighter. It will take rust code from stdin and output the rendered html to stdout. The code below will do this task. Save it as


extern crate rustdoc;

use std::io::{self, Read};
use rustdoc::html::highlight::render_with_highlighting;

fn main() {
    let mut buf = String::new();
    let stdin = io::stdin();
    stdin.lock().read_to_string(&mut buf).unwrap();
    let output = render_with_highlighting(&buf, None, None, None);
    print!("{}", output);
Compile it using:
$ rustup run nightly rustc
To run the binary, you need this hack:
$ LD_LIBRARY_PATH="$(rustup run nightly rustc --print sysroot)/lib" \
./highlight <

You can already transform any rust code to a rendered html output. But to make it colorful, you need the css from librustdoc. The easiest way is by grabbing it from any rust project documentation.

Below some rules that relevant, cherry-picked from librustdoc repository. Also available as file in rust.css

code, pre {
    font-family: "Source Code Pro", Menlo, Monaco, Consolas, "DejaVu Sans Mono", Inconsolata, monospace;
    white-space: pre-wrap;
pre {
    padding: 14px;
pre.rust .kw { color: #8959A8; }
pre.rust .kw-2, pre.rust .prelude-ty { color: #4271AE; }
pre.rust .number, pre.rust .string { color: #718C00; }
pre.rust .self, pre.rust .bool-val, pre.rust .prelude-val,
pre.rust .attribute, pre.rust .attribute .ident { color: #C82829; }
pre.rust .attribute, pre.rust .attribute .ident { color: #C82829; }
pre.rust .macro, pre.rust .macro-nonterminal { color: #3E999F; }
pre.rust .lifetime { color: #B76514; }
pre.rust .question-mark {
    color: #ff9011;
    font-weight: bold;
pre.rust { position: relative; }
pre {
    background-color: #F5F5F5;
pre.rust .comment { color: #8E908C; }
pre.rust .doccomment { color: #4D4D4C; }

Now, you can put those css alongside with your blog's css. The rust code in this post is an example of it in action.