/** * @typedef {import('./index.js').ShjLanguage} ShjLanguage * @typedef {import('./index.js').ShjBuiltinLanguage} ShjBuiltinLanguage */ /** * @type {Partial>} */ const languages = { bash: [[/#!(\/usr)?\/bin\/bash/g, 500], [/\b(if|elif|then|fi|echo)\b|\$/g, 10]], html: [[/<\/?[a-z-]+[^\n>]*>/g, 10], [/^\s+<-]/gm, 10], [/^@@ ?[-+,0-9 ]+ ?@@/gm, 25]], md: [[/^(>|\t\*|\t\d+.)/gm, 10], [/\[.*\](.*)/g, 10]], docker: [[/^(FROM|ENTRYPOINT|RUN)/gm, 500]], xml: [[/<\/?[a-z-]+[^\n>]*>/g, 10], [/^<\?xml/g, 500]], c: [[/#include\b|\bprintf\s+\(/g, 100]], rs: [[/^\s+(use|fn|mut|match)\b/gm, 100]], go: [[/\b(func|fmt|package)\b/g, 100]], java: [[/^import\s+java/gm, 500]], asm: [[/^(section|global main|extern|\t(call|mov|ret))/gm, 100]], // json: [[/\b(true|false|null)\b|\"[^"]+\":/g, 10]], yaml: [[/^(\s+)?[a-z][a-z0-9]*:/gmi, 10]] } /** * Try to find the language the given code belong to * * @param {string} code The code * @returns {ShjLanguage} The language of the code */ export function detectLanguage(code) { return (Object.entries(languages) .map(([lang, features]) => /** @type {[ShjLanguage, number]} */ ([ lang, features.reduce((acc, [match, score]) => acc + [...code.matchAll(match)].length * score, 0) ])) .filter(([lang, score]) => score > 20) .sort((a, b) => b[1] - a[1])[0]?.[0] || 'plain'); }