//! Finds syntax definitions, chooses one for a file, and compiles them on demand. use super::def::*; use super::engine::{Highlighter, State}; use std::collections::{HashMap, HashSet}; use std::io::Read; use std::path::{Path, PathBuf}; use std::sync::Arc; #[derive(Clone, Debug)] pub struct Language { pub name: String, pub alternatives: Vec, pub section: String, pub extensions: Vec, pub mimetypes: Vec, pub priority: i32, pub hidden: bool, pub path: PathBuf, } struct Loaded { root: CtxId, meta: DefMeta, } pub struct Registry { pub languages: Vec, by_name: HashMap, loaded: HashMap, pub compiled: Compiled, lists: HashMap<(String, String), Arc>, } pub fn search_dirs() -> Vec { let mut v = vec![]; if let Some(d) = dirs::data_dir() { v.push(d.join("org.kde.syntax-highlighting/syntax")); v.push(d.join("damson/syntax")); } let shared = std::env::var("XDG_DATA_DIRS").unwrap_or_else(|_| "/usr/local/share:/usr/share".into()); for d in shared.split(':').filter(|s| !s.is_empty()) { v.push(Path::new(d).join("org.kde.syntax-highlighting/syntax")); v.push(Path::new(d).join("org.kde.syntax-highlighting/syntax-bundled")); } if let Ok(exe) = std::env::current_exe() { if let Some(d) = exe.parent() { v.push(d.join("syntax")); v.push(d.join("../share/damson/syntax")); } } v } /// Pulls `name="…"` attributes out of the `` tag without parsing the whole file. fn header_attrs(head: &str) -> HashMap { let mut map = HashMap::new(); let Some(start) = head.find(" q = Some(c), (Some(x), _) if x == c => q = None, (None, '>') => { end = i; break } _ => {} } } end }; let tag = &rest[..tag_end]; let b = tag.as_bytes(); let mut i = 0; while i < b.len() { while i < b.len() && b[i].is_ascii_whitespace() { i += 1 } let ks = i; while i < b.len() && b[i] != b'=' && !b[i].is_ascii_whitespace() { i += 1 } let key = &tag[ks..i]; while i < b.len() && (b[i] == b'=' || b[i].is_ascii_whitespace()) { i += 1 } if i >= b.len() { break } let q = b[i]; if q != b'"' && q != b'\'' { i += 1; continue } i += 1; let vs = i; while i < b.len() && b[i] != q { i += 1 } map.insert(key.to_string(), tag[vs..i.min(tag.len())].replace("&", "&").replace("<", "<").replace(">", ">")); i += 1; } map } fn glob_match(pat: &str, name: &str) -> bool { let p: Vec = pat.chars().collect(); let n: Vec = name.chars().collect(); let (mut i, mut j, mut star, mut mark) = (0, 0, None, 0); while j < n.len() { if i < p.len() && (p[i] == '?' || p[i] == n[j]) { i += 1; j += 1; } else if i < p.len() && p[i] == '*' { star = Some(i); mark = j; i += 1; } else if let Some(s) = star { i = s + 1; mark += 1; j = mark; } else { return false; } } while i < p.len() && p[i] == '*' { i += 1 } i == p.len() } impl Registry { pub fn scan() -> Registry { Self::scan_dirs(&search_dirs()) } pub fn scan_dirs(dirs: &[PathBuf]) -> Registry { let mut languages: Vec = vec![]; let mut by_name: HashMap = HashMap::new(); for dir in dirs { let Ok(rd) = std::fs::read_dir(dir) else { continue }; let mut files: Vec = rd.flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|e| e == "xml")).collect(); files.sort(); for path in files { // earlier folders win, so a definition in the user's folder replaces the system one let mut buf = [0u8; 8192]; let Ok(n) = std::fs::File::open(&path).and_then(|mut f| f.read(&mut buf)) else { continue }; let head = String::from_utf8_lossy(&buf[..n]); let a = header_attrs(&head); let Some(name) = a.get("name").cloned() else { continue }; if by_name.contains_key(&name) { continue } let split = |k: &str| a.get(k).map(|s| s.split(';').map(|x| x.trim().to_string()).filter(|x| !x.is_empty()).collect()).unwrap_or_default(); by_name.insert(name.clone(), languages.len()); languages.push(Language { alternatives: split("alternativeNames"), section: a.get("section").cloned().unwrap_or_default(), extensions: split("extensions"), mimetypes: split("mimetype"), priority: a.get("priority").and_then(|p| p.parse().ok()).unwrap_or(0), hidden: a.get("hidden").is_some_and(|h| h == "true" || h == "1"), path, name, }); } } Registry { languages, by_name, loaded: HashMap::new(), compiled: Compiled::default(), lists: HashMap::new() } } /// The definition for a file name, by Kate's rule: the highest priority among matching globs. pub fn detect(&self, file_name: &str, first_line: &str) -> Option<&str> { // .rev() because max_by_key keeps the last of equals, and the first in the list should win let best = self.languages.iter().rev().filter(|l| !l.hidden && l.extensions.iter().any(|g| glob_match(g, file_name))).max_by_key(|l| l.priority); if let Some(l) = best { return Some(&l.name); } let s = first_line.trim_end(); if let Some(rest) = s.strip_prefix("#!") { let word = rest.trim().rsplit('/').next().unwrap_or(""); let word = if word.starts_with("env") { rest.split_whitespace().nth(1).unwrap_or("") } else { word.split_whitespace().next().unwrap_or("") }; let name = match word.trim_end_matches(|c: char| c.is_ascii_digit() || c == '.') { "python" => "Python", "bash" | "sh" | "zsh" | "dash" | "ksh" => "Bash", "fish" => "Fish", "node" | "deno" => "JavaScript", "ruby" => "Ruby", "perl" => "Perl", "lua" => "Lua", "php" => "PHP", _ => return None, }; return self.by_name.contains_key(name).then_some(name); } None } pub fn knows(&self, name: &str) -> bool { self.by_name.contains_key(name) } /// The extension to suggest when saving a file in this language. pub fn extension_of(&self, name: &str) -> Option { if let Some(e) = super::guess::extension(name) { return Some(e.to_string()); } let lang = self.languages.get(*self.by_name.get(name)?)?; lang.extensions.iter().find_map(|g| g.strip_prefix("*.").filter(|e| e.chars().all(char::is_alphanumeric)).map(str::to_string)) } pub fn meta(&mut self, name: &str) -> DefMeta { self.load(name); self.loaded.get(name).map(|l| l.meta.clone()).unwrap_or_default() } pub fn initial_state(&mut self, name: &str) -> Option { self.load(name)?; self.loaded.get(name).map(|l| Highlighter::initial(l.root)) } fn intern_list(&mut self, def: &str, name: &str, doc: roxmltree::Node) -> Arc { let key = (def.to_string(), name.to_string()); if let Some(l) = self.lists.get(&key) { return l.clone(); } let mut list = KeywordList::default(); let mut seen = HashSet::new(); self.collect_list(name, doc, &mut list, &mut seen); let a = Arc::new(list); self.lists.insert(key, a.clone()); a } fn collect_list(&self, name: &str, doc: roxmltree::Node, out: &mut KeywordList, seen: &mut HashSet) { if !seen.insert(name.to_string()) { return; } let Some(node) = doc.descendants().find(|n| n.has_tag_name("list") && n.attribute("name") == Some(name)) else { return }; for ch in node.children().filter(|n| n.is_element()) { match ch.tag_name().name() { "item" => { if let Some(t) = ch.text() { let t = t.trim(); out.cased.insert(t.to_string()); out.folded.insert(t.to_lowercase()); } } "include" => { if let Some(t) = ch.text() { self.collect_list(t.trim(), doc, out, seen); } } _ => {} } } } fn region(&mut self, def: &str, name: &str) -> u32 { let n = self.compiled.regions.len() as u32; *self.compiled.regions.entry(format!("{def}\0{name}")).or_insert(n) } /// Compiles a definition and everything it includes. Returns its root context. pub fn load(&mut self, name: &str) -> Option { if let Some(l) = self.loaded.get(name) { return Some(l.root); } let idx = *self.by_name.get(name)?; let path = self.languages[idx].path.clone(); let text = std::fs::read_to_string(&path).ok()?; let opts = roxmltree::ParsingOptions { allow_dtd: true, ..Default::default() }; let doc = roxmltree::Document::parse_with_options(&text, opts).ok()?; let root_el = doc.root_element(); let hl = root_el.children().find(|n| n.has_tag_name("highlighting"))?; let general = root_el.children().find(|n| n.has_tag_name("general")); // styles let mut style_of: HashMap = HashMap::new(); if let Some(items) = hl.children().find(|n| n.has_tag_name("itemDatas")) { for it in items.children().filter(|n| n.has_tag_name("itemData")) { let info = StyleInfo { base: DefStyle::parse(it.attribute("defStyleNum").unwrap_or("dsNormal")), bold: it.attribute("bold").map(truthy), italic: it.attribute("italic").map(truthy), underline: it.attribute("underline").is_some_and(truthy), }; self.compiled.styles.push(info); style_of.insert(it.attribute("name").unwrap_or("").to_string(), (self.compiled.styles.len() - 1) as StyleId); } } if self.compiled.styles.is_empty() { self.compiled.styles.push(StyleInfo { base: DefStyle::Normal, bold: None, italic: None, underline: false }); } let default_style = style_of.values().copied().min().unwrap_or(0); // reserve context ids first: contexts refer to each other, and other definitions to these let ctxs: Vec = hl.children().find(|n| n.has_tag_name("contexts")).map(|c| c.children().filter(|n| n.has_tag_name("context")).collect()).unwrap_or_default(); if ctxs.is_empty() { return None; } let base = self.compiled.contexts.len() as CtxId; let mut ids: HashMap = HashMap::new(); for (i, c) in ctxs.iter().enumerate() { ids.entry(c.attribute("name").unwrap_or("").to_string()).or_insert(base + i as CtxId); let placeholder = Context { style: 0, rules: vec![], line_end: Switch::default(), line_empty: None, fallthrough: None, dynamic: false }; self.compiled.contexts.push(placeholder); } let mut meta = DefMeta::default(); if let Some(g) = general { if let Some(cm) = g.children().find(|n| n.has_tag_name("comments")) { for c in cm.children().filter(|n| n.has_tag_name("comment")) { match c.attribute("name") { Some("singleLine") => meta.line_comment = c.attribute("start").map(str::to_string), Some("multiLine") => meta.block_comment = c.attribute("start").zip(c.attribute("end")).map(|(a, b)| (a.to_string(), b.to_string())), _ => {} } } } if let Some(f) = g.children().find(|n| n.has_tag_name("folding")) { meta.indent_fold = f.attribute("indentationsensitive").is_some_and(truthy); } } self.loaded.insert(name.to_string(), Loaded { root: base, meta }); let kw = general.and_then(|g| g.children().find(|n| n.has_tag_name("keywords"))); let default_ci = kw.and_then(|k| k.attribute("casesensitive")).is_some_and(|v| !truthy(v)); let delims = Arc::new(Delims::new(kw.and_then(|k| k.attribute("weakDeliminator")).unwrap_or(""), kw.and_then(|k| k.attribute("additionalDeliminator")).unwrap_or(""))); // first pass: own rules, with include markers; second pass flattens the includes let mut includes: Vec<(usize, usize, CtxId, bool)> = vec![]; for (i, c) in ctxs.iter().enumerate() { let cid = (base as usize) + i; let style = c.attribute("attribute").and_then(|a| style_of.get(a).copied()).unwrap_or(default_style); let line_end = self.switch(c.attribute("lineEndContext"), &ids, name); let line_empty = c.attribute("lineEmptyContext").map(|s| self.switch(Some(s), &ids, name)); let fall = if let Some(f) = c.attribute("fallthroughContext") { Some(self.switch(Some(f), &ids, name)) } else if c.attribute("fallthrough").is_some_and(truthy) { Some(Switch::default()) } else { None }; let fall = fall.filter(|s| !s.is_stay()); let mut rules = vec![]; for r in c.children().filter(|n| n.is_element()) { self.rule(r, &mut rules, &mut includes, cid, doc.root_element(), name, &ids, &style_of, default_ci, &delims); } let dynamic = c.attribute("dynamic").is_some_and(truthy); self.compiled.contexts[cid] = Context { style, rules, line_end, line_empty, fallthrough: fall, dynamic }; } self.flatten(&includes); Some(base) } fn flatten(&mut self, includes: &[(usize, usize, CtxId, bool)]) { // process in reverse so insertion indices of earlier includes in a context stay valid for (cid, at, target, attrib) in includes.iter().rev() { let mut seen = HashSet::from([*cid as CtxId]); let extra = self.clone_rules(*target, &mut seen); let ctx = &mut self.compiled.contexts[*cid]; let at = (*at).min(ctx.rules.len()); ctx.rules.splice(at..at, extra); if *attrib { let (s, f) = { let t = &self.compiled.contexts[*target as usize]; (t.style, t.fallthrough) }; let ctx = &mut self.compiled.contexts[*cid]; ctx.style = s; if ctx.fallthrough.is_none() { ctx.fallthrough = f } } } } fn clone_rules(&self, target: CtxId, _seen: &mut HashSet) -> Vec { self.compiled.contexts[target as usize].rules.iter().map(clone_rule).collect() } fn switch(&mut self, spec: Option<&str>, ids: &HashMap, def: &str) -> Switch { let Some(mut s) = spec else { return Switch::default() }; let mut out = Switch::default(); s = s.trim(); if s.is_empty() || s == "#stay" { return out; } while let Some(r) = s.strip_prefix("#pop") { out.pops += 1; s = r; } let s = s.strip_prefix('!').unwrap_or(s); if s.is_empty() { return out; } out.push = self.resolve(s, ids, def); out } fn resolve(&mut self, s: &str, ids: &HashMap, def: &str) -> Option { if let Some((ctx, other)) = s.split_once("##") { let other = other.trim(); if other == def { return if ctx.is_empty() { ids.values().min().copied() } else { ids.get(ctx).copied() }; } let root = self.load(other)?; if ctx.is_empty() { return Some(root); } return self.find_ctx(other, ctx); } ids.get(s).copied() } /// A named context of an already-loaded definition. Names are re-read from its file. fn find_ctx(&self, def: &str, ctx: &str) -> Option { let idx = *self.by_name.get(def)?; let text = std::fs::read_to_string(&self.languages[idx].path).ok()?; let opts = roxmltree::ParsingOptions { allow_dtd: true, ..Default::default() }; let doc = roxmltree::Document::parse_with_options(&text, opts).ok()?; let root = self.loaded.get(def)?.root; let hl = doc.root_element().children().find(|n| n.has_tag_name("highlighting"))?; let pos = hl.children().find(|n| n.has_tag_name("contexts"))?.children().filter(|n| n.has_tag_name("context")).position(|c| c.attribute("name") == Some(ctx))?; Some(root + pos as CtxId) } #[allow(clippy::too_many_arguments)] fn rule(&mut self, r: roxmltree::Node, out: &mut Vec, inc: &mut Vec<(usize, usize, CtxId, bool)>, cid: usize, doc: roxmltree::Node, def: &str, ids: &HashMap, styles: &HashMap, default_ci: bool, delims: &Arc) { let tag = r.tag_name().name(); if tag == "IncludeRules" { if let Some(t) = r.attribute("context").and_then(|s| self.resolve(s, ids, def)) { inc.push((cid, out.len(), t, r.attribute("includeAttrib").is_some_and(truthy))); } return; } let a = |k: &str| r.attribute(k); let ch = |k: &str| a(k).and_then(|s| s.chars().next()); let ci = a("insensitive").map(truthy).unwrap_or(false); let dynamic = a("dynamic").is_some_and(truthy); let matcher = match tag { "DetectChar" => { let c = ch("char").unwrap_or('\0'); let dyn_idx = (dynamic && c.is_ascii_digit()).then(|| c.to_digit(10).unwrap() as usize); Matcher::DetectChar { c, dyn_idx } } "Detect2Chars" => Matcher::Detect2Chars { a: ch("char").unwrap_or('\0'), b: ch("char1").unwrap_or('\0') }, "AnyChar" => Matcher::AnyChar(a("String").unwrap_or("").chars().collect()), "StringDetect" => Matcher::StringDetect { s: a("String").unwrap_or("").to_string(), ci, dynamic }, "WordDetect" => Matcher::WordDetect { s: a("String").unwrap_or("").to_string(), ci }, "RegExpr" => { let source = a("String").unwrap_or("").to_string(); let minimal = a("minimal").is_some_and(truthy); let re = if dynamic { None } else { match compile_regex(&source, ci, minimal) { Ok(r) => Some(Arc::new(r)), Err(e) => { self.compiled.bad_regexes.push((format!("{def}: {source}"), e)); None } } }; Matcher::Regex { re, source, ci, minimal, dynamic } } "keyword" => { let name = a("String").unwrap_or(""); let list = self.intern_list(def, name, doc); let ci = a("insensitive").map(truthy).unwrap_or(default_ci); Matcher::Keyword { list, ci } } "Int" => Matcher::Int, "Float" => Matcher::Float, "HlCOct" => Matcher::HlCOct, "HlCHex" => Matcher::HlCHex, "HlCStringChar" => Matcher::HlCStringChar, "HlCChar" => Matcher::HlCChar, "RangeDetect" => Matcher::RangeDetect { a: ch("char").unwrap_or('\0'), b: ch("char1").unwrap_or('\0') }, "LineContinue" => Matcher::LineContinue { c: ch("char").unwrap_or('\\') }, "DetectSpaces" => Matcher::DetectSpaces, "DetectIdentifier" => Matcher::DetectIdentifier, _ => return, }; let switch = self.switch(a("context"), ids, def); let begin_region = a("beginRegion").map(|n| self.region(def, n)); let end_region = a("endRegion").map(|n| self.region(def, n)); out.push(Rule { matcher, style: a("attribute").and_then(|s| styles.get(s).copied()), switch, look_ahead: a("lookAhead").is_some_and(truthy), first_non_space: a("firstNonSpace").is_some_and(truthy), column: a("column").and_then(|c| c.parse().ok()), begin_region, end_region, delims: delims.clone(), }); } } fn truthy(s: &str) -> bool { matches!(s.to_ascii_lowercase().as_str(), "1" | "true") } fn clone_rule(r: &Rule) -> Rule { let matcher = match &r.matcher { Matcher::DetectChar { c, dyn_idx } => Matcher::DetectChar { c: *c, dyn_idx: *dyn_idx }, Matcher::Detect2Chars { a, b } => Matcher::Detect2Chars { a: *a, b: *b }, Matcher::AnyChar(v) => Matcher::AnyChar(v.clone()), Matcher::StringDetect { s, ci, dynamic } => Matcher::StringDetect { s: s.clone(), ci: *ci, dynamic: *dynamic }, Matcher::WordDetect { s, ci } => Matcher::WordDetect { s: s.clone(), ci: *ci }, Matcher::Regex { re, source, ci, minimal, dynamic } => Matcher::Regex { re: re.clone(), source: source.clone(), ci: *ci, minimal: *minimal, dynamic: *dynamic }, Matcher::Keyword { list, ci } => Matcher::Keyword { list: list.clone(), ci: *ci }, Matcher::Int => Matcher::Int, Matcher::Float => Matcher::Float, Matcher::HlCOct => Matcher::HlCOct, Matcher::HlCHex => Matcher::HlCHex, Matcher::HlCStringChar => Matcher::HlCStringChar, Matcher::HlCChar => Matcher::HlCChar, Matcher::RangeDetect { a, b } => Matcher::RangeDetect { a: *a, b: *b }, Matcher::LineContinue { c } => Matcher::LineContinue { c: *c }, Matcher::DetectSpaces => Matcher::DetectSpaces, Matcher::DetectIdentifier => Matcher::DetectIdentifier, }; Rule { matcher, style: r.style, switch: r.switch, look_ahead: r.look_ahead, first_non_space: r.first_non_space, column: r.column, begin_region: r.begin_region, end_region: r.end_region, delims: r.delims.clone() } }