robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
aa1d8a2702
master
1local api =vim . api 2 3---@type table<integer,vim.treesitter.LanguageTree> 4local parsers =setmetatable ( {} , { __mode ='v' } ) 5 6local M =vim . _defer_require ( 'vim.treesitter' , { 7_fold =... , --- @module 'vim.treesitter._fold' 8_query_linter =... , --- @module 'vim.treesitter._query_linter' 9_range =... , --- @module 'vim.treesitter._range' 10dev =... , --- @module 'vim.treesitter.dev' 11highlighter =... , --- @module 'vim.treesitter.highlighter' 12language =... , --- @module 'vim.treesitter.language' 13languagetree =... , --- @module 'vim.treesitter.languagetree' 14query =... , --- @module 'vim.treesitter.query' 15_select =... , --- @module 'vim.treesitter._select' 16} ) 17 18local LanguageTree =M . languagetree 19 20--- @nodoc 21M . language_version =vim . _ts_get_language_version () 22 23--- @nodoc 24M . minimum_language_version =vim . _ts_get_minimum_language_version () 25 26--- Creates a new parser 27--- 28--- It is not recommended to use this; use |get_parser()| instead. 29--- 30---@param buf integer Buffer the parser will be tied to (0 for current buffer) 31---@param lang string Language of the parser 32---@param opts (table|nil) Options to pass to the created language tree 33--- 34---@return vim.treesitter.LanguageTree object to use for parsing 35function M . _create_parser ( buf , lang , opts ) 36buf =vim . _resolve_bufnr ( buf ) 37 38local self =LanguageTree . new ( buf , lang , opts ) 39 40local function bytes_cb ( _ , ... ) 41self : _on_bytes ( ... ) 42end 43 44local function detach_cb ( _ , ... ) 45if parsers [ buf ] == self then 46parsers [ buf ] =nil 47end 48self : _on_detach ( ... ) 49end 50 51local function reload_cb ( _ ) 52self : _on_reload () 53end 54 55local source =self : source () --[[@as integer]] 56 57api . nvim_buf_attach ( 58source , 59false , 60{ on_bytes =bytes_cb , on_detach =detach_cb , on_reload =reload_cb , preview =true } 61) 62 63return self 64end 65 66--- @param lang string? 67local function valid_lang ( lang ) 68return lang and lang ~= '' 69end 70 71--- Returns the parser for a specific buffer and attaches it to the buffer 72--- 73--- If needed, this will create the parser. 74--- 75--- If no parser can be created, nil (and an error message) is returned. 76--- 77---@param buf integer|nil (default: current buffer) Buffer the parser should be tied to 78---@param lang string|nil (default: from 'filetype') Language of this parser 79---@param opts table|nil Options to pass to the created language tree 80--- 81---@return vim.treesitter.LanguageTree? object to use for parsing 82---@return string? error message, if applicable 83function M . get_parser ( buf , lang , opts ) 84opts =opts or {} 85 86buf =vim . _resolve_bufnr ( buf ) 87 88if not valid_lang ( lang ) then 89lang =M . language . get_lang ( vim . bo [ buf ]. filetype ) 90end 91 92if not valid_lang ( lang ) then 93if not parsers [ buf ] then 94return nil , 95string . format ( 'Parser not found for buffer %s: language could not be determined' , buf ) 96end 97elseif parsers [ buf ] == nil or parsers [ buf ]: lang () ~= lang then 98if not api . nvim_buf_is_loaded ( buf ) then 99return nil , string . format ( 'Buffer %s must be loaded to create parser' , buf ) 100end 101local status , res =pcall ( M . _create_parser , buf , assert ( lang ), opts ) 102if not status then 103local msg ='Parser could not be created for buffer %s and language "%s": %s' 104return nil , string . format ( msg , buf , lang , res ) 105end 106parsers [ buf ] =res 107end 108 109parsers [ buf ]: register_cbs ( opts . buf_attach_cbs ) 110 111return parsers [ buf ] 112end 113 114--- Returns a string parser 115--- 116---@param str string Text to parse 117---@param lang string Language of this string 118---@param opts (table|nil) Options to pass to the created language tree 119--- 120---@return vim.treesitter.LanguageTree object to use for parsing 121function M . get_string_parser ( str , lang , opts ) 122vim . validate ( 'str' , str , 'string' ) 123vim . validate ( 'lang' , lang , 'string' ) 124 125return LanguageTree . new ( str , lang , opts ) 126end 127 128--- Determines whether a node is the ancestor of another 129--- 130---@param dest TSNode Possible ancestor 131---@param source TSNode Possible descendant 132--- 133---@return boolean True if {dest} is an ancestor of {source} 134function M . is_ancestor ( dest , source ) 135if not ( dest and source ) then 136return false 137end 138 139return dest : child_with_descendant ( source ) ~= nil 140end 141 142--- Returns the node's range or an unpacked range table 143--- 144---@param node_or_range TSNode|Range4 Node or table of positions 145--- 146---@return integer start_row 147---@return integer start_col # (byte offset) 148---@return integer end_row 149---@return integer end_col # (byte offset) 150function M . get_node_range ( node_or_range ) 151if type ( node_or_range ) == 'table' then 152--- @cast node_or_range -TSNode LuaLS bug 153return M . _range . unpack4 ( node_or_range ) 154else 155return node_or_range : range ( false ) 156end 157end 158 159---@param node TSNode 160---@param source integer|string Buffer or string from which the {node} is extracted 161---@param offset Range4 162---@return Range6 163local function apply_range_offset ( node , source , offset ) 164---@diagnostic disable-next-line: missing-fields LuaLS varargs bug 165local range ={ node : range () } ---@type Range4 166local start_row_offset =offset [ 1 ] 167local start_col_offset =offset [ 2 ] 168local end_row_offset =offset [ 3 ] 169local end_col_offset =offset [ 4 ] 170 171range [ 1 ] =range [ 1 ] + start_row_offset 172range [ 2 ] =range [ 2 ] + start_col_offset 173range [ 3 ] =range [ 3 ] + end_row_offset 174range [ 4 ] =range [ 4 ] + end_col_offset 175 176if range [ 1 ] < range [ 3 ] or ( range [ 1 ] == range [ 3 ] and range [ 2 ] <= range [ 4 ]) then 177return M . _range . add_bytes ( source , range ) 178end 179 180-- If this produces an invalid range, we just skip it. 181return { node : range ( true ) } 182end 183 184---Get the range of a |TSNode|. Can also supply {source} and {metadata} 185---to get the range with directives applied. 186---@param node TSNode 187---@param source integer|string|nil Buffer or string from which the {node} is extracted 188---@param metadata vim.treesitter.query.TSMetadata|nil 189---@return Range6 190function M . get_range ( node , source , metadata ) 191if metadata then 192if metadata . range then 193return M . _range . add_bytes ( assert ( source ), metadata . range ) 194elseif metadata . offset then 195return apply_range_offset ( node , assert ( source ), metadata . offset ) 196end 197end 198return { node : range ( true ) } 199end 200 201---@param buf integer 202---@param range Range 203---@return string 204local function buf_range_get_text ( buf , range ) 205local start_row , start_col , end_row , end_col =M . _range . unpack4 ( range ) 206local append_newline =end_col == 0 and start_row ~= end_row 207 208if end_col == 0 then 209if start_row == end_row then 210start_col =- 1 211start_row =start_row - 1 212end 213end_col =- 1 214end_row =end_row - 1 215end 216 217local lines =api . nvim_buf_get_text ( buf , start_row , start_col , end_row , end_col ) 218if append_newline then 219table . insert ( lines , '' ) 220end 221 222return table . concat ( lines , '\n' ) 223end 224 225--- Gets the text corresponding to a given node 226--- 227---@param node TSNode 228---@param source (integer|string) Buffer or string from which the {node} is extracted 229---@param opts (table|nil) Optional parameters. 230--- - metadata (table) Metadata of a specific capture. This would be 231--- set to `metadata[capture_id]` when using |vim.treesitter.query.add_directive()|. 232---@return string 233function M . get_node_text ( node , source , opts ) 234opts =opts or {} 235local metadata =opts . metadata or {} 236 237if metadata . text then 238return metadata . text 239elseif type ( source ) == 'number' then 240local range =M . get_range ( node , source , metadata ) 241return buf_range_get_text ( source , range ) 242end 243 244---@cast source string 245return source : sub ( select ( 3 , node : start ()) + 1 , select ( 3 , node : end_ ())) 246end 247 248--- Determines whether (line, col) position is in node range 249--- 250---@param node TSNode defining the range 251---@param line integer Line (0-based) 252---@param col integer Column (0-based) 253--- 254---@return boolean True if the position is in node range 255function M . is_in_node_range ( node , line , col ) 256return M . node_contains ( node , { line , col , line , col + 1 } ) 257end 258 259--- Determines if a node contains a range 260--- 261---@param node TSNode 262---@param range table 263--- 264---@return boolean True if the {node} contains the {range} 265function M . node_contains ( node , range ) 266-- allow a table so nodes can be mocked 267vim . validate ( 'node' , node , { 'userdata' , 'table' } ) 268vim . validate ( 'range' , range , M . _range . validate , 'integer list with 4 or 6 elements' ) 269--- @diagnostic disable-next-line: missing-fields LuaLS bug 270local nrange ={ node : range () } --- @type Range4 271return M . _range . contains ( nrange , range ) 272end 273 274--- @class vim.treesitter.CaptureInfo 275--- @inlinedoc 276--- @field capture string Capture name 277--- @field lang string Language name 278--- @field metadata vim.treesitter.query.TSMetadata Query metadata, e.g. `priority` or `conceal` 279--- @field id integer 1-based capture id in the query 280--- @field pattern_id integer 1-based id of the matched pattern in the query 281--- @field row integer Start row 282--- @field col integer Start column 283--- @field end_row integer End row 284--- @field end_col integer End column (excluded) 285 286---@deprecated Use vim.treesitter.get_captures() instead. 287---@param buf integer 288---@param row integer 289---@param col integer 290---@return vim.treesitter.CaptureInfo[] 291function M . get_captures_at_pos ( buf , row , col ) 292vim . deprecate ( 'vim.treesitter.get_captures_at_pos()' , 'vim.treesitter.get_captures()' , '0.15' ) 293return M . get_captures ( buf , { row , col } ) 294end 295 296--- Returns highlight captures at a position, on a line, or overlapping a range. 297--- 298--- {start} and {stop} can be a row number or a `{row, col}` pair. All rows and 299--- columns are 0-based; columns are byte offsets. 300--- 301--- Without {stop}, a row number queries the whole line and a `{row, col}` pair 302--- queries one position. 303--- 304--- With {stop}, return captures that overlap the range. The stop position is 305--- excluded; a row number excludes that row. Empty ranges return no captures. 306--- 307--- Each result includes the full captured node range, which may extend outside the 308--- requested range. Returns an empty list if treesitter highlighting is not active 309--- in {buf}. 310--- 311---@since 15 312---@param buf integer Buffer number (0 for current buffer) 313---@param start integer|[integer,integer] Start row or `{row, col}` 314---@param stop? integer|[integer,integer] Stop row or `{row, col}` (excluded) 315---@return vim.treesitter.CaptureInfo[] 316function M . get_captures ( buf , start , stop ) 317buf =vim . _resolve_bufnr ( buf ) 318 319--- @type integer, integer, integer, integer 320local start_row , start_col , end_row , end_col 321if type ( start ) == 'number' then 322start_row , start_col =start , 0 323else 324start_row , start_col =start [ 1 ], start [ 2 ] 325end 326 327if stop == nil then 328end_row =type ( start ) == 'number' and start_row + 1 or start_row 329end_col =type ( start ) == 'number' and 0 or start_col + 1 330elseif type ( stop ) == 'number' then 331end_row , end_col =stop , 0 332else 333end_row , end_col =stop [ 1 ], stop [ 2 ] 334end 335 336local buf_highlighter =M . highlighter . active [ buf ] 337 338if not buf_highlighter or M . _range . cmp_pos . ge ( start_row , start_col , end_row , end_col ) then 339return {} 340end 341 342local matches ={} --- @type vim.treesitter.CaptureInfo[] 343local query_range ={ start_row , start_col , end_row , end_col } --- @type Range4 344 345-- Highlighting only parses visible ranges, so offscreen injections may be missing. 346buf_highlighter . tree : parse ( query_range ) 347buf_highlighter . tree : for_each_tree ( function ( tstree , tree ) 348if not tstree then 349return 350end 351 352local root =tstree : root () 353if not M . _range . intercepts ( { root : range () } , query_range ) then 354return 355end 356 357local q =buf_highlighter : get_query ( tree : lang ()) 358local query =q : query () 359 360-- Some injected languages may not have highlight queries. 361if not query then 362return 363end 364 365local iter =query : iter_captures ( root , buf_highlighter . bufnr , start_row , end_row , { 366start_col =start_col , 367end_col =end_col , 368} ) 369for id , node , metadata , match in iter do 370local nsrow , nscol , nerow , necol =node : range () 371if M . _range . intercepts ( { nsrow , nscol , nerow , necol } , query_range ) then 372---@diagnostic disable-next-line: invisible 373local capture =query . captures [ id ] -- name of the capture in the query 374if capture ~= nil then 375local _ , pattern_id =match : info () 376matches [ # matches + 1 ] ={ 377capture =capture , 378metadata =metadata , 379lang =tree : lang (), 380id =id , 381pattern_id =pattern_id , 382row =nsrow , 383col =nscol , 384end_row =nerow , 385end_col =necol , 386} 387end 388end 389end 390end ) 391return matches 392end 393 394--- Returns a list of highlight capture names under the cursor 395--- 396---@param win integer|nil # |window-ID| or 0 for current window (default) 397--- 398---@return string[] List of capture names 399function M . get_captures_at_cursor ( win ) 400win =win or 0 401local bufnr =api . nvim_win_get_buf ( win ) 402local cursor =api . nvim_win_get_cursor ( win ) 403 404local data =M . get_captures ( bufnr , { cursor [ 1 ] - 1 , cursor [ 2 ] } ) 405 406local captures ={} 407 408for _ , capture in ipairs ( data ) do 409table . insert ( captures , capture . capture ) 410end 411 412return captures 413end 414 415--- Optional keyword arguments: 416--- @class vim.treesitter.get_node.Opts : vim.treesitter.LanguageTree.tree_for_range.Opts 417--- @inlinedoc 418--- 419--- Buffer number (nil or 0 for current buffer) 420--- @field bufnr integer? 421--- 422--- 0-indexed (row, col) tuple. Required if {bufnr} is not the current buffer 423--- (default: window-local cursor) 424--- @field pos [integer, integer]? 425--- 426--- Parser language. 427--- (default: from 'filetype') 428--- @field lang string? 429--- 430--- Ignore injected languages 431--- (default: true) 432--- @field ignore_injections boolean? 433--- 434--- Include anonymous nodes 435--- (default: false) 436--- @field include_anonymous boolean? 437 438--- Returns the smallest named node at the given position 439--- 440--- NOTE: Calling this on an unparsed tree can yield an invalid node. 441--- If the tree is not known to be parsed by, e.g., an active highlighter, 442--- parse the tree first via 443--- 444--- ```lua 445--- vim.treesitter.get_parser(bufnr):parse(range) 446--- ``` 447--- 448---@param opts vim.treesitter.get_node.Opts? 449--- 450---@return TSNode | nil Node at the given position 451function M . get_node ( opts ) 452opts =opts or {} 453 454local bufnr =vim . _resolve_bufnr ( opts . bufnr ) 455 456local row , col --- @type integer, integer 457if opts . pos then 458assert ( # opts . pos == 2 , 'Position must be a (row, col) tuple' ) 459row , col =opts . pos [ 1 ], opts . pos [ 2 ] 460else 461assert ( 462bufnr == api . nvim_get_current_buf (), 463'Position must be explicitly provided when not using the current buffer' 464) 465local pos =api . nvim_win_get_cursor ( 0 ) 466-- Subtract one to account for 1-based row indexing in nvim_win_get_cursor 467row , col =pos [ 1 ] - 1 , pos [ 2 ] 468end 469 470assert ( row >= 0 and col >= 0 , 'Invalid position: row and col must be non-negative' ) 471 472local ts_range ={ row , col , row , col } 473 474local root_lang_tree =M . get_parser ( bufnr , opts . lang ) 475if not root_lang_tree then 476return 477end 478 479if opts . include_anonymous then 480return root_lang_tree : node_for_range ( ts_range , opts ) 481end 482return root_lang_tree : named_node_for_range ( ts_range , opts ) 483end 484 485--- Starts treesitter highlighting for a buffer 486--- 487--- Can be used in an ftplugin or FileType autocommand. 488--- 489--- Note: By default, disables regex syntax highlighting, which may be required for some plugins. 490--- In this case, add `vim.bo.syntax = 'ON'` after the call to `start`. 491--- 492--- Note: By default, the highlighter parses code asynchronously, using a segment time of 3ms. 493--- 494--- Example: 495--- 496--- ```lua 497--- vim.api.nvim_create_autocmd( 'FileType', { pattern = 'tex', 498--- callback = function(ev) 499--- vim.treesitter.start(ev.buf, 'latex') 500--- vim.bo[ev.buf].syntax = 'ON' -- only if additional legacy syntax is needed 501--- end 502--- }) 503--- ``` 504--- 505---@param buf integer? (default: current buffer) Buffer to be highlighted 506---@param lang string? (default: from 'filetype') Language of the parser 507function M . start ( buf , lang ) 508buf =vim . _resolve_bufnr ( buf ) 509-- Ensure buffer is loaded. `:edit` over `bufload()` to show swapfile prompt. 510if not api . nvim_buf_is_loaded ( buf ) then 511if api . nvim_buf_get_name ( buf ) ~= '' then 512pcall ( api . nvim_buf_call , buf , vim . cmd . edit ) 513else 514vim . fn . bufload ( buf ) 515end 516end 517local parser =assert ( M . get_parser ( buf , lang )) 518M . highlighter . new ( parser ) 519end 520 521--- Stops treesitter highlighting for a buffer 522--- 523---@param buf integer|nil (default: current buffer) Buffer to stop highlighting 524function M . stop ( buf ) 525buf =vim . _resolve_bufnr ( buf ) 526 527if M . highlighter . active [ buf ] then 528M . highlighter . active [ buf ]: destroy () 529end 530end 531 532--- Open a window that displays a textual representation of the nodes in the language tree. 533--- 534--- While in the window, press "a" to toggle display of anonymous nodes, "I" to toggle the 535--- display of the source language of each node, "o" to toggle the query editor, and press 536--- [<Enter>] to jump to the node under the cursor in the source buffer. Folding also works 537--- (try |zo|, |zc|, etc.). 538--- 539--- Can also be shown with `:InspectTree`. [:InspectTree]() 540--- 541---@since 11 542---@param opts table|nil Optional options table with the following possible keys: 543--- - bufnr (integer|nil): Buffer to draw the tree into. If omitted, a new 544--- buffer is created. 545--- - command (string|nil): Vimscript command to create the window. Default 546--- value is "60vnew". Only used when {winid} is nil. 547--- - lang (string|nil): The language of the source buffer. If omitted, detect 548--- from the filetype of the source buffer. 549--- - title (string|fun(bufnr:integer):string|nil): Title of the window. If a 550--- function, it accepts the buffer number of the source buffer as its only 551--- argument and should return a string. 552--- - winid (integer|nil): Window id to display the tree buffer in. If omitted, 553--- a new window is created with {command}. 554function M . inspect_tree ( opts ) 555---@diagnostic disable-next-line: invisible 556M . dev . inspect_tree ( opts ) 557end 558 559--- Returns the fold level for {lnum} in the current buffer. Can be set directly to 'foldexpr': 560--- 561--- ```lua 562--- vim.wo.foldexpr = vim.treesitter.foldexpr 563--- ``` 564--- 565---@since 11 566---@param lnum integer|nil Line number to calculate fold level for 567---@return string 568function M . foldexpr ( lnum ) 569return M . _fold . foldexpr ( lnum ) 570end 571 572--- Starts or adjusts a |Visual| selection at cursor, based on tree nodes. The `target` parameter 573--- decides the selection behavior. 574--- 575---@param target 'parent'|'child'|'next'|'prev'|'extend_next'|'extend_prev' Decides the selection behavior. 576---@param count? integer (default: 1) Expand or adjust the selection this many times. 577function M . select ( target , count ) 578vim . validate ( 'target' , target , 'string' ) 579vim . validate ( 'count' , count , 'number' , true ) 580count =count or 1 581 582if target == 'parent' then 583return M . _select . select_parent ( count ) 584elseif target == 'child' then 585return M . _select . select_child ( count ) 586elseif target == 'next' then 587return M . _select . select_next ( count ) 588elseif target == 'prev' then 589return M . _select . select_prev ( count ) 590elseif target == 'extend_next' then 591return M . _select . select_grow_next ( count ) 592elseif target == 'extend_prev' then 593return M . _select . select_grow_prev ( count ) 594else 595error (( 'Invalid target: %s' ): format ( target )) 596end 597end 598 599return M