Syntax Highlighting

The minor mode tree-sitter-hl-mode provides the framework for syntax highlighting. It overrides the regex-based highlighting provided by font-lock-mode, using the syntax tree provided by tree-sitter-mode. It is based on tree queries, a system for pattern-matching on Tree-sitter’s syntax trees.

It can be toggled in a buffer by the command tree-sitter-hl-mode, or enabled through major mode hooks:

(add-hook 'rust-mode-hook #'tree-sitter-hl-mode)

To enable it whenever possible (assuming the language major modes were already installed):

(global-tree-sitter-mode)
(add-hook 'tree-sitter-after-on-hook #'tree-sitter-hl-mode)

Like font-lock-mode, tree-sitter-hl-mode provides only the mechanisms. The actual highlighting rules are provided by language-specific packages, or a language bundle like tree-sitter-langs.

tree-sitter-langs

The package tree-sitter-langs provides syntax highlighting queries for some languages.

Most of them are intentionally different from those from upstream repositories, which are more geared towards GitHub’s use cases. We try to be more consistent with Emacs’s existing conventions. The general principles are:

  • Definitions and uses should be differentiated:
    • @function vs. @function.call.
    • @method vs. @method.call.
    • @type.parameter vs. @type.argument.
  • @variable and @variable.parameter should be applied only to declarations/definitions/bindings/mutations (writes), not usage (reads).
  • Special faces should have high priority (placed earlier in the pattern list): @function.macro, @type.builtin, @variable.special.
  • Patterns whose internals may be highlighted should have low priority (placed towards the end). Example: strings with interpolation.

For some languages, the highlighting patterns are similar to those from upstream grammar repositories, instead of extensively following the above principles. They should be considered WIP.

Contributions to improve them are welcome.