robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
aa1d8a2702
master
1local protocol =require ( 'vim.lsp.protocol' ) 2local sync =require ( 'vim.lsp.sync' ) 3local util =require ( 'vim.lsp.util' ) 4 5local api =vim . api 6local uv =vim . uv 7 8local M ={} 9 10--- LSP has 3 different sync modes: 11--- - None (Servers will read the files themselves when needed) 12--- - Full (Client sends the full buffer content on updates) 13--- - Incremental (Client sends only the changed parts) 14--- 15--- Changes are tracked per buffer. 16--- A buffer can have multiple clients attached and each client needs to send the changes 17--- To minimize the amount of changesets to compute, computation is grouped: 18--- 19--- None: One group for all clients 20--- Full: One group for all clients 21--- Incremental: One group per `position_encoding` 22--- 23--- Sending changes can be debounced per buffer. To simplify the implementation the 24--- smallest debounce interval is used and we don't group clients by different intervals. 25--- 26--- @class vim.lsp.CTGroup 27--- @field sync_kind integer TextDocumentSyncKind, considers config.flags.allow_incremental_sync 28--- @field position_encoding "utf-8"|"utf-16"|"utf-32" 29--- 30--- @class vim.lsp.CTBufferState 31--- @field name string name of the buffer 32--- @field lines string[] snapshot of buffer lines from last didChange 33--- @field lines_tmp string[] 34--- @field pending_changes table[] List of debounced changes in incremental sync mode 35--- @field timer? uv.uv_timer_t uv_timer 36--- @field last_flush? number uv.hrtime of the last flush/didChange-notification 37--- @field needs_flush boolean true if buffer updates haven't been sent to clients/servers yet 38--- @field refs integer how many clients are using this group 39--- 40--- @class vim.lsp.CTGroupState 41--- @field buffers table<integer,vim.lsp.CTBufferState> 42--- @field debounce integer debounce duration in ms 43--- @field clients table<integer, vim.lsp.Client> clients using this state. {client_id, client} 44 45---@param group vim.lsp.CTGroup 46---@return string 47local function group_key ( group ) 48if group . sync_kind == protocol . TextDocumentSyncKind . Incremental then 49return tostring ( group . sync_kind ) .. '\0' .. group . position_encoding 50end 51return tostring ( group . sync_kind ) 52end 53 54---@type table<vim.lsp.CTGroup,vim.lsp.CTGroupState> 55local state_by_group =setmetatable ( {} , { 56__index =function ( tbl , k ) 57return rawget ( tbl , group_key ( k )) 58end , 59__newindex =function ( tbl , k , v ) 60rawset ( tbl , group_key ( k ), v ) 61end , 62} ) 63 64---@param client vim.lsp.Client 65---@return vim.lsp.CTGroup 66local function get_group ( client ) 67local allow_inc_sync =vim . nonnil ( client . flags . allow_incremental_sync , true ) 68local change_capability =vim . tbl_get ( client . server_capabilities , 'textDocumentSync' , 'change' ) 69local sync_kind =change_capability or protocol . TextDocumentSyncKind . None 70if not allow_inc_sync and change_capability == protocol . TextDocumentSyncKind . Incremental then 71sync_kind =protocol . TextDocumentSyncKind . Full 72end 73return { 74sync_kind =sync_kind , 75position_encoding =client . offset_encoding , 76} 77end 78 79---@param state vim.lsp.CTBufferState 80---@param encoding 'utf-8'|'utf-16'|'utf-32' 81---@param bufnr integer 82---@param firstline integer 83---@param lastline integer 84---@param new_lastline integer 85---@return lsp.TextDocumentContentChangeEvent 86local function incremental_changes ( state , encoding , bufnr , firstline , lastline , new_lastline ) 87local prev_lines =state . lines 88local curr_lines =state . lines_tmp 89 90local changed_lines =api . nvim_buf_get_lines ( bufnr , firstline , new_lastline , true ) 91for i =1 , firstline do 92curr_lines [ i ] =prev_lines [ i ] 93end 94for i =firstline + 1 , new_lastline do 95curr_lines [ i ] =changed_lines [ i - firstline ] 96end 97for i =lastline + 1 , # prev_lines do 98curr_lines [ i - lastline + new_lastline ] =prev_lines [ i ] 99end 100if vim . tbl_isempty ( curr_lines ) then 101-- Can happen when deleting the entire contents of a buffer, see https://github.com/neovim/neovim/issues/16259. 102curr_lines [ 1 ] ='' 103end 104 105local line_ending =vim . lsp . _buf_get_line_ending ( bufnr ) 106local incremental_change =sync . compute_diff ( 107prev_lines , 108curr_lines , 109firstline , 110lastline , 111new_lastline , 112encoding , 113line_ending 114) 115 116-- Double-buffering of lines tables is used to reduce the load on the garbage collector. 117-- At this point the prev_lines table is useless, but its internal storage has already been allocated, 118-- so let's keep it around for the next didChange event, in which it will become the next 119-- curr_lines table. Note that setting elements to nil doesn't actually deallocate slots in the 120-- internal storage - it merely marks them as free, for the GC to deallocate them. 121for i in ipairs ( prev_lines ) do 122prev_lines [ i ] =nil 123end 124state . lines =curr_lines 125state . lines_tmp =prev_lines 126 127return incremental_change 128end 129 130---@param client vim.lsp.Client 131---@param bufnr integer 132function M . init ( client , bufnr ) 133local group =get_group ( client ) 134local state =state_by_group [ group ] 135if state then 136state . debounce =math . min ( state . debounce , client . flags . debounce_text_changes or 150 ) 137state . clients [ client . id ] =client 138else 139state ={ 140buffers ={} , 141debounce =client . flags . debounce_text_changes or 150 , 142clients ={ 143[ client . id ] =client , 144} , 145} 146state_by_group [ group ] =state 147end 148local buf_state =state . buffers [ bufnr ] 149if buf_state then 150buf_state . refs =buf_state . refs + 1 151else 152buf_state ={ 153name =api . nvim_buf_get_name ( bufnr ), 154lines ={} , 155lines_tmp ={} , 156pending_changes ={} , 157needs_flush =false , 158refs =1 , 159} 160state . buffers [ bufnr ] =buf_state 161if group . sync_kind == protocol . TextDocumentSyncKind . Incremental then 162buf_state . lines =api . nvim_buf_get_lines ( bufnr , 0 , - 1 , true ) 163end 164end 165end 166 167--- Sends didOpen/didClose/didSave to all client groups. 168--- 169--- @param bufnr integer 170function M . _send_did_save ( bufnr ) 171--- Groups of the clients attached to `bufnr`, along with those clients. 172--- Only clients attached to the buffer must be notified. 173local groups ={} ---@type table<string,{group: vim.lsp.CTGroup, clients: vim.lsp.Client[]}> 174for _ , client in pairs ( vim . lsp . get_clients ( { bufnr =bufnr } )) do 175local group =get_group ( client ) 176local key =group_key ( group ) 177local entry =groups [ key ] 178if not entry then 179entry ={ group =group , clients ={} } 180groups [ key ] =entry 181end 182table . insert ( entry . clients , client ) 183end 184 185local uri =vim . uri_from_bufnr ( bufnr ) 186local text =vim . func . _memoize ( 'concat' , vim . lsp . _buf_get_full_text ) 187 188-- Send didOpen/didClose/didSave to all client groups. 189for _ , entry in pairs ( groups ) do 190local name =api . nvim_buf_get_name ( bufnr ) 191local state =state_by_group [ entry . group ] 192local buf_state =state . buffers [ bufnr ] or {} 193local old_name =buf_state . name 194buf_state . name =name 195 196for _ , client in ipairs ( entry . clients ) do 197if old_name and name ~= old_name then 198client : notify ( 'textDocument/didClose' , { 199textDocument ={ 200uri =vim . uri_from_fname ( old_name ), 201} , 202} , bufnr ) 203client : notify ( 'textDocument/didOpen' , { 204textDocument ={ 205version =0 , 206uri =uri , 207languageId =client . get_language_id ( bufnr , vim . bo [ bufnr ]. filetype ), 208text =vim . lsp . _buf_get_full_text ( bufnr ), 209} , 210} , bufnr ) 211util . buf_versions [ bufnr ] =0 212end 213local save_capability =vim . tbl_get ( client . server_capabilities , 'textDocumentSync' , 'save' ) 214if save_capability then 215local included_text --- @type string? 216if type ( save_capability ) == 'table' and save_capability . includeText then 217included_text =text ( bufnr ) 218end 219client : notify ( 'textDocument/didSave' , { 220textDocument ={ 221uri =uri , 222} , 223text =included_text , 224} , bufnr ) 225else 226M . flush ( client , bufnr ) 227end 228end 229end 230end 231 232---@param buf_state vim.lsp.CTBufferState 233local function reset_timer ( buf_state ) 234local timer =buf_state . timer 235if timer then 236buf_state . timer =nil 237if not timer : is_closing () then 238timer : stop () 239timer : close () 240end 241end 242end 243 244--- @param client vim.lsp.Client 245--- @param bufnr integer 246function M . reset_buf ( client , bufnr ) 247M . flush ( client , bufnr ) 248local state =state_by_group [ get_group ( client )] 249if not state then 250return 251end 252local buf_state =state . buffers [ bufnr ] 253if not buf_state then 254return 255end 256buf_state . refs =buf_state . refs - 1 257assert ( buf_state . refs >= 0 , 'refcount on buffer state must not get negative' ) 258if buf_state . refs == 0 then 259state . buffers [ bufnr ] =nil 260reset_timer ( buf_state ) 261end 262end 263 264--- @param client vim.lsp.Client 265function M . reset ( client ) 266local state =state_by_group [ get_group ( client )] 267if not state then 268return 269end 270state . clients [ client . id ] =nil 271if vim . tbl_count ( state . clients ) == 0 then 272for _ , buf_state in pairs ( state . buffers ) do 273reset_timer ( buf_state ) 274end 275state . buffers ={} 276end 277end 278 279-- Adjust debounce time by taking time of last didChange notification into 280-- consideration. If the last didChange happened more than `debounce` time ago, 281-- debounce can be skipped and otherwise maybe reduced. 282-- 283-- This turns the debounce into a kind of client rate limiting 284-- 285---@param debounce integer 286---@param buf_state vim.lsp.CTBufferState 287---@return number 288local function next_debounce ( debounce , buf_state ) 289if debounce == 0 then 290return 0 291end 292local ns_to_ms =0.000001 293if not buf_state . last_flush then 294return debounce 295end 296local now =uv . hrtime () 297local ms_since_last_flush =( now - buf_state . last_flush ) * ns_to_ms 298return math . max ( debounce - ms_since_last_flush , 0 ) 299end 300 301---@param bufnr integer 302---@param sync_kind integer protocol.TextDocumentSyncKind 303---@param state vim.lsp.CTGroupState 304---@param buf_state vim.lsp.CTBufferState 305local function send_changes ( bufnr , sync_kind , state , buf_state ) 306if not buf_state . needs_flush then 307return 308end 309buf_state . last_flush =uv . hrtime () 310buf_state . needs_flush =false 311 312if not api . nvim_buf_is_valid ( bufnr ) then 313buf_state . pending_changes ={} 314return 315end 316 317local changes --- @type lsp.TextDocumentContentChangeEvent[] 318if sync_kind == protocol . TextDocumentSyncKind . None then 319return 320elseif sync_kind == protocol . TextDocumentSyncKind . Incremental then 321changes =buf_state . pending_changes 322buf_state . pending_changes ={} 323else 324changes ={ 325{ text =vim . lsp . _buf_get_full_text ( bufnr ) } , 326} 327end 328local uri =vim . uri_from_bufnr ( bufnr ) 329for _ , client in pairs ( state . clients ) do 330if not client : is_stopped () and vim . lsp . buf_is_attached ( bufnr , client . id ) then 331client : notify ( 'textDocument/didChange' , { 332textDocument ={ 333uri =uri , 334version =util . buf_versions [ bufnr ], 335} , 336contentChanges =changes , 337} , bufnr ) 338end 339end 340end 341 342--- @param bufnr integer 343--- @param firstline integer 344--- @param lastline integer 345--- @param new_lastline integer 346--- @param group vim.lsp.CTGroup 347local function send_changes_for_group ( bufnr , firstline , lastline , new_lastline , group ) 348local state =state_by_group [ group ] 349if not state then 350error ( 351string . format ( 352'changetracking.init must have been called for all LSP clients. group=%s states=%s' , 353vim . inspect ( group ), 354vim . inspect ( vim . tbl_keys ( state_by_group )) 355) 356) 357end 358local buf_state =state . buffers [ bufnr ] 359if not buf_state then 360return 361end 362buf_state . needs_flush =true 363reset_timer ( buf_state ) 364local debounce =next_debounce ( state . debounce , buf_state ) 365if group . sync_kind == protocol . TextDocumentSyncKind . Incremental then 366-- This must be done immediately and cannot be delayed 367-- The contents would further change and startline/endline may no longer fit 368local changes =incremental_changes ( 369buf_state , 370group . position_encoding , 371bufnr , 372firstline , 373lastline , 374new_lastline 375) 376table . insert ( buf_state . pending_changes , changes ) 377end 378if debounce == 0 then 379send_changes ( bufnr , group . sync_kind , state , buf_state ) 380else 381local timer =assert ( uv . new_timer (), 'Must be able to create timer' ) 382buf_state . timer =timer 383timer : start ( 384math . floor ( debounce ), 3850 , 386vim . schedule_wrap ( function () 387reset_timer ( buf_state ) 388send_changes ( bufnr , group . sync_kind , state , buf_state ) 389end ) 390) 391end 392end 393 394--- @param bufnr integer 395--- @param firstline integer 396--- @param lastline integer 397--- @param new_lastline integer 398function M . send_changes ( bufnr , firstline , lastline , new_lastline ) 399local groups ={} ---@type table<string,vim.lsp.CTGroup> 400for _ , client in pairs ( vim . lsp . get_clients ( { bufnr =bufnr } )) do 401local group =get_group ( client ) 402groups [ group_key ( group )] =group 403end 404for _ , group in pairs ( groups ) do 405send_changes_for_group ( bufnr , firstline , lastline , new_lastline , group ) 406end 407end 408 409--- Flushes any outstanding change notification. 410---@param client vim.lsp.Client 411---@param bufnr? integer 412function M . flush ( client , bufnr ) 413local group =get_group ( client ) 414local state =state_by_group [ group ] 415if not state then 416return 417end 418if bufnr then 419local buf_state =state . buffers [ bufnr ] or {} 420reset_timer ( buf_state ) 421send_changes ( bufnr , group . sync_kind , state , buf_state ) 422else 423for buf , buf_state in pairs ( state . buffers ) do 424reset_timer ( buf_state ) 425send_changes ( buf , group . sync_kind , state , buf_state ) 426end 427end 428end 429 430return M