robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
aa1d8a2702
master
1-- Functions shared by Nvim and its test-suite. 2-- 3-- These are "pure" lua functions not depending of the state of the editor. 4-- Thus they should always be available whenever nvim-related lua code is run, 5-- regardless if it is code in the editor itself, or in worker threads/processes, 6-- or the test suite. (Eventually the test suite will be run in a worker process, 7-- so this wouldn't be a separate case to consider) 8 9---@nodoc 10_G . vim =_G . vim or {} --[[@as table]] 11-- TODO(lewis6991): better fix for flaky luals 12 13---@generic T 14---@param orig T 15---@param cache? table<any,any> 16---@return T 17local function deepcopy ( orig , cache ) 18if orig == vim . NIL then 19return vim . NIL 20elseif type ( orig ) == 'userdata' or type ( orig ) == 'thread' then 21error ( 'Cannot deepcopy object of type ' .. type ( orig )) 22elseif type ( orig ) ~= 'table' then 23return orig 24end 25 26--- @cast orig table<any,any> 27 28if cache and cache [ orig ] then 29return cache [ orig ] 30end 31 32local copy ={} --- @type table<any,any> 33 34if cache then 35cache [ orig ] =copy 36end 37 38for k , v in pairs ( orig ) do 39copy [ deepcopy ( k , cache )] =deepcopy ( v , cache ) 40end 41 42return setmetatable ( copy , getmetatable ( orig )) 43end 44 45--- Returns a deep copy of the given object. Non-table objects are copied as 46--- in a typical Lua assignment, whereas table objects are copied recursively. 47--- Functions are naively copied, so functions in the copied table point to the 48--- same functions as those in the input table. Userdata and threads are not 49--- copied and will throw an error. 50--- 51--- Note: `noref=true` is much more performant on tables with unique table 52--- fields, while `noref=false` is more performant on tables that reuse table 53--- fields. 54--- 55---@generic T: table 56---@param orig T Table to copy 57---@param noref? boolean 58--- When `false` (default) a contained table is only copied once and all 59--- references point to this single copy. When `true` every occurrence of a 60--- table results in a new copy. This also means that a cyclic reference can 61--- cause `deepcopy()` to fail. 62---@return T Table of copied keys and (nested) values. 63function vim . deepcopy ( orig , noref ) 64return deepcopy ( orig , not noref and {} or nil ) 65end 66 67--- Returns a shallow copy of `orig`. 68--- 69--- Non-table values are returned as-is. Table keys and values are copied by 70--- reference, and the original metatable is preserved. Use |vim.deepcopy()| 71--- for a recursive copy. 72--- 73--- @nodoc 74--- @generic T 75--- @param orig T 76--- @return T 77function vim . _copy ( orig ) 78if type ( orig ) ~= 'table' then 79return orig 80end 81 82--- @cast orig table<any,any> 83 84local copy ={} --- @type table<any,any> 85for k , v in pairs ( orig ) do 86copy [ k ] =v 87end 88 89return setmetatable ( copy , getmetatable ( orig )) 90end 91 92--- @class vim.gsplit.Opts 93--- @inlinedoc 94--- 95--- Use `sep` literally (as in string.find). 96--- @field plain? boolean 97--- 98--- Discard empty segments at start and end of the sequence. 99--- @field trimempty? boolean 100 101--- Gets an |iterator| that splits a string at each instance of a separator, in "lazy" fashion 102--- (as opposed to |vim.split()| which is "eager"). 103--- 104--- Example: 105--- 106--- ```lua 107--- for s in vim.gsplit(':aa::b:', ':', {plain=true}) do 108--- print(s) 109--- end 110--- ``` 111--- 112--- If you want to also inspect the separator itself (instead of discarding it), use 113--- |string.gmatch()|. Example: 114--- 115--- ```lua 116--- for word, num in ('foo111bar222'):gmatch('([^0-9]*)(%d*)') do 117--- print(('word: %s num: %s'):format(word, num)) 118--- end 119--- ``` 120--- 121--- @see |string.gmatch()| 122--- @see |vim.split()| 123--- @see |lua-pattern|s 124--- @see https://www.lua.org/pil/20.2.html 125--- @see http://lua-users.org/wiki/StringLibraryTutorial 126--- 127--- @param s string String to split 128--- @param sep string Separator or pattern 129--- @param opts? vim.gsplit.Opts Keyword arguments |kwargs|: 130--- @return fun():string? : Iterator over the split components 131function vim . gsplit ( s , sep , opts ) 132local plain --- @type boolean? 133local trimempty =false --- @type boolean? 134if type ( opts ) == 'boolean' then 135plain =opts -- For backwards compatibility. 136else 137vim . validate ( 's' , s , 'string' ) 138vim . validate ( 'sep' , sep , 'string' ) 139vim . validate ( 'opts' , opts , 'table' , true ) 140opts =opts or {} 141plain , trimempty =opts . plain , opts . trimempty 142end 143 144local start =1 145local done =false 146 147-- For `trimempty`: queue of collected segments, to be emitted at next pass. 148local segs ={} 149local empty_start =true -- Only empty segments seen so far. 150 151--- @param i integer? 152--- @param j integer? 153--- @param ... unknown 154--- @return string 155--- @return ... 156local function _pass ( i , j , ... ) 157if i then 158assert ( j ) 159assert ( j + 1 > start , 'Infinite loop detected' ) 160local seg =s : sub ( start , i - 1 ) 161start =j + 1 162return seg , ... 163else 164done =true 165return s : sub ( start ) 166end 167end 168 169return function () 170if trimempty and # segs > 0 then 171-- trimempty: Pop the collected segments. 172return table . remove ( segs ) 173elseif done or ( s == '' and sep == '' ) then 174return nil 175elseif sep == '' then 176if start == # s then 177done =true 178end 179return _pass ( start + 1 , start ) 180end 181 182local seg =_pass ( s : find ( sep , start , plain )) 183 184-- Trim empty segments from start/end. 185if trimempty and seg ~= '' then 186empty_start =false 187elseif trimempty and seg == '' then 188while not done and seg == '' do 189table . insert ( segs , 1 , '' ) 190seg =_pass ( s : find ( sep , start , plain )) 191end 192if done and seg == '' then 193return nil 194elseif empty_start then 195empty_start =false 196segs ={} 197return seg 198end 199if seg ~= '' then 200table . insert ( segs , 1 , seg ) 201end 202return table . remove ( segs ) 203end 204 205return seg 206end 207end 208 209--- Splits a string at each instance of a separator and returns the result as a table (unlike 210--- |vim.gsplit()|). 211--- 212--- Examples: 213--- 214--- ```lua 215--- split(":aa::b:", ":") --> {'','aa','','b',''} 216--- split("axaby", "ab?") --> {'','x','y'} 217--- split("x*yz*o", "*", {plain=true}) --> {'x','yz','o'} 218--- split("|x|y|z|", "|", {trimempty=true}) --> {'x', 'y', 'z'} 219--- ``` 220--- 221---@see |vim.gsplit()| 222---@see |string.gmatch()| 223--- 224---@param s string String to split 225---@param sep string Separator or pattern 226---@param opts? vim.gsplit.Opts Keyword arguments |kwargs|: 227---@return string[] : List of split components 228function vim . split ( s , sep , opts ) 229local t ={} 230for c in vim . gsplit ( s , sep , opts ) do 231table . insert ( t , c ) 232end 233return t 234end 235 236--- Return a list of all keys used in a table. 237--- However, the order of the return table of keys is not guaranteed. 238--- 239---@see From https://github.com/premake/premake-core/blob/master/src/base/table.lua 240--- 241---@generic T 242---@param t table<T, any> (table) Table 243---@return T[] : List of keys 244function vim . tbl_keys ( t ) 245vim . validate ( 't' , t , 'table' ) 246--- @cast t table<any,any> 247 248local keys ={} 249for k in pairs ( t ) do 250table . insert ( keys , k ) 251end 252return keys 253end 254 255--- Return a list of all values used in a table. 256--- However, the order of the return table of values is not guaranteed. 257--- 258---@generic T 259---@param t table<any, T> (table) Table 260---@return T[] : List of values 261function vim . tbl_values ( t ) 262vim . validate ( 't' , t , 'table' ) 263 264local values ={} 265for _ , v in 266pairs ( t --[[@as table<any,any>]] ) 267do 268table . insert ( values , v ) 269end 270return values 271end 272 273--- Applies function `fn` to all values of table `t`, in `pairs()` iteration order (which is not 274--- guaranteed to be stable, even when the data doesn't change). 275--- 276---@generic T, R 277---@param fn fun(value: T): R Function 278---@param t table<any, T> Table 279---@return table<any, R> : Table of transformed values 280function vim . tbl_map ( fn , t ) 281vim . validate ( 'fn' , fn , 'callable' ) 282vim . validate ( 't' , t , 'table' ) 283--- @cast t table<any,any> 284 285local rettab ={} --- @type table<any,any> 286for k , v in pairs ( t ) do 287rettab [ k ] =fn ( v ) 288end 289return rettab 290end 291 292--- Filter a table using a predicate function 293--- 294---@generic T 295---@param fn fun(value: T): boolean (function) Function 296---@param t table<any, T> (table) Table 297---@return T[] : Table of filtered values 298function vim . tbl_filter ( fn , t ) 299vim . validate ( 'fn' , fn , 'callable' ) 300vim . validate ( 't' , t , 'table' ) 301--- @cast t table<any,any> 302 303local rettab ={} --- @type table<any,any> 304for _ , entry in pairs ( t ) do 305if fn ( entry ) then 306rettab [ # rettab + 1 ] =entry 307end 308end 309return rettab 310end 311 312--- @class vim.tbl_contains.Opts 313--- @inlinedoc 314--- 315--- `value` is a function reference to be checked 316--- (default: false) 317--- @field predicate? boolean 318 319--- Checks if a table contains a given value, specified either directly or via 320--- a predicate that is checked for each value. 321--- 322--- Example: 323--- 324--- ```lua 325--- vim.tbl_contains({ 'a', { 'b', 'c' } }, function(v) 326--- return vim.deep_equal(v, { 'b', 'c' }) 327--- end, { predicate = true }) 328--- -- true 329--- ``` 330--- 331---@see |vim.list_contains()| for checking values in list-like tables 332--- 333---@param t table Table to check 334---@param value any Value to compare or predicate function reference 335---@param opts? vim.tbl_contains.Opts Keyword arguments |kwargs|: 336---@return boolean `true` if `t` contains `value` 337function vim . tbl_contains ( t , value , opts ) 338vim . validate ( 't' , t , 'table' ) 339vim . validate ( 'opts' , opts , 'table' , true ) 340--- @cast t table<any,any> 341 342local pred --- @type fun(v: any): boolean? 343if opts and opts . predicate then 344vim . validate ( 'value' , value , 'callable' ) 345pred =value 346else 347--- @param v any 348pred =function ( v ) 349return v == value 350end 351end 352 353for _ , v in pairs ( t ) do 354if pred ( v ) then 355return true 356end 357end 358return false 359end 360 361--- Checks if a list-like table (integer keys without gaps) contains `value`. 362--- 363---@see |vim.tbl_contains()| for checking values in general tables 364--- 365---@param t table Table to check (must be list-like, not validated) 366---@param value any Value to compare 367---@return boolean `true` if `t` contains `value` 368function vim . list_contains ( t , value ) 369vim . validate ( 't' , t , 'table' ) 370--- @cast t table<any,any> 371 372for _ , v in ipairs ( t ) do 373if v == value then 374return true 375end 376end 377return false 378end 379 380vim . list ={} 381 382---@generic T 383---@param key? string|fun(val: T): any 384---@return fun(v: T): any 385local function make_key_fn ( key ) 386vim . validate ( 'key' , key , { 'string' , 'function' } , true ) 387 388if not key then 389return function ( v ) 390return v 391end 392end 393 394if type ( key ) == 'string' then 395local field =key 396---@param v any 397key =function ( v ) 398return v and v [ field ] 399end 400end 401 402return key 403end 404 405--- Removes duplicate values from a |lua-list| in-place. 406--- 407--- Only the first occurrence of each value is kept. 408--- The operation is performed in-place and the input table is modified. 409--- 410--- Accepts an optional `key` argument, which if provided is called for each 411--- value in the list to compute a hash key for uniqueness comparison. 412--- If `key` is a string, it is used as the field name to index each value. 413--- This is useful for deduplicating table values or complex objects. 414--- If `key` returns `nil` for a value, that value will be considered unique, 415--- even if multiple values return `nil`. 416--- 417--- Example: 418--- ```lua 419--- 420--- local t = {1, 2, 2, 3, 1} 421--- vim.list.unique(t) 422--- -- t is now {1, 2, 3} 423--- 424--- local t = { {id=1}, {id=2}, {id=1} } 425--- vim.list.unique(t, 'id') 426--- -- t is now { {id=1}, {id=2} } 427--- ``` 428--- 429--- @since 14 430--- @generic T 431--- @param t T[] 432--- @param key? string|fun(x: T): any Optional field name or hash function to determine uniqueness of values 433--- @return T[] : The deduplicated list 434--- @see |Iter:unique()| 435function vim . list . unique ( t , key ) 436vim . validate ( 't' , t , 'table' ) 437local key_fn =make_key_fn ( key ) 438local seen ={} --- @type table<any,boolean> 439 440local finish =# t 441 442local j =1 443for i =1 , finish do 444local v =t [ i ] 445local vh =key_fn ( v ) 446if not seen [ vh ] then 447t [ j ] =v 448if vh ~= nil then 449seen [ vh ] =true 450end 451j =j + 1 452end 453end 454 455for i =j , finish do 456t [ i ] =nil 457end 458 459return t 460end 461 462---@class vim.list.bisect.Opts<T> 463---@inlinedoc 464--- 465--- Start index of the list. 466--- (default: `1`) 467---@field lo? integer 468--- 469--- End index of the list, exclusive. 470--- (default: `#t + 1`) 471---@field hi? integer 472--- 473--- Applied to {val} and the list elements being compared. 474--- If a string, index both by this field name. If a function, it must accept both 475--- {val} and the list elements and return mutually comparable keys. 476---@field key? (string & keyof T)|fun(val: T): any 477--- 478--- Specifies the search variant. 479--- - "lower": returns the first position 480--- where inserting {val} keeps the list sorted. 481--- - "upper": returns the last position 482--- where inserting {val} keeps the list sorted.. 483--- (default: `'lower'`) 484---@field bound? 'lower' | 'upper' 485 486---@generic T, Q 487---@param t T[] 488---@param val Q 489---@param lo integer 490---@param hi integer 491---@param key_fn fun(val: T|Q): any 492---@return integer i in range such that `t[j]` < {val} for all j < i, 493--- and `t[j]` >= {val} for all j >= i, 494--- or return {hi} if no such index is found. 495local function lower_bound ( t , val , lo , hi , key_fn ) 496local bit =require ( 'bit' ) -- Load bitop on demand 497local val_key =key_fn ( val ) 498while lo < hi do 499local mid =bit . rshift ( lo + hi , 1 ) -- Equivalent to floor((lo + hi) / 2) 500if key_fn ( t [ mid ]) < val_key then 501lo =mid + 1 502else 503hi =mid 504end 505end 506return lo 507end 508 509---@generic T, Q 510---@param t T[] 511---@param val Q 512---@param lo integer 513---@param hi integer 514---@param key_fn fun(val: T|Q): any 515---@return integer i in range such that `t[j]` <= {val} for all j < i, 516--- and `t[j]` > {val} for all j >= i, 517--- or return {hi} if no such index is found. 518local function upper_bound ( t , val , lo , hi , key_fn ) 519local bit =require ( 'bit' ) -- Load bitop on demand 520local val_key =key_fn ( val ) 521while lo < hi do 522local mid =bit . rshift ( lo + hi , 1 ) -- Equivalent to floor((lo + hi) / 2) 523if val_key < key_fn ( t [ mid ]) then 524hi =mid 525else 526lo =mid + 1 527end 528end 529return lo 530end 531 532--- Search for a position in a sorted |lua-list| {t} where {val} can be inserted while keeping the 533--- list sorted. 534--- 535--- Use {bound} to determine whether to return the first or the last position, 536--- defaults to "lower", i.e., the first position. 537--- 538--- With {opts.key}, {val} may differ from the list elements, provided the key 539--- function accepts both. For a string key, that field must exist on both. 540--- A partial record is sufficient if it contains all fields used by the key. 541--- 542--- NOTE: The values being compared must support `<`, and the list must be sorted 543--- by those values (after applying {opts.key}, if provided). 544--- 545--- Example: 546--- ```lua 547--- 548--- local t = { 1, 2, 2, 3, 3, 3 } 549--- local first = vim.list.bisect(t, 3) 550--- -- `first` is `val`'s first index if found, 551--- -- useful for existence checks. 552--- print(t[first]) -- 3 553--- 554--- local last = vim.list.bisect(t, 3, { bound = 'upper' }) 555--- -- Note that `last` is 7, not 6, 556--- -- this is suitable for insertion. 557--- 558--- table.insert(t, last, 4) 559--- -- t is now { 1, 2, 2, 3, 3, 3, 4 } 560--- 561--- -- You can use lower bound and upper bound together 562--- -- to obtain the range of occurrences of `val`. 563--- 564--- -- 3 is in [first, last) 565--- for i = first, last - 1 do 566--- print(t[i]) -- { 3, 3, 3 } 567--- end 568--- ``` 569---@since 14 570---@generic T 571---@param t T[] A sorted list. 572---@param val T The value to search. 573---@param opts? vim.list.bisect.Opts<T> 574---@return integer index serves as either the lower bound or the upper bound position. 575---@overload fun<T, Q>(t: T[], val: Q, opts: vim.list.bisect.Opts<T|Q> & { key: fun(val: T|Q): any }): integer 576---@overload fun<T: table, Q: table>(t: T[], val: Q, opts: vim.list.bisect.Opts<T|Q> & { key: string & keyof T & keyof Q }): integer 577function vim . list . bisect ( t , val , opts ) 578vim . validate ( 't' , t , 'table' ) 579vim . validate ( 'opts' , opts , 'table' , true ) 580 581opts =opts or {} 582local lo =opts . lo or 1 583local hi =opts . hi or # t + 1 584local key_fn =make_key_fn ( opts . key ) 585 586if opts . bound == 'upper' then 587return upper_bound ( t , val , lo , hi , key_fn ) 588else 589return lower_bound ( t , val , lo , hi , key_fn ) 590end 591end 592 593--- Checks if a table is empty. 594--- 595---@see https://github.com/premake/premake-core/blob/master/src/base/table.lua 596--- 597---@param t table Table to check 598---@return boolean `true` if `t` is empty 599function vim . tbl_isempty ( t ) 600vim . validate ( 't' , t , 'table' ) 601return next ( t ) == nil 602end 603 604--- We only merge empty tables or tables that are not list-like (indexed by consecutive integers 605--- starting from 1) 606--- @param v any 607local function can_merge ( v ) 608return type ( v ) == 'table' and ( vim . tbl_isempty ( v ) or not vim . islist ( v )) 609end 610 611--- Recursive worker for tbl_extend 612--- @param behavior 'error'|'keep'|'force'|fun(key:any, prev_value:any?, value:any): any 613--- @param deep_extend boolean 614--- @param ... table<any,any> 615local function tbl_extend_rec ( behavior , deep_extend , ... ) 616local ret ={} --- @type table<any,any> 617if vim . _empty_dict_mt ~= nil and getmetatable ( select ( 1 , ... )) == vim . _empty_dict_mt then 618ret =vim . empty_dict () 619end 620 621for i =1 , select ( '#' , ... ) do 622local tbl =select ( i , ... ) --[[@as table<any,any>]] 623if tbl then 624for k , v in pairs ( tbl ) do 625if deep_extend and can_merge ( v ) and can_merge ( ret [ k ]) then 626ret [ k ] =tbl_extend_rec ( behavior , true , ret [ k ], v ) 627elseif type ( behavior ) == 'function' then 628ret [ k ] =behavior ( k , ret [ k ], v ) 629elseif behavior ~= 'force' and ret [ k ] ~= nil then 630if behavior == 'error' then 631error ( 'key found in more than one map: ' .. k ) 632end -- Else behavior is "keep". 633else 634ret [ k ] =v 635end 636end 637end 638end 639 640return ret 641end 642 643--- @param behavior 'error'|'keep'|'force'|fun(key:any, prev_value:any?, value:any): any 644--- @param deep_extend boolean 645--- @param ... table<any,any> 646local function tbl_extend ( behavior , deep_extend , ... ) 647if 648behavior ~= 'error' 649and behavior ~= 'keep' 650and behavior ~= 'force' 651and type ( behavior ) ~= 'function' 652then 653error ( 'invalid "behavior": ' .. tostring ( behavior )) 654end 655 656local nargs =select ( '#' , ... ) 657 658if nargs < 2 then 659error (( 'wrong number of arguments (given %d, expected at least 3)' ): format ( 1 + nargs )) 660end 661 662for i =1 , nargs do 663vim . validate ( 'after the second argument' , select ( i , ... ), 'table' ) 664end 665 666return tbl_extend_rec ( behavior , deep_extend , ... ) 667end 668 669--- Merges two or more tables. 670--- 671---@see |extend()| 672--- 673---@param behavior 'error'|'keep'|'force'|fun(key:any, prev_value:any?, value:any): any Decides what to do if a key is found in more than one map: 674--- - "error": raise an error 675--- - "force": use value from the rightmost map 676--- - "keep": use value from the leftmost map 677--- - If a function, it receives the current key, the previous value in the currently merged table (if present), the current value and should 678--- return the value for the given key in the merged table. 679---@param ... table Two or more tables 680---@return table : Merged table 681function vim . tbl_extend ( behavior , ... ) 682return tbl_extend ( behavior , false , ... ) 683end 684 685--- Merges two or more tables recursively. 686--- 687--- Only |lua-dict| tables are merged recursively; |lua-list| tables are treated as opaque values 688--- (overwritten instead of merged). That is convenient for merging default/user configurations 689--- where lists typically should not be merged together. 690--- 691--- Example: 692--- ```lua 693--- -- Set `config.settings.…` without worrying about whether intermediate dicts exist. 694--- local config = { settings = { tailwindCSS = { foo = 'bar' } } } 695--- local merged = vim.tbl_deep_extend('force', 696--- config, 697--- { settings = { tailwindCSS = { experimental = { configFile = '/my/config.json' } } } } 698--- ) 699--- vim.print(merged) 700--- ``` 701--- 702---@see |vim.tbl_extend()| 703--- 704---@generic T1: table 705---@generic T2: table 706---@param behavior 'error'|'keep'|'force'|fun(key:any, prev_value:any?, value:any): any Decides what to do if a key is found in more than one map: 707--- - "error": raise an error 708--- - "force": use value from the rightmost map 709--- - "keep": use value from the leftmost map 710--- - If a function, it receives the current key, the previous value in the currently merged table (if present), the current value and should 711--- return the value for the given key in the merged table. 712---@param ... T2 Two or more tables 713---@return T1|T2 (table) Merged table 714function vim . tbl_deep_extend ( behavior , ... ) 715return tbl_extend ( behavior , true , ... ) 716end 717 718---@param left any 719---@param right any 720---@param seen? table<table, table<table, boolean>> 721---@return boolean 722local function deep_equal ( left , right , seen ) 723if left == right then 724return true 725end 726 727if type ( left ) ~= type ( right ) then 728return false 729end 730 731if type ( left ) ~= 'table' then 732return false 733end 734 735---@cast left table<any, any> 736---@cast right table<any, any> 737seen =seen or {} 738local seen_left =seen [ left ] 739if seen_left and seen_left [ right ] ~= nil then 740return seen_left [ right ] 741end 742 743seen_left =seen_left or {} 744seen [ left ] =seen_left 745-- Assume equality while descending so recursive structures can terminate. 746seen_left [ right ] =true 747 748for k , v in pairs ( left ) do 749if not deep_equal ( v , right [ k ], seen ) then 750seen_left [ right ] =false 751return false 752end 753end 754 755for k in pairs ( right ) do 756if left [ k ] == nil then 757seen_left [ right ] =false 758return false 759end 760end 761 762return true 763end 764 765--- Deep compare values for equality 766--- 767--- Tables are compared recursively unless they both provide the `eq` metamethod. 768--- All other types are compared using the equality `==` operator. 769--- Cyclic tables are supported. 770---@param a any First value 771---@param b any Second value 772---@return boolean `true` if values are equals, else `false` 773function vim . deep_equal ( a , b ) 774return deep_equal ( a , b ) 775end 776 777--- Gets a (nested) value from table `o` given by a sequence of keys `...`, or `nil` if not found. 778--- 779--- Note: To _set_ deeply nested keys, see |vim.tbl_deep_extend()|. 780--- 781--- Example: 782--- ```lua 783--- local o = { a = { b = true } } 784--- -- Get `o.a.b`. 785--- vim.print(vim.tbl_get(o, 'a', 'b')) -- true 786--- o.a = {} 787--- vim.print(vim.tbl_get(o, 'a', 'b')) -- nil 788--- ``` 789--- 790---@see |unpack()| 791---@see |vim.tbl_deep_extend()| 792--- 793---@param o table Table to index 794---@param ... any Optional keys (0 or more, variadic) via which to index the table 795---@return any # Nested value indexed by key (if it exists), else nil 796function vim . tbl_get ( o , ... ) 797local nargs =select ( '#' , ... ) 798if nargs == 0 then 799return nil 800end 801for i =1 , nargs do 802o =o [ select ( i , ... )] --- @type any 803if o == nil then 804return nil 805elseif type ( o ) ~= 'table' and i ~= nargs then 806return nil 807end 808end 809return o 810end 811 812--- Extends a list-like table with the values of another list-like table. 813--- 814--- NOTE: This mutates dst! 815--- 816---@see |vim.tbl_extend()| 817--- 818---@generic T: table 819---@param dst T List which will be modified and appended to 820---@param src table List from which values will be inserted 821---@param start integer? Start index on src. Defaults to 1 822---@param finish integer? Final index on src. Defaults to `#src` 823---@return T dst 824function vim . list_extend ( dst , src , start , finish ) 825vim . validate ( 'dst' , dst , 'table' ) 826vim . validate ( 'src' , src , 'table' ) 827vim . validate ( 'start' , start , 'number' , true ) 828vim . validate ( 'finish' , finish , 'number' , true ) 829for i =start or 1 , finish or # src do 830table . insert ( dst , src [ i ]) 831end 832return dst 833end 834 835--- @deprecated 836--- Creates a copy of a list-like table such that any nested tables are 837--- "unrolled" and appended to the result. 838--- 839---@see From https://github.com/premake/premake-core/blob/master/src/base/table.lua 840--- 841---@param t table List-like table 842---@return table Flattened copy of the given list-like table 843function vim . tbl_flatten ( t ) 844vim . deprecate ( 'vim.tbl_flatten' , 'vim.iter(…):flatten():totable()' , '0.13' ) 845local result ={} 846--- @param _t table<any,any> 847local function _tbl_flatten ( _t ) 848local n =# _t 849for i =1 , n do 850local v =_t [ i ] 851if type ( v ) == 'table' then 852_tbl_flatten ( v ) 853elseif v then 854table . insert ( result , v ) 855end 856end 857end 858_tbl_flatten ( t ) 859return result 860end 861 862--- Enumerates key-value pairs of a table, ordered by key. 863--- 864---@see Based on https://github.com/premake/premake-core/blob/master/src/base/table.lua 865--- 866---@generic T: table, K, V 867---@param t T Dict-like table 868---@return fun(table: table<K, V>, index?: K):K, V # |for-in| iterator over sorted keys and their values 869---@return T 870function vim . spairs ( t ) 871vim . validate ( 't' , t , 'table' ) 872--- @cast t table<any,any> 873 874-- collect the keys 875local keys ={} --- @type string[] 876for k in pairs ( t ) do 877table . insert ( keys , k ) 878end 879table . sort ( keys ) 880 881-- Return the iterator function. 882local i =0 883return function () 884i =i + 1 885if keys [ i ] then 886return keys [ i ], t [ keys [ i ]] 887end 888end , 889t 890end 891 892--- Tests if `t` is an "array": a table indexed _only_ by integers (potentially non-contiguous). 893--- 894--- If the indexes start from 1 and are contiguous then the array is also a list. |vim.islist()| 895--- 896--- Empty table `{}` is an array, unless it was created by |vim.empty_dict()| or returned as 897--- a dict-like |API| or Vimscript result, for example from |rpcrequest()| or |vim.fn|. 898--- 899---@see https://github.com/openresty/luajit2#tableisarray 900--- 901---@param t? any 902---@return boolean `true` if array-like table, else `false`. 903function vim . isarray ( t ) 904if type ( t ) ~= 'table' then 905return false 906end 907 908--- @cast t table<any,any> 909 910local count =0 911 912for k , _ in pairs ( t ) do 913-- Check if the number k is an integer 914if type ( k ) == 'number' and k == math . floor ( k ) then 915count =count + 1 916else 917return false 918end 919end 920 921if count > 0 then 922return true 923else 924-- TODO(bfredl): in the future, we will always be inside nvim 925-- then this check can be deleted. 926if vim . _empty_dict_mt == nil then 927return false 928end 929return getmetatable ( t ) ~= vim . _empty_dict_mt 930end 931end 932 933--- Tests if `t` is a "list": a table indexed _only_ by contiguous integers starting from 1 (what 934--- |lua-length| calls a "regular array"). 935--- 936--- Empty table `{}` is a list, unless it was created by |vim.empty_dict()| or returned as 937--- a dict-like |API| or Vimscript result, for example from |rpcrequest()| or |vim.fn|. 938--- 939---@see |vim.isarray()| 940--- 941---@param t? any 942---@return boolean `true` if list-like table, else `false`. 943function vim . islist ( t ) 944if type ( t ) ~= 'table' then 945return false 946end 947 948if next ( t ) == nil then 949return getmetatable ( t ) ~= vim . _empty_dict_mt 950end 951 952local j =1 953for _ in 954pairs ( t --[[@as table<any,any>]] ) 955do 956if rawget ( t , j ) == nil then 957return false 958end 959j =j + 1 960end 961 962return true 963end 964 965-- EmmyLua 0.25.1 cannot subtract unions, so return_cast only removes Lua nil on false. 966--- Tests if `t` is `nil` or |vim.NIL|. 967--- 968--- @since 15 969--- @param t? any 970--- @return boolean `true` if `nil` or |vim.NIL|, else `false`. 971--- @return_cast t nil|vim.NIL else -nil 972function vim . isnil ( t ) 973return t == nil or t == vim . NIL 974end 975 976--- Counts the number of non-nil values in table `t`. 977--- 978--- ```lua 979--- vim.tbl_count({ a=1, b=2 }) --> 2 980--- vim.tbl_count({ 1, 2 }) --> 2 981--- ``` 982--- 983---@see https://github.com/Tieske/Penlight/blob/master/lua/pl/tablex.lua 984---@param t table Table 985---@return integer : Number of non-nil values in table 986function vim . tbl_count ( t ) 987vim . validate ( 't' , t , 'table' ) 988--- @cast t table<any,any> 989 990local count =0 991for _ in pairs ( t ) do 992count =count + 1 993end 994return count 995end 996 997--- Creates a copy of a table containing only elements from start to end (inclusive) 998--- 999---@generic T 1000---@param list T[] Table 1001---@param start integer|nil Start range of slice 1002---@param finish integer|nil End range of slice 1003---@return T[] Copy of table sliced from start to finish (inclusive) 1004function vim . list_slice ( list , start , finish ) 1005local new_list ={} --- @type `T`[] 1006for i =start or 1 , finish or # list do 1007new_list [ # new_list + 1 ] =list [ i ] 1008end 1009return new_list 1010end 1011 1012--- Efficiently insert items into the middle of a list. 1013--- 1014--- Calling table.insert() in a loop will re-index the tail of the table on 1015--- every iteration, instead this function will re-index the table exactly 1016--- once. 1017--- 1018--- Based on https://stackoverflow.com/questions/12394841/safely-remove-items-from-an-array-table-while-iterating/53038524#53038524 1019--- 1020---@param t any[] 1021---@param first integer 1022---@param last integer 1023---@param v any 1024function vim . _list_insert ( t , first , last , v ) 1025local n =# t 1026 1027-- Shift table forward 1028for i =n - first , 0 , - 1 do 1029t [ last + 1 + i ] =t [ first + i ] 1030end 1031 1032-- Fill in new values 1033for i =first , last do 1034t [ i ] =v 1035end 1036end 1037 1038--- Efficiently remove items from middle of a list. 1039--- 1040--- Calling table.remove() in a loop will re-index the tail of the table on 1041--- every iteration, instead this function will re-index the table exactly 1042--- once. 1043--- 1044--- Based on https://stackoverflow.com/questions/12394841/safely-remove-items-from-an-array-table-while-iterating/53038524#53038524 1045--- 1046---@param t any[] 1047---@param first integer 1048---@param last integer 1049function vim . _list_remove ( t , first , last ) 1050local n =# t 1051for i =0 , n - first do 1052t [ first + i ] =t [ last + 1 + i ] 1053t [ last + 1 + i ] =nil 1054end 1055end 1056 1057--- Trim whitespace (Lua pattern "%s") from both sides of a string. 1058--- 1059---@see |lua-pattern|s 1060---@see https://www.lua.org/pil/20.2.html 1061---@param s string String to trim 1062---@return string String with whitespace removed from its beginning and end 1063function vim . trim ( s ) 1064vim . validate ( 's' , s , 'string' ) 1065-- `s:match('^%s*(.*%S)')` is slow for long whitespace strings, 1066-- so we are forced to split it into two parts to prevent this 1067return s : gsub ( '^%s+' , '' ): match ( '^.*%S' ) or '' 1068end 1069 1070--- Escapes magic chars in |lua-pattern|s. 1071--- 1072---@see https://github.com/rxi/lume 1073---@param s string String to escape 1074---@return string %-escaped pattern string 1075function vim . pesc ( s ) 1076vim . validate ( 's' , s , 'string' ) 1077return ( s : gsub ( '[%(%)%.%%%+%-%*%?%[%]%^%$]' , '%%%1' )) 1078end 1079 1080--- Tests if `s` starts with `prefix`. 1081--- 1082---@param s string String 1083---@param prefix string Prefix to match 1084---@return boolean `true` if `prefix` is a prefix of `s` 1085function vim . startswith ( s , prefix ) 1086vim . validate ( 's' , s , 'string' ) 1087vim . validate ( 'prefix' , prefix , 'string' ) 1088return s : sub ( 1 , # prefix ) == prefix 1089end 1090 1091--- Tests if `s` ends with `suffix`. 1092--- 1093---@param s string String 1094---@param suffix string Suffix to match 1095---@return boolean `true` if `suffix` is a suffix of `s` 1096function vim . endswith ( s , suffix ) 1097vim . validate ( 's' , s , 'string' ) 1098vim . validate ( 'suffix' , suffix , 'string' ) 1099return # suffix == 0 or s : sub ( -# suffix ) == suffix 1100end 1101 1102do 1103--- @alias vim.validate.Validator 1104--- | type 1105--- | 'callable' 1106--- | (type|'callable')[] 1107--- | fun(v:any):boolean, string? 1108 1109local type_aliases ={ 1110b ='boolean' , 1111c ='callable' , 1112f ='function' , 1113n ='number' , 1114s ='string' , 1115t ='table' , 1116} 1117 1118--- @nodoc 1119--- @class vim.validate.Spec 1120--- @field [1] any Argument value 1121--- @field [2] vim.validate.Validator Argument validator 1122--- @field [3]? boolean|string Optional flag or error message 1123 1124--- @param val any 1125--- @param t string 1126local function is_type ( val , t ) 1127return type ( val ) == t or ( t == 'callable' and vim . is_callable ( val )) 1128end 1129 1130--- @param param_name string 1131--- @param val any 1132--- @param validator vim.validate.Validator 1133--- @param message? string "Expected" message 1134--- @param allow_alias? boolean Allow short type names: 'n', 's', 't', 'b', 'f', 'c' 1135--- @return string? 1136local function is_valid ( param_name , val , validator , message , allow_alias ) 1137if type ( validator ) == 'string' then 1138local expected =allow_alias and type_aliases [ validator ] or validator 1139 1140if not expected then 1141return string . format ( 'invalid type name: %s' , validator ) 1142end 1143 1144if not is_type ( val , expected ) then 1145return ( '%s: expected %s, got %s' ): format ( param_name , message or expected , type ( val )) 1146end 1147elseif vim . is_callable ( validator ) then 1148-- Check user-provided validation function 1149---@cast validator fun(v: any): boolean, string? 1150local valid , opt_msg =validator ( val ) 1151if not valid then 1152local err_msg =( '%s: expected %s, got %s' ): format ( 1153param_name , 1154message or '?' , 1155tostring ( val ) 1156) 1157err_msg =opt_msg and ( '%s. Info: %s' ): format ( err_msg , opt_msg ) or err_msg 1158 1159return err_msg 1160end 1161elseif type ( validator ) == 'table' then 1162for _ , t in ipairs ( validator ) do 1163local expected =allow_alias and type_aliases [ t ] or t 1164if not expected then 1165return string . format ( 'invalid type name: %s' , t ) 1166end 1167 1168if is_type ( val , expected ) then 1169return -- success 1170end 1171end 1172 1173-- Normalize validator types for error message 1174if allow_alias then 1175for i , t in ipairs ( validator ) do 1176validator [ i ] =type_aliases [ t ] or t 1177end 1178end 1179 1180return string . format ( 1181'%s: expected %s, got %s' , 1182param_name , 1183table . concat ( validator , '|' ), 1184type ( val ) 1185) 1186else 1187return string . format ( 'invalid validator: %s' , tostring ( validator )) 1188end 1189end 1190 1191--- @param opt table<type|'callable',vim.validate.Spec> 1192--- @return string? 1193local function validate_spec ( opt ) 1194local report --- @type table<string,string>? 1195 1196for param_name , spec in pairs ( opt ) do 1197local err_msg --- @type string? 1198if type ( spec ) ~= 'table' then 1199err_msg =string . format ( 'opt[%s]: expected table, got %s' , param_name , type ( spec )) 1200else 1201local value , validator =spec [ 1 ], spec [ 2 ] 1202local msg =type ( spec [ 3 ]) == 'string' and spec [ 3 ] or nil --[[@as string?]] 1203local optional =spec [ 3 ] == true 1204if not ( optional and value == nil ) then 1205err_msg =is_valid ( param_name , value , validator , msg , true ) 1206end 1207end 1208 1209if err_msg then 1210report =report or {} 1211report [ param_name ] =err_msg 1212end 1213end 1214 1215if report then 1216for _ , msg in vim . spairs ( report ) do -- luacheck: ignore 1217return msg 1218end 1219end 1220end 1221 1222--- Validate function arguments. 1223--- 1224--- This function has two valid forms: 1225--- 1226--- 1. `vim.validate(name, value, validator[, optional][, message])` 1227--- 1228--- Validates that argument {name} with value {value} satisfies 1229--- {validator}. If {optional} is given and is `true`, then {value} may be 1230--- `nil`. If {message} is given, then it is used as the expected type in the 1231--- error message. 1232--- 1233--- Example: 1234--- 1235--- ```lua 1236--- function vim.startswith(s, prefix) 1237--- vim.validate('s', s, 'string') 1238--- vim.validate('prefix', prefix, 'string') 1239--- -- ... 1240--- end 1241--- ``` 1242--- 1243--- 2. `vim.validate(spec)` (DEPRECATED) where `spec` is of type 1244--- `table<string,[value:any, validator: vim.validate.Validator, optional_or_msg? : boolean|string]>)` 1245--- 1246--- Validates a argument specification. 1247--- Specs are evaluated in alphanumeric order, until the first failure. 1248--- 1249--- Examples: 1250--- 1251--- ```lua 1252--- vim.validate('arg1', {'foo'}, 'table') 1253--- --> NOP (success) 1254--- vim.validate('arg2', 'foo', 'string') 1255--- --> NOP (success) 1256--- 1257--- vim.validate('arg1', 1, 'table') 1258--- --> error('arg1: expected table, got number') 1259--- 1260--- vim.validate('arg1', 3, function(a) return (a % 2) == 0 end, 'even number') 1261--- --> error('arg1: expected even number, got 3') 1262--- 1263--- -- If multiple types are valid they can be given as a list: 1264--- vim.validate('arg1', {'foo'}, {'table', 'string'}) 1265--- vim.validate('arg2', 'foo', {'table', 'string'}) 1266--- -- NOP (success) 1267--- vim.validate('arg1', 1, {'string', 'table'}) 1268--- -- error('arg1: expected string|table, got number') 1269--- ``` 1270--- 1271--- @note `validator` set to a value returned by |lua-type()| provides the 1272--- best performance. 1273--- 1274--- @param name string Argument name 1275--- @param value any Argument value 1276--- @param validator vim.validate.Validator : 1277--- - (`string|string[]`): Any value that can be returned from |lua-type()| in addition to 1278--- `'callable'`: `'boolean'`, `'callable'`, `'function'`, `'nil'`, `'number'`, `'string'`, `'table'`, 1279--- `'thread'`, `'userdata'`. 1280--- - (`fun(val:any): boolean, string?`) A function that returns a boolean and an optional 1281--- string message. 1282--- @param optional? boolean (default: false) Parameter is optional (may be omitted or nil) 1283--- @param message? string message when validation fails 1284--- @overload fun(name: string, val: any, validator: vim.validate.Validator, message: string) 1285--- @overload fun(spec: table<string,[any, vim.validate.Validator, boolean|string]>) 1286function vim . validate ( name , value , validator , optional , message ) 1287local err_msg --- @type string? 1288if validator then -- Form 1 1289-- Check validator as a string first to optimize the common case. 1290local ok =( type ( value ) == validator ) or ( value == nil and optional == true ) 1291if not ok then 1292local msg =type ( optional ) == 'string' and optional or message --[[@as string?]] 1293-- Check more complicated validators 1294err_msg =is_valid ( name , value , validator , msg , false ) 1295end 1296elseif type ( name ) == 'table' then -- Form 2 1297vim . deprecate ( 'vim.validate{<table>}' , 'vim.validate(<params>)' , '1.0' ) 1298err_msg =validate_spec ( name ) 1299else 1300error ( 'invalid arguments' ) 1301end 1302 1303if err_msg then 1304error ( err_msg , 2 ) 1305end 1306end 1307end 1308 1309--- Returns true if object `f` can be called as a function. 1310--- 1311---@param f? any Any object 1312---@return boolean `true` if `f` is callable, else `false` 1313function vim . is_callable ( f ) 1314if type ( f ) == 'function' then 1315return true 1316end 1317local m =getmetatable ( f ) 1318if m == nil then 1319return false 1320end 1321return type ( rawget ( m , '__call' )) == 'function' 1322end 1323 1324--- Creates a table whose missing keys are provided by {createfn} (like Python's "defaultdict"). 1325--- 1326--- If {createfn} is `nil` it defaults to defaulttable() itself, so accessing nested keys creates 1327--- nested tables: 1328--- 1329--- ```lua 1330--- local a = vim.defaulttable() 1331--- a.b.c = 1 1332--- ``` 1333--- 1334---@param createfn? fun(key:any):any Provides the value for a missing `key`. 1335---@return table # Empty table with `__index` metamethod. 1336function vim . defaulttable ( createfn ) 1337createfn =createfn or function ( _ ) 1338return vim . defaulttable () 1339end 1340return setmetatable ( {} , { 1341__index =function ( tbl , key ) 1342rawset ( tbl , key , createfn ( key )) 1343return rawget ( tbl , key ) 1344end , 1345} ) 1346end 1347 1348do 1349---@class vim.Ringbuf<T> 1350---@field private _items table<integer, T?> 1351---@field private _idx_read integer 1352---@field private _idx_write integer 1353---@field private _size integer 1354---@overload fun(self: vim.Ringbuf<T>): T? 1355local Ringbuf ={} 1356 1357--- Clear all items 1358function Ringbuf . clear ( self ) 1359self . _items ={} 1360self . _idx_read =0 1361self . _idx_write =0 1362end 1363 1364--- Adds an item, overriding the oldest item if the buffer is full. 1365---@param item T 1366function Ringbuf . push ( self , item ) 1367self . _items [ self . _idx_write ] =item 1368self . _idx_write =( self . _idx_write + 1 ) % self . _size 1369if self . _idx_write == self . _idx_read then 1370self . _idx_read =( self . _idx_read + 1 ) % self . _size 1371end 1372end 1373 1374--- Removes and returns the first unread item 1375---@return T? 1376function Ringbuf . pop ( self ) 1377local idx_read =self . _idx_read 1378if idx_read == self . _idx_write then 1379return nil 1380end 1381local item =self . _items [ idx_read ] 1382self . _items [ idx_read ] =nil 1383self . _idx_read =( idx_read + 1 ) % self . _size 1384return item 1385end 1386 1387--- Returns the first unread item without removing it 1388---@return T? 1389function Ringbuf . peek ( self ) 1390if self . _idx_read == self . _idx_write then 1391return nil 1392end 1393return self . _items [ self . _idx_read ] 1394end 1395 1396--- Create a ring buffer limited to a maximal number of items. 1397--- Once the buffer is full, adding a new entry overrides the oldest entry. 1398--- 1399--- ```lua 1400--- local ringbuf = vim.ringbuf(4) 1401--- ringbuf:push("a") 1402--- ringbuf:push("b") 1403--- ringbuf:push("c") 1404--- ringbuf:push("d") 1405--- ringbuf:push("e") -- overrides "a" 1406--- print(ringbuf:pop()) -- returns "b" 1407--- print(ringbuf:pop()) -- returns "c" 1408--- 1409--- -- Can be used as iterator. Pops remaining items: 1410--- for val in ringbuf do 1411--- print(val) 1412--- end 1413--- ``` 1414--- 1415--- Returns a Ringbuf instance with the following methods: 1416--- 1417--- - |Ringbuf:push()| 1418--- - |Ringbuf:pop()| 1419--- - |Ringbuf:peek()| 1420--- - |Ringbuf:clear()| 1421--- 1422---@param size integer 1423---@return vim.Ringbuf<any> ringbuf 1424function vim . ringbuf ( size ) 1425local ringbuf ={ 1426_items ={} , 1427_size =size + 1 , 1428_idx_read =0 , 1429_idx_write =0 , 1430} 1431return setmetatable ( ringbuf , { 1432__index =Ringbuf , 1433__call =function ( self ) 1434return self : pop () 1435end , 1436} ) 1437end 1438end 1439 1440--- @generic T 1441--- @param root string 1442--- @param mod T 1443--- @return T 1444function vim . _defer_require ( root , mod ) 1445return setmetatable ( { _submodules =mod } , { 1446---@param t table<string, any> 1447---@param k string 1448__index =function ( t , k ) 1449if not mod [ k ] then 1450return 1451end 1452local name =string . format ( '%s.%s' , root , k ) 1453t [ k ] =require ( name ) 1454return t [ k ] 1455end , 1456} ) 1457end 1458 1459--- Creates a module alias/shim that lazy-loads a target module. 1460--- 1461--- Unlike `vim.defaulttable()` this also: 1462--- - implements __call 1463--- - calls vim.deprecate() 1464--- 1465--- @param old_name string Name of the deprecated module, which will be shimmed. 1466--- @param new_name string Name of the new module, which will be loaded by require(). 1467function vim . _defer_deprecated_module ( old_name , new_name ) 1468return setmetatable ( {} , { 1469---@param _ table<string, any> 1470---@param k string 1471__index =function ( _ , k ) 1472vim . deprecate ( old_name , new_name , '2.0.0' , nil , false ) 1473--- @diagnostic disable-next-line:no-unknown 1474local target =require ( new_name ) 1475return target [ k ] 1476end , 1477__call =function ( self ) 1478vim . deprecate ( old_name , new_name , '2.0.0' , nil , false ) 1479--- @diagnostic disable-next-line:no-unknown 1480local target =require ( new_name ) 1481return target ( self ) 1482end , 1483} ) 1484end 1485 1486--- @nodoc 1487--- @class vim.context.mods 1488--- @field bo? table<string, any> 1489--- @field buf? integer 1490--- @field cwd? string 1491--- @field emsg_silent? boolean 1492--- @field env? table<string, any> 1493--- @field go? table<string, any> 1494--- @field hide? boolean 1495--- @field keepalt? boolean 1496--- @field keepcwd? boolean 1497--- @field keepjumps? boolean 1498--- @field keepmarks? boolean 1499--- @field keeppatterns? boolean 1500--- @field lockmarks? boolean 1501--- @field noautocmd? boolean 1502--- @field o? table<string, any> 1503--- @field sandbox? boolean 1504--- @field silent? boolean 1505--- @field unsilent? boolean 1506--- @field win? integer 1507--- @field wo? table<string, any> 1508 1509--- @nodoc 1510--- @class vim.context.state 1511--- @field bo table<string, any> 1512--- @field env table<string, any> 1513--- @field go table<string, any> 1514--- @field wo table<string, any> 1515 1516local scope_map ={ buf ='bo' , global ='go' , win ='wo' } 1517local scope_order ={ 'o' , 'wo' , 'bo' , 'go' , 'env' } 1518local state_restore_order ={ 'bo' , 'wo' , 'go' , 'env' } 1519 1520--- Gets data about current state, enough to properly restore specified options/env/etc. 1521--- @param context vim.context.mods 1522--- @return vim.context.state 1523local function get_context_state ( context ) 1524--- @type vim.context.state 1525local res ={ bo ={} , env ={} , go ={} , wo ={} } 1526 1527-- Use specific order from possibly most to least intrusive 1528for _ , scope in ipairs ( scope_order ) do 1529for name , _ in 1530pairs ( context [ scope ] or {} --[[@as table<string,any>]] ) 1531do 1532local sc =scope == 'o' and scope_map [ vim . api . nvim_get_option_info2 ( name ). scope ] or scope 1533 1534-- Do not override already set state and fall back to `vim.NIL` for 1535-- state `nil` values (which still needs restoring later) 1536res [ sc ][ name ] =vim . nonnil ( res [ sc ][ name ], vim [ sc ][ name ], vim . NIL ) 1537 1538-- Always track global option value to properly restore later. 1539-- This matters for at least `o` and `wo` (which might set either/both 1540-- local and global option values). 1541if sc ~= 'env' and res . go [ name ] == nil then 1542res . go [ name ] =vim . go [ name ] 1543end 1544end 1545end 1546 1547return res 1548end 1549 1550--- Executes function `f` with the given `context` spec: after execution, the original state 1551--- indicated by the spec is restored. 1552--- 1553--- Notes: 1554--- - Context `{ buf = buf }` has no guarantees about current window when 1555--- inside context. 1556--- - Context `{ buf = buf, win = win }` is yet not allowed, but this seems 1557--- to be an implementation detail. 1558--- - There should be no way to revert currently set `context.sandbox = true` 1559--- (like with nested `vim._with()` calls). Otherwise it kind of breaks the 1560--- whole purpose of sandbox execution. 1561--- - Saving and restoring option contexts (`bo`, `go`, `o`, `wo`) trigger 1562--- `OptionSet` events. This is an implementation issue because not doing it 1563--- seems to mean using either 'eventignore' option or extra nesting with 1564--- `{ noautocmd = true }` (which itself is a wrapper for 'eventignore'). 1565--- As `{ go = { eventignore = '...' } }` is a valid context which should be 1566--- properly set and restored, this is not a good approach. 1567--- Not triggering `OptionSet` seems to be a good idea, though. So probably 1568--- only moving context save and restore to lower level might resolve this. 1569--- 1570--- @generic R... 1571--- @param context vim.context.mods 1572--- @param f fun(): R... 1573--- @return R... 1574function vim . _with ( context , f ) 1575vim . validate ( 'context' , context , 'table' ) 1576vim . validate ( 'f' , f , 'function' ) 1577 1578vim . validate ( 'context.bo' , context . bo , 'table' , true ) 1579vim . validate ( 'context.buf' , context . buf , 'number' , true ) 1580vim . validate ( 'context.cwd' , context . cwd , 'string' , true ) 1581vim . validate ( 'context.emsg_silent' , context . emsg_silent , 'boolean' , true ) 1582vim . validate ( 'context.env' , context . env , 'table' , true ) 1583vim . validate ( 'context.go' , context . go , 'table' , true ) 1584vim . validate ( 'context.hide' , context . hide , 'boolean' , true ) 1585vim . validate ( 'context.keepalt' , context . keepalt , 'boolean' , true ) 1586vim . validate ( 'context.keepcwd' , context . keepcwd , 'boolean' , true ) 1587vim . validate ( 'context.keepjumps' , context . keepjumps , 'boolean' , true ) 1588vim . validate ( 'context.keepmarks' , context . keepmarks , 'boolean' , true ) 1589vim . validate ( 'context.keeppatterns' , context . keeppatterns , 'boolean' , true ) 1590vim . validate ( 'context.lockmarks' , context . lockmarks , 'boolean' , true ) 1591vim . validate ( 'context.noautocmd' , context . noautocmd , 'boolean' , true ) 1592vim . validate ( 'context.o' , context . o , 'table' , true ) 1593vim . validate ( 'context.sandbox' , context . sandbox , 'boolean' , true ) 1594vim . validate ( 'context.silent' , context . silent , 'boolean' , true ) 1595vim . validate ( 'context.unsilent' , context . unsilent , 'boolean' , true ) 1596vim . validate ( 'context.win' , context . win , 'number' , true ) 1597vim . validate ( 'context.wo' , context . wo , 'table' , true ) 1598 1599-- Check buffer exists 1600if context . buf then 1601if not vim . api . nvim_buf_is_valid ( context . buf ) then 1602error ( 'Invalid buffer id: ' .. context . buf ) 1603end 1604context . buf =context . buf == 0 and vim . api . nvim_get_current_buf () or context . buf 1605end 1606 1607-- Check window exists 1608if context . win then 1609if not vim . api . nvim_win_is_valid ( context . win ) then 1610error ( 'Invalid window id: ' .. context . win ) 1611end 1612-- TODO: Maybe allow it? 1613if context . buf and vim . api . nvim_win_get_buf ( context . win ) ~= context . buf then 1614error ( 'Can not set both `buf` and `win` context.' ) 1615end 1616context . win =context . win == 0 and vim . api . nvim_get_current_win () or context . win 1617end 1618 1619-- Decorate so that save-set-restore options is done in correct window-buffer 1620local callback =function () 1621-- Cache current values to be changed by context 1622-- Abort early in case of bad context value 1623local ok , state =pcall ( get_context_state , context ) 1624if not ok then 1625error ( state , 0 ) 1626end 1627 1628-- Apply some parts of the context in specific order 1629-- NOTE: triggers `OptionSet` event 1630for _ , scope in ipairs ( scope_order ) do 1631for name , context_value in 1632pairs ( context [ scope ] or {} --[[@as table<string,any>]] ) 1633do 1634--- @diagnostic disable-next-line:no-unknown 1635vim [ scope ][ name ] =context_value 1636end 1637end 1638 1639--- @type string 1640local state_cwd 1641if context . cwd then 1642-- NOTE: triggers `DirChanged{Pre,}` events 1643state_cwd =vim . fn . chdir ( context . cwd ) 1644end 1645 1646-- Execute 1647local res ={ pcall ( f ) } 1648 1649-- Restore relevant cached values in specific order, global scope last 1650-- NOTE: triggers `OptionSet` event 1651for _ , scope in ipairs ( state_restore_order ) do 1652for name , cached_value in 1653pairs ( state [ scope ] --[[@as table<string,any>]] ) 1654do 1655--- @diagnostic disable-next-line:no-unknown 1656vim [ scope ][ name ] =cached_value 1657end 1658end 1659 1660if state_cwd then 1661-- NOTE: triggers `DirChanged{Pre,}` events 1662vim . fn . chdir ( state_cwd ) 1663end 1664 1665-- Return 1666if not res [ 1 ] then 1667error ( res [ 2 ], 0 ) 1668end 1669table . remove ( res , 1 ) 1670return unpack ( res , 1 , table . maxn ( res )) 1671end 1672 1673return vim . _with_c ( context , callback ) 1674end 1675 1676--- @param buf? integer 1677--- @return integer 1678function vim . _resolve_bufnr ( buf ) 1679if buf == nil or buf == 0 then 1680return vim . api . nvim_get_current_buf () 1681end 1682vim . validate ( 'buf' , buf , 'number' ) 1683return buf 1684end 1685 1686--- @generic T 1687--- @param x T|T[] 1688--- @return T[] 1689function vim . _ensure_list ( x ) 1690if type ( x ) == 'table' then 1691--- @cast x T[] 1692return x 1693end 1694return { x } 1695end 1696 1697--- Coerces {x} to an integer, like `tonumber()`, but rejects fractional values. 1698--- 1699--- Returns `nil` if {x} cannot be converted with `tonumber()`, or if the 1700--- resulting number is not integral. 1701--- 1702--- @param x any Value to convert. 1703--- @param base? integer Numeric base passed to `tonumber()`. 1704--- @return integer? integer Converted integer value, or `nil`. 1705function vim . _tointeger ( x , base ) 1706--- @diagnostic disable-next-line:param-type-mismatch optional `base` is equivalent to `tonumber(x)` 1707local nx =tonumber ( x , base ) 1708if nx and nx == math . floor ( nx ) then 1709--- @cast nx integer 1710return nx 1711end 1712end 1713 1714--- Coerces {x} to an integer and errors if conversion fails. 1715--- 1716--- This is the throwing counterpart to |vim._tointeger()| and should be used 1717--- when non-integer input is a programming error. 1718--- 1719--- @param x any Value to convert. 1720--- @param base? integer Numeric base passed to `tonumber()`. 1721--- @return integer integer Converted integer value. 1722function vim . _assert_integer ( x , base ) 1723return vim . _tointeger ( x , base ) or error (( 'Cannot convert %s to integer' ): format ( x )) 1724end 1725 1726-- Use max 32-bit signed int value to avoid overflow on 32-bit systems. #31633 1727vim . _maxint =2 ^ 32 - 1 1728 1729--- Returns the first argument which is not nil. 1730--- 1731--- If all arguments are nil, returns nil. 1732--- 1733--- Example: 1734--- 1735--- ```lua 1736--- local a = nil 1737--- local b = nil 1738--- local c = 42 1739--- local d = true 1740--- assert(vim.nonnil(a, b, c, d) == 42) 1741--- ``` 1742--- 1743--- @since 15 1744--- @generic T 1745--- @param ... T 1746--- @return T 1747function vim . nonnil ( ... ) 1748local nargs =select ( '#' , ... ) 1749for i =1 , nargs do 1750local v =select ( i , ... ) 1751if v ~= nil then 1752return v 1753end 1754end 1755return nil 1756end 1757 1758--- Calls the function `fn` in `protected mode` like |pcall()|, but returns 1759--- `nil` on error. 1760--- 1761--- @since 15 1762--- @generic T 1763--- @param fn fun(...):T 1764--- @param ... any? 1765--- @return T ... 1766function vim . npcall ( fn , ... ) 1767return ( function ( success , ... ) 1768if success then 1769return ... 1770end 1771end )( pcall ( fn , ... )) 1772end 1773 1774---@generic T 1775---@param fn fun(...):T 1776---@param ... any? 1777---@return T ... 1778function vim . wrap ( fn , ... ) 1779local props =vim . F . pack_len ( ... ) 1780return function () 1781return vim . npcall ( fn , vim . F . unpack_len ( props )) 1782end 1783end 1784 1785return vim