robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
aa1d8a2702
master
1local api =vim . api 2local nvim_on =require ( 'vim._core.util' ). nvim_on 3local bit =require ( 'bit' ) 4local util =require ( 'vim.lsp.util' ) 5local Range =require ( 'vim.treesitter._range' ) 6local uv =vim . uv 7 8local Capability =require ( 'vim.lsp._capability' ) 9 10local M ={} 11 12--- @class (private) STTokenRange 13--- @field line integer line number 0-based 14--- @field start_col integer start column 0-based 15--- @field end_line integer end line number 0-based 16--- @field end_col integer end column 0-based 17--- @field type string token type as string 18--- @field modifiers table<string,boolean> token modifiers as a set. E.g., { static = true, readonly = true } 19--- @field marked boolean whether this token has had extmarks applied 20 21--- @class (private) STCurrentResult 22--- @field version? integer document version associated with this result 23--- @field result_id? string resultId from the server; used with delta requests 24--- @field highlights? STTokenRange[] cache of highlight ranges for this document version 25--- @field tokens? uinteger[] raw token array as received by the server. used for calculating delta responses 26--- @field namespace_cleared? boolean whether the namespace was cleared for this result yet 27 28--- @class (private) STActiveRequest 29--- @field request_id? integer the LSP request ID of the most recent request sent to the server 30--- @field version? integer the document version associated with the most recent request 31 32--- @class (private) STClientState 33--- @field namespace integer 34--- @field supports_range boolean 35--- @field supports_delta boolean 36--- @field active_request STActiveRequest 37--- @field active_range_request STActiveRequest 38--- @field current_result STCurrentResult 39--- @field timer uv.uv_timer_t? uv_timer for debouncing requests for new tokens 40--- @field has_full_result boolean 41 42---@class (private) STHighlighter : vim.lsp.Capability 43---@field active table<integer, STHighlighter> 44---@field debounce integer milliseconds to debounce requests for new tokens 45---@field client_state table<integer, STClientState?> 46local STHighlighter ={ 47name ='semantic_tokens' , 48method ='textDocument/semanticTokens' , 49debounce =200 , 50active ={} , 51} 52STHighlighter . __index =STHighlighter 53setmetatable ( STHighlighter , Capability ) 54Capability . all [ STHighlighter . name ] =STHighlighter 55 56--- Extracts modifier strings from the encoded number in the token array 57--- 58---@param x integer 59---@param modifiers_table table<integer,string> 60---@return table<string, boolean> 61local function modifiers_from_number ( x , modifiers_table ) 62local modifiers ={} ---@type table<string,boolean> 63local idx =1 64while x > 0 do 65if bit . band ( x , 1 ) == 1 then 66modifiers [ modifiers_table [ idx ]] =true 67end 68x =bit . rshift ( x , 1 ) 69idx =idx + 1 70end 71 72return modifiers 73end 74 75--- Converts a raw token list to a list of highlight ranges used by the on_win callback 76--- 77---@async 78---@param data integer[] 79---@param bufnr integer 80---@param client vim.lsp.Client 81---@param request STActiveRequest 82---@param ranges STTokenRange[] 83---@return STTokenRange[] 84local function tokens_to_ranges ( data , bufnr , client , request , ranges ) 85local legend =assert ( client . server_capabilities . semanticTokensProvider ). legend 86local token_types =legend . tokenTypes 87local token_modifiers =legend . tokenModifiers 88local encoding =client . offset_encoding 89local lines =api . nvim_buf_get_lines ( bufnr , 0 , - 1 , false ) 90-- For all encodings, \r\n takes up two code points, and \n (or \r) takes up one. 91local eol_offset =vim . bo [ bufnr ]. fileformat == 'dos' and 2 or 1 92local version =request . version 93local request_id =request . request_id 94local last_insert_idx =1 95 96local start =uv . hrtime () 97local ms_to_ns =1e6 98local yield_interval_ns =5 * ms_to_ns 99local co , is_main =coroutine . running () 100 101local line ---@type integer? 102local start_char =0 103for i =1 , # data , 5 do 104-- if this function is called from the main coroutine, let it run to completion with no yield 105if not is_main then 106local elapsed_ns =uv . hrtime () - start 107 108if elapsed_ns > yield_interval_ns then 109vim . schedule ( function () 110-- Ensure the request hasn't become stale since the last time the coroutine ran. 111-- If it's stale, we don't resume the coroutine so it'll be garbage collected. 112if 113version == util . buf_versions [ bufnr ] 114---@diagnostic disable-next-line: preferred-local-alias 115and request_id == request . request_id 116and api . nvim_buf_is_valid ( bufnr ) 117then 118coroutine . resume ( co ) 119end 120end ) 121 122coroutine . yield () 123start =uv . hrtime () 124end 125end 126 127-- The protocol encodes each token as five integers. 128local delta_line =data [ i ] 129line =line and line + delta_line or delta_line 130local delta_start =assert ( data [ i + 1 ]) 131start_char =delta_line == 0 and start_char + delta_start or delta_start 132 133-- data[i+3] +1 because Lua tables are 1-indexed 134local token_type =token_types [ assert ( data [ i + 3 ]) + 1 ] 135 136if token_type then 137local modifiers =modifiers_from_number ( assert ( data [ i + 4 ]), token_modifiers ) 138local end_char =start_char + assert ( data [ i + 2 ]) 139local buf_line =lines [ line + 1 ] or '' 140local end_line =line ---@type integer 141local start_col =vim . str_byteindex ( buf_line , encoding , start_char , false ) 142 143---@type integer LuaLS bug, type must be marked explicitly here 144local new_end_char =end_char - vim . str_utfindex ( buf_line , encoding ) - eol_offset 145-- While end_char goes past the given line, extend the token range to the next line 146while new_end_char > 0 and end_line < # lines - 1 do 147end_char =new_end_char 148end_line =end_line + 1 149buf_line =lines [ end_line + 1 ] or '' 150new_end_char =new_end_char - vim . str_utfindex ( buf_line , encoding ) - eol_offset 151end 152 153local end_col =vim . str_byteindex ( buf_line , encoding , end_char , false ) 154 155---@type STTokenRange 156local range ={ 157line =line , 158end_line =end_line , 159start_col =start_col , 160end_col =end_col , 161type =token_type , 162modifiers =modifiers , 163marked =false , 164} 165 166if last_insert_idx < # ranges then 167local needs_insert =true 168local idx =vim . list . bisect ( ranges , range , { 169lo =last_insert_idx , 170key =function ( highlight ) 171return highlight . line 172end , 173} ) 174while idx <= # ranges do 175local token =assert ( ranges [ idx ]) 176 177if 178token . line > range . line 179or ( token . line == range . line and token . start_col > range . start_col ) 180then 181break 182end 183 184if 185range . line == token . line 186and range . start_col == token . start_col 187and range . end_line == token . end_line 188and range . end_col == token . end_col 189and range . type == token . type 190then 191needs_insert =false 192break 193end 194 195idx =idx + 1 196end 197 198last_insert_idx =idx 199if needs_insert then 200table . insert ( ranges , last_insert_idx , range ) 201end 202else 203last_insert_idx =# ranges + 1 204ranges [ last_insert_idx ] =range 205end 206end 207end 208 209return ranges 210end 211 212---@package 213---@param bufnr integer 214function STHighlighter : new ( bufnr ) 215self =Capability . new ( self , bufnr ) 216 217nvim_on ( 'BufWinEnter' , self . augroup , { buf =self . bufnr } , function () 218for client_id , _ in pairs ( self . client_state ) do 219self : send_request ( client_id ) 220end 221end ) 222 223nvim_on ( 'WinScrolled' , self . augroup , { buf =self . bufnr } , function () 224for client_id , state in pairs ( self . client_state ) do 225if state . supports_range then 226self : debounce_request ( client_id ) 227end 228end 229end ) 230 231return self 232end 233 234---@package 235---@param client_id integer 236function STHighlighter : on_attach ( client_id ) 237local client =vim . lsp . get_client_by_id ( client_id ) 238local state =self . client_state [ client_id ] 239if not state then 240state ={ 241namespace =api . nvim_create_namespace ( 'nvim.lsp.semantic_tokens:' .. client_id ), 242supports_range =client 243and client : supports_method ( 'textDocument/semanticTokens/range' , self . bufnr ) 244or false , 245supports_delta =client 246and client : supports_method ( 'textDocument/semanticTokens/full/delta' , self . bufnr ) 247or false , 248active_request ={} , 249active_range_request ={} , 250current_result ={} , 251has_full_result =false , 252} 253self . client_state [ client_id ] =state 254end 255 256self : send_request ( client_id ) 257end 258 259---@package 260---@param client_id integer 261function STHighlighter : on_detach ( client_id ) 262local state =self . client_state [ client_id ] 263if state then 264--TODO: delete namespace if/when that becomes possible 265api . nvim_buf_clear_namespace ( self . bufnr , state . namespace , 0 , - 1 ) 266self : reset_timer ( state ) 267self . client_state [ client_id ] =nil 268end 269end 270 271---@private 272---@param client_id integer 273function STHighlighter : on_close ( client_id ) 274self : reset ( client_id ) 275end 276 277---@private 278---@param client_id integer 279function STHighlighter : on_change ( client_id ) 280self : send_request ( client_id ) 281end 282 283--- This is the entry point for getting all the tokens in a buffer. 284--- 285--- For the given client, this sends semantic token requests to ask for semantic tokens. If the 286--- server supports range requests and a full result has not been processed yet, it will send a 287--- range request for the current visible range. Additionally, if a result for the current document 288--- version hasn't been processed yet, it sends either a full or delta request, depending on what 289--- the server supports and whether there's a current full result for the previous document version. 290--- 291--- This function will skip full/delta requests on servers where there is an already an active 292--- full/delta request in flight for the same version. If there is a stale request in flight, that 293--- is cancelled prior to sending a new one. 294--- 295--- Finally, for successful requests, the requestId (full/delta) and document version are saved to 296--- facilitate document synchronization in the response. 297--- 298---@package 299---@param client_id integer 300function STHighlighter : send_request ( client_id ) 301local client =vim . lsp . get_client_by_id ( client_id ) 302local state =self . client_state [ client_id ] 303 304if client and state then 305self : reset_timer ( state ) 306 307local version =util . buf_versions [ self . bufnr ] 308 309-- If the server supports range and there's no full result yet, then start with a range 310-- request 311if state . supports_range and not state . has_full_result then 312self : send_range_request ( client , state , version ) 313end 314 315if 316( not state . has_full_result or state . current_result . version ~= version ) 317and state . active_request . version ~= version 318then 319self : send_full_delta_request ( client , state , version ) 320end 321end 322end 323 324--- Send a range request for the visible area 325--- 326---@private 327---@param client vim.lsp.Client 328---@param state STClientState 329---@param version integer 330function STHighlighter : send_range_request ( client , state , version ) 331local active_request =state . active_range_request 332 333-- cancel stale in-flight request 334if active_request and active_request . request_id then 335client : cancel_request ( active_request . request_id ) 336active_request . request_id =nil 337active_request . version =nil 338end 339 340---@type lsp.SemanticTokensRangeParams 341local params ={ 342textDocument =util . make_text_document_params ( self . bufnr ), 343range =self : get_overscan_range (), 344} 345 346---@type vim.lsp.protocol.Method.ClientToServer.Request 347local method ='textDocument/semanticTokens/range' 348 349---@param response? lsp.SemanticTokens 350local success , request_id =client : request ( method , params , function ( err , response , ctx ) 351local bufnr =assert ( ctx . bufnr ) 352local highlighter =STHighlighter . active [ bufnr ] 353if not highlighter then 354return 355end 356 357-- Only process range response if we got a valid response and don't have a full result yet 358if err or not response or state . has_full_result then 359if err then 360vim . lsp . log . error ( 'semantic_tokens' , err ) 361end 362active_request . request_id =nil 363active_request . version =nil 364return 365end 366 367coroutine . wrap ( STHighlighter . process_response )( 368highlighter , 369response , 370client , 371ctx . request_id , 372version , 373true 374) 375end , self . bufnr ) 376 377if success then 378active_request . request_id =request_id 379active_request . version =version 380end 381end 382 383--- Send a full or delta request 384--- 385---@private 386---@param client vim.lsp.Client 387---@param state STClientState 388---@param version integer 389function STHighlighter : send_full_delta_request ( client , state , version ) 390local current_result =state . current_result 391local active_request =state . active_request 392 393-- cancel stale in-flight request 394if active_request . request_id then 395client : cancel_request ( active_request . request_id ) 396active_request . request_id =nil 397active_request . version =nil 398end 399 400---@type lsp.SemanticTokensParams|lsp.SemanticTokensDeltaParams 401local params ={ textDocument =util . make_text_document_params ( self . bufnr ) } 402 403---@type vim.lsp.protocol.Method.ClientToServer.Request 404local method ='textDocument/semanticTokens/full' 405 406if state . supports_delta and current_result . result_id then 407method ='textDocument/semanticTokens/full/delta' 408params . previousResultId =current_result . result_id 409end 410 411---@param response? lsp.SemanticTokens|lsp.SemanticTokensDelta 412local success , request_id =client : request ( method , params , function ( err , response , ctx ) 413local bufnr =assert ( ctx . bufnr ) 414local highlighter =STHighlighter . active [ bufnr ] 415if not highlighter then 416return 417end 418 419if err or not response then 420if err then 421vim . lsp . log . error ( 'semantic_tokens' , err ) 422end 423active_request . request_id =nil 424active_request . version =nil 425return 426end 427 428coroutine . wrap ( STHighlighter . process_response )( 429highlighter , 430response , 431client , 432ctx . request_id , 433version , 434false 435) 436end , self . bufnr ) 437 438if success then 439active_request . request_id =request_id 440active_request . version =version 441end 442end 443 444---@private 445---@param client_id integer 446function STHighlighter : cancel_active_request ( client_id ) 447local state =assert ( self . client_state [ client_id ]) 448local client =vim . lsp . get_client_by_id ( client_id ) 449 450---@param request STActiveRequest 451local function clear ( request ) 452if client and request . request_id then 453client : cancel_request ( request . request_id ) 454request . request_id =nil 455request . version =nil 456end 457end 458 459clear ( state . active_range_request ) 460clear ( state . active_request ) 461end 462 463--- Gets a range that encompasses all visible lines plus overscan across all windows 464--- @private 465--- @return lsp.Range 466function STHighlighter : get_overscan_range () 467local wins =vim . fn . win_findbuf ( self . bufnr ) 468local num_lines =api . nvim_buf_line_count ( self . bufnr ) 469local min_start , max_end =nil , nil 470 471for _ , win in ipairs ( wins ) do 472local wininfo =vim . fn . getwininfo ( win )[ 1 ] 473if wininfo then 474-- Overscan the token request by the height of the window on each side 475-- to prevent flickering when navigating up and down. 476local start_line =math . max ( 0 , wininfo . topline - 1 - wininfo . height ) 477local end_line =math . min ( num_lines , wininfo . botline + wininfo . height ) 478if not min_start or start_line < min_start then 479min_start =start_line 480end 481if not max_end or end_line > max_end then 482max_end =end_line 483end 484end 485end 486 487---@type lsp.Range 488return { 489[ 'start' ] ={ line =min_start or 0 , character =0 } , 490[ 'end' ] ={ line =max_end or 0 , character =0 } , 491} 492end 493 494--- This function will parse the semantic token responses and set up the cache 495--- (current_result). It also performs document synchronization by checking the 496--- version of the document associated with the resulting request_id and only 497--- performing work if the response is not out-of-date. 498--- 499--- Delta edits are applied if necessary, and new highlight ranges are calculated 500--- and stored in the buffer state. 501--- 502--- Finally, a redraw command is issued to force nvim to redraw the screen to 503--- pick up changed highlight tokens. 504--- 505---@async 506---@param response lsp.SemanticTokens|lsp.SemanticTokensDelta 507---@param client vim.lsp.Client 508---@param request_id integer 509---@param version integer 510---@param is_range_request boolean 511---@private 512function STHighlighter : process_response ( response , client , request_id , version , is_range_request ) 513local state =self . client_state [ client . id ] 514if not state then 515return 516end 517 518---@type STActiveRequest 519local active_request 520if is_range_request then 521active_request =state . active_range_request 522else 523active_request =state . active_request 524end 525 526-- ignore stale responses 527if active_request . request_id and request_id ~= active_request . request_id then 528return 529end 530 531if not api . nvim_buf_is_valid ( self . bufnr ) then 532return 533end 534 535-- if we have a response to a delta request, update the state of our tokens 536-- appropriately. if it's a full response, just use that 537local tokens ---@type integer[] 538if response . edits then 539local token_edits =response . edits 540table . sort ( token_edits , function ( a , b ) 541return a . start < b . start 542end ) 543 544tokens ={} --- @type integer[] 545local old_tokens =assert ( state . current_result . tokens ) 546local idx =1 547for _ , token_edit in ipairs ( token_edits ) do 548vim . list_extend ( tokens , old_tokens , idx , token_edit . start ) 549if token_edit . data then 550vim . list_extend ( tokens , token_edit . data ) 551end 552idx =token_edit . start + token_edit . deleteCount + 1 553end 554vim . list_extend ( tokens , old_tokens , idx ) 555else 556tokens =response . data 557end 558 559local current_result =state . current_result 560local version_changed =version ~= current_result . version 561local highlights =not version_changed and current_result . highlights or {} 562 563-- convert token list to highlight ranges 564-- this could yield and run over multiple event loop iterations 565highlights =tokens_to_ranges ( tokens , self . bufnr , client , active_request , highlights ) 566 567-- if this was a full result, mark the state as having processed it 568if not is_range_request then 569state . has_full_result =true 570end 571 572-- reset active request 573active_request . request_id =nil 574active_request . version =nil 575 576-- update the state with the new results 577current_result . version =version 578current_result . result_id =not is_range_request and response . resultId or nil 579current_result . tokens =tokens 580current_result . highlights =highlights 581if version_changed then 582current_result . namespace_cleared =false 583end 584 585-- redraw all windows displaying buffer 586if vim . fn . win_gettype ( vim . fn . bufwinid ( self . bufnr )) == '' then 587api . nvim__redraw ( { buf =self . bufnr , valid =true } ) 588end 589end 590 591--- @param bufnr integer 592--- @param ns integer 593--- @param token STTokenRange 594--- @param hl_group string 595--- @param priority integer 596local function set_mark ( bufnr , ns , token , hl_group , priority ) 597api . nvim_buf_set_extmark ( bufnr , ns , token . line , token . start_col , { 598hl_group =hl_group , 599end_line =token . end_line , 600end_col =token . end_col , 601priority =priority , 602strict =false , 603} ) 604end 605 606--- @param lnum integer 607--- @param foldend integer? 608--- @return boolean, integer? 609local function check_fold ( lnum , foldend ) 610if foldend and lnum <= foldend then 611return true , foldend 612end 613 614local folded =vim . fn . foldclosed ( lnum ) 615 616if folded == - 1 then 617return false , nil 618end 619 620return folded ~= lnum , vim . fn . foldclosedend ( lnum ) 621end 622 623--- on_win handler for the decoration provider (see |nvim_set_decoration_provider|) 624--- 625--- If there is a current result for the buffer and the version matches the 626--- current document version, then the tokens are valid and can be applied. As 627--- the buffer is drawn, this function will add extmark highlights for every 628--- token in the range of visible lines. Once a highlight has been added, it 629--- sticks around until the document changes and there's a new set of matching 630--- highlight tokens available. 631--- 632--- If this is the first time a buffer is being drawn with a new set of 633--- highlights for the current document version, the namespace is cleared to 634--- remove extmarks from the last version. It's done here instead of the response 635--- handler to avoid the "blink" that occurs due to the timing between the 636--- response handler and the actual redraw. 637--- 638---@package 639---@param topline integer 640---@param botline integer 641function STHighlighter : on_win ( topline , botline ) 642for client_id , state in pairs ( self . client_state ) do 643local current_result =state . current_result 644if current_result . version == util . buf_versions [ self . bufnr ] then 645if not current_result . namespace_cleared then 646api . nvim_buf_clear_namespace ( self . bufnr , state . namespace , 0 , - 1 ) 647current_result . namespace_cleared =true 648end 649 650-- We can't use ephemeral extmarks because the buffer updates are not in 651-- sync with the list of semantic tokens. There's a delay between the 652-- buffer changing and when the LSP server can respond with updated 653-- tokens, and we don't want to "blink" the token highlights while 654-- updates are in flight, and we don't want to use stale tokens because 655-- they likely won't line up right with the actual buffer. 656-- 657-- Instead, we have to use normal extmarks that can attach to locations 658-- in the buffer and are persisted between redraws. 659-- 660-- `strict = false` is necessary here for the 1% of cases where the 661-- current result doesn't actually match the buffer contents. Some 662-- LSP servers can respond with stale tokens on requests if they are 663-- still processing changes from a didChange notification. 664-- 665-- LSP servers that do this _should_ follow up known stale responses 666-- with a refresh notification once they've finished processing the 667-- didChange notification, which would re-synchronize the tokens from 668-- our end. 669-- 670-- The server I know of that does this is clangd when the preamble of 671-- a file changes and the token request is processed with a stale 672-- preamble while the new one is still being built. Once the preamble 673-- finishes, clangd sends a refresh request which lets the client 674-- re-synchronize the tokens. 675 676--- @param token STTokenRange 677--- @param hl_group string 678--- @param delta integer 679local function set_mark0 ( token , hl_group , delta ) 680set_mark ( 681self . bufnr , 682state . namespace , 683token , 684hl_group , 685vim . hl . priorities . semantic_tokens + delta 686) 687end 688 689local ft =vim . bo [ self . bufnr ]. filetype 690local highlights =assert ( current_result . highlights ) 691local first =vim . list . bisect ( highlights , { end_line =topline } , { 692key =function ( highlight ) 693return highlight . end_line 694end , 695} ) 696local last =vim . list . bisect ( highlights , { line =botline } , { 697lo =first , 698bound ='upper' , 699key =function ( highlight ) 700return highlight . line 701end , 702} ) - 1 703 704--- @type boolean?, integer? 705local is_folded , foldend 706 707for i =first , last do 708local token =assert ( highlights [ i ]) 709 710is_folded , foldend =check_fold ( token . line + 1 , foldend ) 711 712if not is_folded and not token . marked then 713set_mark0 ( token , string . format ( '@lsp.type.%s.%s' , token . type , ft ), 0 ) 714for modifier in pairs ( token . modifiers ) do 715set_mark0 ( token , string . format ( '@lsp.mod.%s.%s' , modifier , ft ), 1 ) 716set_mark0 ( token , string . format ( '@lsp.typemod.%s.%s.%s' , token . type , modifier , ft ), 2 ) 717end 718token . marked =true 719 720api . nvim_exec_autocmds ( 'LspTokenUpdate' , { 721buf =self . bufnr , 722modeline =false , 723data ={ 724token =token , 725client_id =client_id , 726} , 727} ) 728end 729end 730end 731end 732end 733 734--- Reset the buffer's highlighting state and clears the extmark highlights. 735--- 736---@package 737---@param client_id integer 738function STHighlighter : reset ( client_id ) 739local state =assert ( self . client_state [ client_id ]) 740self : cancel_active_request ( client_id ) 741api . nvim_buf_clear_namespace ( self . bufnr , state . namespace , 0 , - 1 ) 742state . current_result ={} 743state . has_full_result =false 744end 745 746--- Mark a client's results as dirty. This method will cancel any active 747--- requests to the server and pause new highlights from being added 748--- in the on_win callback. The rest of the current results are saved 749--- in case the server supports delta requests. 750--- 751---@package 752---@param client_id integer 753function STHighlighter : mark_dirty ( client_id ) 754local state =assert ( self . client_state [ client_id ]) 755 756-- if we clear the version from current_result, it'll cause the next 757-- full/delta request to be sent and will also pause new highlights 758-- from being added in on_win until a new result comes from the server 759if state . current_result then 760state . current_result . version =nil 761end 762 763-- clearing this flag will also allow range requests to fire to 764-- potentially get a faster result 765state . has_full_result =false 766 767self : cancel_active_request ( client_id ) 768end 769 770---@package 771---@param client_id integer 772function STHighlighter : debounce_request ( client_id ) 773local state =assert ( self . client_state [ client_id ]) 774self : reset_timer ( state ) 775if self . debounce > 0 then 776state . timer =vim . defer_fn ( function () 777self : send_request ( client_id ) 778end , self . debounce ) 779else 780self : send_request ( client_id ) 781end 782end 783 784---@private 785---@param state STClientState 786function STHighlighter . reset_timer ( _ , state ) 787local timer =state . timer 788if timer then 789state . timer =nil 790if not timer : is_closing () then 791timer : stop () 792timer : close () 793end 794end 795end 796 797--- Start the semantic token highlighting engine for the given buffer with the 798--- given client. The client must already be attached to the buffer. 799--- 800--- NOTE: This is currently called automatically by |vim.lsp.buf_attach_client()|. To 801--- opt-out of semantic highlighting with a server that supports it, you can 802--- delete the semanticTokensProvider table from the {server_capabilities} of 803--- your client in your |LspAttach| callback or your configuration's 804--- `on_attach` callback: 805--- 806--- ```lua 807--- client.server_capabilities.semanticTokensProvider = nil 808--- ``` 809--- 810---@deprecated 811---@param bufnr (integer) Buffer number, or `0` for current buffer 812---@param client_id (integer) The ID of the |vim.lsp.Client| 813---@param opts? (table) Optional keyword arguments 814--- - debounce (integer, default: 200): Debounce token requests 815--- to the server by the given number in milliseconds 816function M . start ( bufnr , client_id , opts ) 817vim . deprecate ( 'vim.lsp.semantic_tokens.start' , 'vim.lsp.semantic_tokens.enable(true)' , '0.13.0' ) 818vim . validate ( 'bufnr' , bufnr , 'number' ) 819vim . validate ( 'client_id' , client_id , 'number' ) 820 821M . enable ( true , { bufnr =bufnr , client_id =client_id } ) 822 823if opts and opts . debounce and STHighlighter . active [ bufnr ] then 824local highlighter =STHighlighter . active [ bufnr ] 825local prev =rawget ( highlighter , 'debounce' ) 826highlighter . debounce =prev and math . max ( prev , opts . debounce ) or opts . debounce 827end 828end 829 830--- Stop the semantic token highlighting engine for the given buffer with the 831--- given client. 832--- 833---@deprecated 834---@param bufnr (integer) Buffer number, or `0` for current buffer 835---@param client_id (integer) The ID of the |vim.lsp.Client| 836function M . stop ( bufnr , client_id ) 837vim . deprecate ( 'vim.lsp.semantic_tokens.stop' , 'vim.lsp.semantic_tokens.enable(false)' , '0.13.0' ) 838M . enable ( false , { bufnr =bufnr , client_id =client_id } ) 839end 840 841--- Query whether semantic tokens is enabled in the {filter}ed scope 842---@param filter? vim.lsp.capability.enable.Filter 843function M . is_enabled ( filter ) 844return vim . lsp . _capability . is_enabled ( 'semantic_tokens' , filter ) 845end 846 847--- Enables or disables semantic tokens for the {filter}ed scope. 848--- 849--- To "toggle", pass the inverse of `is_enabled()`: 850--- 851--- ```lua 852--- vim.lsp.semantic_tokens.enable(not vim.lsp.semantic_tokens.is_enabled()) 853--- ``` 854--- 855---@param enable? boolean true/nil to enable, false to disable 856---@param filter? vim.lsp.capability.enable.Filter 857function M . enable ( enable , filter ) 858vim . lsp . _capability . enable ( 'semantic_tokens' , enable , filter ) 859end 860 861--- @nodoc 862--- @class STTokenRangeInspect : STTokenRange 863--- @field client_id integer 864 865--- Return the semantic token(s) at the given position. 866--- If called without arguments, returns the token under the cursor. 867--- 868---@param bufnr integer|nil Buffer number (0 for current buffer, default) 869---@param row integer|nil Position row (default cursor position) 870---@param col integer|nil Position column (default cursor position) 871--- 872---@return STTokenRangeInspect[]|nil (table|nil) List of tokens at position. Each token has 873--- the following fields: 874--- - line (integer) line number, 0-based 875--- - start_col (integer) start column, 0-based 876--- - end_line (integer) end line number, 0-based 877--- - end_col (integer) end column, 0-based 878--- - type (string) token type as string, e.g. "variable" 879--- - modifiers (table) token modifiers as a set. E.g., { static = true, readonly = true } 880--- - client_id (integer) 881function M . get_at_pos ( bufnr , row , col ) 882bufnr =vim . _resolve_bufnr ( bufnr ) 883 884local highlighter =STHighlighter . active [ bufnr ] 885if not highlighter then 886return 887end 888 889if row == nil or col == nil then 890local cursor =api . nvim_win_get_cursor ( 0 ) 891row , col =cursor [ 1 ] - 1 , cursor [ 2 ] 892end 893 894local position ={ row , col , row , col } 895 896local tokens ={} --- @type STTokenRangeInspect[] 897for client_id , client in pairs ( highlighter . client_state ) do 898local highlights =client . current_result . highlights 899if highlights then 900local idx =vim . list . bisect ( highlights , { end_line =row } , { 901key =function ( highlight ) 902return highlight . end_line 903end , 904} ) 905for i =idx , # highlights do 906local token =highlights [ i ] 907--- @cast token STTokenRangeInspect 908 909if token . line > row then 910break 911end 912 913if 914Range . contains ( { token . line , token . start_col , token . end_line , token . end_col } , position ) 915then 916token . client_id =client_id 917tokens [ # tokens + 1 ] =token 918end 919end 920end 921end 922return tokens 923end 924 925--- Force a refresh of all semantic tokens 926--- 927--- Only has an effect if the buffer is currently active for semantic token 928--- highlighting (|vim.lsp.semantic_tokens.enable()| has been called for it) 929--- 930---@param bufnr (integer|nil) filter by buffer. All buffers if nil, current 931--- buffer if 0 932function M . force_refresh ( bufnr ) 933vim . validate ( 'bufnr' , bufnr , 'number' , true ) 934 935local buffers =bufnr == nil and vim . tbl_keys ( STHighlighter . active ) 936or { vim . _resolve_bufnr ( bufnr ) } 937 938for _ , buffer in ipairs ( buffers ) do 939local highlighter =STHighlighter . active [ buffer ] 940if highlighter then 941for client_id , _ in pairs ( highlighter . client_state ) do 942highlighter : reset ( client_id ) 943highlighter : send_request ( client_id ) 944end 945end 946end 947end 948 949--- @class vim.lsp.semantic_tokens.highlight_token.Opts 950--- @inlinedoc 951--- 952--- Priority for the applied extmark. 953--- (Default: `vim.hl.priorities.semantic_tokens + 3`) 954--- @field priority? integer 955 956--- Highlight a semantic token. 957--- 958--- Apply an extmark with a given highlight group for a semantic token. The 959--- mark will be deleted by the semantic token engine when appropriate; for 960--- example, when the LSP sends updated tokens. This function is intended for 961--- use inside |LspTokenUpdate| callbacks. 962---@param token (table) Semantic token, provided as `ev.data.token` in |LspTokenUpdate| 963---@param bufnr (integer) Buffer to highlight, or `0` for current buffer. 964---@param client_id (integer) ID of the |vim.lsp.Client| 965---@param hl_group (string) Highlight group name 966---@param opts? vim.lsp.semantic_tokens.highlight_token.Opts Optional parameters: 967function M . highlight_token ( token , bufnr , client_id , hl_group , opts ) 968bufnr =vim . _resolve_bufnr ( bufnr ) 969local highlighter =STHighlighter . active [ bufnr ] 970if not highlighter then 971return 972end 973 974local state =highlighter . client_state [ client_id ] 975if not state then 976return 977end 978 979local priority =opts and opts . priority or vim . hl . priorities . semantic_tokens + 3 980 981set_mark ( bufnr , state . namespace , token , hl_group , priority ) 982end 983 984--- |lsp-handler| for the method `workspace/semanticTokens/refresh` 985--- 986--- Refresh requests are sent by the server to indicate a project-wide change 987--- that requires all tokens to be re-requested by the client. This handler will 988--- invalidate the current results of all buffers and automatically kick off a 989--- new request for buffers that are displayed in a window. For those that aren't, 990--- the BufWinEnter event should take care of it next time it's displayed. 991---@param err lsp.ResponseError? 992---@param ctx lsp.HandlerContext 993function M . _refresh ( err , _ , ctx ) 994if err then 995return vim . NIL 996end 997 998for bufnr , highlighter in pairs ( STHighlighter . active ) do 999if highlighter . client_state [ ctx . client_id ] then 1000highlighter : mark_dirty ( ctx . client_id ) 1001 1002if not vim . tbl_isempty ( vim . fn . win_findbuf ( bufnr )) then 1003-- some LSPs send rapid fire refresh notifications, so we'll debounce them with debounce_request() 1004highlighter : debounce_request ( ctx . client_id ) 1005end 1006end 1007end 1008 1009return vim . NIL 1010end 1011 1012-- Semantic tokens is enabled by default 1013M . enable ( true ) 1014 1015--- for testing only! there is no guarantee of API stability with this! 1016--- 1017---@private 1018M . __STHighlighter =STHighlighter 1019 1020return M