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,yoperators:vafselects 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.outerselects comments — great for quick deletion- Swap parameters: textobjects includes a swap module for
@parameter.inner goto_next_startlets you jump between functions:]mfor next method