shared.lua 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679
  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. local vim = vim or {}
  9. --- Returns a deep copy of the given object. Non-table objects are copied as
  10. --- in a typical Lua assignment, whereas table objects are copied recursively.
  11. --- Functions are naively copied, so functions in the copied table point to the
  12. --- same functions as those in the input table. Userdata and threads are not
  13. --- copied and will throw an error.
  14. ---
  15. ---@param orig table Table to copy
  16. ---@returns New table of copied keys and (nested) values.
  17. function vim.deepcopy(orig) end -- luacheck: no unused
  18. vim.deepcopy = (function()
  19. local function _id(v)
  20. return v
  21. end
  22. local deepcopy_funcs = {
  23. table = function(orig, cache)
  24. if cache[orig] then return cache[orig] end
  25. local copy = {}
  26. cache[orig] = copy
  27. local mt = getmetatable(orig)
  28. for k, v in pairs(orig) do
  29. copy[vim.deepcopy(k, cache)] = vim.deepcopy(v, cache)
  30. end
  31. return setmetatable(copy, mt)
  32. end,
  33. number = _id,
  34. string = _id,
  35. ['nil'] = _id,
  36. boolean = _id,
  37. ['function'] = _id,
  38. }
  39. return function(orig, cache)
  40. local f = deepcopy_funcs[type(orig)]
  41. if f then
  42. return f(orig, cache or {})
  43. else
  44. error("Cannot deepcopy object of type "..type(orig))
  45. end
  46. end
  47. end)()
  48. --- Splits a string at each instance of a separator.
  49. ---
  50. ---@see |vim.split()|
  51. ---@see https://www.lua.org/pil/20.2.html
  52. ---@see http://lua-users.org/wiki/StringLibraryTutorial
  53. ---
  54. ---@param s String to split
  55. ---@param sep Separator string or pattern
  56. ---@param plain If `true` use `sep` literally (passed to String.find)
  57. ---@returns Iterator over the split components
  58. function vim.gsplit(s, sep, plain)
  59. vim.validate{s={s,'s'},sep={sep,'s'},plain={plain,'b',true}}
  60. local start = 1
  61. local done = false
  62. local function _pass(i, j, ...)
  63. if i then
  64. assert(j+1 > start, "Infinite loop detected")
  65. local seg = s:sub(start, i - 1)
  66. start = j + 1
  67. return seg, ...
  68. else
  69. done = true
  70. return s:sub(start)
  71. end
  72. end
  73. return function()
  74. if done or (s == '' and sep == '') then
  75. return
  76. end
  77. if sep == '' then
  78. if start == #s then
  79. done = true
  80. end
  81. return _pass(start+1, start)
  82. end
  83. return _pass(s:find(sep, start, plain))
  84. end
  85. end
  86. --- Splits a string at each instance of a separator.
  87. ---
  88. --- Examples:
  89. --- <pre>
  90. --- split(":aa::b:", ":") --> {'','aa','','b',''}
  91. --- split("axaby", "ab?") --> {'','x','y'}
  92. --- split("x*yz*o", "*", {plain=true}) --> {'x','yz','o'}
  93. --- split("|x|y|z|", "|", {trimempty=true}) --> {'x', 'y', 'z'}
  94. --- </pre>
  95. ---
  96. ---@see |vim.gsplit()|
  97. ---
  98. ---@param s String to split
  99. ---@param sep Separator string or pattern
  100. ---@param kwargs Keyword arguments:
  101. --- - plain: (boolean) If `true` use `sep` literally (passed to string.find)
  102. --- - trimempty: (boolean) If `true` remove empty items from the front
  103. --- and back of the list
  104. ---@returns List-like table of the split components.
  105. function vim.split(s, sep, kwargs)
  106. local plain
  107. local trimempty = false
  108. if type(kwargs) == 'boolean' then
  109. -- Support old signature for backward compatibility
  110. plain = kwargs
  111. else
  112. vim.validate { kwargs = {kwargs, 't', true} }
  113. kwargs = kwargs or {}
  114. plain = kwargs.plain
  115. trimempty = kwargs.trimempty
  116. end
  117. local t = {}
  118. local skip = trimempty
  119. for c in vim.gsplit(s, sep, plain) do
  120. if c ~= "" then
  121. skip = false
  122. end
  123. if not skip then
  124. table.insert(t, c)
  125. end
  126. end
  127. if trimempty then
  128. for i = #t, 1, -1 do
  129. if t[i] ~= "" then
  130. break
  131. end
  132. table.remove(t, i)
  133. end
  134. end
  135. return t
  136. end
  137. --- Return a list of all keys used in a table.
  138. --- However, the order of the return table of keys is not guaranteed.
  139. ---
  140. ---@see From https://github.com/premake/premake-core/blob/master/src/base/table.lua
  141. ---
  142. ---@param t Table
  143. ---@returns list of keys
  144. function vim.tbl_keys(t)
  145. assert(type(t) == 'table', string.format("Expected table, got %s", type(t)))
  146. local keys = {}
  147. for k, _ in pairs(t) do
  148. table.insert(keys, k)
  149. end
  150. return keys
  151. end
  152. --- Return a list of all values used in a table.
  153. --- However, the order of the return table of values is not guaranteed.
  154. ---
  155. ---@param t Table
  156. ---@returns list of values
  157. function vim.tbl_values(t)
  158. assert(type(t) == 'table', string.format("Expected table, got %s", type(t)))
  159. local values = {}
  160. for _, v in pairs(t) do
  161. table.insert(values, v)
  162. end
  163. return values
  164. end
  165. --- Apply a function to all values of a table.
  166. ---
  167. ---@param func function or callable table
  168. ---@param t table
  169. function vim.tbl_map(func, t)
  170. vim.validate{func={func,'c'},t={t,'t'}}
  171. local rettab = {}
  172. for k, v in pairs(t) do
  173. rettab[k] = func(v)
  174. end
  175. return rettab
  176. end
  177. --- Filter a table using a predicate function
  178. ---
  179. ---@param func function or callable table
  180. ---@param t table
  181. function vim.tbl_filter(func, t)
  182. vim.validate{func={func,'c'},t={t,'t'}}
  183. local rettab = {}
  184. for _, entry in pairs(t) do
  185. if func(entry) then
  186. table.insert(rettab, entry)
  187. end
  188. end
  189. return rettab
  190. end
  191. --- Checks if a list-like (vector) table contains `value`.
  192. ---
  193. ---@param t Table to check
  194. ---@param value Value to compare
  195. ---@returns true if `t` contains `value`
  196. function vim.tbl_contains(t, value)
  197. vim.validate{t={t,'t'}}
  198. for _,v in ipairs(t) do
  199. if v == value then
  200. return true
  201. end
  202. end
  203. return false
  204. end
  205. --- Checks if a table is empty.
  206. ---
  207. ---@see https://github.com/premake/premake-core/blob/master/src/base/table.lua
  208. ---
  209. ---@param t Table to check
  210. function vim.tbl_isempty(t)
  211. assert(type(t) == 'table', string.format("Expected table, got %s", type(t)))
  212. return next(t) == nil
  213. end
  214. --- we only merge empty tables or tables that are not a list
  215. ---@private
  216. local function can_merge(v)
  217. return type(v) == "table" and (vim.tbl_isempty(v) or not vim.tbl_islist(v))
  218. end
  219. local function tbl_extend(behavior, deep_extend, ...)
  220. if (behavior ~= 'error' and behavior ~= 'keep' and behavior ~= 'force') then
  221. error('invalid "behavior": '..tostring(behavior))
  222. end
  223. if select('#', ...) < 2 then
  224. error('wrong number of arguments (given '..tostring(1 + select('#', ...))..', expected at least 3)')
  225. end
  226. local ret = {}
  227. if vim._empty_dict_mt ~= nil and getmetatable(select(1, ...)) == vim._empty_dict_mt then
  228. ret = vim.empty_dict()
  229. end
  230. for i = 1, select('#', ...) do
  231. local tbl = select(i, ...)
  232. vim.validate{["after the second argument"] = {tbl,'t'}}
  233. if tbl then
  234. for k, v in pairs(tbl) do
  235. if deep_extend and can_merge(v) and can_merge(ret[k]) then
  236. ret[k] = tbl_extend(behavior, true, ret[k], v)
  237. elseif behavior ~= 'force' and ret[k] ~= nil then
  238. if behavior == 'error' then
  239. error('key found in more than one map: '..k)
  240. end -- Else behavior is "keep".
  241. else
  242. ret[k] = v
  243. end
  244. end
  245. end
  246. end
  247. return ret
  248. end
  249. --- Merges two or more map-like tables.
  250. ---
  251. ---@see |extend()|
  252. ---
  253. ---@param behavior Decides what to do if a key is found in more than one map:
  254. --- - "error": raise an error
  255. --- - "keep": use value from the leftmost map
  256. --- - "force": use value from the rightmost map
  257. ---@param ... Two or more map-like tables.
  258. function vim.tbl_extend(behavior, ...)
  259. return tbl_extend(behavior, false, ...)
  260. end
  261. --- Merges recursively two or more map-like tables.
  262. ---
  263. ---@see |tbl_extend()|
  264. ---
  265. ---@param behavior Decides what to do if a key is found in more than one map:
  266. --- - "error": raise an error
  267. --- - "keep": use value from the leftmost map
  268. --- - "force": use value from the rightmost map
  269. ---@param ... Two or more map-like tables.
  270. function vim.tbl_deep_extend(behavior, ...)
  271. return tbl_extend(behavior, true, ...)
  272. end
  273. --- Deep compare values for equality
  274. ---
  275. --- Tables are compared recursively unless they both provide the `eq` methamethod.
  276. --- All other types are compared using the equality `==` operator.
  277. ---@param a first value
  278. ---@param b second value
  279. ---@returns `true` if values are equals, else `false`.
  280. function vim.deep_equal(a, b)
  281. if a == b then return true end
  282. if type(a) ~= type(b) then return false end
  283. if type(a) == 'table' then
  284. for k, v in pairs(a) do
  285. if not vim.deep_equal(v, b[k]) then
  286. return false
  287. end
  288. end
  289. for k, _ in pairs(b) do
  290. if a[k] == nil then
  291. return false
  292. end
  293. end
  294. return true
  295. end
  296. return false
  297. end
  298. --- Add the reverse lookup values to an existing table.
  299. --- For example:
  300. --- ``tbl_add_reverse_lookup { A = 1 } == { [1] = 'A', A = 1 }``
  301. --
  302. --Do note that it *modifies* the input.
  303. ---@param o table The table to add the reverse to.
  304. function vim.tbl_add_reverse_lookup(o)
  305. local keys = vim.tbl_keys(o)
  306. for _, k in ipairs(keys) do
  307. local v = o[k]
  308. if o[v] then
  309. error(string.format("The reverse lookup found an existing value for %q while processing key %q", tostring(v), tostring(k)))
  310. end
  311. o[v] = k
  312. end
  313. return o
  314. end
  315. --- Index into a table (first argument) via string keys passed as subsequent arguments.
  316. --- Return `nil` if the key does not exist.
  317. --_
  318. --- Examples:
  319. --- <pre>
  320. --- vim.tbl_get({ key = { nested_key = true }}, 'key', 'nested_key') == true
  321. --- vim.tbl_get({ key = {}}, 'key', 'nested_key') == nil
  322. --- </pre>
  323. ---
  324. ---@param o Table to index
  325. ---@param ... Optional strings (0 or more, variadic) via which to index the table
  326. ---
  327. ---@returns nested value indexed by key if it exists, else nil
  328. function vim.tbl_get(o, ...)
  329. local keys = {...}
  330. if #keys == 0 then
  331. return
  332. end
  333. for i, k in ipairs(keys) do
  334. if type(o[k]) ~= 'table' and next(keys, i) then
  335. return nil
  336. end
  337. o = o[k]
  338. if o == nil then
  339. return
  340. end
  341. end
  342. return o
  343. end
  344. --- Extends a list-like table with the values of another list-like table.
  345. ---
  346. --- NOTE: This mutates dst!
  347. ---
  348. ---@see |vim.tbl_extend()|
  349. ---
  350. ---@param dst list which will be modified and appended to.
  351. ---@param src list from which values will be inserted.
  352. ---@param start Start index on src. defaults to 1
  353. ---@param finish Final index on src. defaults to #src
  354. ---@returns dst
  355. function vim.list_extend(dst, src, start, finish)
  356. vim.validate {
  357. dst = {dst, 't'};
  358. src = {src, 't'};
  359. start = {start, 'n', true};
  360. finish = {finish, 'n', true};
  361. }
  362. for i = start or 1, finish or #src do
  363. table.insert(dst, src[i])
  364. end
  365. return dst
  366. end
  367. --- Creates a copy of a list-like table such that any nested tables are
  368. --- "unrolled" and appended to the result.
  369. ---
  370. ---@see From https://github.com/premake/premake-core/blob/master/src/base/table.lua
  371. ---
  372. ---@param t List-like table
  373. ---@returns Flattened copy of the given list-like table.
  374. function vim.tbl_flatten(t)
  375. local result = {}
  376. local function _tbl_flatten(_t)
  377. local n = #_t
  378. for i = 1, n do
  379. local v = _t[i]
  380. if type(v) == "table" then
  381. _tbl_flatten(v)
  382. elseif v then
  383. table.insert(result, v)
  384. end
  385. end
  386. end
  387. _tbl_flatten(t)
  388. return result
  389. end
  390. --- Tests if a Lua table can be treated as an array.
  391. ---
  392. --- Empty table `{}` is assumed to be an array, unless it was created by
  393. --- |vim.empty_dict()| or returned as a dict-like |API| or Vimscript result,
  394. --- for example from |rpcrequest()| or |vim.fn|.
  395. ---
  396. ---@param t Table
  397. ---@returns `true` if array-like table, else `false`.
  398. function vim.tbl_islist(t)
  399. if type(t) ~= 'table' then
  400. return false
  401. end
  402. local count = 0
  403. for k, _ in pairs(t) do
  404. if type(k) == "number" then
  405. count = count + 1
  406. else
  407. return false
  408. end
  409. end
  410. if count > 0 then
  411. return true
  412. else
  413. -- TODO(bfredl): in the future, we will always be inside nvim
  414. -- then this check can be deleted.
  415. if vim._empty_dict_mt == nil then
  416. return nil
  417. end
  418. return getmetatable(t) ~= vim._empty_dict_mt
  419. end
  420. end
  421. --- Counts the number of non-nil values in table `t`.
  422. ---
  423. --- <pre>
  424. --- vim.tbl_count({ a=1, b=2 }) => 2
  425. --- vim.tbl_count({ 1, 2 }) => 2
  426. --- </pre>
  427. ---
  428. ---@see https://github.com/Tieske/Penlight/blob/master/lua/pl/tablex.lua
  429. ---@param t Table
  430. ---@returns Number that is the number of the value in table
  431. function vim.tbl_count(t)
  432. vim.validate{t={t,'t'}}
  433. local count = 0
  434. for _ in pairs(t) do count = count + 1 end
  435. return count
  436. end
  437. --- Creates a copy of a table containing only elements from start to end (inclusive)
  438. ---
  439. ---@param list table table
  440. ---@param start integer Start range of slice
  441. ---@param finish integer End range of slice
  442. ---@returns Copy of table sliced from start to finish (inclusive)
  443. function vim.list_slice(list, start, finish)
  444. local new_list = {}
  445. for i = start or 1, finish or #list do
  446. new_list[#new_list+1] = list[i]
  447. end
  448. return new_list
  449. end
  450. --- Trim whitespace (Lua pattern "%s") from both sides of a string.
  451. ---
  452. ---@see https://www.lua.org/pil/20.2.html
  453. ---@param s String to trim
  454. ---@returns String with whitespace removed from its beginning and end
  455. function vim.trim(s)
  456. vim.validate{s={s,'s'}}
  457. return s:match('^%s*(.*%S)') or ''
  458. end
  459. --- Escapes magic chars in a Lua pattern.
  460. ---
  461. ---@see https://github.com/rxi/lume
  462. ---@param s String to escape
  463. ---@returns %-escaped pattern string
  464. function vim.pesc(s)
  465. vim.validate{s={s,'s'}}
  466. return s:gsub('[%(%)%.%%%+%-%*%?%[%]%^%$]', '%%%1')
  467. end
  468. --- Tests if `s` starts with `prefix`.
  469. ---
  470. ---@param s (string) a string
  471. ---@param prefix (string) a prefix
  472. ---@return (boolean) true if `prefix` is a prefix of s
  473. function vim.startswith(s, prefix)
  474. vim.validate { s = {s, 's'}; prefix = {prefix, 's'}; }
  475. return s:sub(1, #prefix) == prefix
  476. end
  477. --- Tests if `s` ends with `suffix`.
  478. ---
  479. ---@param s (string) a string
  480. ---@param suffix (string) a suffix
  481. ---@return (boolean) true if `suffix` is a suffix of s
  482. function vim.endswith(s, suffix)
  483. vim.validate { s = {s, 's'}; suffix = {suffix, 's'}; }
  484. return #suffix == 0 or s:sub(-#suffix) == suffix
  485. end
  486. --- Validates a parameter specification (types and values).
  487. ---
  488. --- Usage example:
  489. --- <pre>
  490. --- function user.new(name, age, hobbies)
  491. --- vim.validate{
  492. --- name={name, 'string'},
  493. --- age={age, 'number'},
  494. --- hobbies={hobbies, 'table'},
  495. --- }
  496. --- ...
  497. --- end
  498. --- </pre>
  499. ---
  500. --- Examples with explicit argument values (can be run directly):
  501. --- <pre>
  502. --- vim.validate{arg1={{'foo'}, 'table'}, arg2={'foo', 'string'}}
  503. --- => NOP (success)
  504. ---
  505. --- vim.validate{arg1={1, 'table'}}
  506. --- => error('arg1: expected table, got number')
  507. ---
  508. --- vim.validate{arg1={3, function(a) return (a % 2) == 0 end, 'even number'}}
  509. --- => error('arg1: expected even number, got 3')
  510. --- </pre>
  511. ---
  512. --- If multiple types are valid they can be given as a list.
  513. --- <pre>
  514. --- vim.validate{arg1={{'foo'}, {'table', 'string'}}, arg2={'foo', {'table', 'string'}}}
  515. --- => NOP (success)
  516. ---
  517. --- vim.validate{arg1={1, {'string', table'}}}
  518. --- => error('arg1: expected string|table, got number')
  519. ---
  520. --- </pre>
  521. ---
  522. ---@param opt table of parameter names to validations. Each key is a parameter
  523. --- name; each value is a tuple in one of these forms:
  524. --- 1. (arg_value, type_name, optional)
  525. --- - arg_value: argument value
  526. --- - type_name: string|table type name, one of: ("table", "t", "string",
  527. --- "s", "number", "n", "boolean", "b", "function", "f", "nil",
  528. --- "thread", "userdata") or list of them.
  529. --- - optional: (optional) boolean, if true, `nil` is valid
  530. --- 2. (arg_value, fn, msg)
  531. --- - arg_value: argument value
  532. --- - fn: any function accepting one argument, returns true if and
  533. --- only if the argument is valid. Can optionally return an additional
  534. --- informative error message as the second returned value.
  535. --- - msg: (optional) error string if validation fails
  536. function vim.validate(opt) end -- luacheck: no unused
  537. do
  538. local type_names = {
  539. ['table'] = 'table', t = 'table',
  540. ['string'] = 'string', s = 'string',
  541. ['number'] = 'number', n = 'number',
  542. ['boolean'] = 'boolean', b = 'boolean',
  543. ['function'] = 'function', f = 'function',
  544. ['callable'] = 'callable', c = 'callable',
  545. ['nil'] = 'nil',
  546. ['thread'] = 'thread',
  547. ['userdata'] = 'userdata',
  548. }
  549. local function _is_type(val, t)
  550. return type(val) == t or (t == 'callable' and vim.is_callable(val))
  551. end
  552. ---@private
  553. local function is_valid(opt)
  554. if type(opt) ~= 'table' then
  555. return false, string.format('opt: expected table, got %s', type(opt))
  556. end
  557. for param_name, spec in pairs(opt) do
  558. if type(spec) ~= 'table' then
  559. return false, string.format('opt[%s]: expected table, got %s', param_name, type(spec))
  560. end
  561. local val = spec[1] -- Argument value.
  562. local types = spec[2] -- Type name, or callable.
  563. local optional = (true == spec[3])
  564. if type(types) == 'string' then
  565. types = {types}
  566. end
  567. if vim.is_callable(types) then
  568. -- Check user-provided validation function.
  569. local valid, optional_message = types(val)
  570. if not valid then
  571. local error_message = string.format("%s: expected %s, got %s", param_name, (spec[3] or '?'), tostring(val))
  572. if optional_message ~= nil then
  573. error_message = error_message .. string.format(". Info: %s", optional_message)
  574. end
  575. return false, error_message
  576. end
  577. elseif type(types) == 'table' then
  578. local success = false
  579. for i, t in ipairs(types) do
  580. local t_name = type_names[t]
  581. if not t_name then
  582. return false, string.format('invalid type name: %s', t)
  583. end
  584. types[i] = t_name
  585. if (optional and val == nil) or _is_type(val, t_name) then
  586. success = true
  587. break
  588. end
  589. end
  590. if not success then
  591. return false, string.format("%s: expected %s, got %s", param_name, table.concat(types, '|'), type(val))
  592. end
  593. else
  594. return false, string.format("invalid type name: %s", tostring(types))
  595. end
  596. end
  597. return true, nil
  598. end
  599. function vim.validate(opt)
  600. local ok, err_msg = is_valid(opt)
  601. if not ok then
  602. error(err_msg, 2)
  603. end
  604. end
  605. end
  606. --- Returns true if object `f` can be called as a function.
  607. ---
  608. ---@param f Any object
  609. ---@return true if `f` is callable, else false
  610. function vim.is_callable(f)
  611. if type(f) == 'function' then return true end
  612. local m = getmetatable(f)
  613. if m == nil then return false end
  614. return type(m.__call) == 'function'
  615. end
  616. return vim
  617. -- vim:sw=2 ts=2 et