Syntax Highlighting In Rust Apps With The syntect Crate
-
Look at and combine these posts: 2ujekgik
Introduction
I looked at using `syntect`` for syntax highlighting on my site. Initiail tests were very slow so I'm not going with it. Might take a look at some caching stuff later, but that's more than I want to get into. For now I'll just use one of the javascript front ends like prism.
The notes below are for reference for usage.
(I'm also not sure if I'm doing something that is causing the slowness. I'll re-examine at some point to see if there's something to be done about it)
Inline Styles Included
This is the first approach I'm using. It adds inline styles but doesn't wrap things in a `
Code
use HighlightLines;
use ThemeSet;
use ;
use SyntaxSet;
Core Usage
-
Write up details on this approach
Code
use syntect::html::{ClassStyle, ClassedHTMLGenerator};
use syntect::parsing::SyntaxSet;
use syntect::util::LinesWithEndings;
fn main() {
let current_code = r#"<h1>Alfa</h1>
<p>Bravo</p>"#;
let syntax_set = SyntaxSet::load_defaults_newlines();
let syntax = syntax_set.find_syntax_by_name("HTML").unwrap();
let mut html_generator =
ClassedHTMLGenerator::new_with_class_style(syntax, &syntax_set, ClassStyle::Spaced);
for line in LinesWithEndings::from(current_code) {
html_generator.parse_html_for_line_which_includes_newline(line);
}
let output_html = html_generator.finalize();
dbg!(output_html);
}
-
show how to generate the css file
Alternate Approach
The crate offers a way to style things directly inline as well. That code looks like this:
Code
use ThemeSet;
use highlighted_html_for_string;
use SyntaxSet;
Installation
I installed the crate that got all these working with:
cargo add syntect
References
-
A syntax highlighting library for Rust that uses Sublime Text syntax definitions. It aims to be a good solution for any Rust project that needs syntax highlighting
-
I copied the code I'm using directly from this example.
-
Sublime Syntax files are YAML files with a small header, followed by a list of contexts. Each context has a list of patterns that describe how to highlight text in that context, and how to change the current text.
-