robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
aa1d8a2702
master
1--- @brief This Lua |treesitter-query| interface allows you to create queries and use them to parse 2--- text. See |vim.treesitter.query.parse()| for a working example. 3 4local api =vim . api 5local nvim_on =require ( 'vim._core.util' ). nvim_on 6local language =require ( 'vim.treesitter.language' ) 7local memoize =vim . func . _memoize 8local cmp_ge =require ( 'vim.treesitter._range' ). cmp_pos . ge 9 10local MODELINE_FORMAT ='^;+%s*inherits%s*:?%s*([a-z_,()]+)%s*$' 11local EXTENDS_FORMAT ='^;+%s*extends%s*$' 12 13local M ={} 14 15---Parsed query, see |vim.treesitter.query.parse()| 16--- 17---@class vim.treesitter.Query 18---@field lang string parser language name 19---@field captures string[] list of (unique) capture names defined in query 20---@field info vim.treesitter.QueryInfo query context (e.g. captures, predicates, directives) 21---@field has_conceal_line boolean whether the query sets conceal_lines metadata 22---@field has_combined_injections boolean whether the query contains combined injections 23---@field query TSQuery userdata query object 24---@field private _processed_patterns table<integer, vim.treesitter.query.ProcessedPattern> 25local Query ={} 26Query . __index =Query 27 28---@param name string 29local function is_directive ( name ) 30return string . sub ( name , - 1 ) == '!' 31end 32 33---@nodoc 34---@class vim.treesitter.query.ProcessedPredicate 35---@field [1] string predicate name 36---@field [2] boolean should match 37---@field [3] (integer|string)[] the original predicate 38 39---@alias vim.treesitter.query.ProcessedDirective (integer|string)[] 40 41---@nodoc 42---@class vim.treesitter.query.ProcessedPattern { 43---@field predicates vim.treesitter.query.ProcessedPredicate[] 44---@field directives vim.treesitter.query.ProcessedDirective[] 45 46--- Splits the query patterns into predicates and directives. 47function Query : _process_patterns () 48self . _processed_patterns ={} 49 50for k , pattern_list in pairs ( self . info . patterns ) do 51---@type vim.treesitter.query.ProcessedPredicate[] 52local predicates ={} 53---@type vim.treesitter.query.ProcessedDirective[] 54local directives ={} 55 56for _ , pattern in ipairs ( pattern_list ) do 57-- Note: tree-sitter strips the leading # from predicates for us. 58local pred_name =pattern [ 1 ] 59---@cast pred_name string 60 61if is_directive ( pred_name ) then 62table . insert ( directives , pattern ) 63if vim . deep_equal ( pattern , { 'set!' , 'injection.combined' } ) then 64self . has_combined_injections =true 65end 66if vim . deep_equal ( pattern , { 'set!' , 'conceal_lines' , '' } ) then 67self . has_conceal_line =true 68end 69else 70local should_match =true 71if pred_name : match ( '^not%-' ) then 72pred_name =pred_name : sub ( 5 ) 73should_match =false 74end 75table . insert ( predicates , { pred_name , should_match , pattern } ) 76end 77end 78 79self . _processed_patterns [ k ] ={ predicates =predicates , directives =directives } 80end 81end 82 83---@package 84---@see vim.treesitter.query.parse 85---@param lang string 86---@param ts_query TSQuery 87---@return vim.treesitter.Query 88function Query . new ( lang , ts_query ) 89local self =setmetatable ( {} , Query ) 90local query_info =ts_query : inspect () ---@type TSQueryInfo 91self . query =ts_query 92self . lang =lang 93self . info ={ 94captures =query_info . captures , 95patterns =query_info . patterns , 96} 97self . captures =self . info . captures 98self : _process_patterns () 99return self 100end 101 102---@nodoc 103---Information for Query, see |vim.treesitter.query.parse()| 104---@class vim.treesitter.QueryInfo 105--- 106---List of (unique) capture names defined in query. 107---@field captures string[] 108--- 109---Contains information about predicates and directives. 110---Key is pattern id, and value is list of predicates or directives defined in the pattern. 111---A predicate or directive is a list of (integer|string); integer represents `capture_id`, and 112---string represents (literal) arguments to predicate/directive. See |treesitter-predicates| 113---and |treesitter-directives| for more details. 114---@field patterns table<integer, (integer|string)[][]> 115 116---@param files string[] 117---@return string[] 118local function dedupe_files ( files ) 119local result ={} 120---@type table<string,boolean> 121local seen ={} 122 123for _ , path in ipairs ( files ) do 124if not seen [ path ] then 125table . insert ( result , path ) 126seen [ path ] =true 127end 128end 129 130return result 131end 132 133--- @param filename string 134--- @param read_quantifier '*a'|'*l' 135local function safe_read ( filename , read_quantifier ) 136local file , err =io . open ( filename , 'r' ) 137if not file then 138error ( err ) 139end 140local content =file : read ( read_quantifier ) 141io . close ( file ) 142return content 143end 144 145--- Adds {ilang} to {base_langs}, only if {ilang} is different than {lang} 146--- 147---@param base_langs string[] 148---@param lang string 149---@param ilang string 150---@return boolean true If lang == ilang 151local function add_included_lang ( base_langs , lang , ilang ) 152if lang == ilang then 153return true 154end 155table . insert ( base_langs , ilang ) 156return false 157end 158 159--- Gets the list of files used to make up a query 160--- 161---@param lang string Language to get query for 162---@param query_name string Name of the query to load (e.g., "highlights") 163---@param is_included? boolean Internal parameter, most of the time left as `nil` 164---@return string[] query_files List of files to load for given query and language 165function M . get_files ( lang , query_name , is_included ) 166local query_path =string . format ( 'queries/%s/%s.scm' , lang , query_name ) 167local lang_files =dedupe_files ( api . nvim_get_runtime_file ( query_path , true )) 168 169if # lang_files == 0 then 170return {} 171end 172 173local base_query =nil ---@type string? 174local extensions ={} 175 176local base_langs ={} ---@type string[] 177 178-- Now get the base languages by looking at the first line of every file 179-- The syntax is the following : 180-- ;+ inherits: ({language},)*{language} 181-- 182-- {language} ::= {lang} | ({lang}) 183for _ , filename in ipairs ( lang_files ) do 184local file , err =io . open ( filename , 'r' ) 185if not file then 186error ( err ) 187end 188 189local extension =false 190 191for modeline in 192---@return string 193function () 194return file : read ( '*l' ) 195end 196do 197if not vim . startswith ( modeline , ';' ) then 198break 199end 200 201local langlist =modeline : match ( MODELINE_FORMAT ) 202if langlist then 203---@diagnostic disable-next-line:param-type-mismatch 204for _ , incllang in ipairs ( vim . split ( langlist , ',' )) do 205local is_optional =incllang : match ( '%(.*%)' ) 206 207if is_optional then 208if not is_included then 209if add_included_lang ( base_langs , lang , incllang : sub ( 2 , # incllang - 1 )) then 210extension =true 211end 212end 213else 214if add_included_lang ( base_langs , lang , incllang ) then 215extension =true 216end 217end 218end 219elseif modeline : match ( EXTENDS_FORMAT ) then 220extension =true 221end 222end 223 224if extension then 225table . insert ( extensions , filename ) 226elseif base_query == nil then 227base_query =filename 228end 229io . close ( file ) 230end 231 232local query_files ={} 233for _ , base_lang in ipairs ( base_langs ) do 234local base_files =M . get_files ( base_lang , query_name , true ) 235vim . list_extend ( query_files , base_files ) 236end 237vim . list_extend ( query_files , { base_query } ) 238vim . list_extend ( query_files , extensions ) 239 240return query_files 241end 242 243---@param filenames string[] 244---@return string 245local function read_query_files ( filenames ) 246local contents ={} 247 248for _ , filename in ipairs ( filenames ) do 249table . insert ( contents , safe_read ( filename , '*a' )) 250end 251 252return table . concat ( contents , '' ) 253end 254 255-- The explicitly set query strings from |vim.treesitter.query.set()| 256---@type table<string,table<string,string>> 257local explicit_queries =setmetatable ( {} , { 258__index =function ( t , k ) 259local lang_queries ={} 260rawset ( t , k , lang_queries ) 261 262return lang_queries 263end , 264} ) 265 266--- Sets the runtime query named {query_name} for {lang} 267--- 268--- This allows users to override or extend any runtime files and/or configuration 269--- set by plugins. 270--- 271--- For example, you could enable spellchecking of `C` identifiers with the 272--- following code: 273--- ```lua 274--- vim.treesitter.query.set( 275--- 'c', 276--- 'highlights', 277--- [[;inherits c 278--- (identifier) @spell]] 279--- ) 280--- ``` 281--- 282---@param lang string Language to use for the query 283---@param query_name string Name of the query (e.g., "highlights") 284---@param text string Query text (unparsed). 285function M . set ( lang , query_name , text ) 286--- @diagnostic disable-next-line: undefined-field LuaLS bad at generics 287M . get : clear ( lang , query_name ) 288explicit_queries [ lang ][ query_name ] =text 289end 290 291--- Returns the runtime query {query_name} for {lang}. 292--- 293---@param lang string Language to use for the query 294---@param query_name string Name of the query (e.g. "highlights") 295--- 296---@return vim.treesitter.Query? : Parsed query. `nil` if no query files are found. 297M . get =memoize ( 'concat-2' , function ( lang , query_name ) 298local query_string ---@type string 299 300if explicit_queries [ lang ][ query_name ] then 301local query_files ={} 302local base_langs ={} ---@type string[] 303 304for line in explicit_queries [ lang ][ query_name ]: gmatch ( '([^\n]*)\n?' ) do 305if not vim . startswith ( line , ';' ) then 306break 307end 308 309local lang_list =line : match ( MODELINE_FORMAT ) 310if lang_list then 311for _ , incl_lang in ipairs ( vim . split ( lang_list , ',' )) do 312local is_optional =incl_lang : match ( '%(.*%)' ) 313 314if is_optional then 315add_included_lang ( base_langs , lang , incl_lang : sub ( 2 , # incl_lang - 1 )) 316else 317add_included_lang ( base_langs , lang , incl_lang ) 318end 319end 320elseif line : match ( EXTENDS_FORMAT ) then 321table . insert ( base_langs , lang ) 322end 323end 324 325for _ , base_lang in ipairs ( base_langs ) do 326local base_files =M . get_files ( base_lang , query_name , true ) 327vim . list_extend ( query_files , base_files ) 328end 329 330query_string =read_query_files ( query_files ) .. explicit_queries [ lang ][ query_name ] 331else 332local query_files =M . get_files ( lang , query_name ) 333query_string =read_query_files ( query_files ) 334end 335 336if # query_string == 0 then 337return nil 338end 339 340return M . parse ( lang , query_string ) 341end , false ) 342 343nvim_on ( 344'OptionSet' , 345api . nvim_create_augroup ( 'nvim.treesitter.query_cache_reset' , { clear =true } ), 346{ 347pattern ={ 'runtimepath' } , 348} , 349function () 350--- @diagnostic disable-next-line: undefined-field LuaLS bad at generics 351M . get : clear () 352end 353) 354 355--- Parses a {query} string and returns a `Query` object (|lua-treesitter-query|), which can be used 356--- to search the tree for the query patterns (via |Query:iter_captures()|, |Query:iter_matches()|), 357--- or inspect/modify the query via these fields: 358--- - `captures`: a list of unique capture names defined in the query (alias: `info.captures`). 359--- - `info.patterns`: information about predicates. 360--- - `query`: the underlying |TSQuery| which can be used to disable patterns or captures. 361--- 362--- Example: 363--- ```lua 364--- local query = vim.treesitter.query.parse('vimdoc', [[ 365--- ; query 366--- ((h1) @str 367--- (#trim! @str 1 1 1 1)) 368--- ]]) 369--- local tree = vim.treesitter.get_parser():parse()[1] 370--- for id, node, metadata in query:iter_captures(tree:root(), 0) do 371--- -- Print the node name and source text. 372--- vim.print({node:type(), vim.treesitter.get_node_text(node, vim.api.nvim_get_current_buf())}) 373--- end 374--- ``` 375--- 376---@param lang string Language to use for the query 377---@param query string Query text, in s-expr syntax 378--- 379---@return vim.treesitter.Query : Parsed query 380--- 381---@see [vim.treesitter.query.get()] 382M . parse =memoize ( 'concat-2' , function ( lang , query ) 383assert ( language . add ( lang )) 384local ts_query =vim . _ts_parse_query ( lang , query ) 385return Query . new ( lang , ts_query ) 386end , false ) 387 388--- Implementations of predicates that can optionally be prefixed with "any-". 389--- 390--- These functions contain the implementations for each predicate, correctly 391--- handling the "any" vs "all" semantics. They are called from the 392--- predicate_handlers table with the appropriate arguments for each predicate. 393local impl ={ 394--- @param match table<integer,TSNode[]?> 395--- @param source integer|string 396--- @param predicate any[] 397--- @param any boolean 398[ 'eq' ] =function ( match , source , predicate , any ) 399local nodes =match [ predicate [ 2 ]] 400if not nodes or # nodes == 0 then 401return true 402end 403 404for _ , node in ipairs ( nodes ) do 405local node_text =vim . treesitter . get_node_text ( node , source ) 406 407local str ---@type string 408if type ( predicate [ 3 ]) == 'string' then 409-- (#eq? @aa "foo") 410str =predicate [ 3 ] 411else 412-- (#eq? @aa @bb) 413local other =assert ( match [ predicate [ 3 ]]) 414assert ( # other == 1 , '#eq? does not support comparison with captures on multiple nodes' ) 415str =vim . treesitter . get_node_text ( other [ 1 ], source ) 416end 417 418local res =str ~= nil and node_text == str 419if any and res then 420return true 421elseif not any and not res then 422return false 423end 424end 425 426return not any 427end , 428 429--- @param match table<integer,TSNode[]> 430--- @param source integer|string 431--- @param predicate any[] 432--- @param any boolean 433[ 'lua-match' ] =function ( match , source , predicate , any ) 434local nodes =match [ predicate [ 2 ]] 435if not nodes or # nodes == 0 then 436return true 437end 438 439for _ , node in ipairs ( nodes ) do 440local regex =predicate [ 3 ] 441local res =string . find ( vim . treesitter . get_node_text ( node , source ), regex ) ~= nil 442if any and res then 443return true 444elseif not any and not res then 445return false 446end 447end 448 449return not any 450end , 451 452[ 'match' ] =( function () 453local magic_prefixes ={ [ '\\v' ] =true , [ '\\m' ] =true , [ '\\M' ] =true , [ '\\V' ] =true } 454--- @param str string 455local function check_magic ( str ) 456if string . len ( str ) < 2 or magic_prefixes [ string . sub ( str , 1 , 2 )] then 457return str 458end 459return '\\v' .. str 460end 461 462local compiled_vim_regexes =setmetatable ( {} , { 463__index =function ( t , pattern ) 464local res =vim . regex ( check_magic ( pattern )) 465rawset ( t , pattern , res ) 466return res 467end , 468} ) 469 470--- @param match table<integer,TSNode[]> 471--- @param source integer|string 472--- @param predicate any[] 473--- @param any boolean 474return function ( match , source , predicate , any ) 475local nodes =match [ predicate [ 2 ]] 476if not nodes or # nodes == 0 then 477return true 478end 479 480for _ , node in ipairs ( nodes ) do 481local regex =compiled_vim_regexes [ predicate [ 3 ]] ---@type vim.regex 482local res =regex : match_str ( vim . treesitter . get_node_text ( node , source )) 483if any and res then 484return true 485elseif not any and not res then 486return false 487end 488end 489return not any 490end 491end )(), 492 493--- @param match table<integer,TSNode[]> 494--- @param source integer|string 495--- @param predicate any[] 496--- @param any boolean 497[ 'contains' ] =function ( match , source , predicate , any ) 498local nodes =match [ predicate [ 2 ]] 499if not nodes or # nodes == 0 then 500return true 501end 502 503for _ , node in ipairs ( nodes ) do 504local node_text =vim . treesitter . get_node_text ( node , source ) 505 506for i =3 , # predicate do 507local res =string . find ( node_text , predicate [ i ], 1 , true ) 508if any and res then 509return true 510elseif not any and not res then 511return false 512end 513end 514end 515 516return not any 517end , 518} 519 520---@alias TSPredicate fun(match: table<integer,TSNode[]>, pattern: integer, source: integer|string, predicate: any[]): boolean 521 522-- Predicate handler receive the following arguments 523-- (match, pattern, bufnr, predicate) 524---@type table<string,TSPredicate> 525local predicate_handlers ={ 526[ 'eq?' ] =function ( match , _ , source , predicate ) 527return impl [ 'eq' ]( match , source , predicate , false ) 528end , 529 530[ 'any-eq?' ] =function ( match , _ , source , predicate ) 531return impl [ 'eq' ]( match , source , predicate , true ) 532end , 533 534[ 'lua-match?' ] =function ( match , _ , source , predicate ) 535return impl [ 'lua-match' ]( match , source , predicate , false ) 536end , 537 538[ 'any-lua-match?' ] =function ( match , _ , source , predicate ) 539return impl [ 'lua-match' ]( match , source , predicate , true ) 540end , 541 542[ 'match?' ] =function ( match , _ , source , predicate ) 543return impl [ 'match' ]( match , source , predicate , false ) 544end , 545 546[ 'any-match?' ] =function ( match , _ , source , predicate ) 547return impl [ 'match' ]( match , source , predicate , true ) 548end , 549 550[ 'contains?' ] =function ( match , _ , source , predicate ) 551return impl [ 'contains' ]( match , source , predicate , false ) 552end , 553 554[ 'any-contains?' ] =function ( match , _ , source , predicate ) 555return impl [ 'contains' ]( match , source , predicate , true ) 556end , 557 558--- @param predicate any[] & { string_set?: table<string, boolean> } 559[ 'any-of?' ] =function ( match , _ , source , predicate ) 560local nodes =match [ predicate [ 2 ]] 561if not nodes or # nodes == 0 then 562return true 563end 564 565for _ , node in ipairs ( nodes ) do 566local node_text =vim . treesitter . get_node_text ( node , source ) 567 568-- Since 'predicate' will not be used by callers of this function, use it 569-- to store a string set built from the list of words to check against. 570local string_set =predicate [ 'string_set' ] 571if not string_set then 572string_set ={} 573for i =3 , # predicate do 574string_set [ predicate [ i ]] =true 575end 576predicate [ 'string_set' ] =string_set 577end 578 579if string_set [ node_text ] then 580return true 581end 582end 583 584return false 585end , 586 587[ 'has-ancestor?' ] =function ( match , _ , _ , predicate ) 588local nodes =match [ predicate [ 2 ]] 589if not nodes or # nodes == 0 then 590return true 591end 592 593for _ , node in ipairs ( nodes ) do 594if node : __has_ancestor ( predicate ) then 595return true 596end 597end 598return false 599end , 600 601[ 'has-parent?' ] =function ( match , _ , _ , predicate ) 602local nodes =match [ predicate [ 2 ]] 603if not nodes or # nodes == 0 then 604return true 605end 606 607for _ , node in ipairs ( nodes ) do 608local parent =node : parent () 609if parent and vim . list_contains ( { unpack ( predicate , 3 ) } , parent : type ()) then 610return true 611end 612end 613return false 614end , 615} 616 617-- As we provide lua-match? also expose vim-match? 618predicate_handlers [ 'vim-match?' ] =predicate_handlers [ 'match?' ] 619predicate_handlers [ 'any-vim-match?' ] =predicate_handlers [ 'any-match?' ] 620 621---@nodoc 622---@class vim.treesitter.query.TSMetadata 623---@field range? Range 624---@field offset? Range4 625---@field conceal? string|boolean 626---@field bo.commentstring? string 627---@field [integer]? vim.treesitter.query.TSMetadata 628---@field [string]? integer|string 629 630---@alias TSDirective fun(match: table<integer,TSNode[]>, _, _, predicate: (string|integer)[], metadata: vim.treesitter.query.TSMetadata) 631 632-- Predicate handler receive the following arguments 633-- (match, pattern, bufnr, predicate) 634 635-- Directives store metadata or perform side effects against a match. 636-- Directives should always end with a `!`. 637-- Directive handler receive the following arguments 638-- (match, pattern, bufnr, predicate, metadata) 639---@type table<string,TSDirective> 640local directive_handlers ={ 641[ 'set!' ] =function ( _ , _ , _ , pred , metadata ) 642if # pred >= 3 and type ( pred [ 2 ]) == 'number' then 643-- (#set! @capture key value) 644local capture_id , key , value =pred [ 2 ], pred [ 3 ], pred [ 4 ] 645if not metadata [ capture_id ] then 646metadata [ capture_id ] ={} 647end 648metadata [ capture_id ][ key ] =value 649else 650-- (#set! key value) 651local key , value =pred [ 2 ], pred [ 3 ] 652metadata [ key ] =value or true 653end 654end , 655-- Shifts the range of a node. 656-- Example: (#offset! @_node 0 1 0 -1) 657[ 'offset!' ] =function ( match , _ , _ , pred , metadata ) 658local capture_id =pred [ 2 ] --[[@as integer]] 659local nodes =match [ capture_id ] 660if not nodes or # nodes == 0 then 661return 662end 663 664if not metadata [ capture_id ] then 665metadata [ capture_id ] ={} 666end 667 668metadata [ capture_id ]. offset ={ 669pred [ 3 ] --[[@as integer]] or 0 , 670pred [ 4 ] --[[@as integer]] or 0 , 671pred [ 5 ] --[[@as integer]] or 0 , 672pred [ 6 ] --[[@as integer]] or 0 , 673} 674end , 675-- Transform the content of the node 676-- Example: (#gsub! @_node ".*%.(.*)" "%1") 677[ 'gsub!' ] =function ( match , _ , bufnr , pred , metadata ) 678assert ( # pred == 4 ) 679 680local id =pred [ 2 ] 681assert ( type ( id ) == 'number' ) 682 683local nodes =match [ id ] 684if not nodes or # nodes == 0 then 685return 686end 687assert ( # nodes == 1 , '#gsub! does not support captures on multiple nodes' ) 688local node =nodes [ 1 ] 689local text =vim . treesitter . get_node_text ( node , bufnr , { metadata =metadata [ id ] } ) or '' 690 691if not metadata [ id ] then 692metadata [ id ] ={} 693end 694 695local pattern , replacement =pred [ 3 ], pred [ 4 ] 696assert ( type ( pattern ) == 'string' ) 697assert ( type ( replacement ) == 'string' ) 698 699metadata [ id ]. text =text : gsub ( pattern , replacement ) 700end , 701-- Trim whitespace from both sides of the node 702-- Example: (#trim! @fold 1 1 1 1) 703[ 'trim!' ] =function ( match , _ , bufnr , pred , metadata ) 704local capture_id =pred [ 2 ] 705assert ( type ( capture_id ) == 'number' ) 706 707local trim_start_lines =pred [ 3 ] == '1' 708local trim_start_cols =pred [ 4 ] == '1' 709local trim_end_lines =pred [ 5 ] == '1' or not pred [ 3 ] -- default true for backwards compatibility 710local trim_end_cols =pred [ 6 ] == '1' 711 712local nodes =match [ capture_id ] 713if not nodes or # nodes == 0 then 714return 715end 716assert ( # nodes == 1 , '#trim! does not support captures on multiple nodes' ) 717local node =nodes [ 1 ] 718 719local start_row , start_col , end_row , end_col =node : range () 720 721local node_text =vim . split ( vim . treesitter . get_node_text ( node , bufnr ), '\n' ) 722 723local end_idx =# node_text 724local start_idx =1 725 726local end_line =node_text [ end_idx ] 727if trim_end_lines then 728while end_line and end_line : find ( '^%s*$' ) do 729end_idx =end_idx - 1 730end_line =node_text [ end_idx ] 731end_row =end_row - 1 732-- set the end position to the last column of the next line, or 0 if we just trimmed the 733-- last line 734end_col =end_line and # end_line or 0 735end 736end 737if trim_end_cols then 738if not end_line then 739end_row =start_row 740end_col =start_col 741else 742local whitespace_start =assert ( end_line : find ( '(%s*)$' )) 743end_col =( whitespace_start - 1 ) + ( end_idx == 1 and start_col or 0 ) 744end 745end 746 747local start_line =node_text [ start_idx ] 748if trim_start_lines then 749while start_idx <= end_idx and assert ( start_line ): find ( '^%s*$' ) do 750start_idx =start_idx + 1 751start_line =node_text [ start_idx ] 752start_row =start_row + 1 753start_col =0 754end 755end 756if trim_start_cols and start_line then 757local _ , whitespace_end =start_line : find ( '^(%s*)' ) 758whitespace_end =whitespace_end or 0 759start_col =( start_idx == 1 and start_col or 0 ) + whitespace_end 760end 761 762-- If this produces an invalid range, we just skip it. 763if start_row < end_row or ( start_row == end_row and start_col <= end_col ) then 764metadata [ capture_id ] =metadata [ capture_id ] or {} 765metadata [ capture_id ]. range ={ start_row , start_col , end_row , end_col } 766end 767end , 768} 769 770--- @class vim.treesitter.query.add_predicate.Opts 771--- @inlinedoc 772--- 773--- Override an existing predicate of the same name 774--- @field force? boolean 775 776--- Adds a new predicate to be used in queries 777--- 778---@param name string Name of the predicate, without leading # 779---@param handler fun(match: table<integer,TSNode[]>, pattern: integer, source: integer|string, predicate: any[], metadata: vim.treesitter.query.TSMetadata): boolean? # 780--- - see |vim.treesitter.query.add_directive()| for argument meanings 781---@param opts? vim.treesitter.query.add_predicate.Opts 782function M . add_predicate ( name , handler , opts ) 783-- Backward compatibility: old signature had "force" as boolean argument 784if type ( opts ) == 'boolean' then 785opts ={ force =opts } 786end 787 788opts =opts or {} 789 790if predicate_handlers [ name ] and not opts . force then 791error ( string . format ( 'Overriding existing predicate %s' , name )) 792end 793 794predicate_handlers [ name ] =handler 795end 796 797--- Adds a new directive to be used in queries 798--- 799--- Handlers can set match level data by setting directly on the 800--- metadata object `metadata.key = value`. Additionally, handlers 801--- can set node level data by using the capture id on the 802--- metadata table `metadata[capture_id].key = value` 803--- 804---@param name string Name of the directive, without leading # 805---@param handler fun(match: table<integer,TSNode[]>, pattern: integer, source: integer|string, predicate: any[], metadata: vim.treesitter.query.TSMetadata) # 806--- - match: A table mapping capture IDs to a list of captured nodes 807--- - pattern: the index of the matching pattern in the query file 808--- - predicate: list of strings containing the full directive being called, e.g. 809--- `(node (#set! conceal "-"))` would get the predicate `{ "#set!", "conceal", "-" }` 810---@param opts vim.treesitter.query.add_predicate.Opts 811function M . add_directive ( name , handler , opts ) 812-- Backward compatibility: old signature had "force" as boolean argument 813if type ( opts ) == 'boolean' then 814opts ={ force =opts } 815end 816 817opts =opts or {} 818 819if directive_handlers [ name ] and not opts . force then 820error ( string . format ( 'Overriding existing directive %s' , name )) 821end 822 823directive_handlers [ name ] =handler 824end 825 826--- Lists the currently available directives to use in queries. 827---@return string[] : Supported directives. 828function M . list_directives () 829return vim . tbl_keys ( directive_handlers ) 830end 831 832--- Lists the currently available predicates to use in queries. 833---@return string[] : Supported predicates. 834function M . list_predicates () 835return vim . tbl_keys ( predicate_handlers ) 836end 837 838---@private 839---@param pattern_i integer 840---@param predicates vim.treesitter.query.ProcessedPredicate[] 841---@param captures table<integer, TSNode[]> 842---@param source integer|string 843---@return boolean whether the predicates match 844function Query . _match_predicates ( predicates , pattern_i , captures , source ) 845for _ , predicate in ipairs ( predicates ) do 846local processed_name =predicate [ 1 ] 847local should_match =predicate [ 2 ] 848local orig_predicate =predicate [ 3 ] 849 850local handler =predicate_handlers [ processed_name ] 851if not handler then 852error ( string . format ( 'No handler for %s' , orig_predicate [ 1 ])) 853return false 854end 855 856local does_match =handler ( captures , pattern_i , source , orig_predicate ) 857if does_match ~= should_match then 858return false 859end 860end 861return true 862end 863 864---@private 865---@param pattern_i integer 866---@param directives vim.treesitter.query.ProcessedDirective[] 867---@param source integer|string 868---@param captures table<integer, TSNode[]> 869---@return vim.treesitter.query.TSMetadata metadata 870function Query . _apply_directives ( _ , directives , pattern_i , captures , source ) 871---@type vim.treesitter.query.TSMetadata 872local metadata ={} 873 874for _ , directive in pairs ( directives ) do 875local handler =directive_handlers [ directive [ 1 ]] 876 877if not handler then 878error ( string . format ( 'No handler for %s' , directive [ 1 ])) 879end 880 881handler ( captures , pattern_i , source , directive , metadata ) 882end 883 884return metadata 885end 886 887--- Returns the start and stop value if set else the node's range. 888-- When the node's range is used, the stop is incremented by 1 889-- to make the search inclusive. 890---@param start integer? 891---@param stop integer? 892---@param node TSNode 893---@return integer, integer 894local function value_or_node_range ( start , stop , node ) 895if start == nil then 896start =node : start () 897end 898if stop == nil then 899stop =node : end_ () + 1 -- Make stop inclusive 900end 901 902return start , stop 903end 904 905--- Iterates over all captures from all matches in {node}. 906--- 907--- {source} is required if the query contains predicates; then the caller 908--- must ensure to use a freshly parsed tree consistent with the current 909--- text of the buffer (if relevant). {start} and {stop} can be used to limit 910--- matches inside a row range (this is typically used with root node 911--- as the {node}, i.e., to get syntax highlight matches in the current 912--- viewport). When omitted, the {start} and {stop} row values are used from the given node. 913--- 914--- The iterator returns four values: 915--- 1. the numeric id identifying the capture 916--- 2. the captured node 917--- 3. metadata from any directives processing the match 918--- 4. the match itself 919--- 920--- Example: how to get captures by name: 921--- ```lua 922--- for id, node, metadata, match in query:iter_captures(tree:root(), bufnr, first, last) do 923--- local name = query.captures[id] -- name of the capture in the query 924--- -- typically useful info about the node: 925--- local type = node:type() -- type of the captured node 926--- local row1, col1, row2, col2 = node:range() -- range of the capture 927--- -- ... use the info here ... 928--- end 929--- ``` 930--- 931---@param node TSNode under which the search will occur 932---@param source (integer|string) Source buffer or string to extract text from 933---@param start_row? integer Starting line for the search. Defaults to `node:start()`. 934---@param end_row? integer Stopping line for the search (end-inclusive, unless `stop_col` is provided). Defaults to `node:end_()`. 935---@param opts? table Optional keyword arguments: 936--- - end_col (integer) Stopping column for the search (end-exclusive). 937--- - match_limit (integer) Set the maximum number of in-progress matches (Default: none). 938--- - max_start_depth (integer) if non-zero, sets the maximum start depth 939--- for each match. This is used to prevent traversing too deep into a tree. 940--- - start_col (integer) Starting column for the search. 941--- 942---@return (fun(end_line: integer|nil, end_col: integer|nil): integer, TSNode, vim.treesitter.query.TSMetadata, TSQueryMatch, TSTree): 943--- capture-id, capture-node, metadata, match, tree 944--- 945---@note Captures are only returned if the query pattern of a specific capture contained predicates. 946function Query : iter_captures ( node , source , start_row , end_row , opts ) 947opts =opts or {} 948 949if type ( source ) == 'number' and source == 0 then 950source =api . nvim_get_current_buf () 951end 952 953start_row , end_row =value_or_node_range ( start_row , end_row , node ) 954 955local tree =node : tree () 956local cursor =vim . _create_ts_querycursor ( node , self . query , { 957start_row =start_row , 958start_col =opts . start_col or 0 , 959end_row =end_row , 960end_col =opts . end_col or 0 , 961max_start_depth =opts . max_start_depth , 962match_limit =opts . match_limit , 963} ) 964 965-- For faster checks that a match is not in the cache. 966local highest_cached_match_id =- 1 967---@type table<integer, vim.treesitter.query.TSMetadata> 968local match_cache ={} 969 970---@param end_line? integer 971---@param end_col? integer 972local function iter ( end_line , end_col ) 973local capture , captured_node , match =cursor : next_capture () 974 975if not capture then 976return 977end 978 979local match_id , pattern_i =match : info () 980 981--- @type vim.treesitter.query.TSMetadata? 982local metadata 983if match_id <= highest_cached_match_id then 984metadata =match_cache [ match_id ] 985end 986 987if not metadata then 988metadata ={} 989 990local processed_pattern =self . _processed_patterns [ pattern_i ] 991if processed_pattern then 992local captures =match : captures () 993 994local predicates =processed_pattern . predicates 995if not self . _match_predicates ( predicates , pattern_i , captures , source ) then 996cursor : remove_match ( match_id ) 997 998local row , col =captured_node : range () 999 1000local outside =false 1001if end_line then 1002if end_col then 1003outside =cmp_ge ( row , col , end_line , end_col ) 1004else 1005outside =row > end_line 1006end 1007end 1008 1009if outside then 1010return nil , captured_node , nil , nil 1011end 1012 1013return iter ( end_line ) -- tail call: try next match 1014end 1015 1016local directives =processed_pattern . directives 1017metadata =self : _apply_directives ( directives , pattern_i , captures , source ) 1018end 1019 1020highest_cached_match_id =math . max ( highest_cached_match_id , match_id ) 1021match_cache [ match_id ] =metadata 1022end 1023 1024return capture , captured_node , metadata , match , tree 1025end 1026return iter 1027end 1028 1029--- Iterates the matches of self on a given range. 1030--- 1031--- Iterate over all matches within a {node}. The arguments are the same as for 1032--- |Query:iter_captures()| but the iterated values are different: an (1-based) 1033--- index of the pattern in the query, a table mapping capture indices to a list 1034--- of nodes, and metadata from any directives processing the match. 1035--- 1036--- Example: 1037--- 1038--- ```lua 1039--- for pattern, match, metadata in cquery:iter_matches(tree:root(), bufnr, 0, -1) do 1040--- for id, nodes in pairs(match) do 1041--- local name = query.captures[id] 1042--- for _, node in ipairs(nodes) do 1043--- -- `node` was captured by the `name` capture in the match 1044--- 1045--- local node_data = metadata[id] -- Node level metadata 1046--- -- ... use the info here ... 1047--- end 1048--- end 1049--- end 1050--- ``` 1051--- 1052--- 1053---@param node TSNode under which the search will occur 1054---@param source (integer|string) Source buffer or string to search 1055---@param start? integer Starting line for the search. Defaults to `node:start()`. 1056---@param stop? integer Stopping line for the search (end-exclusive). Defaults to `node:end_()`. 1057---@param opts? table Optional keyword arguments: 1058--- - match_limit (integer) Set the maximum number of in-progress matches (Default: none). 1059--- - max_start_depth (integer) if non-zero, sets the maximum start depth 1060--- for each match. This is used to prevent traversing too deep into a tree. 1061--- 1062---@return (fun(): integer, table<integer, TSNode[]>, vim.treesitter.query.TSMetadata, TSTree): pattern-id, match, metadata, tree 1063function Query : iter_matches ( node , source , start , stop , opts ) 1064opts =opts or {} 1065 1066if type ( source ) == 'number' and source == 0 then 1067source =api . nvim_get_current_buf () 1068end 1069 1070start , stop =value_or_node_range ( start , stop , node ) 1071 1072local tree =node : tree () 1073local cursor =vim . _create_ts_querycursor ( node , self . query , { 1074start_row =start , 1075start_col =0 , 1076end_row =stop , 1077end_col =0 , 1078max_start_depth =opts . max_start_depth , 1079match_limit =opts . match_limit , 1080} ) 1081 1082local function iter () 1083local match =cursor : next_match () 1084 1085if not match then 1086return 1087end 1088 1089local match_id , pattern_i =match : info () 1090local processed_pattern =self . _processed_patterns [ pattern_i ] 1091local captures =match : captures () 1092 1093--- @type vim.treesitter.query.TSMetadata 1094local metadata ={} 1095if processed_pattern then 1096local predicates =processed_pattern . predicates 1097if not self . _match_predicates ( predicates , pattern_i , captures , source ) then 1098cursor : remove_match ( match_id ) 1099return iter () -- tail call: try next match 1100end 1101local directives =processed_pattern . directives 1102metadata =self : _apply_directives ( directives , pattern_i , captures , source ) 1103end 1104 1105-- TODO(lewis6991): create a new function that returns {match, metadata} 1106return pattern_i , captures , metadata , tree 1107end 1108return iter 1109end 1110 1111--- Optional keyword arguments: 1112--- @class vim.treesitter.query.lint.Opts 1113--- @inlinedoc 1114--- 1115--- Language(s) to use for checking the query. 1116--- If multiple languages are specified, queries are validated for all of them 1117--- @field langs? string|string[] 1118--- 1119--- Just clear current lint errors 1120--- @field clear? boolean 1121 1122--- Lint treesitter queries using installed parser, or clear lint errors. 1123--- 1124--- Use |treesitter-parsers| in runtimepath to check the query file in {buf} for errors: 1125--- 1126--- - verify that used nodes are valid identifiers in the grammar. 1127--- - verify that predicates and directives are valid. 1128--- - verify that top-level s-expressions are valid. 1129--- 1130--- The found diagnostics are reported using |diagnostic-api|. 1131--- By default, the parser used for verification is determined by the containing folder 1132--- of the query file, e.g., if the path ends in `/lua/highlights.scm`, the parser for the 1133--- `lua` language will be used. 1134---@param buf (integer) Buffer handle 1135---@param opts? vim.treesitter.query.lint.Opts 1136function M . lint ( buf , opts ) 1137if opts and opts . clear then 1138vim . treesitter . _query_linter . clear ( buf ) 1139else 1140vim . treesitter . _query_linter . lint ( buf , opts ) 1141end 1142end 1143 1144--- Omnifunc for completing node names and predicates in treesitter queries. 1145--- 1146--- Use via 1147--- 1148--- ```lua 1149--- vim.bo.omnifunc = vim.treesitter.query.omnifunc 1150--- ``` 1151--- 1152--- @param findstart 0|1 1153--- @param base string 1154function M . omnifunc ( findstart , base ) 1155return vim . treesitter . _query_linter . omnifunc ( findstart , base ) 1156end 1157 1158--- Opens a live editor to query the buffer you started from. 1159--- 1160--- Can also be shown with the [:EditQuery]() command. `:EditQuery <tab>` completes available 1161--- parsers. 1162--- 1163--- If you move the cursor to a capture name ("@foo"), text matching the capture is highlighted 1164--- with |hl-DiagnosticVirtualTextHint| in the source buffer. The query editor is a scratch buffer, 1165--- use `:write` to save it. You can find example queries at `$VIMRUNTIME/queries/`. 1166--- 1167--- @param lang? string language to open the query editor for. If omitted, inferred from the current buffer's filetype. 1168function M . edit ( lang ) 1169assert ( vim . treesitter . dev . edit_query ( lang )) 1170end 1171 1172return M