rob-revisited/ide/ui/js/twig-lang.js

77 lines
4.9 KiB
JavaScript

// Twig for Monaco (the IDE's editor and the quick editor): the JumPHP build of Monaco has no Twig, so it is made here from
// Monaco's own HTML rules, with Twig's tags in every state of them: {{ expression }}, {% statement %}, {# comment #}
// (keywords, filters after |, strings, numbers, operators), and its brackets and comments for the editor.
let ready = null;
const KEYWORDS = ['if', 'elseif', 'else', 'endif', 'for', 'endfor', 'in', 'block', 'endblock', 'extends', 'include', 'embed', 'endembed',
'set', 'endset', 'macro', 'endmacro', 'import', 'from', 'as', 'with', 'endwith', 'only', 'ignore', 'missing', 'use', 'apply', 'endapply',
'autoescape', 'endautoescape', 'verbatim', 'endverbatim', 'spaceless', 'endspaceless', 'filter', 'endfilter', 'do', 'flush', 'sandbox',
'endsandbox', 'deprecated', 'guard', 'endguard', 'cache', 'endcache', 'trans', 'endtrans', 'form_theme', 'stopwatch', 'endstopwatch',
'not', 'and', 'or', 'b-and', 'b-or', 'b-xor', 'is', 'defined', 'null', 'none', 'true', 'false', 'empty', 'even', 'odd', 'iterable',
'same', 'divisible', 'by', 'matches', 'starts', 'ends', 'loop'];
/** the rules inside {{ }} and {% %} (state name: twigExpr / twigStmt) */
function inside(end) {
return [
[end, { token: 'delimiter.twig', next: '@pop' }],
[/\s+/, ''],
[/"([^"\\]|\\.)*"/, 'string.twig'],
[/'([^'\\]|\\.)*'/, 'string.twig'],
[/\d+(\.\d+)?/, 'number.twig'],
[/\|\s*[a-zA-Z_]\w*/, 'type.twig'], // a filter
[/[a-zA-Z_][\w-]*(?=\s*\()/, 'function.twig'],
[/[a-zA-Z_][\w-]*/, { cases: { '@twigKeywords': 'keyword.twig', '@default': 'variable.twig' } }],
[/[.,:?~=<>!+\-*/%()[\]{}]/, 'operator.twig'],
[/./, ''],
];
}
/** Registers the language "twig" once (the HTML rules must be loadable: Monaco's basic-languages/html). */
export function registerTwig(monaco) {
if (ready) return ready;
ready = (async () => {
// Monaco declares "twig" itself but this build has no file for it (its loader fails): ours is set over it
if (!monaco.languages.getLanguages().some((l) => l.id === 'twig')) monaco.languages.register({ id: 'twig', extensions: ['.twig'], aliases: ['Twig', 'twig'] });
let html = null;
try { html = await monaco.languages.getLanguages().find((l) => l.id === 'html')?.loader?.(); } catch (e) { html = null; }
const twig = [
[/\{#/, { token: 'comment.twig', next: '@twigComment' }],
[/\{\{-?/, { token: 'delimiter.twig', next: '@twigExpr' }],
[/\{%-?/, { token: 'delimiter.twig', next: '@twigStmt' }],
];
const tokenizer = {};
for (const [state, rules] of Object.entries(html?.language?.tokenizer || { root: [[/[^{]+/, ''], [/./, '']] })) {
tokenizer[state] = [...twig, ...rules];
}
tokenizer.twigComment = [[/#\}/, { token: 'comment.twig', next: '@pop' }], [/[^#]+/, 'comment.twig'], [/#/, 'comment.twig']];
tokenizer.twigExpr = inside(/-?\}\}/);
tokenizer.twigStmt = inside(/-?%\}/);
monaco.languages.setMonarchTokensProvider('twig', { ...(html?.language || {}), twigKeywords: KEYWORDS, tokenizer, tokenPostfix: '' });
monaco.languages.setLanguageConfiguration('twig', {
...(html?.conf || {}),
comments: { blockComment: ['{#', '#}'] },
brackets: [['{{', '}}'], ['{%', '%}'], ['<', '>'], ['(', ')'], ['[', ']'], ['{', '}']],
autoClosingPairs: [{ open: '{{', close: ' }}' }, { open: '{%', close: ' %}' }, { open: '{#', close: ' #}' }, { open: '(', close: ')' },
{ open: '[', close: ']' }, { open: '"', close: '"' }, { open: "'", close: "'" }],
surroundingPairs: [{ open: '"', close: '"' }, { open: "'", close: "'" }, { open: '(', close: ')' }, { open: '[', close: ']' }],
});
})();
return ready;
}
/** The languages of this Monaco build: a language it lacks gets the nearest one it has, else plain text. */
const NEAREST = { kotlin: 'java', scala: 'java', dart: 'java', swift: 'typescript', c: 'cpp', 'objective-c': 'cpp', proto: 'protobuf',
sol: 'solidity', coffee: 'javascript', hcl: 'ini', bicep: 'ini', tcl: 'shell', fsharp: 'csharp', vb: 'csharp', ruby: 'python',
r: 'python', elixir: 'python', clojure: 'plaintext', pascal: 'plaintext', bat: 'shell', sass: 'scss', handlebars: 'handlebars' };
/** what this build of Monaco really ships (vendor/monaco/vs/basic-languages and language/): it declares more than it has */
const SHIPPED = new Set(['cpp', 'csharp', 'css', 'dockerfile', 'go', 'graphql', 'handlebars', 'html', 'ini', 'java', 'javascript', 'less', 'lua',
'markdown', 'mdx', 'perl', 'pgsql', 'php', 'powershell', 'protobuf', 'pug', 'python', 'rust', 'scss', 'shell', 'solidity', 'sql', 'typescript',
'xml', 'yaml', 'json', 'plaintext', 'twig']);
export function availableLanguage(monaco, id) {
const have = new Set(monaco.languages.getLanguages().map((l) => l.id).filter((l) => SHIPPED.has(l)));
if (have.has(id)) return id;
const near = NEAREST[id];
return near && have.has(near) ? near : 'plaintext';
}