Post

Today I shipped a huge change to syntax highlighting in Discord: code blocks and file previews on web are now being highlighted by Tree-sitter, instead of highlight.js.

Why, you might ask? highlight.js is a genuinely great project, but it suffers from one great weakness: regular expressions. This comes with 2 main downsides: RegEx is often vulnerable to denial-of-service, and it has no semantic understanding of the code.

highlight.js is fairly resilient to ReDoS, but even so we'd occasionally have to field some security reports about it. Tree-sitter is not immune to DoS either, but we can tune it to protect against DoS in ways that aren't possible with RegEx.

More importantly, however, tree-sitter is semantically aware, meaning that it can highlight code in context rather than based on keywords and pattern matching. This means that your code blocks in Discord are now as accurate as the best code editors. For example, None is not a keyword anymore.

Shout-out to the tree-sitter contributors and the hundreds of independent grammar authors for creating such a strong ecosystem, and shout-out @fasterthanli.me for building Arborium (the basis for our new syntax highlighter).

i'm super interested to add some grammars. would you be willing to put up some documentation on how to add one via PR?

I'll see if I can put something together tomorrow, but it's fairly straightforward if you look at the existing languages we've had to modify. The main challenge is building the project locally since it requires some more niche tooling.

0 reposts1 like

oh i see now that most of the languages are being tracked in `arborium`, i'll contribute there! thanks so much

You might have some trouble landing it upstream since there hasn't been a ton of activity there lately, so we're happy to accept the patch in the meantime if it doesn't land.