Neovim 101 — Contextual Semantic Highlighting
Context-aware semantic highlighting using LSP and Tree-sitter.
We configured semantic highlighting using Tree-sitter and LSP in a previous article. As semantic tokens support is now part of Neovim, we will use the LSP semantic tokens if it is supported, and fall back to Tree-sitter if the capability is unavailable.
This article is part of the Neovim 101 series.
The Neovim configuration files are available in this repository.
Starting Neovim release 0.9, semantic tokens are supported (
:h lsp-semantic-tokens). However, not all language servers provide this capability.
We will check out Lua APIs and user commands that help us inspect all the items at a given buffer location, including semantic tokens. With this information, we will configure semantic highlighting using LSP or Tree-sitter.
User Command and Lua APIs
Neovim provides us with user commands and Lua APIs (
:h lua-inspector) to get information related to Tree-sitter, semantic tokens, extmarks, syntax groups, and other information at a given buffer location.
Inspect and vim.inspect_pos()
:h vim.inspect_pos()) API gets all the items at a given buffer position.
The corresponding user command is
- treesitter: a list of treesitter captures
- syntax: a list of syntax groups
- semantic_tokens: a list of semantic tokens
- extmarks: a list of extmarks
In the screenshot below, we use the
:Inspect! command to get all items at the current buffer location. We can see that the Lua language server (
sumneko_lua) supports semantic tokens.