custom-syntax-highlighter
custom-syntax-highlighter copied to clipboard
Matching a keyword
Hey, great library!
Sorry if I'm being a bit dumb, but I'm struggling with how I would match a keyword without it being part of another word. Essentially, what I'm trying to achieve is they way the var
keyword is highlighted below:
var my_var;var anothervar; var yet1varmore;
I want it to match the word exactly, but taking into consideration what came before it (i.e. anything that isn't an alphanumeric or _ character).
So far I've got:
"key": /^(var|true|false)\b/
but that highlights the matches, no matter where they are.
I think what you should do is create a proxy object of a regex. from there, when you call the test
or match
function, you can add traps to decide based on context if the token is a variable or a keyword.
const patterns: [{
match: new Proxy(/^[$_a-zA-Z][$_a-zA-Z0-9]*\b/, {
get(target: any[], prop: string, receiver: any) {
if (prop in RegExp.prototype)
if (prop === "test")
return function (param: string): boolean {
// do logic here
}
else
return Reflect.get(target, prop, receiver); // do the expected behaviour
else
return null; // the requested parameter doesn't exit
}
}),
name: "KeyWord"
}];
highlight(patterns);
it's not elegant but it'll work...
EDIT: Upon further scrolling down the page (I kid you not, 10 lines) I realised that the match property takes a function as well. So it's probably best to make use of these as you'll be able to look at the previous token (you'll need to store a reference to each in an array as I don't think there is a way of looking at this information yet) and access the previous token and decide then, what to label it as.