This is a presentation created for Youtube video tutorial on Treesitter Query
- Neovim Treesitter Playground
- Language Tree & Syntax Tree
- Parse Query, Predicates & Directives
- Captures and Matches
Nvim treesitter playground GitHub
- Put the following configuration to packer package list
- Close Neovim and reopen
- Run
:PackerInstall
and:PackerCompile
use {
'nvim-treesitter/playground',
requires = { 'nvim-treesitter/nvim-treesitter' },
cmd = 'TSPlaygroundToggle',
config = function()
R'nvim-treesitter.configs'.setup({})
end,
}
- Get language tree for a given buffer
local language_tree = vim.treesitter.get_parser(<bufnr>)
- Build syntax tree
local syntax_tree = language_tree:parse()
- Root node of the syntax tree
local root = syntax_tree[1]:root()
:h lua-treesitter-query
:h parse_query
:h lua-treesitter-predicates
:h lua-treesitter-directives
local query = vim.treesitter.parse_query( 'java', '(method_declaration)')
for id, match, metadata in query:iter_matches(root, <bufnr>, root:start(), root:end_()) do
print(vim.inspect(getmetatable(match[1])))
end
local query = vim.treesitter.parse_query('java', '(method_declaration) @method')
local query = vim.treesitter.parse_query( 'java', [[
(method_declaration
(modifiers
(marker_annotation
name: (identifier) @annotation (#eq? @annotation "Test"))))
]])
local q = R 'vim.treesitter.query'
local query = vim.treesitter.parse_query( 'java', [[
(method_declaration
(modifiers
(marker_annotation
name: (identifier) @annotation (#eq? @annotation "Test")))
name: (identifier) @method-name)
]])
for id, match, metadata in query:iter_matches(root, <bufnr>, root:start(), root:end_()) do
print(q.get_node_text(match[2], <bufnr>))
end
local query = vim.treesitter.parse_query('java', [[
(method_declaration
(modifiers
(marker_annotation
name: (identifier) @annotation (#eq? @annotation "Test")))
name: (identifier) @method-name (#offset! @method-name))
]])
for id, match, metadata in query:iter_matches(root, <bufnr>, root:start(), root:end_()) do
print(vim.inspect(metadata))
end