Skip to content

s1n7ax/youtube-neovim-treesitter-query

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

4 Commits
 
 
 
 
 
 
 
 

Repository files navigation

Youtube Neovim Treesitter Query

This is a presentation created for Youtube video tutorial on Treesitter Query

Click here to watch the video

Neovim Treesitter Query

  • Neovim Treesitter Playground
  • Language Tree & Syntax Tree
  • Parse Query, Predicates & Directives
  • Captures and Matches

Treesitter Playground

How to install

Nvim treesitter playground GitHub

Packer

  • 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,
}

Language Tree & Syntax Tree

  • 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()

Parse Query, Predicates & Directives

Help

  • :h lua-treesitter-query
  • :h parse_query
  • :h lua-treesitter-predicates
  • :h lua-treesitter-directives

Create a query

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

Create a capture

local query = vim.treesitter.parse_query('java', '(method_declaration) @method')

Add predicate

local query = vim.treesitter.parse_query( 'java', [[
(method_declaration
  (modifiers
    (marker_annotation
      name: (identifier) @annotation (#eq? @annotation "Test"))))
]])

Get node text

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

Get offset of the node

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