'How to create syntax highlighting rule
I'm trying out monaco editor and I'm having real difficulty understanding how to create my own rule for syntax highlighting. (I'd really appreciate it if you had a resource that explains how to create rules)
I'm starting with the simple stuff:
- I'd like to add a special color for my variable at declaration. ie:
a = 12, having color ona - Add a special color for builtins functions. ie:
builtin(a, b), having color onbuiltin
I'm using https://microsoft.github.io/monaco-editor/monarch.html to try the rule in real-time here is my syntax definition
// Create your own language definition here
// You can safely look at other samples without losing modifications.
// Modifications are not saved on browser refresh/close though -- copy often!
return {
defaultToken: '',
tokenPostfix: '.ds',
keywords: [
'do', 'then', 'end', 'function', 'if', 'else', 'return', 'continue', 'break', 'for',
'while', 'to', 'until', 'in', 'static', 'step', 'delete', 'true', 'false'
],
builtins: [
'print', 'builtin'
],
operators: [
'=', '>', '<', '!', '?', ':', '==', '<=', '>=', '!=',
'&&', '||', '++', '--', '**', '+', '-', '*', '/', '%',
'<<', '>>', '+=', '-=', '*=', '/=', '%=',
],
// we include these common regular expressions
symbols: /[=><!~?:&|+\-*\/\^%]+/,
escapes: /\\(?:[abfnrtv\\"']|x[0-9A-Fa-f]{1,4}|u[0-9A-Fa-f]{4}|U[0-9A-Fa-f]{8})/,
// The main tokenizer for our languages
tokenizer: {
root: [
// My attempt for variable syntax colorization
["^[a-zA-Z_]+(?=\s*=)", 'variable.name' ],
// identifiers and keywords
[
/[a-zA-Z_]\w*/,
{
cases: {
'@keywords': { token: 'keyword.$0' },
// My attempt for builtins syntax colorizatio
'@builtins': 'predefined',
'@default': 'identifier'
}
}
],
// whitespace
{ include: '@whitespace' },
// delimiters and operators
[/[{}()\[\]]/, '@brackets'],
[
/@symbols/,
{
cases: {
'@operators': 'delimiter',
'@default': ''
}
}
],
// numbers
[/\d*\.\d+([eE][\-+]?\d+)?/, 'number.float'],
[/0[xX][0-9a-fA-F_]*[0-9a-fA-F]/, 'number.hex'],
[/\d+?/, 'number'],
// delimiter: after number because of .\d floats
[/[;,.]/, 'delimiter'],
// strings: recover on non-terminated strings
[/"([^"\\]|\\.)*$/, 'string.invalid'], // non-teminated string
[/'([^'\\]|\\.)*$/, 'string.invalid'], // non-teminated string
[/"/, 'string', '@string."'],
[/'/, 'string', "@string.'"]
],
},
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
