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

How do I select functions, classes, and other code structures using Treesitter?

Answer

:TSTextobjectSelect @function.outer

Explanation

The nvim-treesitter-textobjects plugin provides syntax-aware text objects powered by Treesitter's AST parsing. Unlike regex-based text objects, these understand your code's actual structure, allowing precise selection of functions, classes, parameters, and more.

How it works

  • @function.outer — select the entire function (including signature)
  • @function.inner — select the function body only
  • @class.outer / @class.inner — select classes
  • @parameter.inner — select a function parameter
  • Use with v, d, c, y operators: vaf selects around function

Example

" In your Neovim config:
require'nvim-treesitter.configs'.setup {
  textobjects = {
    select = {
      enable = true,
      keymaps = {
        ['af'] = '@function.outer',
        ['if'] = '@function.inner',
        ['ac'] = '@class.outer',
        ['ia'] = '@parameter.inner',
      },
    },
  },
}

Tips

  • Works across all languages Treesitter supports (Python, Go, JS, Rust, etc.)
  • @comment.outer selects comments — great for quick deletion
  • Swap parameters: textobjects includes a swap module for @parameter.inner
  • goto_next_start lets you jump between functions: ]m for next method

Next

How do I return to normal mode from absolutely any mode in Vim?