vimtricks.wiki Concise Vim tricks, one at a time.

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

  • grninit 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 node
  • grcscope incremental: expands to the next scope (e.g., from an if body to the entire function)
  • grmnode 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:

  1. bar (identifier)
  2. bar + baz (binary expression)
  3. return bar + baz; (return statement)
  4. { return bar + baz; } (block)
  5. The entire function declaration

Press grm at any point to shrink back one level.

Tips

  • Requires nvim-treesitter with the incremental_selection module enabled in your config
  • The keybindings are configurable — grn, grc, and grm are the defaults but can be remapped
  • Combine with operators: expand to the right node, then press d, c, or y to act on it
  • Works across all languages with treesitter parser support (most popular languages are covered)

Next

How do I ignore whitespace changes when using Vim's diff mode?