Damson: a Material You code editor in Rust
Runs Kate's syntax definitions directly, on a hand-written editor core. Spring-driven UI with a pop-out scrolling preview, baked-in terminal grown from a morphing button, jelly tabs, command palette, side panels, git, language servers and hot exit. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
commit
8151aa71c0
4 changed files with 13923 additions and 0 deletions
237
src/syntax/def.rs
Normal file
237
src/syntax/def.rs
Normal file
|
|
@ -0,0 +1,237 @@
|
|||
//! Compiled form of a Kate syntax definition. All definitions live in one `Compiled` arena, because
|
||||
//! rules include contexts from other definitions (`##Doxygen`, `##Comments`, …).
|
||||
|
||||
use fancy_regex::Regex;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
pub type StyleId = u16;
|
||||
pub type CtxId = u32;
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
|
||||
pub enum DefStyle {
|
||||
Normal, Keyword, Function, Variable, ControlFlow, Operator, BuiltIn, Extension, Preprocessor,
|
||||
Attribute, Char, SpecialChar, String, VerbatimString, SpecialString, Import, DataType, DecVal,
|
||||
BaseN, Float, Constant, Comment, Documentation, Annotation, CommentVar, RegionMarker,
|
||||
Information, Warning, Alert, Others, Error,
|
||||
}
|
||||
|
||||
impl DefStyle {
|
||||
pub fn parse(s: &str) -> DefStyle {
|
||||
use DefStyle::*;
|
||||
match s.trim_start_matches("ds").to_ascii_lowercase().as_str() {
|
||||
"keyword" => Keyword, "function" => Function, "variable" => Variable,
|
||||
"controlflow" => ControlFlow, "operator" => Operator, "builtin" => BuiltIn,
|
||||
"extension" => Extension, "preprocessor" => Preprocessor, "attribute" => Attribute,
|
||||
"char" => Char, "specialchar" => SpecialChar, "string" => String,
|
||||
"verbatimstring" => VerbatimString, "specialstring" => SpecialString, "import" => Import,
|
||||
"datatype" => DataType, "decval" => DecVal, "basen" => BaseN, "float" => Float,
|
||||
"constant" => Constant, "comment" => Comment, "documentation" => Documentation,
|
||||
"annotation" => Annotation, "commentvar" => CommentVar, "regionmarker" => RegionMarker,
|
||||
"information" => Information, "warning" => Warning, "alert" => Alert, "others" => Others,
|
||||
"error" => Error, _ => Normal,
|
||||
}
|
||||
}
|
||||
|
||||
/// The name Kate's `.theme` files use for this style.
|
||||
pub fn theme_key(self) -> &'static str {
|
||||
use DefStyle::*;
|
||||
match self {
|
||||
Normal => "Normal", Keyword => "Keyword", Function => "Function", Variable => "Variable",
|
||||
ControlFlow => "ControlFlow", Operator => "Operator", BuiltIn => "BuiltIn",
|
||||
Extension => "Extension", Preprocessor => "Preprocessor", Attribute => "Attribute",
|
||||
Char => "Char", SpecialChar => "SpecialChar", String => "String",
|
||||
VerbatimString => "VerbatimString", SpecialString => "SpecialString", Import => "Import",
|
||||
DataType => "DataType", DecVal => "DecVal", BaseN => "BaseN", Float => "Float",
|
||||
Constant => "Constant", Comment => "Comment", Documentation => "Documentation",
|
||||
Annotation => "Annotation", CommentVar => "CommentVar", RegionMarker => "RegionMarker",
|
||||
Information => "Information", Warning => "Warning", Alert => "Alert", Others => "Others",
|
||||
Error => "Error",
|
||||
}
|
||||
}
|
||||
|
||||
pub const ALL: [DefStyle; 31] = {
|
||||
use DefStyle::*;
|
||||
[Normal, Keyword, Function, Variable, ControlFlow, Operator, BuiltIn, Extension, Preprocessor,
|
||||
Attribute, Char, SpecialChar, String, VerbatimString, SpecialString, Import, DataType, DecVal,
|
||||
BaseN, Float, Constant, Comment, Documentation, Annotation, CommentVar, RegionMarker,
|
||||
Information, Warning, Alert, Others, Error]
|
||||
};
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct StyleInfo {
|
||||
pub base: DefStyle,
|
||||
pub bold: Option<bool>,
|
||||
pub italic: Option<bool>,
|
||||
pub underline: bool,
|
||||
}
|
||||
|
||||
/// What a rule (or a line end) does to the context stack.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct Switch {
|
||||
pub pops: u8,
|
||||
pub push: Option<CtxId>,
|
||||
}
|
||||
|
||||
impl Switch {
|
||||
pub fn is_stay(&self) -> bool {
|
||||
self.pops == 0 && self.push.is_none()
|
||||
}
|
||||
}
|
||||
|
||||
pub enum Matcher {
|
||||
DetectChar { c: char, dyn_idx: Option<usize> },
|
||||
Detect2Chars { a: char, b: char },
|
||||
AnyChar(Vec<char>),
|
||||
StringDetect { s: String, ci: bool, dynamic: bool },
|
||||
WordDetect { s: String, ci: bool },
|
||||
Regex { re: Option<Arc<Regex>>, source: String, ci: bool, minimal: bool, dynamic: bool },
|
||||
Keyword { list: Arc<KeywordList>, ci: bool },
|
||||
Int, Float, HlCOct, HlCHex, HlCStringChar, HlCChar,
|
||||
RangeDetect { a: char, b: char },
|
||||
LineContinue { c: char },
|
||||
DetectSpaces,
|
||||
DetectIdentifier,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct KeywordList {
|
||||
pub cased: HashSet<String>,
|
||||
pub folded: HashSet<String>,
|
||||
}
|
||||
|
||||
pub struct Rule {
|
||||
pub matcher: Matcher,
|
||||
pub style: Option<StyleId>,
|
||||
pub switch: Switch,
|
||||
pub look_ahead: bool,
|
||||
pub first_non_space: bool,
|
||||
pub column: Option<usize>,
|
||||
pub begin_region: Option<u32>,
|
||||
pub end_region: Option<u32>,
|
||||
/// Bit set of the ASCII word delimiters of the owning definition.
|
||||
pub delims: Arc<Delims>,
|
||||
}
|
||||
|
||||
pub struct Delims(pub [bool; 128]);
|
||||
|
||||
impl Delims {
|
||||
pub fn new(weak: &str, extra: &str) -> Delims {
|
||||
let mut d = [false; 128];
|
||||
for c in " \t.():!+,-<=>%&*/;?[]^{|}~\\".chars().chain(extra.chars()) {
|
||||
if (c as usize) < 128 {
|
||||
d[c as usize] = true;
|
||||
}
|
||||
}
|
||||
for c in weak.chars() {
|
||||
if (c as usize) < 128 {
|
||||
d[c as usize] = false;
|
||||
}
|
||||
}
|
||||
Delims(d)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn is(&self, c: u8) -> bool {
|
||||
c < 128 && self.0[c as usize]
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Context {
|
||||
pub style: StyleId,
|
||||
pub rules: Vec<Rule>,
|
||||
pub line_end: Switch,
|
||||
pub line_empty: Option<Switch>,
|
||||
pub fallthrough: Option<Switch>,
|
||||
pub dynamic: bool,
|
||||
}
|
||||
|
||||
/// Comment syntax and folding mode from a definition's `<general>` block.
|
||||
#[derive(Clone, Default, Debug)]
|
||||
pub struct DefMeta {
|
||||
pub line_comment: Option<String>,
|
||||
pub block_comment: Option<(String, String)>,
|
||||
pub indent_fold: bool,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct Compiled {
|
||||
pub contexts: Vec<Context>,
|
||||
pub styles: Vec<StyleInfo>,
|
||||
pub regions: HashMap<String, u32>,
|
||||
pub bad_regexes: Vec<(String, String)>,
|
||||
}
|
||||
|
||||
/// Rewrites the PCRE syntax the regex crates don't take; returns the pattern to compile.
|
||||
pub fn translate_regex(src: &str, ci: bool, minimal: bool) -> String {
|
||||
let mut out = String::with_capacity(src.len() + 8);
|
||||
if ci || minimal {
|
||||
out.push_str("(?");
|
||||
if ci { out.push('i') }
|
||||
if minimal { out.push('U') }
|
||||
out.push(')');
|
||||
}
|
||||
let cs: Vec<char> = src.chars().collect();
|
||||
let (mut i, mut in_class) = (0, false);
|
||||
while i < cs.len() {
|
||||
let c = cs[i];
|
||||
if c == '\\' && i + 1 < cs.len() {
|
||||
match cs[i + 1] {
|
||||
'h' => out.push_str(if in_class { " \\t" } else { "[ \\t]" }),
|
||||
'H' if !in_class => out.push_str("[^ \\t]"),
|
||||
// a literal character the regex crate refuses to see escaped
|
||||
'<' | '>' | '"' | '\'' | '`' | '=' | '!' | '%' | ';' | ':' | ',' | '@' | '/' | '_' => out.push(cs[i + 1]),
|
||||
n => { out.push('\\'); out.push(n) }
|
||||
}
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
if in_class {
|
||||
if c == '[' && cs.get(i + 1) == Some(&':') {
|
||||
out.push('[');
|
||||
} else if c == '[' {
|
||||
out.push_str("\\[");
|
||||
} else {
|
||||
if c == ']' { in_class = false }
|
||||
out.push(c);
|
||||
}
|
||||
if c == '[' && cs.get(i + 1) == Some(&':') {
|
||||
// copy a POSIX class whole so its closing bracket doesn't end the set
|
||||
i += 1;
|
||||
while i < cs.len() {
|
||||
out.push(cs[i]);
|
||||
if cs[i] == ']' { break }
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
match c {
|
||||
'[' => {
|
||||
in_class = true;
|
||||
out.push('[');
|
||||
if cs.get(i + 1) == Some(&'^') { out.push('^'); i += 1 }
|
||||
if cs.get(i + 1) == Some(&']') { out.push_str("\\]"); i += 1 }
|
||||
}
|
||||
'(' if cs.get(i + 1) == Some(&'?') && cs.get(i + 2) == Some(&'#') => {
|
||||
while i < cs.len() && cs[i] != ')' { i += 1 }
|
||||
}
|
||||
'(' if cs.get(i + 1) == Some(&'?') && cs.get(i + 2) == Some(&'|') => {
|
||||
out.push_str("(?:");
|
||||
i += 2;
|
||||
}
|
||||
_ => out.push(c),
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
pub fn compile_regex(src: &str, ci: bool, minimal: bool) -> Result<Regex, String> {
|
||||
fancy_regex::RegexBuilder::new(&translate_regex(src, ci, minimal))
|
||||
.backtrack_limit(20_000)
|
||||
.build()
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
440
src/syntax/engine.rs
Normal file
440
src/syntax/engine.rs
Normal file
|
|
@ -0,0 +1,440 @@
|
|||
//! Walks one line through the compiled contexts, following the rules KSyntaxHighlighting uses.
|
||||
|
||||
use super::def::*;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
#[derive(Clone, PartialEq, Eq, Debug)]
|
||||
pub struct Frame {
|
||||
pub ctx: CtxId,
|
||||
pub captures: Option<Arc<Vec<String>>>,
|
||||
}
|
||||
|
||||
/// The context stack at the end of a line. Equal states mean later lines need no re-highlighting.
|
||||
#[derive(Clone, PartialEq, Eq, Debug, Default)]
|
||||
pub struct State {
|
||||
pub stack: Vec<Frame>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct Span {
|
||||
pub start: u32,
|
||||
pub end: u32,
|
||||
pub style: StyleId,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum FoldEvent {
|
||||
Begin(u32),
|
||||
End(u32),
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct LineResult {
|
||||
pub spans: Vec<Span>,
|
||||
pub folds: Vec<(u32, FoldEvent)>,
|
||||
}
|
||||
|
||||
fn word_at(line: &[u8], at: usize, d: &Delims) -> bool {
|
||||
at == 0 || d.is(line[at - 1])
|
||||
}
|
||||
|
||||
fn word_end(line: &[u8], at: usize, d: &Delims) -> bool {
|
||||
at >= line.len() || d.is(line[at])
|
||||
}
|
||||
|
||||
fn char_at(text: &str, at: usize) -> Option<char> {
|
||||
text.get(at..)?.chars().next()
|
||||
}
|
||||
|
||||
fn starts_with_ci(hay: &str, needle: &str) -> Option<usize> {
|
||||
let (mut h, mut n) = (hay.chars(), needle.chars());
|
||||
let mut used = 0;
|
||||
loop {
|
||||
let Some(nc) = n.next() else { return Some(used) };
|
||||
let hc = h.next()?;
|
||||
if !hc.to_lowercase().eq(nc.to_lowercase()) {
|
||||
return None;
|
||||
}
|
||||
used += hc.len_utf8();
|
||||
}
|
||||
}
|
||||
|
||||
fn is_ident_start(c: u8) -> bool {
|
||||
c.is_ascii_alphabetic() || c == b'_' || c >= 128
|
||||
}
|
||||
|
||||
fn is_ident(c: u8) -> bool {
|
||||
c.is_ascii_alphanumeric() || c == b'_' || c >= 128
|
||||
}
|
||||
|
||||
fn c_escape(l: &[u8], at: usize) -> Option<usize> {
|
||||
if l.get(at) != Some(&b'\\') {
|
||||
return None;
|
||||
}
|
||||
let n = *l.get(at + 1)?;
|
||||
Some(match n {
|
||||
b'a' | b'b' | b'e' | b'f' | b'n' | b'r' | b't' | b'v' | b'\'' | b'"' | b'\\' | b'?' => at + 2,
|
||||
b'x' => {
|
||||
let mut i = at + 2;
|
||||
while i < l.len() && i < at + 4 && l[i].is_ascii_hexdigit() { i += 1 }
|
||||
if i == at + 2 { return None }
|
||||
i
|
||||
}
|
||||
b'0'..=b'7' => {
|
||||
let mut i = at + 1;
|
||||
while i < l.len() && i < at + 4 && (b'0'..=b'7').contains(&l[i]) { i += 1 }
|
||||
i
|
||||
}
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
fn match_float(l: &[u8], at: usize, d: &Delims) -> Option<usize> {
|
||||
if !word_at(l, at, d) {
|
||||
return None;
|
||||
}
|
||||
let mut i = at;
|
||||
let digits_a = { let s = i; while i < l.len() && l[i].is_ascii_digit() { i += 1 } i - s };
|
||||
let mut dot = false;
|
||||
let mut digits_b = 0;
|
||||
if l.get(i) == Some(&b'.') {
|
||||
dot = true;
|
||||
i += 1;
|
||||
let s = i;
|
||||
while i < l.len() && l[i].is_ascii_digit() { i += 1 }
|
||||
digits_b = i - s;
|
||||
}
|
||||
if digits_a + digits_b == 0 {
|
||||
return None;
|
||||
}
|
||||
let mut exp = false;
|
||||
if matches!(l.get(i), Some(b'e' | b'E')) {
|
||||
let mut j = i + 1;
|
||||
if matches!(l.get(j), Some(b'+' | b'-')) { j += 1 }
|
||||
let s = j;
|
||||
while j < l.len() && l[j].is_ascii_digit() { j += 1 }
|
||||
if j > s {
|
||||
exp = true;
|
||||
i = j;
|
||||
}
|
||||
}
|
||||
(dot || exp).then_some(i)
|
||||
}
|
||||
|
||||
/// Per-line memo of where each regex rule next matches, so a miss is only searched for once.
|
||||
#[derive(Default)]
|
||||
struct RegexMemo {
|
||||
next: HashMap<*const Rule, Option<(usize, usize, Arc<Vec<String>>)>>,
|
||||
}
|
||||
|
||||
pub struct Highlighter<'a> {
|
||||
pub c: &'a Compiled,
|
||||
dyn_cache: HashMap<String, Option<Arc<fancy_regex::Regex>>>,
|
||||
}
|
||||
|
||||
impl<'a> Highlighter<'a> {
|
||||
pub fn new(c: &'a Compiled) -> Self {
|
||||
Highlighter { c, dyn_cache: HashMap::new() }
|
||||
}
|
||||
|
||||
fn apply(&self, st: &mut State, sw: Switch, caps: Option<Arc<Vec<String>>>) {
|
||||
for _ in 0..sw.pops {
|
||||
if st.stack.len() > 1 {
|
||||
st.stack.pop();
|
||||
}
|
||||
}
|
||||
if let Some(p) = sw.push {
|
||||
let keep = self.c.contexts[p as usize].dynamic;
|
||||
st.stack.push(Frame { ctx: p, captures: if keep { caps } else { None } });
|
||||
}
|
||||
}
|
||||
|
||||
pub fn initial(root: CtxId) -> State {
|
||||
State { stack: vec![Frame { ctx: root, captures: None }] }
|
||||
}
|
||||
|
||||
fn try_rule(&mut self, r: &Rule, text: &str, at: usize, first: usize, caps: &Option<Arc<Vec<String>>>, memo: &mut RegexMemo) -> Option<(usize, Option<Arc<Vec<String>>>)> {
|
||||
if r.first_non_space && at != first {
|
||||
return None;
|
||||
}
|
||||
if let Some(col) = r.column {
|
||||
if col != at {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
let l = text.as_bytes();
|
||||
let d = &*r.delims;
|
||||
let end = match &r.matcher {
|
||||
Matcher::DetectChar { c, dyn_idx } => {
|
||||
let want = match dyn_idx {
|
||||
Some(i) => caps.as_ref().and_then(|v| v.get(*i)).and_then(|s| s.chars().next())?,
|
||||
None => *c,
|
||||
};
|
||||
let h = char_at(text, at)?;
|
||||
(h == want).then(|| at + h.len_utf8())?
|
||||
}
|
||||
Matcher::Detect2Chars { a, b } => {
|
||||
let mut it = text[at..].chars();
|
||||
let (x, y) = (it.next()?, it.next()?);
|
||||
(x == *a && y == *b).then(|| at + x.len_utf8() + y.len_utf8())?
|
||||
}
|
||||
Matcher::AnyChar(set) => {
|
||||
let h = char_at(text, at)?;
|
||||
set.contains(&h).then(|| at + h.len_utf8())?
|
||||
}
|
||||
Matcher::StringDetect { s, ci, dynamic } => {
|
||||
let owned;
|
||||
let needle: &str = if *dynamic {
|
||||
owned = substitute(s, caps, false);
|
||||
&owned
|
||||
} else {
|
||||
s
|
||||
};
|
||||
if needle.is_empty() {
|
||||
return None;
|
||||
}
|
||||
if *ci {
|
||||
at + starts_with_ci(&text[at..], needle)?
|
||||
} else {
|
||||
text[at..].starts_with(needle).then(|| at + needle.len())?
|
||||
}
|
||||
}
|
||||
Matcher::WordDetect { s, ci } => {
|
||||
if !word_at(l, at, d) {
|
||||
return None;
|
||||
}
|
||||
let e = if *ci { at + starts_with_ci(&text[at..], s)? } else { text[at..].starts_with(s.as_str()).then(|| at + s.len())? };
|
||||
if !word_end(l, e, d) {
|
||||
return None;
|
||||
}
|
||||
e
|
||||
}
|
||||
Matcher::Keyword { list, ci } => {
|
||||
if !word_at(l, at, d) {
|
||||
return None;
|
||||
}
|
||||
let mut e = at;
|
||||
while e < l.len() && !d.is(l[e]) { e += 1 }
|
||||
if e == at {
|
||||
return None;
|
||||
}
|
||||
let w = &text[at..e];
|
||||
let hit = if *ci { list.folded.contains(&w.to_lowercase()) } else { list.cased.contains(w) };
|
||||
if !hit {
|
||||
return None;
|
||||
}
|
||||
e
|
||||
}
|
||||
Matcher::Int => {
|
||||
if !word_at(l, at, d) {
|
||||
return None;
|
||||
}
|
||||
let mut e = at;
|
||||
while e < l.len() && l[e].is_ascii_digit() { e += 1 }
|
||||
if e == at {
|
||||
return None;
|
||||
}
|
||||
e
|
||||
}
|
||||
Matcher::Float => match_float(l, at, d)?,
|
||||
Matcher::HlCOct => {
|
||||
if !word_at(l, at, d) || l.get(at) != Some(&b'0') {
|
||||
return None;
|
||||
}
|
||||
let mut e = at + 1;
|
||||
while e < l.len() && (b'0'..=b'7').contains(&l[e]) { e += 1 }
|
||||
if e == at + 1 {
|
||||
return None;
|
||||
}
|
||||
e
|
||||
}
|
||||
Matcher::HlCHex => {
|
||||
if !word_at(l, at, d) || l.get(at) != Some(&b'0') || !matches!(l.get(at + 1), Some(b'x' | b'X')) {
|
||||
return None;
|
||||
}
|
||||
let mut e = at + 2;
|
||||
while e < l.len() && l[e].is_ascii_hexdigit() { e += 1 }
|
||||
if e == at + 2 {
|
||||
return None;
|
||||
}
|
||||
e
|
||||
}
|
||||
Matcher::HlCStringChar => c_escape(l, at)?,
|
||||
Matcher::HlCChar => {
|
||||
if l.get(at) != Some(&b'\'') {
|
||||
return None;
|
||||
}
|
||||
let inner = if l.get(at + 1) == Some(&b'\\') { c_escape(l, at + 1)? } else { at + 1 + char_at(text, at + 1).filter(|c| *c != '\'')?.len_utf8() };
|
||||
if l.get(inner) != Some(&b'\'') {
|
||||
return None;
|
||||
}
|
||||
inner + 1
|
||||
}
|
||||
Matcher::RangeDetect { a, b } => {
|
||||
if char_at(text, at)? != *a {
|
||||
return None;
|
||||
}
|
||||
let start = at + a.len_utf8();
|
||||
start + text[start..].find(*b)? + b.len_utf8()
|
||||
}
|
||||
Matcher::LineContinue { c } => {
|
||||
let h = char_at(text, at)?;
|
||||
(h == *c && at + h.len_utf8() == text.len()).then_some(text.len())?
|
||||
}
|
||||
Matcher::DetectSpaces => {
|
||||
let mut e = at;
|
||||
while e < l.len() && (l[e] == b' ' || l[e] == b'\t') { e += 1 }
|
||||
if e == at {
|
||||
return None;
|
||||
}
|
||||
e
|
||||
}
|
||||
Matcher::DetectIdentifier => {
|
||||
if !is_ident_start(*l.get(at)?) {
|
||||
return None;
|
||||
}
|
||||
let mut e = at + 1;
|
||||
while e < l.len() && is_ident(l[e]) { e += 1 }
|
||||
e
|
||||
}
|
||||
Matcher::Regex { re, source, ci, minimal, dynamic } => {
|
||||
let re: Arc<fancy_regex::Regex> = if *dynamic {
|
||||
let pat = substitute(source, caps, true);
|
||||
self.dyn_cache
|
||||
.entry(format!("{}{}{pat}", *ci as u8, *minimal as u8))
|
||||
.or_insert_with(|| compile_regex(&pat, *ci, *minimal).ok().map(Arc::new))
|
||||
.clone()?
|
||||
} else {
|
||||
re.clone()?
|
||||
};
|
||||
let key = r as *const Rule;
|
||||
if let Some(entry) = memo.next.get(&key) {
|
||||
match entry {
|
||||
None => return None,
|
||||
Some((s, e, c)) if *s >= at => {
|
||||
return (*s == at && *e > at).then(|| (*e, Some(c.clone())));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let found = re.captures_from_pos(text, at).ok().flatten();
|
||||
let Some(m) = found else {
|
||||
memo.next.insert(key, None);
|
||||
return None;
|
||||
};
|
||||
let whole = m.get(0)?;
|
||||
let v: Vec<String> = (0..m.len()).map(|i| m.get(i).map(|x| x.as_str().to_string()).unwrap_or_default()).collect();
|
||||
let v = Arc::new(v);
|
||||
memo.next.insert(key, Some((whole.start(), whole.end(), v.clone())));
|
||||
if whole.start() != at || whole.end() == at {
|
||||
return None;
|
||||
}
|
||||
return Some((whole.end(), Some(v)));
|
||||
}
|
||||
};
|
||||
Some((end, None))
|
||||
}
|
||||
|
||||
/// Highlights `text` (no line break), moving `st` to the state at the end of the line.
|
||||
pub fn line(&mut self, text: &str, st: &mut State) -> LineResult {
|
||||
let mut out = LineResult::default();
|
||||
let c = self.c;
|
||||
if st.stack.is_empty() {
|
||||
return out;
|
||||
}
|
||||
let first = text.len() - text.trim_start_matches([' ', '\t']).len();
|
||||
let mut memo = RegexMemo::default();
|
||||
let mut at = 0usize;
|
||||
let mut continued = false;
|
||||
// lookahead and fallthrough switches consume nothing; this bounds a definition that loops
|
||||
let mut idle = 0;
|
||||
|
||||
if text.is_empty() {
|
||||
let mut guard = 0;
|
||||
loop {
|
||||
let top = st.stack.last().unwrap().ctx as usize;
|
||||
let Some(sw) = c.contexts[top].line_empty.or(Some(c.contexts[top].line_end)) else { break };
|
||||
if sw.is_stay() || guard > 32 { break }
|
||||
self.apply(st, sw, None);
|
||||
guard += 1;
|
||||
if c.contexts[top].line_empty.is_some() { break }
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
'outer: while at < text.len() {
|
||||
let top = st.stack.last().unwrap().clone();
|
||||
let ctx = &c.contexts[top.ctx as usize];
|
||||
for r in &ctx.rules {
|
||||
let Some((end, caps)) = self.try_rule(r, text, at, first, &top.captures, &mut memo) else { continue };
|
||||
if let Some(id) = r.end_region { out.folds.push((at as u32, FoldEvent::End(id))) }
|
||||
if let Some(id) = r.begin_region { out.folds.push((at as u32, FoldEvent::Begin(id))) }
|
||||
if r.look_ahead {
|
||||
if r.switch.is_stay() { continue }
|
||||
self.apply(st, r.switch, caps);
|
||||
idle += 1;
|
||||
if idle > 64 { break }
|
||||
continue 'outer;
|
||||
}
|
||||
self.apply(st, r.switch, caps);
|
||||
let style = r.style.unwrap_or_else(|| c.contexts[st.stack.last().unwrap().ctx as usize].style);
|
||||
push(&mut out.spans, at, end, style);
|
||||
continued = matches!(r.matcher, Matcher::LineContinue { .. });
|
||||
at = end;
|
||||
idle = 0;
|
||||
continue 'outer;
|
||||
}
|
||||
if let Some(sw) = ctx.fallthrough {
|
||||
if idle <= 64 {
|
||||
self.apply(st, sw, None);
|
||||
idle += 1;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
let w = char_at(text, at).map_or(1, |x| x.len_utf8());
|
||||
push(&mut out.spans, at, at + w, ctx.style);
|
||||
at += w;
|
||||
continued = false;
|
||||
idle = 0;
|
||||
}
|
||||
if !continued {
|
||||
let mut guard = 0;
|
||||
loop {
|
||||
let sw = c.contexts[st.stack.last().unwrap().ctx as usize].line_end;
|
||||
if sw.is_stay() || guard > 32 { break }
|
||||
self.apply(st, sw, None);
|
||||
guard += 1;
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
fn push(v: &mut Vec<Span>, a: usize, b: usize, style: StyleId) {
|
||||
if let Some(l) = v.last_mut() {
|
||||
if l.style == style && l.end as usize == a {
|
||||
l.end = b as u32;
|
||||
return;
|
||||
}
|
||||
}
|
||||
v.push(Span { start: a as u32, end: b as u32, style });
|
||||
}
|
||||
|
||||
fn substitute(s: &str, caps: &Option<Arc<Vec<String>>>, for_regex: bool) -> String {
|
||||
let mut out = String::with_capacity(s.len());
|
||||
let cs: Vec<char> = s.chars().collect();
|
||||
let mut i = 0;
|
||||
while i < cs.len() {
|
||||
if cs[i] == '%' && cs.get(i + 1).is_some_and(|c| c.is_ascii_digit()) {
|
||||
let n = cs[i + 1].to_digit(10).unwrap() as usize;
|
||||
let v = caps.as_ref().and_then(|c| c.get(n)).map(String::as_str).unwrap_or("");
|
||||
if for_regex { out.push_str(&fancy_regex::escape(v)) } else { out.push_str(v) }
|
||||
i += 2;
|
||||
} else {
|
||||
out.push(cs[i]);
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
12
src/syntax/mod.rs
Normal file
12
src/syntax/mod.rs
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
//! Runs Kate's own syntax definitions (the KSyntaxHighlighting XML format).
|
||||
//!
|
||||
//! `def` reads the XML into compiled contexts and rules, `engine` walks a line through them, and
|
||||
//! `registry` finds definitions on disk and picks one for a file.
|
||||
|
||||
pub mod def;
|
||||
pub mod engine;
|
||||
pub mod registry;
|
||||
|
||||
pub use def::{DefStyle, StyleId};
|
||||
pub use engine::{FoldEvent, LineResult, Span, State};
|
||||
pub use registry::{Language, Registry};
|
||||
482
src/syntax/registry.rs
Normal file
482
src/syntax/registry.rs
Normal file
|
|
@ -0,0 +1,482 @@
|
|||
//! 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<String>,
|
||||
pub section: String,
|
||||
pub extensions: Vec<String>,
|
||||
pub mimetypes: Vec<String>,
|
||||
pub priority: i32,
|
||||
pub hidden: bool,
|
||||
pub path: PathBuf,
|
||||
}
|
||||
|
||||
struct Loaded {
|
||||
root: CtxId,
|
||||
meta: DefMeta,
|
||||
}
|
||||
|
||||
pub struct Registry {
|
||||
pub languages: Vec<Language>,
|
||||
by_name: HashMap<String, usize>,
|
||||
loaded: HashMap<String, Loaded>,
|
||||
pub compiled: Compiled,
|
||||
lists: HashMap<(String, String), Arc<KeywordList>>,
|
||||
}
|
||||
|
||||
pub fn search_dirs() -> Vec<PathBuf> {
|
||||
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 `<language …>` tag without parsing the whole file.
|
||||
fn header_attrs(head: &str) -> HashMap<String, String> {
|
||||
let mut map = HashMap::new();
|
||||
let Some(start) = head.find("<language") else { return map };
|
||||
let rest = &head[start + 9..];
|
||||
let tag_end = {
|
||||
let (mut q, mut end) = (None, rest.len());
|
||||
for (i, c) in rest.char_indices() {
|
||||
match (q, c) {
|
||||
(None, '"' | '\'') => 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<char> = pat.chars().collect();
|
||||
let n: Vec<char> = 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<Language> = vec![];
|
||||
let mut by_name: HashMap<String, usize> = HashMap::new();
|
||||
for dir in dirs {
|
||||
let Ok(rd) = std::fs::read_dir(dir) else { continue };
|
||||
let mut files: Vec<PathBuf> = 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> {
|
||||
let best = self.languages.iter().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 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<State> {
|
||||
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<KeywordList> {
|
||||
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<String>) {
|
||||
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<CtxId> {
|
||||
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<String, StyleId> = 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<roxmltree::Node> = 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<String, CtxId> = 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<CtxId>) -> Vec<Rule> {
|
||||
self.compiled.contexts[target as usize].rules.iter().map(clone_rule).collect()
|
||||
}
|
||||
|
||||
fn switch(&mut self, spec: Option<&str>, ids: &HashMap<String, CtxId>, 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<String, CtxId>, def: &str) -> Option<CtxId> {
|
||||
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<CtxId> {
|
||||
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<Rule>, inc: &mut Vec<(usize, usize, CtxId, bool)>, cid: usize, doc: roxmltree::Node, def: &str, ids: &HashMap<String, CtxId>, styles: &HashMap<String, StyleId>, default_ci: bool, delims: &Arc<Delims>) {
|
||||
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() }
|
||||
}
|
||||
Loading…
Reference in a new issue