shared.lua 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423
  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. ---@nodoc
  9. ---@diagnostic disable-next-line: lowercase-global
  10. vim = vim or {}
  11. ---@generic T
  12. ---@param orig T
  13. ---@param cache? table<any,any>
  14. ---@return T
  15. local function deepcopy(orig, cache)
  16. if orig == vim.NIL then
  17. return vim.NIL
  18. elseif type(orig) == 'userdata' or type(orig) == 'thread' then
  19. error('Cannot deepcopy object of type ' .. type(orig))
  20. elseif type(orig) ~= 'table' then
  21. return orig
  22. end
  23. --- @cast orig table<any,any>
  24. if cache and cache[orig] then
  25. return cache[orig]
  26. end
  27. local copy = {} --- @type table<any,any>
  28. if cache then
  29. cache[orig] = copy
  30. end
  31. for k, v in pairs(orig) do
  32. copy[deepcopy(k, cache)] = deepcopy(v, cache)
  33. end
  34. return setmetatable(copy, getmetatable(orig))
  35. end
  36. --- Returns a deep copy of the given object. Non-table objects are copied as
  37. --- in a typical Lua assignment, whereas table objects are copied recursively.
  38. --- Functions are naively copied, so functions in the copied table point to the
  39. --- same functions as those in the input table. Userdata and threads are not
  40. --- copied and will throw an error.
  41. ---
  42. --- Note: `noref=true` is much more performant on tables with unique table
  43. --- fields, while `noref=false` is more performant on tables that reuse table
  44. --- fields.
  45. ---
  46. ---@generic T: table
  47. ---@param orig T Table to copy
  48. ---@param noref? boolean
  49. --- When `false` (default) a contained table is only copied once and all
  50. --- references point to this single copy. When `true` every occurrence of a
  51. --- table results in a new copy. This also means that a cyclic reference can
  52. --- cause `deepcopy()` to fail.
  53. ---@return T Table of copied keys and (nested) values.
  54. function vim.deepcopy(orig, noref)
  55. return deepcopy(orig, not noref and {} or nil)
  56. end
  57. --- @class vim.gsplit.Opts
  58. --- @inlinedoc
  59. ---
  60. --- Use `sep` literally (as in string.find).
  61. --- @field plain? boolean
  62. ---
  63. --- Discard empty segments at start and end of the sequence.
  64. --- @field trimempty? boolean
  65. --- Gets an |iterator| that splits a string at each instance of a separator, in "lazy" fashion
  66. --- (as opposed to |vim.split()| which is "eager").
  67. ---
  68. --- Example:
  69. ---
  70. --- ```lua
  71. --- for s in vim.gsplit(':aa::b:', ':', {plain=true}) do
  72. --- print(s)
  73. --- end
  74. --- ```
  75. ---
  76. --- If you want to also inspect the separator itself (instead of discarding it), use
  77. --- |string.gmatch()|. Example:
  78. ---
  79. --- ```lua
  80. --- for word, num in ('foo111bar222'):gmatch('([^0-9]*)(%d*)') do
  81. --- print(('word: %s num: %s'):format(word, num))
  82. --- end
  83. --- ```
  84. ---
  85. --- @see |string.gmatch()|
  86. --- @see |vim.split()|
  87. --- @see |lua-patterns|
  88. --- @see https://www.lua.org/pil/20.2.html
  89. --- @see http://lua-users.org/wiki/StringLibraryTutorial
  90. ---
  91. --- @param s string String to split
  92. --- @param sep string Separator or pattern
  93. --- @param opts? vim.gsplit.Opts Keyword arguments |kwargs|:
  94. --- @return fun():string? : Iterator over the split components
  95. function vim.gsplit(s, sep, opts)
  96. local plain --- @type boolean?
  97. local trimempty = false
  98. if type(opts) == 'boolean' then
  99. plain = opts -- For backwards compatibility.
  100. else
  101. vim.validate('s', s, 'string')
  102. vim.validate('sep', sep, 'string')
  103. vim.validate('opts', opts, 'table', true)
  104. opts = opts or {}
  105. plain, trimempty = opts.plain, opts.trimempty
  106. end
  107. local start = 1
  108. local done = false
  109. -- For `trimempty`: queue of collected segments, to be emitted at next pass.
  110. local segs = {}
  111. local empty_start = true -- Only empty segments seen so far.
  112. --- @param i integer?
  113. --- @param j integer
  114. --- @param ... unknown
  115. --- @return string
  116. --- @return ...
  117. local function _pass(i, j, ...)
  118. if i then
  119. assert(j + 1 > start, 'Infinite loop detected')
  120. local seg = s:sub(start, i - 1)
  121. start = j + 1
  122. return seg, ...
  123. else
  124. done = true
  125. return s:sub(start)
  126. end
  127. end
  128. return function()
  129. if trimempty and #segs > 0 then
  130. -- trimempty: Pop the collected segments.
  131. return table.remove(segs)
  132. elseif done or (s == '' and sep == '') then
  133. return nil
  134. elseif sep == '' then
  135. if start == #s then
  136. done = true
  137. end
  138. return _pass(start + 1, start)
  139. end
  140. local seg = _pass(s:find(sep, start, plain))
  141. -- Trim empty segments from start/end.
  142. if trimempty and seg ~= '' then
  143. empty_start = false
  144. elseif trimempty and seg == '' then
  145. while not done and seg == '' do
  146. table.insert(segs, 1, '')
  147. seg = _pass(s:find(sep, start, plain))
  148. end
  149. if done and seg == '' then
  150. return nil
  151. elseif empty_start then
  152. empty_start = false
  153. segs = {}
  154. return seg
  155. end
  156. if seg ~= '' then
  157. table.insert(segs, 1, seg)
  158. end
  159. return table.remove(segs)
  160. end
  161. return seg
  162. end
  163. end
  164. --- Splits a string at each instance of a separator and returns the result as a table (unlike
  165. --- |vim.gsplit()|).
  166. ---
  167. --- Examples:
  168. ---
  169. --- ```lua
  170. --- split(":aa::b:", ":") --> {'','aa','','b',''}
  171. --- split("axaby", "ab?") --> {'','x','y'}
  172. --- split("x*yz*o", "*", {plain=true}) --> {'x','yz','o'}
  173. --- split("|x|y|z|", "|", {trimempty=true}) --> {'x', 'y', 'z'}
  174. --- ```
  175. ---
  176. ---@see |vim.gsplit()|
  177. ---@see |string.gmatch()|
  178. ---
  179. ---@param s string String to split
  180. ---@param sep string Separator or pattern
  181. ---@param opts? vim.gsplit.Opts Keyword arguments |kwargs|:
  182. ---@return string[] : List of split components
  183. function vim.split(s, sep, opts)
  184. local t = {}
  185. for c in vim.gsplit(s, sep, opts) do
  186. table.insert(t, c)
  187. end
  188. return t
  189. end
  190. --- Return a list of all keys used in a table.
  191. --- However, the order of the return table of keys is not guaranteed.
  192. ---
  193. ---@see From https://github.com/premake/premake-core/blob/master/src/base/table.lua
  194. ---
  195. ---@generic T
  196. ---@param t table<T, any> (table) Table
  197. ---@return T[] : List of keys
  198. function vim.tbl_keys(t)
  199. vim.validate('t', t, 'table')
  200. --- @cast t table<any,any>
  201. local keys = {}
  202. for k in pairs(t) do
  203. table.insert(keys, k)
  204. end
  205. return keys
  206. end
  207. --- Return a list of all values used in a table.
  208. --- However, the order of the return table of values is not guaranteed.
  209. ---
  210. ---@generic T
  211. ---@param t table<any, T> (table) Table
  212. ---@return T[] : List of values
  213. function vim.tbl_values(t)
  214. vim.validate('t', t, 'table')
  215. local values = {}
  216. for _, v in
  217. pairs(t --[[@as table<any,any>]])
  218. do
  219. table.insert(values, v)
  220. end
  221. return values
  222. end
  223. --- Apply a function to all values of a table.
  224. ---
  225. ---@generic T
  226. ---@param func fun(value: T): any Function
  227. ---@param t table<any, T> Table
  228. ---@return table : Table of transformed values
  229. function vim.tbl_map(func, t)
  230. vim.validate('func', func, 'callable')
  231. vim.validate('t', t, 'table')
  232. --- @cast t table<any,any>
  233. local rettab = {} --- @type table<any,any>
  234. for k, v in pairs(t) do
  235. rettab[k] = func(v)
  236. end
  237. return rettab
  238. end
  239. --- Filter a table using a predicate function
  240. ---
  241. ---@generic T
  242. ---@param func fun(value: T): boolean (function) Function
  243. ---@param t table<any, T> (table) Table
  244. ---@return T[] : Table of filtered values
  245. function vim.tbl_filter(func, t)
  246. vim.validate('func', func, 'callable')
  247. vim.validate('t', t, 'table')
  248. --- @cast t table<any,any>
  249. local rettab = {} --- @type table<any,any>
  250. for _, entry in pairs(t) do
  251. if func(entry) then
  252. rettab[#rettab + 1] = entry
  253. end
  254. end
  255. return rettab
  256. end
  257. --- @class vim.tbl_contains.Opts
  258. --- @inlinedoc
  259. ---
  260. --- `value` is a function reference to be checked (default false)
  261. --- @field predicate? boolean
  262. --- Checks if a table contains a given value, specified either directly or via
  263. --- a predicate that is checked for each value.
  264. ---
  265. --- Example:
  266. ---
  267. --- ```lua
  268. --- vim.tbl_contains({ 'a', { 'b', 'c' } }, function(v)
  269. --- return vim.deep_equal(v, { 'b', 'c' })
  270. --- end, { predicate = true })
  271. --- -- true
  272. --- ```
  273. ---
  274. ---@see |vim.list_contains()| for checking values in list-like tables
  275. ---
  276. ---@param t table Table to check
  277. ---@param value any Value to compare or predicate function reference
  278. ---@param opts? vim.tbl_contains.Opts Keyword arguments |kwargs|:
  279. ---@return boolean `true` if `t` contains `value`
  280. function vim.tbl_contains(t, value, opts)
  281. vim.validate('t', t, 'table')
  282. vim.validate('opts', opts, 'table', true)
  283. --- @cast t table<any,any>
  284. local pred --- @type fun(v: any): boolean?
  285. if opts and opts.predicate then
  286. vim.validate('value', value, 'callable')
  287. pred = value
  288. else
  289. pred = function(v)
  290. return v == value
  291. end
  292. end
  293. for _, v in pairs(t) do
  294. if pred(v) then
  295. return true
  296. end
  297. end
  298. return false
  299. end
  300. --- Checks if a list-like table (integer keys without gaps) contains `value`.
  301. ---
  302. ---@see |vim.tbl_contains()| for checking values in general tables
  303. ---
  304. ---@param t table Table to check (must be list-like, not validated)
  305. ---@param value any Value to compare
  306. ---@return boolean `true` if `t` contains `value`
  307. function vim.list_contains(t, value)
  308. vim.validate('t', t, 'table')
  309. --- @cast t table<any,any>
  310. for _, v in ipairs(t) do
  311. if v == value then
  312. return true
  313. end
  314. end
  315. return false
  316. end
  317. --- Checks if a table is empty.
  318. ---
  319. ---@see https://github.com/premake/premake-core/blob/master/src/base/table.lua
  320. ---
  321. ---@param t table Table to check
  322. ---@return boolean `true` if `t` is empty
  323. function vim.tbl_isempty(t)
  324. vim.validate('t', t, 'table')
  325. return next(t) == nil
  326. end
  327. --- We only merge empty tables or tables that are not list-like (indexed by consecutive integers
  328. --- starting from 1)
  329. local function can_merge(v)
  330. return type(v) == 'table' and (vim.tbl_isempty(v) or not vim.islist(v))
  331. end
  332. --- Recursive worker for tbl_extend
  333. --- @param behavior 'error'|'keep'|'force'
  334. --- @param deep_extend boolean
  335. --- @param ... table<any,any>
  336. local function tbl_extend_rec(behavior, deep_extend, ...)
  337. local ret = {} --- @type table<any,any>
  338. if vim._empty_dict_mt ~= nil and getmetatable(select(1, ...)) == vim._empty_dict_mt then
  339. ret = vim.empty_dict()
  340. end
  341. for i = 1, select('#', ...) do
  342. local tbl = select(i, ...) --[[@as table<any,any>]]
  343. if tbl then
  344. for k, v in pairs(tbl) do
  345. if deep_extend and can_merge(v) and can_merge(ret[k]) then
  346. ret[k] = tbl_extend_rec(behavior, true, ret[k], v)
  347. elseif behavior ~= 'force' and ret[k] ~= nil then
  348. if behavior == 'error' then
  349. error('key found in more than one map: ' .. k)
  350. end -- Else behavior is "keep".
  351. else
  352. ret[k] = v
  353. end
  354. end
  355. end
  356. end
  357. return ret
  358. end
  359. --- @param behavior 'error'|'keep'|'force'
  360. --- @param deep_extend boolean
  361. --- @param ... table<any,any>
  362. local function tbl_extend(behavior, deep_extend, ...)
  363. if behavior ~= 'error' and behavior ~= 'keep' and behavior ~= 'force' then
  364. error('invalid "behavior": ' .. tostring(behavior))
  365. end
  366. local nargs = select('#', ...)
  367. if nargs < 2 then
  368. error(('wrong number of arguments (given %d, expected at least 3)'):format(1 + nargs))
  369. end
  370. for i = 1, nargs do
  371. vim.validate('after the second argument', select(i, ...), 'table')
  372. end
  373. return tbl_extend_rec(behavior, deep_extend, ...)
  374. end
  375. --- Merges two or more tables.
  376. ---
  377. ---@see |extend()|
  378. ---
  379. ---@param behavior 'error'|'keep'|'force' Decides what to do if a key is found in more than one map:
  380. --- - "error": raise an error
  381. --- - "keep": use value from the leftmost map
  382. --- - "force": use value from the rightmost map
  383. ---@param ... table Two or more tables
  384. ---@return table : Merged table
  385. function vim.tbl_extend(behavior, ...)
  386. return tbl_extend(behavior, false, ...)
  387. end
  388. --- Merges recursively two or more tables.
  389. ---
  390. --- Only values that are empty tables or tables that are not |lua-list|s (indexed by consecutive
  391. --- integers starting from 1) are merged recursively. This is useful for merging nested tables
  392. --- like default and user configurations where lists should be treated as literals (i.e., are
  393. --- overwritten instead of merged).
  394. ---
  395. ---@see |vim.tbl_extend()|
  396. ---
  397. ---@generic T1: table
  398. ---@generic T2: table
  399. ---@param behavior 'error'|'keep'|'force' Decides what to do if a key is found in more than one map:
  400. --- - "error": raise an error
  401. --- - "keep": use value from the leftmost map
  402. --- - "force": use value from the rightmost map
  403. ---@param ... T2 Two or more tables
  404. ---@return T1|T2 (table) Merged table
  405. function vim.tbl_deep_extend(behavior, ...)
  406. return tbl_extend(behavior, true, ...)
  407. end
  408. --- Deep compare values for equality
  409. ---
  410. --- Tables are compared recursively unless they both provide the `eq` metamethod.
  411. --- All other types are compared using the equality `==` operator.
  412. ---@param a any First value
  413. ---@param b any Second value
  414. ---@return boolean `true` if values are equals, else `false`
  415. function vim.deep_equal(a, b)
  416. if a == b then
  417. return true
  418. end
  419. if type(a) ~= type(b) then
  420. return false
  421. end
  422. if type(a) == 'table' then
  423. --- @cast a table<any,any>
  424. --- @cast b table<any,any>
  425. for k, v in pairs(a) do
  426. if not vim.deep_equal(v, b[k]) then
  427. return false
  428. end
  429. end
  430. for k in pairs(b) do
  431. if a[k] == nil then
  432. return false
  433. end
  434. end
  435. return true
  436. end
  437. return false
  438. end
  439. --- Add the reverse lookup values to an existing table.
  440. --- For example:
  441. --- `tbl_add_reverse_lookup { A = 1 } == { [1] = 'A', A = 1 }`
  442. ---
  443. --- Note that this *modifies* the input.
  444. ---@deprecated
  445. ---@param o table Table to add the reverse to
  446. ---@return table o
  447. function vim.tbl_add_reverse_lookup(o)
  448. vim.deprecate('vim.tbl_add_reverse_lookup', nil, '0.12')
  449. --- @cast o table<any,any>
  450. --- @type any[]
  451. local keys = vim.tbl_keys(o)
  452. for _, k in ipairs(keys) do
  453. local v = o[k]
  454. if o[v] then
  455. error(
  456. string.format(
  457. 'The reverse lookup found an existing value for %q while processing key %q',
  458. tostring(v),
  459. tostring(k)
  460. )
  461. )
  462. end
  463. o[v] = k
  464. end
  465. return o
  466. end
  467. --- Index into a table (first argument) via string keys passed as subsequent arguments.
  468. --- Return `nil` if the key does not exist.
  469. ---
  470. --- Examples:
  471. ---
  472. --- ```lua
  473. --- vim.tbl_get({ key = { nested_key = true }}, 'key', 'nested_key') == true
  474. --- vim.tbl_get({ key = {}}, 'key', 'nested_key') == nil
  475. --- ```
  476. ---
  477. ---@param o table Table to index
  478. ---@param ... any Optional keys (0 or more, variadic) via which to index the table
  479. ---@return any # Nested value indexed by key (if it exists), else nil
  480. function vim.tbl_get(o, ...)
  481. local keys = { ... }
  482. if #keys == 0 then
  483. return nil
  484. end
  485. for i, k in ipairs(keys) do
  486. o = o[k] --- @type any
  487. if o == nil then
  488. return nil
  489. elseif type(o) ~= 'table' and next(keys, i) then
  490. return nil
  491. end
  492. end
  493. return o
  494. end
  495. --- Extends a list-like table with the values of another list-like table.
  496. ---
  497. --- NOTE: This mutates dst!
  498. ---
  499. ---@see |vim.tbl_extend()|
  500. ---
  501. ---@generic T: table
  502. ---@param dst T List which will be modified and appended to
  503. ---@param src table List from which values will be inserted
  504. ---@param start integer? Start index on src. Defaults to 1
  505. ---@param finish integer? Final index on src. Defaults to `#src`
  506. ---@return T dst
  507. function vim.list_extend(dst, src, start, finish)
  508. vim.validate('dst', dst, 'table')
  509. vim.validate('src', src, 'table')
  510. vim.validate('start', start, 'number', true)
  511. vim.validate('finish', finish, 'number', true)
  512. for i = start or 1, finish or #src do
  513. table.insert(dst, src[i])
  514. end
  515. return dst
  516. end
  517. --- @deprecated
  518. --- Creates a copy of a list-like table such that any nested tables are
  519. --- "unrolled" and appended to the result.
  520. ---
  521. ---@see From https://github.com/premake/premake-core/blob/master/src/base/table.lua
  522. ---
  523. ---@param t table List-like table
  524. ---@return table Flattened copy of the given list-like table
  525. function vim.tbl_flatten(t)
  526. vim.deprecate('vim.tbl_flatten', 'vim.iter(…):flatten():totable()', '0.13')
  527. local result = {}
  528. --- @param _t table<any,any>
  529. local function _tbl_flatten(_t)
  530. local n = #_t
  531. for i = 1, n do
  532. local v = _t[i]
  533. if type(v) == 'table' then
  534. _tbl_flatten(v)
  535. elseif v then
  536. table.insert(result, v)
  537. end
  538. end
  539. end
  540. _tbl_flatten(t)
  541. return result
  542. end
  543. --- Enumerates key-value pairs of a table, ordered by key.
  544. ---
  545. ---@see Based on https://github.com/premake/premake-core/blob/master/src/base/table.lua
  546. ---
  547. ---@generic T: table, K, V
  548. ---@param t T Dict-like table
  549. ---@return fun(table: table<K, V>, index?: K):K, V # |for-in| iterator over sorted keys and their values
  550. ---@return T
  551. function vim.spairs(t)
  552. vim.validate('t', t, 'table')
  553. --- @cast t table<any,any>
  554. -- collect the keys
  555. local keys = {}
  556. for k in pairs(t) do
  557. table.insert(keys, k)
  558. end
  559. table.sort(keys)
  560. -- Return the iterator function.
  561. local i = 0
  562. return function()
  563. i = i + 1
  564. if keys[i] then
  565. return keys[i], t[keys[i]]
  566. end
  567. end,
  568. t
  569. end
  570. --- Tests if `t` is an "array": a table indexed _only_ by integers (potentially non-contiguous).
  571. ---
  572. --- If the indexes start from 1 and are contiguous then the array is also a list. |vim.islist()|
  573. ---
  574. --- Empty table `{}` is an array, unless it was created by |vim.empty_dict()| or returned as
  575. --- a dict-like |API| or Vimscript result, for example from |rpcrequest()| or |vim.fn|.
  576. ---
  577. ---@see https://github.com/openresty/luajit2#tableisarray
  578. ---
  579. ---@param t? table
  580. ---@return boolean `true` if array-like table, else `false`.
  581. function vim.isarray(t)
  582. if type(t) ~= 'table' then
  583. return false
  584. end
  585. --- @cast t table<any,any>
  586. local count = 0
  587. for k, _ in pairs(t) do
  588. -- Check if the number k is an integer
  589. if type(k) == 'number' and k == math.floor(k) then
  590. count = count + 1
  591. else
  592. return false
  593. end
  594. end
  595. if count > 0 then
  596. return true
  597. else
  598. -- TODO(bfredl): in the future, we will always be inside nvim
  599. -- then this check can be deleted.
  600. if vim._empty_dict_mt == nil then
  601. return false
  602. end
  603. return getmetatable(t) ~= vim._empty_dict_mt
  604. end
  605. end
  606. --- @deprecated
  607. function vim.tbl_islist(t)
  608. vim.deprecate('vim.tbl_islist', 'vim.islist', '0.12')
  609. return vim.islist(t)
  610. end
  611. --- Tests if `t` is a "list": a table indexed _only_ by contiguous integers starting from 1 (what
  612. --- |lua-length| calls a "regular array").
  613. ---
  614. --- Empty table `{}` is a list, unless it was created by |vim.empty_dict()| or returned as
  615. --- a dict-like |API| or Vimscript result, for example from |rpcrequest()| or |vim.fn|.
  616. ---
  617. ---@see |vim.isarray()|
  618. ---
  619. ---@param t? table
  620. ---@return boolean `true` if list-like table, else `false`.
  621. function vim.islist(t)
  622. if type(t) ~= 'table' then
  623. return false
  624. end
  625. if next(t) == nil then
  626. return getmetatable(t) ~= vim._empty_dict_mt
  627. end
  628. local j = 1
  629. for _ in
  630. pairs(t--[[@as table<any,any>]])
  631. do
  632. if t[j] == nil then
  633. return false
  634. end
  635. j = j + 1
  636. end
  637. return true
  638. end
  639. --- Counts the number of non-nil values in table `t`.
  640. ---
  641. --- ```lua
  642. --- vim.tbl_count({ a=1, b=2 }) --> 2
  643. --- vim.tbl_count({ 1, 2 }) --> 2
  644. --- ```
  645. ---
  646. ---@see https://github.com/Tieske/Penlight/blob/master/lua/pl/tablex.lua
  647. ---@param t table Table
  648. ---@return integer : Number of non-nil values in table
  649. function vim.tbl_count(t)
  650. vim.validate('t', t, 'table')
  651. --- @cast t table<any,any>
  652. local count = 0
  653. for _ in pairs(t) do
  654. count = count + 1
  655. end
  656. return count
  657. end
  658. --- Creates a copy of a table containing only elements from start to end (inclusive)
  659. ---
  660. ---@generic T
  661. ---@param list T[] Table
  662. ---@param start integer|nil Start range of slice
  663. ---@param finish integer|nil End range of slice
  664. ---@return T[] Copy of table sliced from start to finish (inclusive)
  665. function vim.list_slice(list, start, finish)
  666. local new_list = {} --- @type `T`[]
  667. for i = start or 1, finish or #list do
  668. new_list[#new_list + 1] = list[i]
  669. end
  670. return new_list
  671. end
  672. --- Efficiently insert items into the middle of a list.
  673. ---
  674. --- Calling table.insert() in a loop will re-index the tail of the table on
  675. --- every iteration, instead this function will re-index the table exactly
  676. --- once.
  677. ---
  678. --- Based on https://stackoverflow.com/questions/12394841/safely-remove-items-from-an-array-table-while-iterating/53038524#53038524
  679. ---
  680. ---@param t any[]
  681. ---@param first integer
  682. ---@param last integer
  683. ---@param v any
  684. function vim._list_insert(t, first, last, v)
  685. local n = #t
  686. -- Shift table forward
  687. for i = n - first, 0, -1 do
  688. t[last + 1 + i] = t[first + i]
  689. end
  690. -- Fill in new values
  691. for i = first, last do
  692. t[i] = v
  693. end
  694. end
  695. --- Efficiently remove items from middle of a list.
  696. ---
  697. --- Calling table.remove() in a loop will re-index the tail of the table on
  698. --- every iteration, instead this function will re-index the table exactly
  699. --- once.
  700. ---
  701. --- Based on https://stackoverflow.com/questions/12394841/safely-remove-items-from-an-array-table-while-iterating/53038524#53038524
  702. ---
  703. ---@param t any[]
  704. ---@param first integer
  705. ---@param last integer
  706. function vim._list_remove(t, first, last)
  707. local n = #t
  708. for i = 0, n - first do
  709. t[first + i] = t[last + 1 + i]
  710. t[last + 1 + i] = nil
  711. end
  712. end
  713. --- Trim whitespace (Lua pattern "%s") from both sides of a string.
  714. ---
  715. ---@see |lua-patterns|
  716. ---@see https://www.lua.org/pil/20.2.html
  717. ---@param s string String to trim
  718. ---@return string String with whitespace removed from its beginning and end
  719. function vim.trim(s)
  720. vim.validate('s', s, 'string')
  721. return s:match('^%s*(.*%S)') or ''
  722. end
  723. --- Escapes magic chars in |lua-patterns|.
  724. ---
  725. ---@see https://github.com/rxi/lume
  726. ---@param s string String to escape
  727. ---@return string %-escaped pattern string
  728. function vim.pesc(s)
  729. vim.validate('s', s, 'string')
  730. return (s:gsub('[%(%)%.%%%+%-%*%?%[%]%^%$]', '%%%1'))
  731. end
  732. --- Tests if `s` starts with `prefix`.
  733. ---
  734. ---@param s string String
  735. ---@param prefix string Prefix to match
  736. ---@return boolean `true` if `prefix` is a prefix of `s`
  737. function vim.startswith(s, prefix)
  738. vim.validate('s', s, 'string')
  739. vim.validate('prefix', prefix, 'string')
  740. return s:sub(1, #prefix) == prefix
  741. end
  742. --- Tests if `s` ends with `suffix`.
  743. ---
  744. ---@param s string String
  745. ---@param suffix string Suffix to match
  746. ---@return boolean `true` if `suffix` is a suffix of `s`
  747. function vim.endswith(s, suffix)
  748. vim.validate('s', s, 'string')
  749. vim.validate('suffix', suffix, 'string')
  750. return #suffix == 0 or s:sub(-#suffix) == suffix
  751. end
  752. do
  753. --- @alias vim.validate.Validator
  754. --- | type
  755. --- | 'callable'
  756. --- | (type|'callable')[]
  757. --- | fun(v:any):boolean, string?
  758. local type_aliases = {
  759. b = 'boolean',
  760. c = 'callable',
  761. f = 'function',
  762. n = 'number',
  763. s = 'string',
  764. t = 'table',
  765. }
  766. --- @nodoc
  767. --- @class vim.validate.Spec
  768. --- @field [1] any Argument value
  769. --- @field [2] vim.validate.Validator Argument validator
  770. --- @field [3]? boolean|string Optional flag or error message
  771. local function is_type(val, t)
  772. return type(val) == t or (t == 'callable' and vim.is_callable(val))
  773. end
  774. --- @param param_name string
  775. --- @param val any
  776. --- @param validator vim.validate.Validator
  777. --- @param message? string
  778. --- @param allow_alias? boolean Allow short type names: 'n', 's', 't', 'b', 'f', 'c'
  779. --- @return string?
  780. local function is_valid(param_name, val, validator, message, allow_alias)
  781. if type(validator) == 'string' then
  782. local expected = allow_alias and type_aliases[validator] or validator
  783. if not expected then
  784. return string.format('invalid type name: %s', validator)
  785. end
  786. if not is_type(val, expected) then
  787. return string.format('%s: expected %s, got %s', param_name, expected, type(val))
  788. end
  789. elseif vim.is_callable(validator) then
  790. -- Check user-provided validation function
  791. local valid, opt_msg = validator(val)
  792. if not valid then
  793. local err_msg =
  794. string.format('%s: expected %s, got %s', param_name, message or '?', tostring(val))
  795. if opt_msg then
  796. err_msg = string.format('%s. Info: %s', err_msg, opt_msg)
  797. end
  798. return err_msg
  799. end
  800. elseif type(validator) == 'table' then
  801. for _, t in ipairs(validator) do
  802. local expected = allow_alias and type_aliases[t] or t
  803. if not expected then
  804. return string.format('invalid type name: %s', t)
  805. end
  806. if is_type(val, expected) then
  807. return -- success
  808. end
  809. end
  810. -- Normalize validator types for error message
  811. if allow_alias then
  812. for i, t in ipairs(validator) do
  813. validator[i] = type_aliases[t] or t
  814. end
  815. end
  816. return string.format(
  817. '%s: expected %s, got %s',
  818. param_name,
  819. table.concat(validator, '|'),
  820. type(val)
  821. )
  822. else
  823. return string.format('invalid validator: %s', tostring(validator))
  824. end
  825. end
  826. --- @param opt table<type|'callable',vim.validate.Spec>
  827. --- @return string?
  828. local function validate_spec(opt)
  829. local report --- @type table<string,string>?
  830. for param_name, spec in pairs(opt) do
  831. local err_msg --- @type string?
  832. if type(spec) ~= 'table' then
  833. err_msg = string.format('opt[%s]: expected table, got %s', param_name, type(spec))
  834. else
  835. local value, validator = spec[1], spec[2]
  836. local msg = type(spec[3]) == 'string' and spec[3] or nil --[[@as string?]]
  837. local optional = spec[3] == true
  838. if not (optional and value == nil) then
  839. err_msg = is_valid(param_name, value, validator, msg, true)
  840. end
  841. end
  842. if err_msg then
  843. report = report or {}
  844. report[param_name] = err_msg
  845. end
  846. end
  847. if report then
  848. for _, msg in vim.spairs(report) do -- luacheck: ignore
  849. return msg
  850. end
  851. end
  852. end
  853. --- Validate function arguments.
  854. ---
  855. --- This function has two valid forms:
  856. ---
  857. --- 1. `vim.validate(name, value, validator[, optional][, message])`
  858. ---
  859. --- Validates that argument {name} with value {value} satisfies
  860. --- {validator}. If {optional} is given and is `true`, then {value} may be
  861. --- `nil`. If {message} is given, then it is used as the expected type in the
  862. --- error message.
  863. ---
  864. --- Example:
  865. ---
  866. --- ```lua
  867. --- function vim.startswith(s, prefix)
  868. --- vim.validate('s', s, 'string')
  869. --- vim.validate('prefix', prefix, 'string')
  870. --- -- ...
  871. --- end
  872. --- ```
  873. ---
  874. --- 2. `vim.validate(spec)` (deprecated)
  875. --- where `spec` is of type
  876. --- `table<string,[value:any, validator: vim.validate.Validator, optional_or_msg? : boolean|string]>)`
  877. ---
  878. --- Validates a argument specification.
  879. --- Specs are evaluated in alphanumeric order, until the first failure.
  880. ---
  881. --- Example:
  882. ---
  883. --- ```lua
  884. --- function user.new(name, age, hobbies)
  885. --- vim.validate{
  886. --- name={name, 'string'},
  887. --- age={age, 'number'},
  888. --- hobbies={hobbies, 'table'},
  889. --- }
  890. --- -- ...
  891. --- end
  892. --- ```
  893. ---
  894. --- Examples with explicit argument values (can be run directly):
  895. ---
  896. --- ```lua
  897. --- vim.validate('arg1', {'foo'}, 'table')
  898. --- --> NOP (success)
  899. --- vim.validate('arg2', 'foo', 'string')
  900. --- --> NOP (success)
  901. ---
  902. --- vim.validate('arg1', 1, 'table')
  903. --- --> error('arg1: expected table, got number')
  904. ---
  905. --- vim.validate('arg1', 3, function(a) return (a % 2) == 0 end, 'even number')
  906. --- --> error('arg1: expected even number, got 3')
  907. --- ```
  908. ---
  909. --- If multiple types are valid they can be given as a list.
  910. ---
  911. --- ```lua
  912. --- vim.validate('arg1', {'foo'}, {'table', 'string'})
  913. --- vim.validate('arg2', 'foo', {'table', 'string'})
  914. --- -- NOP (success)
  915. ---
  916. --- vim.validate('arg1', 1, {'string', 'table'})
  917. --- -- error('arg1: expected string|table, got number')
  918. --- ```
  919. ---
  920. --- @note `validator` set to a value returned by |lua-type()| provides the
  921. --- best performance.
  922. ---
  923. --- @param name string Argument name
  924. --- @param value any Argument value
  925. --- @param validator vim.validate.Validator
  926. --- - (`string|string[]`): Any value that can be returned from |lua-type()| in addition to
  927. --- `'callable'`: `'boolean'`, `'callable'`, `'function'`, `'nil'`, `'number'`, `'string'`, `'table'`,
  928. --- `'thread'`, `'userdata'`.
  929. --- - (`fun(val:any): boolean, string?`) A function that returns a boolean and an optional
  930. --- string message.
  931. --- @param optional? boolean Argument is optional (may be omitted)
  932. --- @param message? string message when validation fails
  933. --- @overload fun(name: string, val: any, validator: vim.validate.Validator, message: string)
  934. --- @overload fun(spec: table<string,[any, vim.validate.Validator, boolean|string]>)
  935. function vim.validate(name, value, validator, optional, message)
  936. local err_msg --- @type string?
  937. if validator then -- Form 1
  938. -- Check validator as a string first to optimize the common case.
  939. local ok = (type(value) == validator) or (value == nil and optional == true)
  940. if not ok then
  941. local msg = type(optional) == 'string' and optional or message --[[@as string?]]
  942. -- Check more complicated validators
  943. err_msg = is_valid(name, value, validator, msg, false)
  944. end
  945. elseif type(name) == 'table' then -- Form 2
  946. vim.deprecate('vim.validate', 'vim.validate(name, value, validator, optional_or_msg)', '1.0')
  947. err_msg = validate_spec(name)
  948. else
  949. error('invalid arguments')
  950. end
  951. if err_msg then
  952. error(err_msg, 2)
  953. end
  954. end
  955. end
  956. --- Returns true if object `f` can be called as a function.
  957. ---
  958. ---@param f any Any object
  959. ---@return boolean `true` if `f` is callable, else `false`
  960. function vim.is_callable(f)
  961. if type(f) == 'function' then
  962. return true
  963. end
  964. local m = getmetatable(f)
  965. if m == nil then
  966. return false
  967. end
  968. return type(rawget(m, '__call')) == 'function'
  969. end
  970. --- Creates a table whose missing keys are provided by {createfn} (like Python's "defaultdict").
  971. ---
  972. --- If {createfn} is `nil` it defaults to defaulttable() itself, so accessing nested keys creates
  973. --- nested tables:
  974. ---
  975. --- ```lua
  976. --- local a = vim.defaulttable()
  977. --- a.b.c = 1
  978. --- ```
  979. ---
  980. ---@param createfn? fun(key:any):any Provides the value for a missing `key`.
  981. ---@return table # Empty table with `__index` metamethod.
  982. function vim.defaulttable(createfn)
  983. createfn = createfn or function(_)
  984. return vim.defaulttable()
  985. end
  986. return setmetatable({}, {
  987. __index = function(tbl, key)
  988. rawset(tbl, key, createfn(key))
  989. return rawget(tbl, key)
  990. end,
  991. })
  992. end
  993. do
  994. ---@class vim.Ringbuf<T>
  995. ---@field private _items table[]
  996. ---@field private _idx_read integer
  997. ---@field private _idx_write integer
  998. ---@field private _size integer
  999. ---@overload fun(self): table?
  1000. local Ringbuf = {}
  1001. --- Clear all items
  1002. function Ringbuf.clear(self)
  1003. self._items = {}
  1004. self._idx_read = 0
  1005. self._idx_write = 0
  1006. end
  1007. --- Adds an item, overriding the oldest item if the buffer is full.
  1008. ---@generic T
  1009. ---@param item T
  1010. function Ringbuf.push(self, item)
  1011. self._items[self._idx_write] = item
  1012. self._idx_write = (self._idx_write + 1) % self._size
  1013. if self._idx_write == self._idx_read then
  1014. self._idx_read = (self._idx_read + 1) % self._size
  1015. end
  1016. end
  1017. --- Removes and returns the first unread item
  1018. ---@generic T
  1019. ---@return T?
  1020. function Ringbuf.pop(self)
  1021. local idx_read = self._idx_read
  1022. if idx_read == self._idx_write then
  1023. return nil
  1024. end
  1025. local item = self._items[idx_read]
  1026. self._items[idx_read] = nil
  1027. self._idx_read = (idx_read + 1) % self._size
  1028. return item
  1029. end
  1030. --- Returns the first unread item without removing it
  1031. ---@generic T
  1032. ---@return T?
  1033. function Ringbuf.peek(self)
  1034. if self._idx_read == self._idx_write then
  1035. return nil
  1036. end
  1037. return self._items[self._idx_read]
  1038. end
  1039. --- Create a ring buffer limited to a maximal number of items.
  1040. --- Once the buffer is full, adding a new entry overrides the oldest entry.
  1041. ---
  1042. --- ```lua
  1043. --- local ringbuf = vim.ringbuf(4)
  1044. --- ringbuf:push("a")
  1045. --- ringbuf:push("b")
  1046. --- ringbuf:push("c")
  1047. --- ringbuf:push("d")
  1048. --- ringbuf:push("e") -- overrides "a"
  1049. --- print(ringbuf:pop()) -- returns "b"
  1050. --- print(ringbuf:pop()) -- returns "c"
  1051. ---
  1052. --- -- Can be used as iterator. Pops remaining items:
  1053. --- for val in ringbuf do
  1054. --- print(val)
  1055. --- end
  1056. --- ```
  1057. ---
  1058. --- Returns a Ringbuf instance with the following methods:
  1059. ---
  1060. --- - |Ringbuf:push()|
  1061. --- - |Ringbuf:pop()|
  1062. --- - |Ringbuf:peek()|
  1063. --- - |Ringbuf:clear()|
  1064. ---
  1065. ---@param size integer
  1066. ---@return vim.Ringbuf ringbuf
  1067. function vim.ringbuf(size)
  1068. local ringbuf = {
  1069. _items = {},
  1070. _size = size + 1,
  1071. _idx_read = 0,
  1072. _idx_write = 0,
  1073. }
  1074. return setmetatable(ringbuf, {
  1075. __index = Ringbuf,
  1076. __call = function(self)
  1077. return self:pop()
  1078. end,
  1079. })
  1080. end
  1081. end
  1082. --- @private
  1083. --- @generic T
  1084. --- @param root string
  1085. --- @param mod T
  1086. --- @return T
  1087. function vim._defer_require(root, mod)
  1088. return setmetatable({ _submodules = mod }, {
  1089. ---@param t table<string, any>
  1090. ---@param k string
  1091. __index = function(t, k)
  1092. if not mod[k] then
  1093. return
  1094. end
  1095. local name = string.format('%s.%s', root, k)
  1096. t[k] = require(name)
  1097. return t[k]
  1098. end,
  1099. })
  1100. end
  1101. --- @private
  1102. --- Creates a module alias/shim that lazy-loads a target module.
  1103. ---
  1104. --- Unlike `vim.defaulttable()` this also:
  1105. --- - implements __call
  1106. --- - calls vim.deprecate()
  1107. ---
  1108. --- @param old_name string Name of the deprecated module, which will be shimmed.
  1109. --- @param new_name string Name of the new module, which will be loaded by require().
  1110. function vim._defer_deprecated_module(old_name, new_name)
  1111. return setmetatable({}, {
  1112. ---@param _ table<string, any>
  1113. ---@param k string
  1114. __index = function(_, k)
  1115. vim.deprecate(old_name, new_name, '2.0.0', nil, false)
  1116. --- @diagnostic disable-next-line:no-unknown
  1117. local target = require(new_name)
  1118. return target[k]
  1119. end,
  1120. __call = function(self)
  1121. vim.deprecate(old_name, new_name, '2.0.0', nil, false)
  1122. --- @diagnostic disable-next-line:no-unknown
  1123. local target = require(new_name)
  1124. return target(self)
  1125. end,
  1126. })
  1127. end
  1128. --- @nodoc
  1129. --- @class vim.context.mods
  1130. --- @field bo? table<string, any>
  1131. --- @field buf? integer
  1132. --- @field emsg_silent? boolean
  1133. --- @field env? table<string, any>
  1134. --- @field go? table<string, any>
  1135. --- @field hide? boolean
  1136. --- @field keepalt? boolean
  1137. --- @field keepjumps? boolean
  1138. --- @field keepmarks? boolean
  1139. --- @field keeppatterns? boolean
  1140. --- @field lockmarks? boolean
  1141. --- @field noautocmd? boolean
  1142. --- @field o? table<string, any>
  1143. --- @field sandbox? boolean
  1144. --- @field silent? boolean
  1145. --- @field unsilent? boolean
  1146. --- @field win? integer
  1147. --- @field wo? table<string, any>
  1148. --- @nodoc
  1149. --- @class vim.context.state
  1150. --- @field bo? table<string, any>
  1151. --- @field env? table<string, any>
  1152. --- @field go? table<string, any>
  1153. --- @field wo? table<string, any>
  1154. local scope_map = { buf = 'bo', global = 'go', win = 'wo' }
  1155. local scope_order = { 'o', 'wo', 'bo', 'go', 'env' }
  1156. local state_restore_order = { 'bo', 'wo', 'go', 'env' }
  1157. --- Gets data about current state, enough to properly restore specified options/env/etc.
  1158. --- @param context vim.context.mods
  1159. --- @return vim.context.state
  1160. local get_context_state = function(context)
  1161. --- @type vim.context.state
  1162. local res = { bo = {}, env = {}, go = {}, wo = {} }
  1163. -- Use specific order from possibly most to least intrusive
  1164. for _, scope in ipairs(scope_order) do
  1165. for name, _ in
  1166. pairs(context[scope] or {} --[[@as table<string,any>]])
  1167. do
  1168. local sc = scope == 'o' and scope_map[vim.api.nvim_get_option_info2(name, {}).scope] or scope
  1169. -- Do not override already set state and fall back to `vim.NIL` for
  1170. -- state `nil` values (which still needs restoring later)
  1171. res[sc][name] = res[sc][name] or vim[sc][name] or vim.NIL
  1172. -- Always track global option value to properly restore later.
  1173. -- This matters for at least `o` and `wo` (which might set either/both
  1174. -- local and global option values).
  1175. if sc ~= 'env' then
  1176. res.go[name] = res.go[name] or vim.go[name]
  1177. end
  1178. end
  1179. end
  1180. return res
  1181. end
  1182. --- Executes function `f` with the given context specification.
  1183. ---
  1184. --- Notes:
  1185. --- - Context `{ buf = buf }` has no guarantees about current window when
  1186. --- inside context.
  1187. --- - Context `{ buf = buf, win = win }` is yet not allowed, but this seems
  1188. --- to be an implementation detail.
  1189. --- - There should be no way to revert currently set `context.sandbox = true`
  1190. --- (like with nested `vim._with()` calls). Otherwise it kind of breaks the
  1191. --- whole purpose of sandbox execution.
  1192. --- - Saving and restoring option contexts (`bo`, `go`, `o`, `wo`) trigger
  1193. --- `OptionSet` events. This is an implementation issue because not doing it
  1194. --- seems to mean using either 'eventignore' option or extra nesting with
  1195. --- `{ noautocmd = true }` (which itself is a wrapper for 'eventignore').
  1196. --- As `{ go = { eventignore = '...' } }` is a valid context which should be
  1197. --- properly set and restored, this is not a good approach.
  1198. --- Not triggering `OptionSet` seems to be a good idea, though. So probably
  1199. --- only moving context save and restore to lower level might resolve this.
  1200. ---
  1201. --- @param context vim.context.mods
  1202. --- @param f function
  1203. --- @return any
  1204. function vim._with(context, f)
  1205. vim.validate('context', context, 'table')
  1206. vim.validate('f', f, 'function')
  1207. vim.validate('context.bo', context.bo, 'table', true)
  1208. vim.validate('context.buf', context.buf, 'number', true)
  1209. vim.validate('context.emsg_silent', context.emsg_silent, 'boolean', true)
  1210. vim.validate('context.env', context.env, 'table', true)
  1211. vim.validate('context.go', context.go, 'table', true)
  1212. vim.validate('context.hide', context.hide, 'boolean', true)
  1213. vim.validate('context.keepalt', context.keepalt, 'boolean', true)
  1214. vim.validate('context.keepjumps', context.keepjumps, 'boolean', true)
  1215. vim.validate('context.keepmarks', context.keepmarks, 'boolean', true)
  1216. vim.validate('context.keeppatterns', context.keeppatterns, 'boolean', true)
  1217. vim.validate('context.lockmarks', context.lockmarks, 'boolean', true)
  1218. vim.validate('context.noautocmd', context.noautocmd, 'boolean', true)
  1219. vim.validate('context.o', context.o, 'table', true)
  1220. vim.validate('context.sandbox', context.sandbox, 'boolean', true)
  1221. vim.validate('context.silent', context.silent, 'boolean', true)
  1222. vim.validate('context.unsilent', context.unsilent, 'boolean', true)
  1223. vim.validate('context.win', context.win, 'number', true)
  1224. vim.validate('context.wo', context.wo, 'table', true)
  1225. -- Check buffer exists
  1226. if context.buf then
  1227. if not vim.api.nvim_buf_is_valid(context.buf) then
  1228. error('Invalid buffer id: ' .. context.buf)
  1229. end
  1230. end
  1231. -- Check window exists
  1232. if context.win then
  1233. if not vim.api.nvim_win_is_valid(context.win) then
  1234. error('Invalid window id: ' .. context.win)
  1235. end
  1236. -- TODO: Maybe allow it?
  1237. if context.buf and vim.api.nvim_win_get_buf(context.win) ~= context.buf then
  1238. error('Can not set both `buf` and `win` context.')
  1239. end
  1240. end
  1241. -- Decorate so that save-set-restore options is done in correct window-buffer
  1242. local callback = function()
  1243. -- Cache current values to be changed by context
  1244. -- Abort early in case of bad context value
  1245. local ok, state = pcall(get_context_state, context)
  1246. if not ok then
  1247. error(state, 0)
  1248. end
  1249. -- Apply some parts of the context in specific order
  1250. -- NOTE: triggers `OptionSet` event
  1251. for _, scope in ipairs(scope_order) do
  1252. for name, context_value in
  1253. pairs(context[scope] or {} --[[@as table<string,any>]])
  1254. do
  1255. --- @diagnostic disable-next-line:no-unknown
  1256. vim[scope][name] = context_value
  1257. end
  1258. end
  1259. -- Execute
  1260. local res = { pcall(f) }
  1261. -- Restore relevant cached values in specific order, global scope last
  1262. -- NOTE: triggers `OptionSet` event
  1263. for _, scope in ipairs(state_restore_order) do
  1264. for name, cached_value in
  1265. pairs(state[scope] --[[@as table<string,any>]])
  1266. do
  1267. --- @diagnostic disable-next-line:no-unknown
  1268. vim[scope][name] = cached_value
  1269. end
  1270. end
  1271. -- Return
  1272. if not res[1] then
  1273. error(res[2], 0)
  1274. end
  1275. table.remove(res, 1)
  1276. return unpack(res, 1, table.maxn(res))
  1277. end
  1278. return vim._with_c(context, callback)
  1279. end
  1280. --- @param bufnr? integer
  1281. --- @return integer
  1282. function vim._resolve_bufnr(bufnr)
  1283. if bufnr == nil or bufnr == 0 then
  1284. return vim.api.nvim_get_current_buf()
  1285. end
  1286. vim.validate('bufnr', bufnr, 'number')
  1287. return bufnr
  1288. end
  1289. --- @generic T
  1290. --- @param x elem_or_list<T>?
  1291. --- @return T[]
  1292. function vim._ensure_list(x)
  1293. if type(x) == 'table' then
  1294. return x
  1295. end
  1296. return { x }
  1297. end
  1298. return vim