|
| 1 | +use super::Chunk; |
| 2 | +use anyhow::{Context, Result}; |
| 3 | +use tree_sitter_highlight::{HighlightConfiguration, HighlightEvent, Highlighter}; |
| 4 | + |
| 5 | +pub fn highlight( |
| 6 | + language: tree_sitter::Language, |
| 7 | + highlights_query: &str, |
| 8 | + tags: &[&'static str], |
| 9 | + input: &[u8], |
| 10 | +) -> Result<Vec<Chunk>> { |
| 11 | + let mut highlighter = Highlighter::new(); |
| 12 | + let mut config = HighlightConfiguration::new(language, "", highlights_query, "", "") |
| 13 | + .context("failed to create highlight configuration")?; |
| 14 | + config.configure(tags); |
| 15 | + |
| 16 | + let highlights = highlighter |
| 17 | + .highlight(&config, input, None, |_| None) |
| 18 | + .context("failed to highlight")?; |
| 19 | + |
| 20 | + let mut chunks: Vec<Chunk> = Vec::new(); |
| 21 | + let mut tag: Option<&'static str> = None; |
| 22 | + |
| 23 | + for event in highlights { |
| 24 | + let event = event.context("highlighter failure")?; |
| 25 | + match event { |
| 26 | + HighlightEvent::Source { start, end } => { |
| 27 | + let contents = &input[start..end]; |
| 28 | + let tag_str = tag.unwrap_or(""); |
| 29 | + |
| 30 | + match chunks.last_mut() { |
| 31 | + Some(x) if x.0 == tag_str => { |
| 32 | + x.1.push_str(&String::from_utf8_lossy(contents)); |
| 33 | + } |
| 34 | + _ => chunks.push( |
| 35 | + (tag_str, String::from_utf8_lossy(contents).to_string()) |
| 36 | + ), |
| 37 | + } |
| 38 | + } |
| 39 | + HighlightEvent::HighlightStart(s) => { |
| 40 | + tag = Some(tags[s.0]); |
| 41 | + } |
| 42 | + HighlightEvent::HighlightEnd => { |
| 43 | + tag = None; |
| 44 | + } |
| 45 | + } |
| 46 | + } |
| 47 | + Ok(chunks) |
| 48 | +} |
| 49 | + |
| 50 | +#[cfg(test)] |
| 51 | +pub(super) fn test_tags_ok( |
| 52 | + language: tree_sitter::Language, |
| 53 | + highlights_query: &str, |
| 54 | + tags: &[&'static str], |
| 55 | +) { |
| 56 | + let config = HighlightConfiguration::new(language, "", highlights_query, "", "").unwrap(); |
| 57 | + for &tag in tags { |
| 58 | + assert!( |
| 59 | + config.names().iter().any(|name| name.contains(tag)), |
| 60 | + "Invalid tag: {},\nAllowed tags: {:?}", |
| 61 | + tag, |
| 62 | + config.names() |
| 63 | + ); |
| 64 | + } |
| 65 | +} |
0 commit comments