Highlight Code In Rust With syntect

TL;DR

This is how I'm highlighting HTML strings in Rust which I use to build my site.

Code
use minijinja::Error;
use syntect::highlighting::ThemeSet;
use syntect::html::highlighted_html_for_string;
use syntect::parsing::SyntaxSet;

pub fn highlight_html(name: String) -> Result<String, Error> {
    let ss = SyntaxSet::load_defaults_newlines();
    let ts = ThemeSet::load_defaults();
    let theme = &ts.themes["base16-ocean.dark"];
    let html = highlighted_html_for_string(name.as_str(), &ss, &ss.syntaxes()[1], theme).unwrap();
    Ok(html)
}
Notes
  • It took a while to figure out the `&ss.syntaxes()[1]`` part based off the docs.

  • I don't understand what's going on there either. Something to investigate.

  • TODO is to look at this for a possibly simpler way: https://docs.rs/syntect/latest/syntect/easy/struct.HighlightLines.html

Reference

Reference

Reference