NOTE: Under Construction - I'm in the middle of upgrading my site and lots of stuff is kinda broken. Please forgive the mess.

Plain-Text Fallback Syntax Highlighting For Rust's Syntect Crate

April 2024

This is a basic approach for providing a fallback to plain-text when using Rust's syntect crate for syntax highlighting. This provides a way to process everything through the same syntax highlighting even if syntect doesn't recognize the requested language.

syntect = "5.2"

use syntect::easy::HighlightLines;
use syntect::highlighting::ThemeSet;
use syntect::html::{styled_line_to_highlighted_html, IncludeBackground};
use syntect::parsing::SyntaxSet;

fn main() {
  let code = "some string of code".to_string();
  let syntax = "unknown-language".to_string();
  let highlighted_code = highlight_code(&code, &syntax);
  println!("{}", highlighted_code.unwrap());

fn highlight_code(code: &String, syntax: &String) -> Result<String, syntect::Error> {
    let ss = SyntaxSet::load_defaults_newlines();
    let ts = ThemeSet::load_defaults();
    let syntax = ss.find_syntax_by_token(syntax).unwrap_or_else(|| ss.find_syntax_plain_text());
    let mut h = HighlightLines::new(syntax, &ts.themes["base16-ocean.dark"]);
    let regions = h.highlight_line(code, &ss).unwrap();
    styled_line_to_highlighted_html(&regions[..], IncludeBackground::No)
some string of code

The key is:

let syntax = ss.find_syntax_by_name(syntax).unwrap_or_else(|| ss.find_syntax_plain_text());

That line attempts to local the requested syntax. If it can't, it falls back to plain-text.

═══ § ═══

Footnotes And References