robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
aa1d8a2702
master
1local ts =vim . treesitter 2 3local Range =require ( 'vim.treesitter._range' ) 4 5local api =vim . api 6local nvim_on =require ( 'vim._core.util' ). nvim_on 7 8---Treesitter folding is done in two steps: 9---(1) compute the fold levels with the syntax tree and cache the result (`compute_folds_levels`) 10---(2) evaluate foldexpr for each window, which reads from the cache (`foldupdate`) 11---@class TS.FoldInfo 12--- 13---@field levels string[] the cached foldexpr result for each line 14---@field levels0 integer[] the cached raw fold levels 15--- 16---The range edited since the last invocation of the callback scheduled in on_bytes. 17---Should compute fold levels in this range. 18---@field on_bytes_range? Range2 19--- 20---The range on which to evaluate foldexpr. 21---When in insert mode, the evaluation is deferred to InsertLeave. 22---@field foldupdate_range? Range2 23--- 24---The treesitter parser associated with this buffer. 25---@field parser? vim.treesitter.LanguageTree 26local FoldInfo ={} 27FoldInfo . __index =FoldInfo 28 29---@private 30---@param buf integer 31function FoldInfo . new ( buf ) 32return setmetatable ( { 33levels0 ={} , 34levels ={} , 35parser =ts . get_parser ( buf , nil ), 36} , FoldInfo ) 37end 38 39---@package 40---@param srow integer 41---@param erow integer 0-indexed, exclusive 42function FoldInfo : remove_range ( srow , erow ) 43vim . _list_remove ( self . levels , srow + 1 , erow ) 44vim . _list_remove ( self . levels0 , srow + 1 , erow ) 45end 46 47---@package 48---@param srow integer 49---@param erow integer 0-indexed, exclusive 50function FoldInfo : add_range ( srow , erow ) 51vim . _list_insert ( self . levels , srow + 1 , erow , - 1 ) 52vim . _list_insert ( self . levels0 , srow + 1 , erow , - 1 ) 53end 54 55---@param range Range2 56---@param srow integer 57---@param erow_old integer 58---@param erow_new integer 0-indexed, exclusive 59local function edit_range ( range , srow , erow_old , erow_new ) 60range [ 1 ] =math . min ( srow , range [ 1 ]) 61if erow_old <= range [ 2 ] then 62range [ 2 ] =range [ 2 ] + ( erow_new - erow_old ) 63end 64range [ 2 ] =math . max ( range [ 2 ], erow_new ) 65end 66 67-- TODO(lewis6991): Setup a decor provider so injections folds can be parsed 68-- as the window is redrawn 69---@param bufnr integer 70---@param info TS.FoldInfo 71---@param srow integer? 72---@param erow integer? 0-indexed, exclusive 73---@param callback function? 74local function compute_folds_levels ( bufnr , info , srow , erow , callback ) 75srow =srow or 0 76erow =erow or api . nvim_buf_line_count ( bufnr ) 77 78local parser =info . parser 79if 80not parser 81-- Parsing an empty buffer results in problems with the parsing state, 82-- resulting in both a broken highlighter and foldexpr. 83or api . nvim_buf_line_count ( bufnr ) == 1 84and api . nvim_buf_call ( bufnr , function () 85return vim . fn . line2byte ( 1 ) <= 0 86end ) 87then 88return 89end 90 91parser : parse ( nil , function ( _ , trees ) 92if not trees then 93return 94end 95 96local enter_counts ={} ---@type table<integer, integer> 97local leave_counts ={} ---@type table<integer, integer> 98local prev_start =- 1 99local prev_stop =- 1 100 101parser : for_each_tree ( function ( tree , ltree ) 102local query =ts . query . get ( ltree : lang (), 'folds' ) 103if not query then 104return 105end 106 107-- Collect folds starting from srow - 1, because we should first subtract the folds that end at 108-- srow - 1 from the level of srow - 1 to get accurate level of srow. 109for _ , match , metadata in query : iter_matches ( tree : root (), bufnr , math . max ( srow - 1 , 0 ), erow ) do 110for id , nodes in pairs ( match ) do 111if query . captures [ id ] == 'fold' then 112local range =ts . get_range ( assert ( nodes [ 1 ]), bufnr , metadata [ id ]) 113local start , _ , stop , stop_col =Range . unpack4 ( range ) 114 115if # nodes > 1 then 116-- assumes nodes are ordered by range 117local end_range =ts . get_range ( nodes [ # nodes ], bufnr , metadata [ id ]) 118local _ , _ , end_stop , end_stop_col =Range . unpack4 ( end_range ) 119stop =end_stop 120stop_col =end_stop_col 121end 122 123if stop_col == 0 then 124stop =stop - 1 125end 126 127local fold_length =stop - start + 1 128 129-- Fold only multiline nodes that are not exactly the same as previously met folds 130-- Checking against just the previously found fold is sufficient if nodes 131-- are returned in preorder or postorder when traversing tree 132if 133fold_length > vim . wo . foldminlines and not ( start == prev_start and stop == prev_stop ) 134then 135enter_counts [ start + 1 ] =( enter_counts [ start + 1 ] or 0 ) + 1 136leave_counts [ stop + 1 ] =( leave_counts [ stop + 1 ] or 0 ) + 1 137prev_start =start 138prev_stop =stop 139end 140end 141end 142end 143end ) 144 145local nestmax =vim . wo . foldnestmax 146local level0_prev =info . levels0 [ srow ] or 0 147local leave_prev =leave_counts [ srow ] or 0 148 149-- We now have the list of fold opening and closing, fill the gaps and mark where fold start 150for lnum =srow + 1 , erow do 151local enter_line =enter_counts [ lnum ] or 0 152local leave_line =leave_counts [ lnum ] or 0 153local level0 =level0_prev - leave_prev + enter_line 154 155-- Determine if it's the start/end of a fold 156-- NB: vim's fold-expr interface does not have a mechanism to indicate that 157-- two (or more) folds start at this line, so it cannot distinguish between 158-- ( \n ( \n )) \n (( \n ) \n ) 159-- versus 160-- ( \n ( \n ) \n ( \n ) \n ) 161-- Both are represented by ['>1', '>2', '2', '>2', '2', '1'], and 162-- vim interprets as the second case. 163-- If it did have such a mechanism, (clamped - clamped_prev) 164-- would be the correct number of starts to pass on. 165local adjusted =level0 ---@type integer 166local prefix ='' 167if enter_line > 0 then 168prefix ='>' 169if leave_line > 0 then 170-- If this line ends a fold f1 and starts a fold f2, then move f1's end to the previous line 171-- so that f2 gets the correct level on this line. This may reduce the size of f1 below 172-- foldminlines, but we don't handle it for simplicity. 173--- @type integer avoid flaky error 174adjusted =level0 - leave_line 175leave_line =0 176end 177end 178 179-- Clamp at foldnestmax. 180local clamped =adjusted 181if adjusted > nestmax then 182prefix ='' 183clamped =nestmax 184end 185 186-- Record the "real" level, so that it can be used as "base" of later compute_folds_levels(). 187info . levels0 [ lnum ] =adjusted 188info . levels [ lnum ] =prefix .. tostring ( clamped ) 189 190leave_prev =leave_line 191level0_prev =adjusted 192end 193 194if callback then 195callback () 196end 197end ) 198end 199 200local M ={} 201 202---@type table<integer,TS.FoldInfo> 203local foldinfos ={} 204 205local group =api . nvim_create_augroup ( 'nvim.treesitter.fold' ) 206 207--- Update the folds in the windows that contain the buffer and use expr foldmethod (assuming that 208--- the user doesn't use different foldexpr for the same buffer). 209--- 210--- Nvim usually automatically updates folds when text changes, but it doesn't work here because 211--- FoldInfo update is scheduled. So we do it manually. 212---@package 213---@param srow integer 214---@param erow integer 0-indexed, exclusive 215---@param bufnr integer 216function FoldInfo : foldupdate ( bufnr , srow , erow ) 217if self . foldupdate_range then 218edit_range ( self . foldupdate_range , srow , erow , erow ) 219else 220self . foldupdate_range ={ srow , erow } 221end 222 223if api . nvim_get_mode (). mode : match ( '^i' ) then 224-- foldUpdate() is guarded in insert mode. So update folds on InsertLeave 225if # ( api . nvim_get_autocmds ( { 226group =group , 227buf =bufnr , 228} )) > 0 then 229return 230end 231nvim_on ( 'InsertLeave' , group , { buf =bufnr , once =true } , function () 232self : do_foldupdate ( bufnr ) 233end ) 234return 235end 236 237self : do_foldupdate ( bufnr ) 238end 239 240---@package 241---@param bufnr integer 242function FoldInfo : do_foldupdate ( bufnr ) 243-- InsertLeave is not executed when <C-C> is used for exiting the insert mode, leaving 244-- do_foldupdate untouched. If another execution of foldupdate consumes foldupdate_range, the 245-- InsertLeave do_foldupdate gets nil foldupdate_range. In that case, skip the update. This is 246-- correct because the update that consumed the range must have incorporated the range that 247-- InsertLeave meant to update. 248if not self . foldupdate_range then 249return 250end 251 252local srow , erow =self . foldupdate_range [ 1 ], self . foldupdate_range [ 2 ] 253self . foldupdate_range =nil 254for _ , win in ipairs ( vim . fn . win_findbuf ( bufnr )) do 255if vim . wo [ win ]. foldmethod == 'expr' then 256vim . _foldupdate ( win , srow , erow ) 257end 258end 259end 260 261--- Schedule a function only if bufnr is loaded. 262--- We schedule fold level computation for the following reasons: 263--- * queries seem to use the old buffer state in on_bytes for some unknown reason; 264--- * to avoid textlock; 265--- * to avoid infinite recursion: 266--- compute_folds_levels → parse → _do_callback → on_changedtree → compute_folds_levels. 267---@param bufnr integer 268---@param fn function 269local function schedule_if_loaded ( bufnr , fn ) 270vim . schedule ( function () 271if not api . nvim_buf_is_loaded ( bufnr ) then 272return 273end 274fn () 275end ) 276end 277 278---@param bufnr integer 279---@param tree_changes Range4[] 280local function on_changedtree ( bufnr , tree_changes ) 281schedule_if_loaded ( bufnr , function () 282-- Buffer reload clears `foldinfos[bufnr]`, which may still be nil when callback is invoked. 283local foldinfo =foldinfos [ bufnr ] 284if not foldinfo then 285return 286end 287 288local srow_upd , erow_upd ---@type integer?, integer? 289local max_erow =api . nvim_buf_line_count ( bufnr ) 290-- TODO(ribru17): Replace this with a proper .all() awaiter once #19624 is resolved 291local iterations =0 292for _ , change in ipairs ( tree_changes ) do 293local srow , _ , erow , ecol =Range . unpack4 ( change ) 294-- If a parser doesn't have any ranges explicitly set, treesitter will 295-- return a range with end_row and end_bytes with a value of UINT32_MAX, 296-- which is represented as -1 on 32-bit platforms, so clip end_row to 297-- the max buffer line. 298-- TODO(lewis6991): Handle this generally 299if erow > max_erow or erow < 0 then 300erow =max_erow 301elseif ecol > 0 then 302erow =erow + 1 303end 304-- Start from `srow - foldminlines`, because this edit may have shrunken the fold below limit. 305srow =math . max ( srow - vim . wo . foldminlines , 0 ) 306srow_upd =srow_upd and math . min ( srow_upd , srow ) or srow 307erow_upd =erow_upd and math . max ( erow_upd , erow ) or erow 308compute_folds_levels ( bufnr , foldinfo , srow , erow , function () 309iterations =iterations + 1 310if iterations == # tree_changes then 311foldinfo : foldupdate ( bufnr , srow_upd , erow_upd ) 312end 313end ) 314end 315end ) 316end 317 318---@param bufnr integer 319---@param start_row integer 320---@param old_row integer 321---@param old_col integer 322---@param new_row integer 323---@param new_col integer 324---@param start_col integer 325local function on_bytes ( bufnr , start_row , start_col , old_row , old_col , new_row , new_col ) 326-- Buffer reload clears `foldinfos[bufnr]`, which may still be nil when callback is invoked. 327local foldinfo =foldinfos [ bufnr ] 328if not foldinfo then 329return 330end 331 332-- extend the end to fully include the range 333local end_row_old =start_row + old_row + 1 334local end_row_new =start_row + new_row + 1 335 336if new_row ~= old_row then 337-- foldexpr can be evaluated before the scheduled callback is invoked. So it may observe the 338-- outdated levels, which may spuriously open the folds that didn't change. So we should shift 339-- folds as accurately as possible. For this to be perfectly accurate, we should track the 340-- actual TSNodes that account for each fold, and compare the node's range with the edited 341-- range. But for simplicity, we just check whether the start row is completely removed (e.g., 342-- `dd`) or shifted (e.g., `o`). 343if new_row < old_row then 344if start_col == 0 and new_row == 0 and new_col == 0 then 345foldinfo : remove_range ( start_row , start_row + ( end_row_old - end_row_new )) 346else 347foldinfo : remove_range ( end_row_new , end_row_old ) 348end 349else 350if start_col == 0 and old_row == 0 and old_col == 0 then 351foldinfo : add_range ( start_row , start_row + ( end_row_new - end_row_old )) 352else 353foldinfo : add_range ( end_row_old , end_row_new ) 354end 355end 356 357if foldinfo . on_bytes_range then 358edit_range ( foldinfo . on_bytes_range , start_row , end_row_old , end_row_new ) 359else 360foldinfo . on_bytes_range ={ start_row , end_row_new } 361end 362if foldinfo . foldupdate_range then 363edit_range ( foldinfo . foldupdate_range , start_row , end_row_old , end_row_new ) 364end 365 366-- This callback must not use on_bytes arguments, because they can be outdated when the callback 367-- is invoked. For example, `J` with non-zero count triggers multiple on_bytes before executing 368-- the scheduled callback. So we accumulate the edited ranges in `on_bytes_range`. 369schedule_if_loaded ( bufnr , function () 370if not ( foldinfo . on_bytes_range and foldinfos [ bufnr ]) then 371return 372end 373local srow , erow =foldinfo . on_bytes_range [ 1 ], foldinfo . on_bytes_range [ 2 ] 374foldinfo . on_bytes_range =nil 375-- Start from `srow - foldminlines`, because this edit may have shrunken the fold below limit. 376srow =math . max ( srow - vim . wo . foldminlines , 0 ) 377compute_folds_levels ( bufnr , foldinfo , srow , erow , function () 378foldinfo : foldupdate ( bufnr , srow , erow ) 379end ) 380end ) 381end 382end 383 384local registered_cbs ={} ---@type table<integer, boolean> 385 386---@param lnum integer|nil 387---@return string 388function M . foldexpr ( lnum ) 389lnum =lnum or vim . v . lnum 390local bufnr =api . nvim_get_current_buf () 391 392if not foldinfos [ bufnr ] then 393foldinfos [ bufnr ] =FoldInfo . new ( bufnr ) 394nvim_on ( { 'BufUnload' , 'VimEnter' , 'FileType' } , nil , { buf =bufnr , once =true } , function () 395foldinfos [ bufnr ] =nil 396end ) 397 398local parser =foldinfos [ bufnr ]. parser 399if not parser then 400return '0' 401end 402 403compute_folds_levels ( bufnr , foldinfos [ bufnr ]) 404 405if not registered_cbs [ bufnr ] then 406parser : register_cbs ( { 407on_changedtree =function ( tree_changes ) 408on_changedtree ( bufnr , tree_changes ) 409end , 410 411on_bytes =function ( 412_ , 413_ , 414start_row , 415start_col , 416_ , 417old_row , 418old_col , 419_ , 420new_row , 421new_col , 422_ 423) 424on_bytes ( bufnr , start_row , start_col , old_row , old_col , new_row , new_col ) 425end , 426 427on_detach =function () 428foldinfos [ bufnr ] =nil 429registered_cbs [ bufnr ] =nil 430end , 431} ) 432 433registered_cbs [ bufnr ] =true 434end 435end 436 437return foldinfos [ bufnr ]. levels [ lnum ] or '0' 438end 439 440nvim_on ( 'OptionSet' , group , { 441pattern ={ 'foldminlines' , 'foldnestmax' } , 442desc ='Refresh treesitter folds' , 443} , function () 444local buf =api . nvim_get_current_buf () 445local bufs =vim . v . option_type == 'global' and vim . tbl_keys ( foldinfos ) 446or foldinfos [ buf ] and { buf } 447or {} 448for _ , bufnr in ipairs ( bufs ) do 449local foldinfo =FoldInfo . new ( bufnr ) 450foldinfos [ bufnr ] =foldinfo 451api . nvim_buf_call ( bufnr , function () 452compute_folds_levels ( bufnr , foldinfo , nil , nil , function () 453-- FileType/BufUnload can clear or replace the fold state while this 454-- async parse is in flight. Ignore callbacks for stale generations. 455if foldinfos [ bufnr ] ~= foldinfo then 456return 457end 458foldinfo : foldupdate ( bufnr , 0 , api . nvim_buf_line_count ( bufnr )) 459end ) 460end ) 461end 462end ) 463return M