Note: This site is currently "Under construction". I'm migrating to a new version of my site building software. Lots of things are in a state of disrepair as a result (for example, footnote links aren't working). It's all part of the process of building in public. Most things should still be readable though.

Add Syntax Highlighting To Strings Of Code In Rust

Code

//! ```cargo
//! [dependencies]
//! syntect = "5.1.0"
//! ```

use syntect::highlighting::ThemeSet;
use syntect::html::highlighted_html_for_string;
use syntect::parsing::SyntaxSet;

fn main() {
    let input = "console.log(`here`)"; 
    let extension = "rust";
    let output = highlight_code(input, extension);
    dbg!(output);
}

fn highlight_code(input: &str, code_type: &str) -> String {
    let ss = SyntaxSet::load_defaults_newlines();
    let syntax = ss.find_syntax_by_token(code_type).unwrap();
    let ts = ThemeSet::load_defaults();
    let theme = &ts.themes["base16-ocean.dark"];
    let html = highlighted_html_for_string(input, &ss, syntax, theme).unwrap();
    html
}

Results

[_active_nvim_run:14] output = "<pre style=\"background-color:#2b303b;\">\n<span style=\"color:#c0c5ce;\">console.</span><span style=\"color:#96b5b4;\">log</span><span style=\"color:#c0c5ce;\">(`here`)</span></pre>\n"