robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
aa1d8a2702
master
1local api =vim . api 2local query =vim . treesitter . query 3local Range =require ( 'vim.treesitter._range' ) 4local cmp_lt =Range . cmp_pos . lt 5 6local ns =api . nvim_create_namespace ( 'nvim.treesitter.highlighter' ) 7 8---@alias vim.treesitter.highlighter.Iter fun(end_line: integer|nil, end_col: integer|nil): integer, TSNode, vim.treesitter.query.TSMetadata, TSQueryMatch, TSTree 9 10---@class (private) vim.treesitter.highlighter.Query 11---@field private _query vim.treesitter.Query? 12---@field private lang string 13---@field private hl_cache table<integer,integer> 14local TSHighlighterQuery ={} 15TSHighlighterQuery . __index =TSHighlighterQuery 16 17---@private 18---@param lang string 19---@param query_string string? 20---@return vim.treesitter.highlighter.Query 21function TSHighlighterQuery . new ( lang , query_string ) 22local self =setmetatable ( {} , TSHighlighterQuery ) 23self . lang =lang 24self . hl_cache ={} 25 26if query_string then 27self . _query =query . parse ( lang , query_string ) 28else 29self . _query =query . get ( lang , 'highlights' ) 30end 31 32return self 33end 34 35---@package 36---@param capture integer 37---@return integer? 38function TSHighlighterQuery : get_hl_from_capture ( capture ) 39if not self . hl_cache [ capture ] then 40local name =assert ( assert ( self . _query ). captures [ capture ]) 41local id =0 42if not vim . startswith ( name , '_' ) then 43id =api . nvim_get_hl_id_by_name ( '@' .. name .. '.' .. self . lang ) 44end 45self . hl_cache [ capture ] =id 46end 47 48return self . hl_cache [ capture ] 49end 50 51---@nodoc 52function TSHighlighterQuery : query () 53return self . _query 54end 55 56---@class (private) vim.treesitter.highlighter.State 57---@field tstree TSTree 58---@field next_row integer 59---@field next_col integer 60---@field iter vim.treesitter.highlighter.Iter? 61---@field highlighter_query vim.treesitter.highlighter.Query 62 63---@nodoc 64---@class vim.treesitter.highlighter 65---@field active table<integer,vim.treesitter.highlighter> 66---@field bufnr integer 67---@field private orig_spelloptions string 68--- A map from window ID to highlight states. 69--- This state is kept during rendering across each line update. 70---@field private _highlight_states vim.treesitter.highlighter.State[] 71---@field private _queries table<string,vim.treesitter.highlighter.Query> 72---@field _conceal_line boolean? 73---@field _conceal_checked table<integer, boolean> 74---@field tree vim.treesitter.LanguageTree 75---@field private redraw_count integer 76--- A map from window ID to whether we are currently parsing that window asynchronously 77---@field parsing boolean 78local TSHighlighter ={ 79active ={} , 80} 81 82TSHighlighter . __index =TSHighlighter 83 84---@nodoc 85--- 86--- Creates a highlighter for `tree`. 87--- 88---@param tree vim.treesitter.LanguageTree parser object to use for highlighting 89---@param opts (table|nil) Configuration of the highlighter: 90--- - queries table overwrite queries used by the highlighter 91---@return vim.treesitter.highlighter Created highlighter object 92function TSHighlighter . new ( tree , opts ) 93local source =tree : source () 94if type ( source ) ~= 'number' then 95error ( 'TSHighlighter can not be used with a string parser source.' ) 96end 97 98-- Calling start() again on an already-highlighted buffer must be a no-op: a second instance 99-- would register duplicate on_bytes/on_changedtree/on_detach callbacks that destroy() never 100-- unregisters, leaking callbacks that keep firing for the orphaned instance. 101local existing =TSHighlighter . active [ source ] 102if existing then 103if existing . tree == tree then 104return existing 105end 106-- Different tree (e.g. a language switch): the old instance would otherwise be silently 107-- orphaned with the same leaked callbacks, so destroy() it first, matching stop() semantics. 108existing : destroy () 109end 110 111local self =setmetatable ( {} , TSHighlighter ) 112 113opts =opts or {} ---@type { queries: table<string,string> } 114self . tree =tree 115tree : register_cbs ( { 116on_detach =function () 117self : on_detach () 118end , 119} ) 120 121--- Enable conceal_lines if query exists for lang and has conceal_lines metadata. 122--- @param lang string 123local function set_conceal_lines ( lang ) 124local hl_query =not self . _conceal_line and self : get_query ( lang ): query () 125if hl_query then 126self . _conceal_line =hl_query . has_conceal_line 127end 128end 129 130tree : register_cbs ( { 131on_bytes =function ( buf ) 132-- Clear conceal_lines marks whenever the buffer text changes. Marks are added 133-- back as either the _conceal_line or on_win callback comes across them. 134local hl =TSHighlighter . active [ buf ] 135if hl and next ( hl . _conceal_checked ) then 136api . nvim_buf_clear_namespace ( buf , ns , 0 , - 1 ) 137hl . _conceal_checked ={} 138end 139end , 140on_changedtree =function ( ... ) 141self : on_changedtree ( ... ) 142end , 143on_child_removed =function ( child ) 144child : for_each_tree ( function ( t ) 145self : on_changedtree ( t : included_ranges ( true )) 146end ) 147end , 148on_child_added =function ( child ) 149child : for_each_tree ( function ( t ) 150set_conceal_lines ( t : lang ()) 151end ) 152end , 153} , true ) 154 155self . bufnr =source 156self . redraw_count =0 157self . _conceal_checked ={} 158self . _queries ={} 159self . _highlight_states ={} 160self . parsing =false 161 162-- Queries for a specific language can be overridden by a custom 163-- string query... if one is not provided it will be looked up by file. 164if opts . queries then 165for lang , query_string in pairs ( opts . queries ) do 166self . _queries [ lang ] =TSHighlighterQuery . new ( lang , query_string ) 167set_conceal_lines ( lang ) 168end 169end 170set_conceal_lines ( tree : lang ()) 171self . orig_spelloptions =vim . bo [ self . bufnr ]. spelloptions 172 173vim . bo [ self . bufnr ]. syntax ='' 174vim . b [ self . bufnr ]. ts_highlight =true 175 176TSHighlighter . active [ self . bufnr ] =self 177 178-- Tricky: if syntax hasn't been enabled, we need to reload color scheme 179-- but use synload.vim rather than syntax.vim to not enable 180-- syntax FileType autocmds. Later on we should integrate with the 181-- `:syntax` and `set syntax=...` machinery properly. 182-- Still need to ensure that syntaxset augroup exists, so that calling :destroy() 183-- immediately afterwards will not error. 184if vim . g . syntax_on ~= 1 then 185vim . cmd . runtime ( { 'syntax/synload.vim' , bang =true } ) 186api . nvim_create_augroup ( 'syntaxset' , { clear =false } ) 187end 188 189vim . _with ( { buf =self . bufnr } , function () 190vim . opt_local . spelloptions : append ( 'noplainbuffer' ) 191end ) 192 193return self 194end 195 196--- @nodoc 197--- Removes all internal references to the highlighter 198function TSHighlighter : destroy () 199TSHighlighter . active [ self . bufnr ] =nil 200 201if api . nvim_buf_is_loaded ( self . bufnr ) then 202vim . bo [ self . bufnr ]. spelloptions =self . orig_spelloptions 203vim . b [ self . bufnr ]. ts_highlight =nil 204api . nvim_buf_clear_namespace ( self . bufnr , ns , 0 , - 1 ) 205if vim . g . syntax_on == 1 then 206api . nvim_exec_autocmds ( 207'FileType' , 208{ group ='syntaxset' , buf =self . bufnr , modeline =false } 209) 210end 211end 212end 213 214---@param srow integer 215---@param erow integer exclusive 216---@private 217function TSHighlighter : prepare_highlight_states ( srow , erow ) 218self . _highlight_states ={} 219 220self . tree : for_each_tree ( function ( tstree , tree ) 221if not tstree then 222return 223end 224 225local root_node =tstree : root () 226local root_start_row , _ , root_end_row , _ =root_node : range () 227 228-- Only consider trees within the visible range 229if root_start_row > erow or root_end_row < srow then 230return 231end 232 233local hl_query =self : get_query ( tree : lang ()) 234-- Some injected languages may not have highlight queries. 235if not hl_query : query () then 236return 237end 238 239-- _highlight_states should be a list so that the highlights are added in the same order as 240-- for_each_tree traversal. This ensures that parents' highlight don't override children's. 241table . insert ( self . _highlight_states , { 242tstree =tstree , 243next_row =0 , 244next_col =0 , 245iter =nil , 246highlighter_query =hl_query , 247} ) 248end ) 249end 250 251---@param fn fun(state: vim.treesitter.highlighter.State) 252---@package 253function TSHighlighter : for_each_highlight_state ( fn ) 254for _ , state in ipairs ( self . _highlight_states ) do 255fn ( state ) 256end 257end 258 259---@package 260function TSHighlighter : on_detach () 261self : destroy () 262end 263 264---@package 265---@param changes Range6[] 266function TSHighlighter : on_changedtree ( changes ) 267for _ , ch in ipairs ( changes ) do 268api . nvim__redraw ( { buf =self . bufnr , range ={ ch [ 1 ], ch [ 4 ] + 1 } , flush =false } ) 269-- Only invalidate the _conceal_checked range if _conceal_line is set and 270-- ch[4] is not UINT32_MAX (empty range on first changedtree). 271if ch [ 4 ] == 2 ^ 32 - 1 then 272self . _conceal_checked ={} 273end 274for i =ch [ 1 ], self . _conceal_line and ch [ 4 ] ~= 2 ^ 32 - 1 and ch [ 4 ] or 0 do 275self . _conceal_checked [ i ] =false 276end 277end 278end 279 280--- Gets the query used for @param lang 281---@nodoc 282---@param lang string Language used by the highlighter. 283---@return vim.treesitter.highlighter.Query 284function TSHighlighter : get_query ( lang ) 285if not self . _queries [ lang ] then 286local success , result =pcall ( TSHighlighterQuery . new , lang ) 287if not success then 288self : destroy () 289error ( result ) 290end 291self . _queries [ lang ] =result 292end 293 294return self . _queries [ lang ] 295end 296 297--- @param match TSQueryMatch 298--- @param bufnr integer 299--- @param capture integer 300--- @param metadata vim.treesitter.query.TSMetadata 301--- @return string? 302local function get_url ( match , bufnr , capture , metadata ) 303---@type string|integer|nil 304local url =metadata [ capture ] and metadata [ capture ]. url 305 306if not url or type ( url ) == 'string' then 307return url 308end 309 310local captures =match : captures () 311 312if not captures [ url ] then 313return 314end 315 316-- Assume there is only one matching node. If there is more than one, take the URL 317-- from the first. 318local other_node =assert ( captures [ url ][ 1 ]) 319 320return vim . treesitter . get_node_text ( other_node , bufnr , { 321metadata =metadata [ url ], 322} ) 323end 324 325--- @param capture_name string 326--- @return boolean?, integer 327local function get_spell ( capture_name ) 328if capture_name == 'spell' then 329return true , 0 330elseif capture_name == 'nospell' then 331-- Give nospell a higher priority so it always overrides spell captures. 332return false , 1 333end 334return nil , 0 335end 336 337---@param self vim.treesitter.highlighter 338---@param buf integer 339---@param range_start_row integer 340---@param range_start_col integer 341---@param range_end_row integer 342---@param range_end_col integer 343---@param on_spell boolean 344---@param on_conceal boolean 345local function on_range_impl ( 346self , 347buf , 348range_start_row , 349range_start_col , 350range_end_row , 351range_end_col , 352on_spell , 353on_conceal 354) 355if self . _conceal_line then 356range_start_col =0 357if range_end_col ~= 0 then 358range_end_row =range_end_row + 1 359range_end_col =0 360end 361end 362for i =range_start_row , range_end_row - 1 do 363self . _conceal_checked [ i ] =self . _conceal_line or nil 364end 365 366local MAX_ROW =2147483647 -- sentinel for skipping to the end of file 367local skip_until_row =MAX_ROW 368local skip_until_col =0 369 370local subtree_counter =0 371self : for_each_highlight_state ( function ( state ) 372subtree_counter =subtree_counter + 1 373local root_node =state . tstree : root () 374local root_range ={ root_node : range () } 375 376if 377not Range . intercepts ( 378root_range , 379{ range_start_row , range_start_col , range_end_row , range_end_col } 380) 381then 382if cmp_lt ( root_range [ 1 ], root_range [ 2 ], skip_until_row , skip_until_col ) then 383skip_until_row =root_range [ 1 ] 384skip_until_col =root_range [ 2 ] 385end 386return 387end 388 389local tree_region =state . tstree : included_ranges ( true ) 390 391local next_row =state . next_row 392local next_col =state . next_col 393local hl_query =assert ( state . highlighter_query : query ()) 394 395if state . iter == nil or cmp_lt ( next_row , next_col , range_start_row , range_start_col ) then 396-- Mainly used to skip over folds 397 398-- TODO(lewis6991): Creating a new iterator loses the cached predicate results for query 399-- matches. Move this logic inside iter_captures() so we can maintain the cache. 400state . iter =hl_query : iter_captures ( 401root_node , 402self . bufnr , 403range_start_row , 404root_range [ 3 ], 405{ start_col =range_start_col , end_col =root_range [ 4 ] } 406) 407end 408 409local captures =hl_query . captures 410 411while cmp_lt ( next_row , next_col , range_end_row , range_end_col ) do 412local capture , node , metadata , match =state . iter ( range_end_row , range_end_col ) 413if not node then 414next_row =vim . _maxint 415next_col =vim . _maxint 416break 417end 418 419local outer_range =vim . treesitter . get_range ( node , buf , metadata and metadata [ capture ]) 420if cmp_lt ( next_row , next_col , outer_range [ 1 ], outer_range [ 2 ]) then 421next_row =outer_range [ 1 ] 422next_col =outer_range [ 2 ] 423end 424 425if not capture then 426break 427end 428 429for _ , range in ipairs ( tree_region ) do 430local intersection =Range . intersection ( range , outer_range ) 431if intersection then 432local start_row , start_col , end_row , end_col =Range . unpack4 ( intersection ) 433 434local hl =state . highlighter_query : get_hl_from_capture ( capture ) 435 436local capture_name =assert ( captures [ capture ]) 437 438local spell , spell_pri_offset =get_spell ( capture_name ) 439 440local is_noconceal =capture_name == 'noconceal' 441-- The "conceal" attribute can be set at the pattern level or on a particular capture 442local conceal_attr =( metadata . conceal ~= nil and metadata . conceal ) 443or ( metadata [ capture ] and metadata [ capture ]. conceal ) 444local conceal ---@type boolean|string? 445if is_noconceal then 446conceal =false 447else 448conceal =conceal_attr 449if conceal_attr == false then 450is_noconceal =true 451end 452end 453is_noconceal =is_noconceal or conceal_attr == false 454local conceal_pri_offset =is_noconceal and 1 or 0 455 456-- The "priority" attribute can be set at the pattern level or on a particular capture 457local priority =( 458vim . _tointeger ( metadata . priority or metadata [ capture ] and metadata [ capture ]. priority ) 459or vim . hl . priorities . treesitter 460) 461+ spell_pri_offset 462+ conceal_pri_offset 463 464local url =get_url ( match , buf , capture , metadata ) 465 466if hl and not on_conceal and ( not on_spell or spell ~= nil ) then 467-- Workaround for #35814: ensure the range is within buffer bounds, 468-- allowing the last line if end_col is 0. 469-- TODO(skewb1k): investigate a proper concurrency-safe handling of extmarks. 470if ( end_row + ( end_col > 0 and 1 or 0 )) <= api . nvim_buf_line_count ( buf ) then 471api . nvim_buf_set_extmark ( buf , ns , start_row , start_col , { 472end_row =end_row , 473end_col =end_col , 474hl_group =hl , 475ephemeral =true , 476priority =priority , 477conceal =conceal , 478spell =spell , 479url =url , 480_subpriority =subtree_counter , 481} ) 482end 483end 484 485if 486( metadata . conceal_lines or metadata [ capture ] and metadata [ capture ]. conceal_lines ) 487and # api . nvim_buf_get_extmarks ( buf , ns , { start_row , 0 } , { start_row , 0 } ) == 0 488then 489api . nvim_buf_set_extmark ( buf , ns , start_row , 0 , { 490end_line =end_row , 491conceal_lines ='' , 492} ) 493end 494end 495end 496end 497 498state . next_row =next_row 499state . next_col =next_col 500if cmp_lt ( next_row , next_col , skip_until_row , skip_until_col ) then 501skip_until_row =next_row 502skip_until_col =next_col 503end 504end ) 505return skip_until_row , skip_until_col 506end 507 508---@private 509---@param buf integer 510---@param br integer 511---@param bc integer 512---@param er integer 513---@param ec integer 514function TSHighlighter . _on_range ( _ , _ , buf , br , bc , er , ec , _ ) 515local self =TSHighlighter . active [ buf ] 516if not self then 517return 518end 519 520return on_range_impl ( self , buf , br , bc , er , ec , false , false ) 521end 522 523---@private 524---@param buf integer 525---@param srow integer 526---@param erow integer 527function TSHighlighter . _on_spell_nav ( _ , _ , buf , srow , _ , erow , _ ) 528local self =TSHighlighter . active [ buf ] 529if not self then 530return 531end 532 533-- Do not affect potentially populated highlight state. Here we just want a temporary 534-- empty state so the C code can detect whether the region should be spell checked. 535local highlight_states =self . _highlight_states 536local search_erow =math . max ( erow , srow + 1 ) 537self : prepare_highlight_states ( srow , erow ) 538 539on_range_impl ( self , buf , srow , 0 , search_erow , 0 , true , false ) 540self . _highlight_states =highlight_states 541end 542 543---@private 544---@param buf integer 545---@param row integer 546function TSHighlighter . _on_conceal_line ( _ , _ , buf , row ) 547local self =TSHighlighter . active [ buf ] 548if not self or not self . _conceal_line or self . _conceal_checked [ row ] then 549return 550end 551 552-- Do not affect potentially populated highlight state. 553local highlight_states =self . _highlight_states 554self . tree : parse ( { row , row + 1 } ) 555self : prepare_highlight_states ( row , row ) 556on_range_impl ( self , buf , row , 0 , row + 1 , 0 , false , true ) 557self . _highlight_states =highlight_states 558end 559 560---@private 561---@param buf integer 562---@param topline integer 563---@param botline integer 564function TSHighlighter . _on_win ( _ , _ , buf , topline , botline ) 565local self =TSHighlighter . active [ buf ] 566if not self then 567return false 568end 569if not self . parsing then 570self . redraw_count =self . redraw_count + 1 571self : prepare_highlight_states ( topline , botline ) 572else 573self : for_each_highlight_state ( function ( state ) 574state . iter =nil 575state . next_row =0 576state . next_col =0 577end ) 578end 579return next ( self . _highlight_states ) ~= nil 580end 581 582function TSHighlighter . _on_start () 583local buf_ranges ={} ---@type table<integer, Range[]> 584for _ , win in ipairs ( api . nvim_tabpage_list_wins ( 0 )) do 585local buf =api . nvim_win_get_buf ( win ) 586if TSHighlighter . active [ buf ] then 587if not buf_ranges [ buf ] then 588buf_ranges [ buf ] ={} 589end 590local topline =vim . fn . line ( 'w0' , win ) - 1 591-- +1 because w$ is the last completely displayed line (w_botline - 1), which may be -1 of the 592-- last line that is at least partially visible. 593local botline =vim . fn . line ( 'w$' , win ) + 1 594table . insert ( buf_ranges [ buf ], { topline , botline } ) 595end 596end 597for buf , ranges in pairs ( buf_ranges ) do 598local highlighter =TSHighlighter . active [ buf ] 599if not highlighter . parsing then 600table . sort ( ranges , function ( a , b ) 601return a [ 1 ] < b [ 1 ] 602end ) 603highlighter . parsing =highlighter . parsing 604or nil 605== highlighter . tree : parse ( ranges , function ( _ , trees ) 606if trees and highlighter . parsing then 607highlighter . parsing =false 608api . nvim__redraw ( { buf =buf , valid =false , flush =false } ) 609end 610end ) 611end 612end 613end 614 615api . nvim_set_decoration_provider ( ns , { 616on_win =TSHighlighter . _on_win , 617on_start =TSHighlighter . _on_start , 618on_range =TSHighlighter . _on_range , 619_on_spell_nav =TSHighlighter . _on_spell_nav , 620_on_conceal_line =TSHighlighter . _on_conceal_line , 621} ) 622 623return TSHighlighter