Home
Head's Up: I'm in the middle of upgrading my site. Most things are in place, but there are something missing and/or broken including image alt text. Please bear with me while I'm getting things fixed.

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

rust
```cargo
[dependencies]
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)
}
results start

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.

The key is :

rust
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