How do I expand or shrink a visual selection based on the syntax tree using Treesitter?
Answer
grn / grc / grm
Explanation
Neovim's nvim-treesitter plugin provides incremental selection based on the abstract syntax tree (AST) of your code. Instead of selecting by characters or lines, you can progressively expand your selection to encompass the next larger syntactic node — from a variable name to the full expression, then the statement, then the block, and so on. This is incredibly precise for code editing because selections always align with meaningful language constructs.
How it works
grn— init selection: starts a visual selection on the current treesitter node (the smallest syntax element under the cursor)grn(again) or node incremental: expands the selection to the next larger syntax nodegrc— scope incremental: expands to the next scope (e.g., from anifbody to the entire function)grm— node decremental: shrinks the selection back to the previous smaller node
Example
With the cursor on bar in this code:
function foo(bar, baz) {
return bar + baz;
}
Pressing grn repeatedly expands the selection through these stages:
bar(identifier)bar + baz(binary expression)return bar + baz;(return statement){ return bar + baz; }(block)- The entire function declaration
Press grm at any point to shrink back one level.
Tips
- Requires
nvim-treesitterwith theincremental_selectionmodule enabled in your config - The keybindings are configurable —
grn,grc, andgrmare the defaults but can be remapped - Combine with operators: expand to the right node, then press
d,c, oryto act on it - Works across all languages with treesitter parser support (most popular languages are covered)