robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

robinmerge: 1dc9728daa1d8a2702

master
51.2 KiB1785 linesraw
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)
18  if orig == vim.NIL then
19    return vim.NIL
20  elseif type(orig) == 'userdata' or type(orig) == 'thread' then
21    error('Cannot deepcopy object of type ' .. type(orig))
22  elseif type(orig) ~= 'table' then
23    return orig
24  end
25
26  --- @cast orig table<any,any>
27
28  if cache and cache[orig] then
29    return cache[orig]
30  end
31
32  local copy = {} --- @type table<any,any>
33
34  if cache then
35    cache[orig] = copy
36  end
37
38  for k, v in pairs(orig) do
39    copy[deepcopy(k, cache)] = deepcopy(v, cache)
40  end
41
42  return 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)
64  return 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)
78  if type(orig) ~= 'table' then
79    return orig
80  end
81
82  --- @cast orig table<any,any>
83
84  local copy = {} --- @type table<any,any>
85  for k, v in pairs(orig) do
86    copy[k] = v
87  end
88
89  return 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)
132  local plain --- @type boolean?
133  local trimempty = false --- @type boolean?
134  if type(opts) == 'boolean' then
135    plain = opts -- For backwards compatibility.
136  else
137    vim.validate('s', s, 'string')
138    vim.validate('sep', sep, 'string')
139    vim.validate('opts', opts, 'table', true)
140    opts = opts or {}
141    plain, trimempty = opts.plain, opts.trimempty
142  end
143
144  local start = 1
145  local done = false
146
147  -- For `trimempty`: queue of collected segments, to be emitted at next pass.
148  local segs = {}
149  local 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 ...
156  local function _pass(i, j, ...)
157    if i then
158      assert(j)
159      assert(j + 1 > start, 'Infinite loop detected')
160      local seg = s:sub(start, i - 1)
161      start = j + 1
162      return seg, ...
163    else
164      done = true
165      return s:sub(start)
166    end
167  end
168
169  return function()
170    if trimempty and #segs > 0 then
171      -- trimempty: Pop the collected segments.
172      return table.remove(segs)
173    elseif done or (s == '' and sep == '') then
174      return nil
175    elseif sep == '' then
176      if start == #s then
177        done = true
178      end
179      return _pass(start + 1, start)
180    end
181
182    local seg = _pass(s:find(sep, start, plain))
183
184    -- Trim empty segments from start/end.
185    if trimempty and seg ~= '' then
186      empty_start = false
187    elseif trimempty and seg == '' then
188      while not done and seg == '' do
189        table.insert(segs, 1, '')
190        seg = _pass(s:find(sep, start, plain))
191      end
192      if done and seg == '' then
193        return nil
194      elseif empty_start then
195        empty_start = false
196        segs = {}
197        return seg
198      end
199      if seg ~= '' then
200        table.insert(segs, 1, seg)
201      end
202      return table.remove(segs)
203    end
204
205    return seg
206  end
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)
229  local t = {}
230  for c in vim.gsplit(s, sep, opts) do
231    table.insert(t, c)
232  end
233  return 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)
245  vim.validate('t', t, 'table')
246  --- @cast t table<any,any>
247
248  local keys = {}
249  for k in pairs(t) do
250    table.insert(keys, k)
251  end
252  return 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)
262  vim.validate('t', t, 'table')
263
264  local values = {}
265  for _, v in
266    pairs(t --[[@as table<any,any>]])
267  do
268    table.insert(values, v)
269  end
270  return 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)
281  vim.validate('fn', fn, 'callable')
282  vim.validate('t', t, 'table')
283  --- @cast t table<any,any>
284
285  local rettab = {} --- @type table<any,any>
286  for k, v in pairs(t) do
287    rettab[k] = fn(v)
288  end
289  return 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)
299  vim.validate('fn', fn, 'callable')
300  vim.validate('t', t, 'table')
301  --- @cast t table<any,any>
302
303  local rettab = {} --- @type table<any,any>
304  for _, entry in pairs(t) do
305    if fn(entry) then
306      rettab[#rettab + 1] = entry
307    end
308  end
309  return 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)
338  vim.validate('t', t, 'table')
339  vim.validate('opts', opts, 'table', true)
340  --- @cast t table<any,any>
341
342  local pred --- @type fun(v: any): boolean?
343  if opts and opts.predicate then
344    vim.validate('value', value, 'callable')
345    pred = value
346  else
347    --- @param v any
348    pred = function(v)
349      return v == value
350    end
351  end
352
353  for _, v in pairs(t) do
354    if pred(v) then
355      return true
356    end
357  end
358  return 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)
369  vim.validate('t', t, 'table')
370  --- @cast t table<any,any>
371
372  for _, v in ipairs(t) do
373    if v == value then
374      return true
375    end
376  end
377  return 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)
386  vim.validate('key', key, { 'string', 'function' }, true)
387
388  if not key then
389    return function(v)
390      return v
391    end
392  end
393
394  if type(key) == 'string' then
395    local field = key
396    ---@param v any
397    key = function(v)
398      return v and v[field]
399    end
400  end
401
402  return 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)
436  vim.validate('t', t, 'table')
437  local key_fn = make_key_fn(key)
438  local seen = {} --- @type table<any,boolean>
439
440  local finish = #t
441
442  local j = 1
443  for i = 1, finish do
444    local v = t[i]
445    local vh = key_fn(v)
446    if not seen[vh] then
447      t[j] = v
448      if vh ~= nil then
449        seen[vh] = true
450      end
451      j = j + 1
452    end
453  end
454
455  for i = j, finish do
456    t[i] = nil
457  end
458
459  return 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)
496  local bit = require('bit') -- Load bitop on demand
497  local val_key = key_fn(val)
498  while lo < hi do
499    local mid = bit.rshift(lo + hi, 1) -- Equivalent to floor((lo + hi) / 2)
500    if key_fn(t[mid]) < val_key then
501      lo = mid + 1
502    else
503      hi = mid
504    end
505  end
506  return 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)
519  local bit = require('bit') -- Load bitop on demand
520  local val_key = key_fn(val)
521  while lo < hi do
522    local mid = bit.rshift(lo + hi, 1) -- Equivalent to floor((lo + hi) / 2)
523    if val_key < key_fn(t[mid]) then
524      hi = mid
525    else
526      lo = mid + 1
527    end
528  end
529  return 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)
578  vim.validate('t', t, 'table')
579  vim.validate('opts', opts, 'table', true)
580
581  opts = opts or {}
582  local lo = opts.lo or 1
583  local hi = opts.hi or #t + 1
584  local key_fn = make_key_fn(opts.key)
585
586  if opts.bound == 'upper' then
587    return upper_bound(t, val, lo, hi, key_fn)
588  else
589    return lower_bound(t, val, lo, hi, key_fn)
590  end
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)
600  vim.validate('t', t, 'table')
601  return 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)
608  return 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, ...)
616  local ret = {} --- @type table<any,any>
617  if vim._empty_dict_mt ~= nil and getmetatable(select(1, ...)) == vim._empty_dict_mt then
618    ret = vim.empty_dict()
619  end
620
621  for i = 1, select('#', ...) do
622    local tbl = select(i, ...) --[[@as table<any,any>]]
623    if tbl then
624      for k, v in pairs(tbl) do
625        if deep_extend and can_merge(v) and can_merge(ret[k]) then
626          ret[k] = tbl_extend_rec(behavior, true, ret[k], v)
627        elseif type(behavior) == 'function' then
628          ret[k] = behavior(k, ret[k], v)
629        elseif behavior ~= 'force' and ret[k] ~= nil then
630          if behavior == 'error' then
631            error('key found in more than one map: ' .. k)
632          end -- Else behavior is "keep".
633        else
634          ret[k] = v
635        end
636      end
637    end
638  end
639
640  return 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, ...)
647  if
648    behavior ~= 'error'
649    and behavior ~= 'keep'
650    and behavior ~= 'force'
651    and type(behavior) ~= 'function'
652  then
653    error('invalid "behavior": ' .. tostring(behavior))
654  end
655
656  local nargs = select('#', ...)
657
658  if nargs < 2 then
659    error(('wrong number of arguments (given %d, expected at least 3)'):format(1 + nargs))
660  end
661
662  for i = 1, nargs do
663    vim.validate('after the second argument', select(i, ...), 'table')
664  end
665
666  return 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, ...)
682  return 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, ...)
715  return 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)
723  if left == right then
724    return true
725  end
726
727  if type(left) ~= type(right) then
728    return false
729  end
730
731  if type(left) ~= 'table' then
732    return false
733  end
734
735  ---@cast left table<any, any>
736  ---@cast right table<any, any>
737  seen = seen or {}
738  local seen_left = seen[left]
739  if seen_left and seen_left[right] ~= nil then
740    return seen_left[right]
741  end
742
743  seen_left = seen_left or {}
744  seen[left] = seen_left
745  -- Assume equality while descending so recursive structures can terminate.
746  seen_left[right] = true
747
748  for k, v in pairs(left) do
749    if not deep_equal(v, right[k], seen) then
750      seen_left[right] = false
751      return false
752    end
753  end
754
755  for k in pairs(right) do
756    if left[k] == nil then
757      seen_left[right] = false
758      return false
759    end
760  end
761
762  return 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)
774  return 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, ...)
797  local nargs = select('#', ...)
798  if nargs == 0 then
799    return nil
800  end
801  for i = 1, nargs do
802    o = o[select(i, ...)] --- @type any
803    if o == nil then
804      return nil
805    elseif type(o) ~= 'table' and i ~= nargs then
806      return nil
807    end
808  end
809  return 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)
825  vim.validate('dst', dst, 'table')
826  vim.validate('src', src, 'table')
827  vim.validate('start', start, 'number', true)
828  vim.validate('finish', finish, 'number', true)
829  for i = start or 1, finish or #src do
830    table.insert(dst, src[i])
831  end
832  return 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)
844  vim.deprecate('vim.tbl_flatten', 'vim.iter(…):flatten():totable()', '0.13')
845  local result = {}
846  --- @param _t table<any,any>
847  local function _tbl_flatten(_t)
848    local n = #_t
849    for i = 1, n do
850      local v = _t[i]
851      if type(v) == 'table' then
852        _tbl_flatten(v)
853      elseif v then
854        table.insert(result, v)
855      end
856    end
857  end
858  _tbl_flatten(t)
859  return 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)
871  vim.validate('t', t, 'table')
872  --- @cast t table<any,any>
873
874  -- collect the keys
875  local keys = {} --- @type string[]
876  for k in pairs(t) do
877    table.insert(keys, k)
878  end
879  table.sort(keys)
880
881  -- Return the iterator function.
882  local i = 0
883  return function()
884    i = i + 1
885    if keys[i] then
886      return keys[i], t[keys[i]]
887    end
888  end,
889    t
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)
904  if type(t) ~= 'table' then
905    return false
906  end
907
908  --- @cast t table<any,any>
909
910  local count = 0
911
912  for k, _ in pairs(t) do
913    -- Check if the number k is an integer
914    if type(k) == 'number' and k == math.floor(k) then
915      count = count + 1
916    else
917      return false
918    end
919  end
920
921  if count > 0 then
922    return true
923  else
924    -- TODO(bfredl): in the future, we will always be inside nvim
925    -- then this check can be deleted.
926    if vim._empty_dict_mt == nil then
927      return false
928    end
929    return getmetatable(t) ~= vim._empty_dict_mt
930  end
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)
944  if type(t) ~= 'table' then
945    return false
946  end
947
948  if next(t) == nil then
949    return getmetatable(t) ~= vim._empty_dict_mt
950  end
951
952  local j = 1
953  for _ in
954    pairs(t--[[@as table<any,any>]])
955  do
956    if rawget(t, j) == nil then
957      return false
958    end
959    j = j + 1
960  end
961
962  return 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)
973  return 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)
987  vim.validate('t', t, 'table')
988  --- @cast t table<any,any>
989
990  local count = 0
991  for _ in pairs(t) do
992    count = count + 1
993  end
994  return 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)
1005  local new_list = {} --- @type `T`[]
1006  for i = start or 1, finish or #list do
1007    new_list[#new_list + 1] = list[i]
1008  end
1009  return 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)
1025  local n = #t
1026
1027  -- Shift table forward
1028  for i = n - first, 0, -1 do
1029    t[last + 1 + i] = t[first + i]
1030  end
1031
1032  -- Fill in new values
1033  for i = first, last do
1034    t[i] = v
1035  end
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)
1050  local n = #t
1051  for i = 0, n - first do
1052    t[first + i] = t[last + 1 + i]
1053    t[last + 1 + i] = nil
1054  end
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)
1064  vim.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
1067  return 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)
1076  vim.validate('s', s, 'string')
1077  return (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)
1086  vim.validate('s', s, 'string')
1087  vim.validate('prefix', prefix, 'string')
1088  return 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)
1097  vim.validate('s', s, 'string')
1098  vim.validate('suffix', suffix, 'string')
1099  return #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
1109  local type_aliases = {
1110    b = 'boolean',
1111    c = 'callable',
1112    f = 'function',
1113    n = 'number',
1114    s = 'string',
1115    t = '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
1126  local function is_type(val, t)
1127    return type(val) == t or (t == 'callable' and vim.is_callable(val))
1128  end
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?
1136  local function is_valid(param_name, val, validator, message, allow_alias)
1137    if type(validator) == 'string' then
1138      local expected = allow_alias and type_aliases[validator] or validator
1139
1140      if not expected then
1141        return string.format('invalid type name: %s', validator)
1142      end
1143
1144      if not is_type(val, expected) then
1145        return ('%s: expected %s, got %s'):format(param_name, message or expected, type(val))
1146      end
1147    elseif vim.is_callable(validator) then
1148      -- Check user-provided validation function
1149      ---@cast validator fun(v: any): boolean, string?
1150      local valid, opt_msg = validator(val)
1151      if not valid then
1152        local err_msg = ('%s: expected %s, got %s'):format(
1153          param_name,
1154          message or '?',
1155          tostring(val)
1156        )
1157        err_msg = opt_msg and ('%s. Info: %s'):format(err_msg, opt_msg) or err_msg
1158
1159        return err_msg
1160      end
1161    elseif type(validator) == 'table' then
1162      for _, t in ipairs(validator) do
1163        local expected = allow_alias and type_aliases[t] or t
1164        if not expected then
1165          return string.format('invalid type name: %s', t)
1166        end
1167
1168        if is_type(val, expected) then
1169          return -- success
1170        end
1171      end
1172
1173      -- Normalize validator types for error message
1174      if allow_alias then
1175        for i, t in ipairs(validator) do
1176          validator[i] = type_aliases[t] or t
1177        end
1178      end
1179
1180      return string.format(
1181        '%s: expected %s, got %s',
1182        param_name,
1183        table.concat(validator, '|'),
1184        type(val)
1185      )
1186    else
1187      return string.format('invalid validator: %s', tostring(validator))
1188    end
1189  end
1190
1191  --- @param opt table<type|'callable',vim.validate.Spec>
1192  --- @return string?
1193  local function validate_spec(opt)
1194    local report --- @type table<string,string>?
1195
1196    for param_name, spec in pairs(opt) do
1197      local err_msg --- @type string?
1198      if type(spec) ~= 'table' then
1199        err_msg = string.format('opt[%s]: expected table, got %s', param_name, type(spec))
1200      else
1201        local value, validator = spec[1], spec[2]
1202        local msg = type(spec[3]) == 'string' and spec[3] or nil --[[@as string?]]
1203        local optional = spec[3] == true
1204        if not (optional and value == nil) then
1205          err_msg = is_valid(param_name, value, validator, msg, true)
1206        end
1207      end
1208
1209      if err_msg then
1210        report = report or {}
1211        report[param_name] = err_msg
1212      end
1213    end
1214
1215    if report then
1216      for _, msg in vim.spairs(report) do -- luacheck: ignore
1217        return msg
1218      end
1219    end
1220  end
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]>)
1286  function vim.validate(name, value, validator, optional, message)
1287    local err_msg --- @type string?
1288    if validator then -- Form 1
1289      -- Check validator as a string first to optimize the common case.
1290      local ok = (type(value) == validator) or (value == nil and optional == true)
1291      if not ok then
1292        local msg = type(optional) == 'string' and optional or message --[[@as string?]]
1293        -- Check more complicated validators
1294        err_msg = is_valid(name, value, validator, msg, false)
1295      end
1296    elseif type(name) == 'table' then -- Form 2
1297      vim.deprecate('vim.validate{<table>}', 'vim.validate(<params>)', '1.0')
1298      err_msg = validate_spec(name)
1299    else
1300      error('invalid arguments')
1301    end
1302
1303    if err_msg then
1304      error(err_msg, 2)
1305    end
1306  end
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)
1314  if type(f) == 'function' then
1315    return true
1316  end
1317  local m = getmetatable(f)
1318  if m == nil then
1319    return false
1320  end
1321  return 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)
1337  createfn = createfn or function(_)
1338    return vim.defaulttable()
1339  end
1340  return setmetatable({}, {
1341    __index = function(tbl, key)
1342      rawset(tbl, key, createfn(key))
1343      return rawget(tbl, key)
1344    end,
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?
1355  local Ringbuf = {}
1356
1357  --- Clear all items
1358  function Ringbuf.clear(self)
1359    self._items = {}
1360    self._idx_read = 0
1361    self._idx_write = 0
1362  end
1363
1364  --- Adds an item, overriding the oldest item if the buffer is full.
1365  ---@param item T
1366  function Ringbuf.push(self, item)
1367    self._items[self._idx_write] = item
1368    self._idx_write = (self._idx_write + 1) % self._size
1369    if self._idx_write == self._idx_read then
1370      self._idx_read = (self._idx_read + 1) % self._size
1371    end
1372  end
1373
1374  --- Removes and returns the first unread item
1375  ---@return T?
1376  function Ringbuf.pop(self)
1377    local idx_read = self._idx_read
1378    if idx_read == self._idx_write then
1379      return nil
1380    end
1381    local item = self._items[idx_read]
1382    self._items[idx_read] = nil
1383    self._idx_read = (idx_read + 1) % self._size
1384    return item
1385  end
1386
1387  --- Returns the first unread item without removing it
1388  ---@return T?
1389  function Ringbuf.peek(self)
1390    if self._idx_read == self._idx_write then
1391      return nil
1392    end
1393    return self._items[self._idx_read]
1394  end
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
1424  function vim.ringbuf(size)
1425    local ringbuf = {
1426      _items = {},
1427      _size = size + 1,
1428      _idx_read = 0,
1429      _idx_write = 0,
1430    }
1431    return setmetatable(ringbuf, {
1432      __index = Ringbuf,
1433      __call = function(self)
1434        return self:pop()
1435      end,
1436    })
1437  end
1438end
1439
1440--- @generic T
1441--- @param root string
1442--- @param mod T
1443--- @return T
1444function vim._defer_require(root, mod)
1445  return setmetatable({ _submodules = mod }, {
1446    ---@param t table<string, any>
1447    ---@param k string
1448    __index = function(t, k)
1449      if not mod[k] then
1450        return
1451      end
1452      local name = string.format('%s.%s', root, k)
1453      t[k] = require(name)
1454      return t[k]
1455    end,
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)
1468  return setmetatable({}, {
1469    ---@param _ table<string, any>
1470    ---@param k string
1471    __index = function(_, k)
1472      vim.deprecate(old_name, new_name, '2.0.0', nil, false)
1473      --- @diagnostic disable-next-line:no-unknown
1474      local target = require(new_name)
1475      return target[k]
1476    end,
1477    __call = function(self)
1478      vim.deprecate(old_name, new_name, '2.0.0', nil, false)
1479      --- @diagnostic disable-next-line:no-unknown
1480      local target = require(new_name)
1481      return target(self)
1482    end,
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
1525  local res = { bo = {}, env = {}, go = {}, wo = {} }
1526
1527  -- Use specific order from possibly most to least intrusive
1528  for _, scope in ipairs(scope_order) do
1529    for name, _ in
1530      pairs(context[scope] or {} --[[@as table<string,any>]])
1531    do
1532      local 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)
1536      res[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).
1541      if sc ~= 'env' and res.go[name] == nil then
1542        res.go[name] = vim.go[name]
1543      end
1544    end
1545  end
1546
1547  return 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)
1575  vim.validate('context', context, 'table')
1576  vim.validate('f', f, 'function')
1577
1578  vim.validate('context.bo', context.bo, 'table', true)
1579  vim.validate('context.buf', context.buf, 'number', true)
1580  vim.validate('context.cwd', context.cwd, 'string', true)
1581  vim.validate('context.emsg_silent', context.emsg_silent, 'boolean', true)
1582  vim.validate('context.env', context.env, 'table', true)
1583  vim.validate('context.go', context.go, 'table', true)
1584  vim.validate('context.hide', context.hide, 'boolean', true)
1585  vim.validate('context.keepalt', context.keepalt, 'boolean', true)
1586  vim.validate('context.keepcwd', context.keepcwd, 'boolean', true)
1587  vim.validate('context.keepjumps', context.keepjumps, 'boolean', true)
1588  vim.validate('context.keepmarks', context.keepmarks, 'boolean', true)
1589  vim.validate('context.keeppatterns', context.keeppatterns, 'boolean', true)
1590  vim.validate('context.lockmarks', context.lockmarks, 'boolean', true)
1591  vim.validate('context.noautocmd', context.noautocmd, 'boolean', true)
1592  vim.validate('context.o', context.o, 'table', true)
1593  vim.validate('context.sandbox', context.sandbox, 'boolean', true)
1594  vim.validate('context.silent', context.silent, 'boolean', true)
1595  vim.validate('context.unsilent', context.unsilent, 'boolean', true)
1596  vim.validate('context.win', context.win, 'number', true)
1597  vim.validate('context.wo', context.wo, 'table', true)
1598
1599  -- Check buffer exists
1600  if context.buf then
1601    if not vim.api.nvim_buf_is_valid(context.buf) then
1602      error('Invalid buffer id: ' .. context.buf)
1603    end
1604    context.buf = context.buf == 0 and vim.api.nvim_get_current_buf() or context.buf
1605  end
1606
1607  -- Check window exists
1608  if context.win then
1609    if not vim.api.nvim_win_is_valid(context.win) then
1610      error('Invalid window id: ' .. context.win)
1611    end
1612    -- TODO: Maybe allow it?
1613    if context.buf and vim.api.nvim_win_get_buf(context.win) ~= context.buf then
1614      error('Can not set both `buf` and `win` context.')
1615    end
1616    context.win = context.win == 0 and vim.api.nvim_get_current_win() or context.win
1617  end
1618
1619  -- Decorate so that save-set-restore options is done in correct window-buffer
1620  local callback = function()
1621    -- Cache current values to be changed by context
1622    -- Abort early in case of bad context value
1623    local ok, state = pcall(get_context_state, context)
1624    if not ok then
1625      error(state, 0)
1626    end
1627
1628    -- Apply some parts of the context in specific order
1629    -- NOTE: triggers `OptionSet` event
1630    for _, scope in ipairs(scope_order) do
1631      for name, context_value in
1632        pairs(context[scope] or {} --[[@as table<string,any>]])
1633      do
1634        --- @diagnostic disable-next-line:no-unknown
1635        vim[scope][name] = context_value
1636      end
1637    end
1638
1639    --- @type string
1640    local state_cwd
1641    if context.cwd then
1642      -- NOTE: triggers `DirChanged{Pre,}` events
1643      state_cwd = vim.fn.chdir(context.cwd)
1644    end
1645
1646    -- Execute
1647    local res = { pcall(f) }
1648
1649    -- Restore relevant cached values in specific order, global scope last
1650    -- NOTE: triggers `OptionSet` event
1651    for _, scope in ipairs(state_restore_order) do
1652      for name, cached_value in
1653        pairs(state[scope] --[[@as table<string,any>]])
1654      do
1655        --- @diagnostic disable-next-line:no-unknown
1656        vim[scope][name] = cached_value
1657      end
1658    end
1659
1660    if state_cwd then
1661      -- NOTE: triggers `DirChanged{Pre,}` events
1662      vim.fn.chdir(state_cwd)
1663    end
1664
1665    -- Return
1666    if not res[1] then
1667      error(res[2], 0)
1668    end
1669    table.remove(res, 1)
1670    return unpack(res, 1, table.maxn(res))
1671  end
1672
1673  return vim._with_c(context, callback)
1674end
1675
1676--- @param buf? integer
1677--- @return integer
1678function vim._resolve_bufnr(buf)
1679  if buf == nil or buf == 0 then
1680    return vim.api.nvim_get_current_buf()
1681  end
1682  vim.validate('buf', buf, 'number')
1683  return buf
1684end
1685
1686--- @generic T
1687--- @param x T|T[]
1688--- @return T[]
1689function vim._ensure_list(x)
1690  if type(x) == 'table' then
1691    --- @cast x T[]
1692    return x
1693  end
1694  return { 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)`
1707  local nx = tonumber(x, base)
1708  if nx and nx == math.floor(nx) then
1709    --- @cast nx integer
1710    return nx
1711  end
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)
1723  return 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(...)
1748  local nargs = select('#', ...)
1749  for i = 1, nargs do
1750    local v = select(i, ...)
1751    if v ~= nil then
1752      return v
1753    end
1754  end
1755  return 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, ...)
1767  return (function(success, ...)
1768    if success then
1769      return ...
1770    end
1771  end)(pcall(fn, ...))
1772end
1773
1774---@generic T
1775---@param fn fun(...):T
1776---@param ... any?
1777---@return T ...
1778function vim.wrap(fn, ...)
1779  local props = vim.F.pack_len(...)
1780  return function()
1781    return vim.npcall(fn, vim.F.unpack_len(props))
1782  end
1783end
1784
1785return vim