Initial highlighting code.

The dust auto-escaping is causing this naive approach to fail so I will have to create a distinction between highlighted code and not-highlighted code.
This commit is contained in:
Tom Alexander
2025-02-22 15:09:00 -05:00
parent ae6f18d19c
commit b06424cb17
3 changed files with 201 additions and 7 deletions

View File

@@ -1,6 +1,12 @@
use std::borrow::Cow;
use super::macros::intermediate;
use crate::error::CustomError;
use organic::types::StandardProperties;
use tree_sitter_highlight::Highlight;
use tree_sitter_highlight::HighlightConfiguration;
use tree_sitter_highlight::HighlightEvent;
use tree_sitter_highlight::Highlighter;
#[derive(Debug, Clone)]
pub(crate) struct ISrcBlock {
@@ -59,6 +65,14 @@ intermediate!(
})
.collect();
let language = original.language.map(str::to_owned);
let lines = match language.as_ref().map(String::as_str) {
Some("nix") => {
// foo
highlight_nix(lines)?
}
_ => lines,
};
Ok(ISrcBlock {
lines,
language,
@@ -76,3 +90,57 @@ fn ascii_whitespace_value(c: char) -> usize {
_ => unreachable!("Only ascii whitespace can reach this code."),
}
}
fn highlight_nix(lines: Vec<String>) -> Result<Vec<String>, CustomError> {
let highlight_names = ["comment", "keyword"];
// Need 1 highlighter per thread
let mut highlighter = Highlighter::new();
let language = tree_sitter_nix::LANGUAGE.into();
let mut config =
HighlightConfiguration::new(language, "nix", tree_sitter_nix::HIGHLIGHTS_QUERY, "", "")
.unwrap();
config.configure(&highlight_names);
let combined_text = lines.join("");
let highlights = highlighter
.highlight(&config, combined_text.as_bytes(), None, |_| None)
.unwrap();
let mut highlighted_text = Vec::new();
for event in highlights {
match event.unwrap() {
HighlightEvent::Source { start, end } => {
highlighted_text.push(Cow::Borrowed(&combined_text[start..end]));
}
HighlightEvent::HighlightStart(s) => {
let class_name = format!("srchl_{}", highlight_names[s.0]);
highlighted_text.push(Cow::Owned(format!(r#"<span class="{}">"#, class_name)));
}
HighlightEvent::HighlightEnd => {
highlighted_text.push(Cow::Borrowed(r#"</span>"#));
}
}
}
let highlighted_text = highlighted_text.join("");
let lines = highlighted_text
.split_inclusive('\n')
.map(str::to_owned)
.collect();
Ok(lines)
}
// use tree_sitter::Parser;
// fn dump_nix<B>(body: B) -> Result<(), CustomError>
// where
// B: AsRef<str>,
// {
// let mut parser = Parser::new();
// parser
// .set_language(&tree_sitter_nix::LANGUAGE.into())
// .expect("Error loading Nix grammar");
// let mut tree = parser.parse(body.as_ref(), None).unwrap();
// println!("{}", tree.root_node());
// Ok(())
// }