git clone https://garage44.eu/jeroen/midas.git.. /web/src/lib/highlight.tsx
import m from '@garage44/mithril'
/**
* Syntax colour for the commands and code in a session: a tokenizer per kind
* of text that splits it into runs, each a `<span class="hl-…">` built as an
* element from the text — nothing an agent writes is ever read as HTML.
*
* Shell is done properly, since commands are what a session shows most: the
* command word of each step of a pipeline, its flags, quoted strings,
* variables and `$(…)`, the operators between steps, comments and keywords.
* Other code gets a lighter pass: keywords, strings, comments, numbers.
*/
export type Kind = 'cmd' | 'flag' | 'str' | 'var' | 'op' | 'com' | 'num' | 'kw' | 'key' | 'text'
export interface Tok {
t: string
k: Kind
}
const SHELL_KW = new Set(['if', 'then', 'else', 'elif', 'fi', 'for', 'while', 'until', 'do', 'done', 'case', 'esac', 'in', 'function', 'select', 'time'])
/** Words that run the word after them: that one is the command, not this. */
const PREFIX = new Set(['sudo', 'env', 'exec', 'nohup', 'time', 'xargs', 'nice', 'command', 'builtin'])
/** A shell command, as runs. */
export function shell(src: string): Tok[] {
const out: Tok[] = []
const push = (t: string, k: Kind) => {
if (!t) return
const last = out[out.length - 1]
if (last && last.k === k && k === 'text') last.t += t
else out.push({t, k})
}
let i = 0
let expectCmd = true
// After `for`, `select` or `case`: a name, then `in`.
let expectIn = false
while (i < src.length) {
const c = src[i]
const rest = src.slice(i)
// Whitespace keeps whatever was expected.
const ws = rest.match(/^[ \t]+/)
if (ws) {
push(ws[0], 'text')
i += ws[0].length
continue
}
if (c === '\n') {
push(c, 'text')
i++
expectCmd = true
continue
}
// A line continuation.
if (rest.startsWith('\\\n')) {
push('\\\n', 'op')
i += 2
continue
}
// A comment: # at a word's start, to the line's end.
if (c === '#') {
const end = src.indexOf('\n', i)
const t = end < 0 ? rest : src.slice(i, end)
push(t, 'com')
i += t.length
continue
}
const op = rest.match(/^(\|\||&&|\|&|;;|[|;&]|[0-9]?>>?(&[0-9-])?|<<<?|<|\$\(|\)|\(|\{|\})/)
if (op) {
push(op[0], 'op')
i += op[0].length
// After a pipe, a sequence or an opening, a new command; after a redirect, a file.
expectCmd = /^(\|\||&&|\|&|;;|[|;&]|\$\(|\(|\{)$/.test(op[0])
continue
}
if (c === "'") {
const end = src.indexOf("'", i + 1)
const t = end < 0 ? rest : src.slice(i, end + 1)
push(t, 'str')
i += t.length
expectCmd = false
continue
}
if (c === '"') {
// To the closing quote, past escaped ones; variables inside keep their colour.
let j = i + 1
while (j < src.length && src[j] !== '"') j += src[j] === '\\' ? 2 : 1
const body = src.slice(i, Math.min(j + 1, src.length))
for (const part of body.split(/(\$\{[^}]*\}|\$[A-Za-z_][A-Za-z0-9_]*|\$[0-9@*#?$!])/)) {
if (part) push(part, /^\$/.test(part) ? 'var' : 'str')
}
i += body.length
expectCmd = false
continue
}
const v = rest.match(/^(\$\{[^}]*\}|\$[A-Za-z_][A-Za-z0-9_]*|\$[0-9@*#?$!])/)
if (v) {
push(v[0], 'var')
i += v[0].length
expectCmd = false
continue
}
const word = rest.match(/^[^\s|;&<>()'"$#{}]+/)
if (word) {
const w = word[0]
i += w.length
if (expectCmd && /^[A-Za-z_][A-Za-z0-9_]*=/.test(w)) {
// VAR=value before a command: the name a variable, the command still to come.
const eq = w.indexOf('=')
push(w.slice(0, eq), 'var')
push(w.slice(eq), 'text')
continue
}
if (expectIn && w === 'in') {
push(w, 'kw')
expectIn = false
continue
}
if (expectCmd && SHELL_KW.has(w)) {
push(w, 'kw')
if (w === 'for' || w === 'select' || w === 'case') {
expectCmd = false
expectIn = true
} else if (w === 'done' || w === 'fi' || w === 'esac') expectCmd = false
continue
}
if (expectCmd) {
push(w, 'cmd')
expectCmd = PREFIX.has(w)
continue
}
if (/^--?[A-Za-z0-9]/.test(w)) {
const eq = w.indexOf('=')
if (eq > 0) {
push(w.slice(0, eq), 'flag')
push(w.slice(eq), 'text')
} else push(w, 'flag')
continue
}
push(w, /^[0-9]+$/.test(w) ? 'num' : 'text')
continue
}
push(c, 'text')
i++
}
return out
}
const KEYWORDS: Record<string, string[]> = {
rust: 'as async await break const continue crate dyn else enum extern false fn for if impl in let loop match mod move mut pub ref return self Self static struct super trait true type unsafe use where while'.split(' '),
ts: 'as async await break case catch class const continue default delete do else enum export extends false finally for from function if implements import in instanceof interface let new null of return static super switch this throw true try type typeof undefined var void while yield'.split(' '),
python: 'and as assert async await break class continue def del elif else except False finally for from global if import in is lambda None nonlocal not or pass raise return True try while with yield'.split(' '),
wgsl: 'alias break case const continue default discard else enable false fn for if let loop override return struct switch true var while'.split(' '),
json: ['true', 'false', 'null'],
toml: ['true', 'false'],
}
const ALIAS: Record<string, string> = {
rs: 'rust',
typescript: 'ts',
tsx: 'ts',
js: 'ts',
javascript: 'ts',
jsx: 'ts',
py: 'python',
yml: 'toml',
yaml: 'toml',
wesl: 'wgsl',
}
const SHELLS = new Set(['sh', 'bash', 'shell', 'zsh', 'console', 'shellsession', 'terminal'])
/** Other code: keywords, strings, comments (line and block ones, or `#` where that is one), numbers; JSON's keys. */
export function code(src: string, lang: string): Tok[] {
const l = ALIAS[lang] ?? lang
const kw = new Set(KEYWORDS[l] ?? [])
const hash = l === 'python' || l === 'toml'
const out: Tok[] = []
const re = hash
? /(#[^\n]*)|("(?:[^"\\\n]|\\.)*"|'(?:[^'\\\n]|\\.)*')|(\b\d[\d_]*(?:\.\d+)?\b)|([A-Za-z_][A-Za-z0-9_]*)/g
: /(\/\/[^\n]*|\/\*[\s\S]*?\*\/)|("(?:[^"\\\n]|\\.)*"|'(?:[^'\\\n]|\\.)*'|`(?:[^`\\]|\\.)*`)|(\b\d[\d_]*(?:\.\d+)?(?:[eE][+-]?\d+)?\b)|([A-Za-z_][A-Za-z0-9_]*)/g
let last = 0
for (let mt = re.exec(src); mt; mt = re.exec(src)) {
if (mt.index > last) out.push({t: src.slice(last, mt.index), k: 'text'})
const [t, com, str, num, word] = mt
if (com) out.push({t, k: 'com'})
else if (str) {
// In JSON a string before a colon is a key.
const key = l === 'json' && /^\s*:/.test(src.slice(mt.index + t.length))
out.push({t, k: key ? 'key' : 'str'})
} else if (num) out.push({t, k: 'num'})
else if (word && kw.has(word)) out.push({t, k: 'kw'})
else out.push({t, k: 'text'})
last = mt.index + t.length
}
if (last < src.length) out.push({t: src.slice(last), k: 'text'})
return out
}
/** The runs for a language name as a code fence gives it; none known: as it is. */
export function tokens(src: string, lang: string): Tok[] {
const l = lang.toLowerCase()
if (SHELLS.has(l)) return shell(src)
if (KEYWORDS[ALIAS[l] ?? l]) return code(src, l)
return [{t: src, k: 'text'}]
}
/** Runs as elements. */
export function highlight(src: string, lang: string): m.Children {
return tokens(src, lang).map((x) => (x.k === 'text' ? x.t : <span class={`hl-${x.k}`}>{x.t}</span>))
}