| 1 |
use std::{ |
| 2 |
cell::RefCell, |
| 3 |
collections::HashMap, |
| 4 |
fmt::Write as FmtWrite, |
| 5 |
io::{ErrorKind, Write as IoWrite}, |
| 6 |
path::Path, |
| 7 |
sync::LazyLock, |
| 8 |
}; |
| 9 |
|
| 10 |
use comrak::adapters::SyntaxHighlighterAdapter; |
| 11 |
use tree_sitter_grammar_repository::{Grammar, Language}; |
| 12 |
use tree_sitter_highlight::{HighlightConfiguration, HighlightEvent, Highlighter}; |
| 13 |
|
| 14 |
thread_local! { |
| 15 |
static HIGHLIGHTER: RefCell<Highlighter> = RefCell::new(Highlighter::new()); |
| 16 |
} |
| 17 |
|
| 18 |
macro_rules! count { |
| 19 |
() => (0); |
| 20 |
($e:expr) => (1); |
| 21 |
($e:expr, $($rest:expr),*) => (1 + count!($($rest),*)); |
| 22 |
} |
| 23 |
|
| 24 |
macro_rules! define_classes { |
| 25 |
($($name:literal => $class:literal),*,) => { |
| 26 |
static HIGHLIGHT_NAMES: [&str; count!($($name),*)] = [ |
| 27 |
$($name),* |
| 28 |
]; |
| 29 |
|
| 30 |
static HIGHLIGHT_CLASSES: [&str; count!($($name),*)] = [ |
| 31 |
$($class),* |
| 32 |
]; |
| 33 |
}; |
| 34 |
} |
| 35 |
|
| 36 |
define_classes! { |
| 37 |
"attribute" => "attribute", |
| 38 |
"boolean" => "boolean", |
| 39 |
"carriage-return" => "carriage-return", |
| 40 |
"comment" => "comment", |
| 41 |
"comment.documentation" => "comment documentation", |
| 42 |
"constant" => "constant", |
| 43 |
"constant.builtin" => "constant builtin", |
| 44 |
"constructor" => "constructor", |
| 45 |
"constructor.builtin" => "constructor builtin", |
| 46 |
"embedded" => "embedded", |
| 47 |
"error" => "error", |
| 48 |
"escape" => "escape", |
| 49 |
"function" => "function", |
| 50 |
"function.builtin" => "function builtin", |
| 51 |
"keyword" => "keyword", |
| 52 |
"markup" => "markup", |
| 53 |
"markup.bold" => "markup bold", |
| 54 |
"markup.heading" => "markup heading", |
| 55 |
"markup.italic" => "markup italic", |
| 56 |
"markup.link" => "markup link", |
| 57 |
"markup.link.url" => "markup link url", |
| 58 |
"markup.list" => "markup list", |
| 59 |
"markup.list.checked" => "markup list checked", |
| 60 |
"markup.list.numbered" => "markup list numbered", |
| 61 |
"markup.list.unchecked" => "markup list unchecked", |
| 62 |
"markup.list.unnumbered" => "markup list unnumbered", |
| 63 |
"markup.quote" => "markup quote", |
| 64 |
"markup.raw" => "markup raw", |
| 65 |
"markup.raw.block" => "markup raw block", |
| 66 |
"markup.raw.inline" => "markup raw inline", |
| 67 |
"markup.strikethrough" => "markup strikethrough", |
| 68 |
"module" => "module", |
| 69 |
"number" => "number", |
| 70 |
"operator" => "operator", |
| 71 |
"property" => "property", |
| 72 |
"property.builtin" => "property builtin", |
| 73 |
"punctuation" => "punctuation", |
| 74 |
"punctuation.bracket" => "punctuation bracket", |
| 75 |
"punctuation.delimiter" => "punctuation delimiter", |
| 76 |
"punctuation.special" => "punctuation special", |
| 77 |
"string" => "string", |
| 78 |
"string.escape" => "string escape", |
| 79 |
"string.regexp" => "string regexp", |
| 80 |
"string.special" => "string special", |
| 81 |
"string.special.symbol" => "string special symbol", |
| 82 |
"tag" => "tag", |
| 83 |
"type" => "type", |
| 84 |
"type.builtin" => "type builtin", |
| 85 |
"variable" => "variable", |
| 86 |
"variable.builtin" => "variable builtin", |
| 87 |
"variable.member" => "variable member", |
| 88 |
"variable.parameter" => "variable parameter",} |
| 89 |
|
| 90 |
pub fn prime_highlighters() { |
| 91 |
let _res = HIGHLIGHTER_CONFIGS.len(); |
| 92 |
} |
| 93 |
|
| 94 |
static HIGHLIGHTER_CONFIGS: LazyLock<Vec<HighlightConfiguration>> = LazyLock::new(|| { |
| 95 |
Grammar::VARIANTS |
| 96 |
.iter() |
| 97 |
.copied() |
| 98 |
.map(Grammar::highlight_configuration_params) |
| 99 |
.map(|v| { |
| 100 |
let mut configuration = HighlightConfiguration::new( |
| 101 |
v.language.into(), |
| 102 |
v.name, |
| 103 |
v.highlights_query, |
| 104 |
v.injection_query, |
| 105 |
v.locals_query, |
| 106 |
) |
| 107 |
.unwrap_or_else(|e| panic!("bad query for {}: {e}", v.name)); |
| 108 |
configuration.configure(&HIGHLIGHT_NAMES); |
| 109 |
configuration |
| 110 |
}) |
| 111 |
.collect() |
| 112 |
}); |
| 113 |
|
| 114 |
pub fn fetch_highlighter_config(file: &Path) -> Option<&'static HighlightConfiguration> { |
| 115 |
Language::from_file_name(file) |
| 116 |
.map(Language::grammar) |
| 117 |
.map(Grammar::idx) |
| 118 |
.map(|idx| &HIGHLIGHTER_CONFIGS[idx]) |
| 119 |
} |
| 120 |
|
| 121 |
pub fn fetch_highlighter_config_by_token(token: &str) -> Option<&'static HighlightConfiguration> { |
| 122 |
Language::from_injection(token) |
| 123 |
.map(Language::grammar) |
| 124 |
.map(Grammar::idx) |
| 125 |
.map(|idx| &HIGHLIGHTER_CONFIGS[idx]) |
| 126 |
} |
| 127 |
|
| 128 |
pub struct ComrakHighlightAdapter; |
| 129 |
|
| 130 |
impl SyntaxHighlighterAdapter for ComrakHighlightAdapter { |
| 131 |
fn write_highlighted( |
| 132 |
&self, |
| 133 |
output: &mut dyn IoWrite, |
| 134 |
lang: Option<&str>, |
| 135 |
code: &str, |
| 136 |
) -> std::io::Result<()> { |
| 137 |
let out = format_file(code, FileIdentifier::Token(lang.unwrap_or_default())) |
| 138 |
.map_err(|e| std::io::Error::new(ErrorKind::Other, e))?; |
| 139 |
output.write_all(out.as_bytes()) |
| 140 |
} |
| 141 |
|
| 142 |
fn write_pre_tag( |
| 143 |
&self, |
| 144 |
output: &mut dyn IoWrite, |
| 145 |
_attributes: HashMap<String, String>, |
| 146 |
) -> std::io::Result<()> { |
| 147 |
write!(output, "<pre>") |
| 148 |
} |
| 149 |
|
| 150 |
fn write_code_tag( |
| 151 |
&self, |
| 152 |
_output: &mut dyn IoWrite, |
| 153 |
_attributes: HashMap<String, String>, |
| 154 |
) -> std::io::Result<()> { |
| 155 |
Ok(()) |
| 156 |
} |
| 157 |
} |
| 158 |
|
| 159 |
#[derive(Copy, Clone, Debug)] |
| 160 |
pub enum FileIdentifier<'a> { |
| 161 |
Path(&'a Path), |
| 162 |
Token(&'a str), |
| 163 |
} |
| 164 |
|
| 165 |
fn render_line_prefix(tag: bool, line_number: usize) -> String { |
| 166 |
if !tag { |
| 167 |
return "".to_string(); |
| 168 |
} |
| 169 |
format!("<span class='lnb'><a id='n{0}' href='#n{0}'>{0}</a></span><code>", line_number) |
| 170 |
} |
| 171 |
|
| 172 |
fn render_line_suffix(tag: bool, line_number: usize) -> String { |
| 173 |
if !tag { |
| 174 |
return "\n".to_string(); |
| 175 |
} |
| 176 |
"</code>\n".to_string() |
| 177 |
} |
| 178 |
|
| 179 |
pub fn format_file(content: &str, identifier: FileIdentifier<'_>) -> Result<String. Error> { |
| 180 |
let mut out = String::new(); |
| 181 |
format_file_inner(&mut out, content, identifier, true)?; |
| 182 |
Ok(out) |
| 183 |
} |
| 184 |
|
| 185 |
pub fn format_file_inner( |
| 186 |
out: &mut String, |
| 187 |
content: &str, |
| 188 |
identifier: FileIdentifier<'_>, |
| 189 |
code_tag: bool, |
| 190 |
) -> anyhow::Result<()> { |
| 191 |
let config = match identifier { |
| 192 |
FileIdentifier::Path(v) => fetch_highlighter_config(v), |
| 193 |
FileIdentifier::Token(v) => fetch_highlighter_config_by_token(v), |
| 194 |
}; |
| 195 |
|
| 196 |
let Some(config) = config else { |
| 197 |
for (i, line) in content.lines().enumerate() { |
| 198 |
out.push_str(&render_line_prefix(code_tag, i)); |
| 199 |
v_htmlescape::b_escape(line.as_bytes(), out); |
| 200 |
out.push_str(&render_line_suffix(code_tag, i)); |
| 201 |
} |
| 202 |
|
| 203 |
return Ok(()); |
| 204 |
}; |
| 205 |
|
| 206 |
let mut line_number = 0; |
| 207 |
HIGHLIGHTER.with_borrow_mut(|highlighter| { |
| 208 |
highlighter.parser().reset(); |
| 209 |
|
| 210 |
let spans = highlighter.highlight(config, content.as_bytes(), None, |injection| { |
| 211 |
debug!(injection, "Highlighter switch requested"); |
| 212 |
fetch_highlighter_config_by_token(injection) |
| 213 |
}); |
| 214 |
|
| 215 |
let mut spans = match spans { |
| 216 |
Ok(v) => v, |
| 217 |
Err(error) => { |
| 218 |
error!( |
| 219 |
?error, |
| 220 |
"Failed to run highlighter, falling back to plaintext" |
| 221 |
); |
| 222 |
|
| 223 |
for line in content.lines() { |
| 224 |
line_number = line_number + 1; |
| 225 |
out.push_str(&render_line_prefix(code_tag, line_number)); |
| 226 |
v_htmlescape::b_escape(line.as_bytes(), out); |
| 227 |
out.push_str(&render_line_suffix(code_tag, line_number)); |
| 228 |
} |
| 229 |
|
| 230 |
return Ok(()); |
| 231 |
} |
| 232 |
}; |
| 233 |
|
| 234 |
let mut tag_open = true; |
| 235 |
line_number = line_number + 1; |
| 236 |
out.push_str(&render_line_prefix(code_tag, line_number)); |
| 237 |
|
| 238 |
while let Some(span) = spans.next().transpose()? { |
| 239 |
if !tag_open { |
| 240 |
line_number = line_number + 1; |
| 241 |
out.push_str(&render_line_prefix(code_tag, line_number)); |
| 242 |
tag_open = true; |
| 243 |
} |
| 244 |
|
| 245 |
match span { |
| 246 |
HighlightEvent::Source { start, end } => { |
| 247 |
let content = &content[start..end]; |
| 248 |
|
| 249 |
for (i, line) in content.lines().enumerate() { |
| 250 |
if i != 0 { |
| 251 |
out.push_str(&render_line_suffix(code_tag, line_number)); |
| 252 |
line_number = line_number + 1; |
| 253 |
out.push_str(&render_line_prefix(code_tag, line_number)); |
| 254 |
} |
| 255 |
v_htmlescape::b_escape(line.as_bytes(), out); |
| 256 |
} |
| 257 |
|
| 258 |
if content.ends_with('\n') { |
| 259 |
out.push_str(&render_line_suffix(code_tag, line_number)); |
| 260 |
tag_open = false; |
| 261 |
} |
| 262 |
} |
| 263 |
HighlightEvent::HighlightStart(highlight) => { |
| 264 |
write!( |
| 265 |
out, |
| 266 |
r#"<span class="highlight {}">"#, |
| 267 |
HIGHLIGHT_CLASSES[highlight.0] |
| 268 |
)?; |
| 269 |
} |
| 270 |
HighlightEvent::HighlightEnd => { |
| 271 |
out.push_str("</span>"); |
| 272 |
} |
| 273 |
} |
| 274 |
} |
| 275 |
|
| 276 |
if tag_open { |
| 277 |
out.push_str(&render_line_suffix(code_tag, line_number)); |
| 278 |
} |
| 279 |
|
| 280 |
Ok::<_, anyhow::Error>(()) |
| 281 |
})?; |
| 282 |
|
| 283 |
Ok(()) |
| 284 |
} |