Tree-sitter-angular
A tree-sitter grammar parser for Angular
I’ve been using Neovim as the main code editor for several years now. Syntax highlighting is made possible by using tree-sitter, an incremental parsing library. It builds the syntax tree for a source file. nvim-treesitter is built on top, that includes an API to download and install so-called grammar parsers.
For Angular, there was an existing parser already that provided basic syntax tree and custom highlighting. The parser worked because it was injected into several parts of HTML that could contain Angular specific code. However, as Angular added support for the new Control Flow Syntax, which wasn’t valid HTML, the parser quickly became out of date. It wasn’t enough to inject the parser into Angular-specific parts.
For example:
<span *ngIf="someCondition">Show me</span>
Is using Angulars old structural directive1, which is still valid HTML. However, the new syntax is:
@if (someCondition) {
<span>Show me</span>
}
The HTML parser would already choke on this.
Rebuild
Due to the existing parser not being maintained anymore, I decided to give it a go. I build the parser completely from scratch, built on top of the HTML parser, extending the grammar instead of being injected into specific parts. It allowed me to specify exactly what an Angular file would look like, using grammar rules in JavaScript.
Not only does this enable correct syntax highlighting, it also allows correct indentation rules, due to the syntax tree being correctly interpreted. Note: the syntax and indentation queries are built inside nvim-treesitter
Footnotes
-
A directive that would change the DOM structure by injecting or removing elements. ↩