a self-highlighting main.rs that leaves the code valid rust
:)
// version: 5.3.0
use syntect::{
easy::HighlightLines,
highlighting::{Style, ThemeSet},
parsing::SyntaxSet,
util::LinesWithEndings,
};
fn main() {
let ps = SyntaxSet::load_defaults_newlines();
let ts = ThemeSet::load_defaults();
let mut h = HighlightLines::new(
ps.find_syntax_by_extension("rs").unwrap(),
&ts.themes["base16-eighties.dark"],
);
let s = std::fs::read_to_string("main.rs").unwrap();
for line in LinesWithEndings::from(&s) {
let ranges: Vec<(Style, &str)> =
h.highlight_line(line, &ps).unwrap();
let line_without_ending =
line.trim_end_matches('\n');
print!("{line_without_ending}//\x1b[;G");
for (style, mut s) in ranges {
s = s.trim_end_matches('\n');
let (r, g, b) = (
style.foreground.r,
style.foreground.g,
style.foreground.b,
);
print!("\x1b[38;2;{r};{g};{b}m{s}");
}
println!(" "); // erases the comment
}
}
