Lightweight native Discord client for Windows, Linux and macOS, written in Rust. No Electron, no browser engine.
Rust desktop-appdiscorddiscord-clienteguielectron-alternativelightweightlinuxmacosnative-apprustwindows
//! Code-block syntax highlighting the way Discord does it: highlight.js
//! classes (keyword, type / built_in, title, string, number, comment, meta,
//! attr, addition / deletion), coloured with Discord's `--text-code-*`
//! palette (`style::Syntax`). A small hand-written tokenizer per language
//! family covers the languages people post most; anything else stays plain,
//! as it does in Discord without a language tag.
use std::cell::RefCell;
use std::collections::HashMap;
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Tok {
Plain,
Keyword,
Type,
BuiltIn,
Title,
Literal,
Attr,
Meta,
Number,
Str,
Comment,
Section,
Addition,
Deletion,
}
#[derive(Default)]
struct Lang {
keywords: &'static [&'static str],
types: &'static [&'static str],
builtins: &'static [&'static str],
literals: &'static [&'static str],
/// Words whose next identifier is a definition's name (`fn main`).
defs: &'static [&'static str],
line_comments: &'static [&'static str],
block_comment: Option<(&'static str, &'static str)>,
quotes: &'static [u8],
/// `name(` is a function call (title.function.invoke).
calls: bool,
/// Rust: `#[attr]`, `name!` macros, 'a lifetimes.
rust: bool,
/// Python / TS / Java: `@decorator`.
decorators: bool,
/// C family: `#include` lines.
preprocessor: bool,
/// JSON / YAML / TOML: `key:` / `key =` names.
keys: bool,
/// TOML / INI: `[section]` lines.
sections: bool,
/// `$var` names (shell, PHP).
dollar_vars: bool,
case_insensitive: bool,
}
const RUST_KW: &[&str] = &[
"as", "async", "await", "break", "const", "continue", "crate", "dyn", "else", "enum", "extern", "fn", "for", "if", "impl", "in", "let", "loop", "match",
"mod", "move", "mut", "pub", "ref", "return", "self", "static", "struct", "super", "trait", "type", "union", "unsafe", "use", "where", "while", "yield",
];
const RUST_TYPES: &[&str] = &[
"i8", "i16", "i32", "i64", "i128", "isize", "u8", "u16", "u32", "u64", "u128", "usize", "f32", "f64", "str", "char", "bool", "Box", "Option", "Result",
"String", "Vec", "Self",
];
const RUST_BUILTINS: &[&str] = &[
"Copy", "Send", "Sized", "Sync", "Drop", "Fn", "FnMut", "FnOnce", "ToOwned", "Clone", "Debug", "PartialEq", "PartialOrd", "Eq", "Ord", "AsRef",
"AsMut", "Into", "From", "Default", "Iterator", "Extend", "IntoIterator", "DoubleEndedIterator", "ExactSizeIterator", "SliceConcatExt", "ToString",
"Some", "None", "Ok", "Err", "drop",
];
const JS_KW: &[&str] = &[
"as", "async", "await", "break", "case", "catch", "class", "const", "continue", "debugger", "default", "delete", "do", "else", "export", "extends",
"finally", "for", "from", "function", "get", "if", "import", "in", "instanceof", "let", "new", "of", "return", "set", "static", "super", "switch",
"this", "throw", "try", "typeof", "var", "void", "while", "with", "yield", "interface", "type", "enum", "implements", "private", "public",
"protected", "readonly", "declare", "namespace", "abstract", "keyof",
];
const JS_TYPES: &[&str] = &["string", "number", "boolean", "any", "unknown", "never", "object", "symbol", "bigint"];
const JS_BUILTINS: &[&str] = &[
"Object", "Array", "String", "Number", "Boolean", "Function", "Symbol", "Map", "Set", "WeakMap", "WeakSet", "Promise", "JSON", "Math", "Date",
"RegExp", "Error", "TypeError", "console", "window", "document", "require", "module", "exports", "process", "globalThis", "setTimeout",
"setInterval", "clearTimeout", "clearInterval", "parseInt", "parseFloat", "fetch",
];
const JS_LIT: &[&str] = &["true", "false", "null", "undefined", "NaN", "Infinity"];
const PY_KW: &[&str] = &[
"and", "as", "assert", "async", "await", "break", "class", "continue", "def", "del", "elif", "else", "except", "finally", "for", "from", "global",
"if", "import", "in", "is", "lambda", "nonlocal", "not", "or", "pass", "raise", "return", "try", "while", "with", "yield", "match", "case", "self",
"cls",
];
const PY_BUILTINS: &[&str] = &[
"print", "len", "range", "open", "str", "int", "float", "list", "dict", "set", "tuple", "bool", "type", "isinstance", "super", "enumerate", "zip",
"map", "filter", "sorted", "sum", "min", "max", "abs", "input", "repr", "round", "any", "all", "iter", "next", "object", "Exception",
];
const PY_LIT: &[&str] = &["True", "False", "None"];
const C_KW: &[&str] = &[
"auto", "break", "case", "catch", "class", "const", "constexpr", "continue", "default", "delete", "do", "else", "enum", "explicit", "extern",
"for", "friend", "goto", "if", "inline", "namespace", "new", "operator", "private", "protected", "public", "return", "sizeof", "static",
"struct", "switch", "template", "this", "throw", "try", "typedef", "typename", "union", "using", "virtual", "volatile", "while", "override",
"final", "import", "package", "extends", "implements", "interface", "abstract", "synchronized", "throws", "instanceof", "var", "val", "fun",
"when", "is", "in", "out", "object", "companion", "base", "readonly", "ref", "foreach", "get", "set", "async", "await", "lock", "params",
"go", "func", "chan", "defer", "select", "range", "fallthrough", "map", "type",
];
const C_TYPES: &[&str] = &[
"int", "long", "short", "char", "float", "double", "void", "bool", "unsigned", "signed", "size_t", "uint8_t", "uint16_t", "uint32_t", "uint64_t",
"int8_t", "int16_t", "int32_t", "int64_t", "string", "String", "boolean", "byte", "decimal", "object", "dynamic", "Integer", "Object", "Int",
"Unit", "Any", "List", "error", "rune", "uint", "uint8", "uint32", "uint64", "int8", "int32", "int64", "float32", "float64", "std",
];
const C_LIT: &[&str] = &["true", "false", "null", "nullptr", "NULL", "nil", "iota"];
const C_BUILTINS: &[&str] = &["printf", "scanf", "malloc", "free", "cout", "cin", "endl", "System", "Console", "println", "fmt", "make", "len", "append", "cap", "panic"];
const LUA_KW: &[&str] = &["and", "break", "do", "else", "elseif", "end", "for", "function", "goto", "if", "in", "local", "not", "or", "repeat", "return", "then", "until", "while"];
const LUA_BUILTINS: &[&str] = &[
"print", "pairs", "ipairs", "type", "tostring", "tonumber", "require", "table", "string", "math", "game", "workspace", "script", "Instance",
"Vector3", "CFrame", "wait", "task", "pcall", "error", "setmetatable", "getmetatable", "select", "next",
];
const LUA_LIT: &[&str] = &["true", "false", "nil"];
const SH_KW: &[&str] = &["if", "then", "else", "elif", "fi", "for", "while", "do", "done", "case", "esac", "in", "function", "return", "export", "local", "until", "select"];
const SH_BUILTINS: &[&str] = &[
"echo", "cd", "ls", "cat", "grep", "sed", "awk", "rm", "cp", "mv", "mkdir", "sudo", "apt", "npm", "pip", "cargo", "git", "curl", "chmod", "source",
"exit", "read", "printf", "set", "unset", "Write-Host", "Get-ChildItem", "Set-Location",
];
const SQL_KW: &[&str] = &[
"select", "from", "where", "insert", "into", "values", "update", "set", "delete", "create", "table", "drop", "alter", "add", "join", "left",
"right", "inner", "outer", "on", "as", "and", "or", "not", "null", "is", "in", "like", "order", "by", "group", "having", "limit", "offset",
"distinct", "primary", "key", "foreign", "references", "index", "union", "all", "case", "when", "then", "else", "end", "exists", "default",
];
const SQL_TYPES: &[&str] = &["int", "integer", "bigint", "text", "varchar", "char", "boolean", "date", "timestamp", "real", "float", "decimal", "serial", "blob"];
const CSS_KW: &[&str] = &["important", "media", "import", "keyframes", "from", "to", "font-face", "supports"];
const BOOL_LIT: &[&str] = &["true", "false", "null", "yes", "no", "on", "off", "~"];
fn lang(name: &str) -> Option<Lang> {
let name = name.trim().to_ascii_lowercase();
let c_like = |kw, types, lit, builtins| Lang {
keywords: kw,
types,
literals: lit,
builtins,
defs: &["class", "struct", "interface", "enum", "func", "fun", "namespace"],
line_comments: &["//"],
block_comment: Some(("/*", "*/")),
quotes: b"\"'`",
calls: true,
decorators: true,
preprocessor: true,
..Default::default()
};
Some(match name.as_str() {
"rust" | "rs" => Lang {
keywords: RUST_KW,
types: RUST_TYPES,
builtins: RUST_BUILTINS,
literals: &["true", "false"],
defs: &["fn", "struct", "enum", "trait", "type", "union", "mod"],
line_comments: &["//"],
block_comment: Some(("/*", "*/")),
quotes: b"\"'",
calls: true,
rust: true,
..Default::default()
},
"js" | "javascript" | "jsx" | "mjs" | "cjs" | "ts" | "typescript" | "tsx" | "node" => Lang {
keywords: JS_KW,
types: JS_TYPES,
builtins: JS_BUILTINS,
literals: JS_LIT,
defs: &["function", "class", "interface", "enum", "type"],
line_comments: &["//"],
block_comment: Some(("/*", "*/")),
quotes: b"\"'`",
calls: true,
decorators: true,
..Default::default()
},
"py" | "python" | "python3" | "py3" | "gyp" => Lang {
keywords: PY_KW,
builtins: PY_BUILTINS,
literals: PY_LIT,
defs: &["def", "class"],
line_comments: &["#"],
quotes: b"\"'",
decorators: true,
..Default::default()
},
"c" | "h" | "cpp" | "c++" | "cc" | "hpp" | "cxx" | "cs" | "csharp" | "c#" | "java" | "kotlin" | "kt" | "go" | "golang" | "swift" | "dart"
| "scala" | "php" | "glsl" | "hlsl" | "arduino" | "ino" => c_like(C_KW, C_TYPES, C_LIT, C_BUILTINS),
"lua" | "luau" => Lang {
keywords: LUA_KW,
builtins: LUA_BUILTINS,
literals: LUA_LIT,
defs: &["function"],
line_comments: &["--"],
block_comment: Some(("--[[", "]]")),
quotes: b"\"'",
calls: true,
..Default::default()
},
"sh" | "bash" | "shell" | "zsh" | "console" | "ps1" | "powershell" | "pwsh" | "bat" | "cmd" => Lang {
keywords: SH_KW,
builtins: SH_BUILTINS,
literals: &["true", "false"],
line_comments: &["#"],
quotes: b"\"'",
dollar_vars: true,
..Default::default()
},
"sql" | "mysql" | "pgsql" | "postgres" | "sqlite" => Lang {
keywords: SQL_KW,
types: SQL_TYPES,
literals: &["true", "false"],
line_comments: &["--"],
block_comment: Some(("/*", "*/")),
quotes: b"'\"",
case_insensitive: true,
..Default::default()
},
"json" | "jsonc" | "json5" => Lang { literals: &["true", "false", "null"], line_comments: &["//"], quotes: b"\"", keys: true, ..Default::default() },
"yaml" | "yml" => Lang { literals: BOOL_LIT, line_comments: &["#"], quotes: b"\"'", keys: true, ..Default::default() },
"toml" | "ini" | "cfg" | "conf" | "properties" | "env" => {
Lang { literals: &["true", "false"], line_comments: &["#", ";"], quotes: b"\"'", keys: true, sections: true, ..Default::default() }
}
"css" | "scss" | "sass" | "less" => Lang { keywords: CSS_KW, line_comments: &["//"], block_comment: Some(("/*", "*/")), quotes: b"\"'", keys: true, ..Default::default() },
"html" | "xml" | "svg" | "xhtml" | "vue" => return None,
_ => return None,
})
}
/// Byte ranges of `code` and their classes (gaps are plain).
pub fn highlight(lang_name: &str, code: &str) -> Vec<(usize, usize, Tok)> {
thread_local! {
static CACHE: RefCell<HashMap<(String, String), Vec<(usize, usize, Tok)>>> = RefCell::new(HashMap::new());
}
// Keyed by the code itself, not a hash of it: the ranges index into it,
// so another block's ranges must never come back.
let key = (lang_name.to_string(), code.to_string());
if let Some(hit) = CACHE.with(|c| c.borrow().get(&key).cloned()) {
return hit;
}
let out = tokenize(lang_name, code);
CACHE.with(|c| {
let mut c = c.borrow_mut();
if c.len() > 256 {
c.clear();
}
c.insert(key, out.clone());
});
out
}
fn tokenize(lang_name: &str, code: &str) -> Vec<(usize, usize, Tok)> {
let ln = lang_name.trim().to_ascii_lowercase();
if ln == "diff" || ln == "patch" {
return diff(code);
}
if matches!(ln.as_str(), "html" | "xml" | "svg" | "xhtml" | "vue") {
return markup(code);
}
let Some(l) = lang(&ln) else { return Vec::new() };
let b = code.as_bytes();
let n = b.len();
let mut out = Vec::new();
let mut i = 0;
let mut line_start = true;
let mut prev_word = String::new();
let is_ident_start = |c: u8| c.is_ascii_alphabetic() || c == b'_' || c >= 0x80;
let is_ident = |c: u8| c.is_ascii_alphanumeric() || c == b'_' || c >= 0x80;
let at = |i: usize, s: &str| b[i..].starts_with(s.as_bytes());
let line_end = |i: usize| b[i..].iter().position(|&c| c == b'\n').map_or(n, |p| i + p);
while i < n {
let c = b[i];
if c == b'\n' {
line_start = true;
i += 1;
continue;
}
if c == b' ' || c == b'\t' || c == b'\r' {
i += 1;
continue;
}
let was_line_start = line_start;
line_start = false;
// Block comment (checked before line comments: Lua's --[[).
if let Some((open, close)) = l.block_comment {
if at(i, open) {
let end = code[i + open.len()..].find(close).map_or(n, |p| i + open.len() + p + close.len());
out.push((i, end, Tok::Comment));
i = end;
continue;
}
}
if l.line_comments.iter().any(|p| at(i, p)) && !(l.rust && at(i, "#")) {
let end = line_end(i);
out.push((i, end, Tok::Comment));
i = end;
continue;
}
if l.sections && was_line_start && c == b'[' {
let end = line_end(i);
out.push((i, end, Tok::Section));
i = end;
continue;
}
if l.preprocessor && was_line_start && c == b'#' {
let end = line_end(i);
out.push((i, end, Tok::Meta));
i = end;
continue;
}
if l.rust && c == b'#' && (at(i, "#[") || at(i, "#![")) {
let mut depth = 0;
let mut j = i;
while j < n {
match b[j] {
b'[' => depth += 1,
b']' => {
depth -= 1;
if depth == 0 {
j += 1;
break;
}
}
b'\n' => break,
_ => {}
}
j += 1;
}
out.push((i, j, Tok::Meta));
i = j;
continue;
}
if l.decorators && c == b'@' && i + 1 < n && is_ident_start(b[i + 1]) {
let mut j = i + 1;
while j < n && (is_ident(b[j]) || b[j] == b'.') {
j += 1;
}
out.push((i, j, Tok::Meta));
i = j;
continue;
}
if l.dollar_vars && c == b'$' {
let mut j = i + 1;
if j < n && b[j] == b'{' {
while j < n && b[j] != b'}' && b[j] != b'\n' {
j += 1;
}
j = (j + 1).min(n);
} else {
while j < n && is_ident(b[j]) {
j += 1;
}
}
out.push((i, j, Tok::Literal));
i = j;
continue;
}
if l.quotes.contains(&c) {
// Rust: 'a is a lifetime, 'x' / '\n' a char.
if l.rust && c == b'\'' {
let is_char = (i + 2 < n && b[i + 2] == b'\'') || (i + 1 < n && b[i + 1] == b'\\');
if !is_char {
let mut j = i + 1;
while j < n && is_ident(b[j]) {
j += 1;
}
i = j.max(i + 1);
continue;
}
}
let triple = (c == b'"' || c == b'\'') && i + 2 < n && b[i + 1] == c && b[i + 2] == c;
let mut j = i + if triple { 3 } else { 1 };
loop {
if j >= n {
break;
}
if b[j] == b'\\' {
j += 2;
continue;
}
if triple {
if j + 2 < n && b[j] == c && b[j + 1] == c && b[j + 2] == c {
j += 3;
break;
}
} else if b[j] == c {
j += 1;
break;
} else if b[j] == b'\n' && c != b'`' && !(l.rust && c == b'"') {
break;
}
j += 1;
}
let j = j.min(n);
// A JSON / YAML key: a string followed by ':'.
let next = b[j..].iter().find(|&&x| x != b' ' && x != b'\t').copied();
let tok = if l.keys && next == Some(b':') { Tok::Attr } else { Tok::Str };
out.push((i, j, tok));
i = j;
continue;
}
if c.is_ascii_digit() || (c == b'.' && i + 1 < n && b[i + 1].is_ascii_digit()) {
let mut j = i + 1;
while j < n && (b[j].is_ascii_alphanumeric() || b[j] == b'_' || (b[j] == b'.' && j + 1 < n && b[j + 1].is_ascii_digit())) {
j += 1;
}
out.push((i, j, Tok::Number));
i = j;
continue;
}
if is_ident_start(c) {
let mut j = i + 1;
while j < n && (is_ident(b[j]) || (l.keys && b[j] == b'-')) {
j += 1;
}
// Keep multi-byte characters whole.
while j < n && !code.is_char_boundary(j) {
j += 1;
}
let word = &code[i..j];
let cmp = if l.case_insensitive { word.to_ascii_lowercase() } else { word.to_string() };
let next = b[j..].iter().find(|&&x| x != b' ' && x != b'\t').copied();
let tok = if l.rust && j < n && b[j] == b'!' && b.get(j + 1) != Some(&b'=') {
// Rust macros (println!, vec!, …): highlight.js marks them built_in.
out.push((i, j + 1, Tok::BuiltIn));
prev_word = cmp;
i = j + 1;
continue;
} else if l.keys && (next == Some(b':') || (l.sections && next == Some(b'='))) && was_line_start {
Tok::Attr
} else if l.keywords.contains(&cmp.as_str()) {
Tok::Keyword
} else if l.literals.contains(&cmp.as_str()) {
Tok::Literal
} else if l.types.contains(&cmp.as_str()) {
Tok::Type
} else if l.builtins.contains(&cmp.as_str()) {
Tok::BuiltIn
} else if l.defs.contains(&prev_word.as_str()) {
Tok::Title
} else if l.calls && next == Some(b'(') {
Tok::Title
} else {
Tok::Plain
};
if tok != Tok::Plain {
out.push((i, j, tok));
}
prev_word = cmp;
i = j;
continue;
}
// Punctuation: plain. Multi-byte characters stay whole.
i += 1;
while i < n && !code.is_char_boundary(i) {
i += 1;
}
}
out
}
/// `diff`: + / - lines, @@ hunks and file headers.
fn diff(code: &str) -> Vec<(usize, usize, Tok)> {
let mut out = Vec::new();
let mut start = 0;
for line in code.split_inclusive('\n') {
let end = start + line.trim_end_matches('\n').len();
let tok = if line.starts_with("+++") || line.starts_with("---") || line.starts_with("@@") {
Some(Tok::Meta)
} else if line.starts_with('+') {
Some(Tok::Addition)
} else if line.starts_with('-') {
Some(Tok::Deletion)
} else {
None
};
if let Some(t) = tok {
out.push((start, end, t));
}
start += line.len();
}
out
}
/// HTML / XML: tag names, attribute names, strings, comments.
fn markup(code: &str) -> Vec<(usize, usize, Tok)> {
let b = code.as_bytes();
let n = b.len();
let mut out = Vec::new();
let mut i = 0;
while i < n {
if b[i..].starts_with(b"<!--") {
let end = code[i..].find("-->").map_or(n, |p| i + p + 3);
out.push((i, end, Tok::Comment));
i = end;
continue;
}
if b[i] == b'<' {
let mut j = i + 1;
if j < n && (b[j] == b'/' || b[j] == b'!' || b[j] == b'?') {
j += 1;
}
let name_start = j;
while j < n && (b[j].is_ascii_alphanumeric() || b[j] == b'-' || b[j] == b':') {
j += 1;
}
if j > name_start {
out.push((name_start, j, Tok::Section));
}
// Attributes until '>'.
while j < n && b[j] != b'>' {
if b[j] == b'"' || b[j] == b'\'' {
let q = b[j];
let s = j;
j += 1;
while j < n && b[j] != q {
j += 1;
}
j = (j + 1).min(n);
out.push((s, j, Tok::Str));
continue;
}
if b[j].is_ascii_alphabetic() {
let s = j;
while j < n && (b[j].is_ascii_alphanumeric() || b[j] == b'-' || b[j] == b':' || b[j] == b'_') {
j += 1;
}
out.push((s, j, Tok::Attr));
continue;
}
j += 1;
}
i = (j + 1).min(n);
continue;
}
i += 1;
}
out
}
#[cfg(test)]
mod tests {
use super::*;
fn classes(lang: &str, code: &str) -> Vec<(String, Tok)> {
highlight(lang, code).into_iter().map(|(s, e, t)| (code[s..e].to_string(), t)).collect()
}
#[test]
fn rust_like_highlight_js() {
let c = classes("rust", "fn main() {\n println!(\"hello\"); // hi\n let x: u8 = 5;\n}");
assert!(c.contains(&("fn".into(), Tok::Keyword)));
assert!(c.contains(&("main".into(), Tok::Title)));
assert!(c.contains(&("println!".into(), Tok::BuiltIn)));
assert!(c.contains(&("\"hello\"".into(), Tok::Str)));
assert!(c.contains(&("// hi".into(), Tok::Comment)));
assert!(c.contains(&("u8".into(), Tok::Type)));
assert!(c.contains(&("5".into(), Tok::Number)));
}
#[test]
fn json_keys_and_unknown_languages() {
let c = classes("json", "{\"a\": \"b\", \"n\": 1}");
assert_eq!(c[0], ("\"a\"".into(), Tok::Attr));
assert_eq!(c[1], ("\"b\"".into(), Tok::Str));
assert!(highlight("brainfuck", "+++").is_empty());
let c = classes("python", "def f(x):\n return None # é");
assert!(c.contains(&("f".into(), Tok::Title)));
assert!(c.contains(&("None".into(), Tok::Literal)));
}
}