| 1 | ## Adding highlight queries |
| 2 | |
| 3 | `highlights.scm` queries assign a highlight scope (`@function`, `@type`, |
| 4 | `@keyword`, ...) to nodes in the syntax tree; the theme then maps each scope to a |
| 5 | colour. Highlighting is the one query file that every language needs. |
| 6 | |
| 7 | Query files should be placed in `runtime/queries/{language}/highlights.scm` when |
| 8 | contributing to Helix. |
| 9 | |
| 10 | ## Scopes |
| 11 | |
| 12 | The full list of highlight scopes, and what each is for, is documented on the |
| 13 | [themes page]. Match the most specific scope that fits the node — for example a |
| 14 | method call is `@function.method` while a plain field access is |
| 15 | `@variable.other.member`. |
| 16 | |
| 17 | A query file may reuse another language's with `; inherits: <lang>` on the first |
| 18 | line (for example `tsx` inherits `typescript`, which inherits `ecma`). An |
| 19 | inherited file is compiled against *each* inheriting grammar, so every capture |
| 20 | must be valid there too. |
| 21 | |
| 22 | ## Precedence |
| 23 | |
| 24 | Two rules decide which capture wins when more than one matches the same text: |
| 25 | |
| 26 | 1. **Same span: last match wins.** Among captures covering the same bytes, the |
| 27 | pattern that appears later in the file wins. Put a generic rule *before* the |
| 28 | specific one that should override it. |
| 29 | 2. **Nested nodes: innermost wins.** When a parent and a child node both cover |
| 30 | the text, the child's capture wins, regardless of file order. |
| 31 | |
| 32 | A common consequence of rule 2: capture the *leaf* you mean. A call captured on |
| 33 | a wrapping node loses to a base `(identifier) @variable` on the inner identifier, |
| 34 | so put `@function` on the identifier itself. |
| 35 | |
| 36 | Where the grammar can't distinguish a scope, casing is often used as a heuristic: |
| 37 | |
| 38 | ```scm |
| 39 | ((identifier) @constant |
| 40 | (#match? @constant "^[A-Z][A-Z_]*$")) |
| 41 | ``` |
| 42 | |
| 43 | ## Testing |
| 44 | |
| 45 | `cargo xtask query-check [language]` confirms the queries are valid against the |
| 46 | grammar. `cargo xtask highlight-check [language]` runs the real highlighter over |
| 47 | the fixtures in `tests/query/highlights/<language-id>/<name>.<ext>`, where a |
| 48 | caret comment line (`// ^ @capture`) asserts the winning scope at the column |
| 49 | above it; this catches the precedence mistakes that `query-check` cannot see. |
| 50 | `cargo xtask highlight-check --dump <language> <file>` prints the winning capture |
| 51 | per span for an arbitrary file. |
| 52 | |
| 53 | [themes page]: https://docs.helix-editor.com/themes.html#scopes |