docs(api): improve shared lua functions docs (#17933)

This commit is contained in:
adrian5
2022-05-11 18:23:46 +02:00
committed by GitHub
parent e36e0f7b2f
commit a6f4cfdefa
2 changed files with 347 additions and 328 deletions

View File

@@ -15,7 +15,7 @@ The Lua 5.1 language is builtin and always available. Try this command to get
an idea of what lurks beneath: >
:lua print(vim.inspect(package.loaded))
<
Nvim includes a "standard library" |lua-stdlib| for Lua. It complements the
"editor stdlib" (|builtin-functions| and Ex commands) and the |API|, all of
which can be used from Lua code. A good overview of using Lua in neovim is
@@ -36,20 +36,20 @@ the order they appear. Any `.` in the module name is treated as a directory
separator when searching. For a module `foo.bar`, each directory is searched
for `lua/foo/bar.lua`, then `lua/foo/bar/init.lua`. If no files are found,
the directories are searched again for a shared library with a name matching
`lua/foo/bar.?`, where `?` is a list of suffixes (such as `so` or `dll`)
derived from the initial value of `package.cpath`. If still no files are
found, Nvim falls back to Lua's default search mechanism. The first script
found is run and `require()` returns the value returned by the script if any,
else `true`.
`lua/foo/bar.?`, where `?` is a list of suffixes (such as `so` or `dll`) derived from
the initial value of `package.cpath`. If still no files are found, Nvim falls
back to Lua's default search mechanism. The first script found is run and
`require()` returns the value returned by the script if any, else `true`.
The return value is cached after the first call to `require()` for each
module, with subsequent calls returning the cached value without searching for
or executing any script. For further details on `require()`, see the Lua
The return value is cached after the first call to `require()` for each module,
with subsequent calls returning the cached value without searching for, or
executing any script. For further details on `require()`, see the Lua
documentation at https://www.lua.org/manual/5.1/manual.html#pdf-require.
For example, if 'runtimepath' is `foo,bar` and `package.cpath` was
`./?.so;./?.dll` at startup, `require('mod')` searches these paths in order
and loads the first module found:
foo/lua/mod.lua
foo/lua/mod/init.lua
bar/lua/mod.lua
@@ -59,8 +59,7 @@ and loads the first module found:
bar/lua/mod.so
bar/lua/mod.dll
*lua-package-path*
Nvim automatically adjusts `package.path` and `package.cpath` according to
Nvim automatically adjusts `package.path` and `package.cpath` according to the
effective 'runtimepath' value. Adjustment happens whenever 'runtimepath' is
changed. `package.path` is adjusted by simply appending `/lua/?.lua` and
`/lua/?/init.lua` to each directory from 'runtimepath' (`/` is actually the
@@ -83,11 +82,11 @@ the existing `package.cpath` are used. Example:
as the suffix of the first path from `package.path` (i.e. `./?.so`). Which
leaves `/?.so` and `/a?d/j/g.elf`, in this order.
4. 'runtimepath' has three paths: `/foo/bar`, `/xxx;yyy/baz` and `/abc`. The
second one contains semicolon which is a paths separator so it is out,
second one contains a semicolon which is a paths separator so it is out,
leaving only `/foo/bar` and `/abc`, in order.
5. The cartesian product of paths from 4. and suffixes from 3. is taken,
giving four variants. In each variant `/lua` path segment is inserted
between path and suffix, leaving
giving four variants. In each variant, a `/lua` path segment is inserted
between path and suffix, leaving:
- `/foo/bar/lua/?.so`
- `/foo/bar/lua/a?d/j/g.elf`
@@ -119,8 +118,8 @@ Note:
- Skipping paths from 'runtimepath' which contain semicolons applies both to
`package.path` and `package.cpath`. Given that there are some badly written
plugins using shell which will not work with paths containing semicolons it
is better to not have them in 'runtimepath' at all.
plugins using shell, which will not work with paths containing semicolons,
it is better to not have them in 'runtimepath' at all.
==============================================================================
Lua Syntax Information *lua-syntax-help*
@@ -136,8 +135,7 @@ Lua functions can be called in multiple ways. Consider the function: >
print("A is: ", a)
print("B is: ", b)
end
<
The first way to call this function is: >
example_func(1, 2)
@@ -154,7 +152,6 @@ not supplied are automatically set to `nil`. For example: >
-- A is: 1
-- B is: nil
<
Additionally, if any extra parameters are passed, they are discarded
completely.
@@ -172,13 +169,11 @@ single dictionary, for example: >
func_with_opts { foo = true, filename = "hello.world" }
<
In this style, each "parameter" is passed via keyword. It is still valid
to call the function in the standard style: >
func_with_opts({ foo = true, filename = "hello.world" })
<
But often in the documentation, you will see the former rather than the
latter style due to its brevity.
@@ -223,7 +218,7 @@ autoload/charblob.vim: >
\ 'require("charblob").encode(unpack(_A))',
\ [getline(1, '$'), &textwidth, ' ']))
endfunction
<
plugin/charblob.vim: >
if exists('g:charblob_loaded')
@@ -232,7 +227,7 @@ plugin/charblob.vim: >
let g:charblob_loaded = 1
command MakeCharBlob :call charblob#encode_buffer()
<
lua/charblob.lua: >
local function charblob_bytes_iter(lines)
@@ -282,7 +277,7 @@ lua/charblob.lua: >
bytes_iter = charblob_bytes_iter,
encode = charblob_encode,
}
<
==============================================================================
COMMANDS *lua-commands*
@@ -298,7 +293,7 @@ arguments separated by " " (space) instead of "\t" (tab).
*:lua*
:[range]lua {chunk}
Executes Lua chunk {chunk}.
if {chunk} starts with "=" the rest of the chunk is
If {chunk} starts with "=" the rest of the chunk is
evaluated as an expression and printed. `:lua =expr`
is equivalent to `:lua print(vim.inspect(expr))`
Examples: >
@@ -328,8 +323,8 @@ arguments separated by " " (space) instead of "\t" (tab).
linenr, #curline))
EOF
endfunction
< Note that the `local` variables will disappear when
<
Note that the `local` variables will disappear when
the block finishes. But not globals.
*:luado*
@@ -349,7 +344,6 @@ arguments separated by " " (space) instead of "\t" (tab).
:lua bp = lpeg.P{ "(" * ((1 - lpeg.S"()") + lpeg.V(1))^0 * ")" }
:luado if bp:match(line) then return "-->\t" .. line end
<
*:luafile*
:[range]luafile {file}
Execute Lua script in {file}.
@@ -368,14 +362,14 @@ luaeval() *lua-eval* *luaeval()*
The (dual) equivalent of "vim.eval" for passing Lua values to Nvim is
"luaeval". "luaeval" takes an expression string and an optional argument used
for _A inside expression and returns the result of the expression. It is
semantically equivalent in Lua to:
>
semantically equivalent in Lua to: >
local chunkheader = "local _A = select(1, ...) return "
function luaeval (expstr, arg)
local chunk = assert(loadstring(chunkheader .. expstr, "luaeval"))
return chunk(arg) -- return typval
end
<
Lua nils, numbers, strings, tables and booleans are converted to their
respective Vimscript types. If a Lua string contains a NUL byte, it will be
converted to a |Blob|. Conversion of other Lua types is an error.
@@ -387,7 +381,7 @@ Example: >
42
:echo luaeval('string.match(_A, "[a-z]+")', 'XYXfoo123')
foo
<
Lua tables are used as both dictionaries and lists, so it is impossible to
determine whether empty table is meant to be empty list or empty dictionary.
Additionally Lua does not have integer numbers. To distinguish between these
@@ -425,8 +419,8 @@ Examples: >
: return luaeval('(_A.y-_A.x)*math.random()+_A.x', {'x':a:x,'y':a:y})
: endfunction
:echo Rand(1,10)
Note: second argument to `luaeval` is converted ("marshalled") from Vimscript
<
Note: Second argument to `luaeval` is converted ("marshalled") from Vimscript
to Lua, so changes to Lua containers do not affect values in Vimscript. Return
value is also always converted. When converting, |msgpack-special-dict|s are
treated specially.
@@ -447,7 +441,7 @@ is equivalent to the Lua chunk >
In addition, functions of packages can be accessed like >
v:lua.require'mypack'.func(arg1, arg2)
v:lua.require'mypack.submod'.func(arg1, arg2)
Note: only single quote form without parens is allowed. Using
Note: Only single quote form without parens is allowed. Using
`require"mypack"` or `require('mypack')` as prefixes do NOT work (the latter
is still valid as a function call of itself, in case require returns a useful
value).
@@ -455,7 +449,7 @@ value).
The `v:lua` prefix may be used to call Lua functions as |method|s. For
example: >
arg1->v:lua.somemod.func(arg2)
<
You can use `v:lua` in "func" options like 'tagfunc', 'omnifunc', etc.
For example consider the following Lua omnifunc handler: >
@@ -468,7 +462,7 @@ For example consider the following Lua omnifunc handler: >
end
vim.api.nvim_buf_set_option(0, 'omnifunc', 'v:lua.mymod.omnifunc')
Note: the module ("mymod" in the above example) must either be a Lua global,
Note: The module ("mymod" in the above example) must either be a Lua global,
or use the require syntax as specified above to access it from a package.
Note: `v:lua` without a call is not allowed in a Vimscript expression:
@@ -478,13 +472,12 @@ Note: `v:lua` without a call is not allowed in a Vimscript expression:
call SomeFunc(v:lua.mycallback) " Error
let g:foo = v:lua " Error
let g:foo = v:['lua'] " Error
<
==============================================================================
Lua standard modules *lua-stdlib*
The Nvim Lua "standard library" (stdlib) is the `vim` module, which exposes
various functions and sub-modules. It is always loaded, thus require("vim")
various functions and sub-modules. It is always loaded, thus `require("vim")`
is unnecessary.
You can peek at the module properties: >
@@ -522,7 +515,7 @@ API that provides functionality for networking, filesystem, and process
management. Try this command to see available functions: >
:lua print(vim.inspect(vim.loop))
<
Reference: https://github.com/luvit/luv/blob/master/docs.md
Examples: https://github.com/luvit/luv/tree/master/examples
@@ -534,15 +527,16 @@ It is an error to directly invoke `vim.api` functions (except |api-fast|) in
timer:start(1000, 0, function()
vim.api.nvim_command('echomsg "test"')
end)
<
To avoid the error use |vim.schedule_wrap()| to defer the callback: >
local timer = vim.loop.new_timer()
timer:start(1000, 0, vim.schedule_wrap(function()
vim.api.nvim_command('echomsg "test"')
end))
(For one-shot timers, see |vim.defer_fn()|, which automatically adds the wrapping.)
<
(For one-shot timers, see |vim.defer_fn()|, which automatically adds the
wrapping.)
Example: repeating timer
1. Save this code to a file.
@@ -560,8 +554,7 @@ Example: repeating timer
i = i + 1
end)
print('sleeping');
<
Example: File-change detection *watch-file*
1. Save this code to a file.
2. Execute it with ":luafile %".
@@ -586,8 +579,7 @@ Example: File-change detection *watch-file*
end
vim.api.nvim_command(
"command! -nargs=1 Watch call luaeval('watch_file(_A)', expand('<args>'))")
<
Example: TCP echo-server *tcp-server*
1. Save this code to a file.
2. Execute it with ":luafile %".
@@ -616,8 +608,7 @@ Example: TCP echo-server *tcp-server*
end)
end)
print('TCP echo-server listening on port: '..server:getsockname().port)
<
Multithreading *lua-loop-threading*
Plugins can perform work in separate (os-level) threads using the threading
@@ -654,7 +645,6 @@ If you want to exclude visual selections from highlighting on yank, use
>
au TextYankPost * silent! lua vim.highlight.on_yank {on_visual=false}
<
vim.highlight.on_yank({opts}) *vim.highlight.on_yank()*
Highlights the yanked text. The fields of the optional dict {opts}
control the highlight:
@@ -678,8 +668,8 @@ vim.highlight.range({bufnr}, {ns}, {hlgroup}, {start}, {finish}, {opts})
{opts} optional parameters:
• `regtype`: type of range (characterwise, linewise,
or blockwise, see |setreg|), default `'v'`
• `inclusive`: range includes end position, default
`false`
• `inclusive`: range includes end position,
default `false`
• `priority`: priority of highlight, default
`vim.highlight.user` (see below)
@@ -701,7 +691,7 @@ matching within a single line.
vim.regex({re}) *vim.regex()*
Parse the Vim regex {re} and return a regex object. Regexes are
"magic" and case-insensitive by default, regardless of 'magic' and
'ignorecase'. The can be controlled with flags, see |/magic|.
'ignorecase'. They can be controlled with flags, see |/magic|.
Methods on the regex object:
@@ -728,6 +718,7 @@ vim.diff({a}, {b}, {opts}) *vim.diff()*
1-based.
Examples: >
vim.diff('a\n', 'b\nc\n')
-->
@@ -1 +1,2 @@
@@ -757,7 +748,7 @@ vim.diff({a}, {b}, {opts}) *vim.diff()*
• `result_type` (string): Form of the returned diff:
• "unified": (default) String in unified format.
• "indices": Array of hunk locations.
Note this option is ignored if `on_hunk` is
Note: This option is ignored if `on_hunk` is
used.
• `algorithm` (string):
Diff algorithm to use. Values:
@@ -806,17 +797,17 @@ vim.spell.check({str}) *vim.spell.check()*
|spellbadword()|.
Note: The behaviour of this function is dependent on: 'spelllang',
'spellfile', 'spellcapcheck' and 'spelloptions' which can all be local
to the buffer. Consider calling this with |nvim_buf_call()|.
'spellfile', 'spellcapcheck' and 'spelloptions' which can all be
local to the buffer. Consider calling this with |nvim_buf_call()|.
Example: >
vim.spell.check("the quik brown fox")
-->
{
{'quik', 'bad', 4}
}
<
Parameters: ~
{str} String to spell check.
@@ -860,7 +851,7 @@ vim.empty_dict() *vim.empty_dict()*
Vimscript or API types. Nvim by default converts an empty table `{}`
without this metatable to an list/array.
Note: if numeric keys are present in the table, Nvim ignores the
Note: If numeric keys are present in the table, Nvim ignores the
metatable marker and converts the dict to a list/array anyway.
vim.rpcnotify({channel}, {method}[, {args}...]) *vim.rpcnotify()*
@@ -895,9 +886,9 @@ vim.str_byteindex({str}, {index}[, {use_utf16}]) *vim.str_byteindex()*
Convert UTF-32 or UTF-16 {index} to byte index. If {use_utf16} is not
supplied, it defaults to false (use UTF-32). Returns the byte index.
Invalid UTF-8 and NUL is treated like by |vim.str_byteindex()|. An {index}
in the middle of a UTF-16 sequence is rounded upwards to the end of that
sequence.
Invalid UTF-8 and NUL is treated like by |vim.str_byteindex()|.
An {index} in the middle of a UTF-16 sequence is rounded upwards to
the end of that sequence.
vim.schedule({callback}) *vim.schedule()*
Schedules {callback} to be invoked soon by the main event-loop. Useful
@@ -992,7 +983,7 @@ vim.types *vim.types*
values for |vim.type_idx|. Currently contains pairs for `float`,
`array` and `dictionary` types.
Note: one must expect that values corresponding to `vim.types.float`,
Note: One must expect that values corresponding to `vim.types.float`,
`vim.types.array` and `vim.types.dictionary` fall under only two
following assumptions:
1. Value may serve both as a key and as a value in a table. Given the
@@ -1026,7 +1017,7 @@ vim.call({func}, {...}) *vim.call()*
See also |vim.fn|.
Equivalent to: >
vim.fn[func]({...})
<
vim.cmd({cmd}) *vim.cmd()*
Executes multiple lines of Vimscript at once. It is an alias to
|nvim_exec()|, where `output` is set to false. Thus it works identical
@@ -1040,7 +1031,7 @@ vim.cmd({cmd}) *vim.cmd()*
autocmd FileType c setlocal cindent
augroup END
]])
<
vim.fn.{func}({...}) *vim.fn*
Invokes |vim-function| or |user-function| {func} with arguments {...}.
To call autoload functions, use the syntax: >
@@ -1070,7 +1061,7 @@ Example: >
print(vim.g.foo) -- Get and print the g:foo Vimscript variable.
vim.g.foo = nil -- Delete (:unlet) the Vimscript variable.
vim.b[2].foo = 6 -- Set b:foo for buffer 2
<
vim.g *vim.g*
Global (|g:|) editor variables.
Key with no value returns `nil`.
@@ -1144,7 +1135,6 @@ from within Lua.
-- or using the `:append(...)` method
vim.opt.wildignore:append { "*.pyc", "node_modules" }
<
To replicate the behavior of |:set^=|, use: >
-- vim.opt supports prepending options via the "^" operator
@@ -1270,8 +1260,7 @@ vim.o *vim.o*
Example: >
vim.o.cmdheight = 4
print(vim.o.columns)
<
vim.go *vim.go*
Get or set an |option|. Invalid key is an error.
@@ -1284,7 +1273,6 @@ vim.go *vim.go*
Example: >
vim.go.cmdheight = 4
<
vim.bo *vim.bo*
Get or set buffer-scoped |local-options|. Invalid key is an error.
@@ -1294,7 +1282,7 @@ vim.bo *vim.bo*
Example: >
vim.bo.buflisted = true
print(vim.bo.comments)
<
vim.wo *vim.wo*
Get or set window-scoped |local-options|. Invalid key is an error.
@@ -1304,8 +1292,7 @@ vim.wo *vim.wo*
Example: >
vim.wo.cursorcolumn = true
print(vim.wo.foldmarker)
<
==============================================================================
Lua module: vim *lua-vim*
@@ -1476,14 +1463,14 @@ schedule_wrap({cb}) *vim.schedule_wrap()*
deep_equal({a}, {b}) *vim.deep_equal()*
Deep compare values for equality
Tables are compared recursively unless they both provide the `eq` methamethod. All other types are compared using the equality `==` operator.
Tables are compared recursively unless they both provide the `eq` metamethod. All other types are compared using the equality `==` operator.
Parameters: ~
{a} first value
{b} second value
{a} any First value
{b} any Second value
Return: ~
`true` if values are equals, else `false`.
boolean `true` if values are equals, else `false`
deepcopy({orig}) *vim.deepcopy()*
Returns a deep copy of the given object. Non-table objects are
@@ -1497,29 +1484,29 @@ deepcopy({orig}) *vim.deepcopy()*
{orig} table Table to copy
Return: ~
New table of copied keys and (nested) values.
table Table of copied keys and (nested) values.
endswith({s}, {suffix}) *vim.endswith()*
Tests if `s` ends with `suffix`.
Parameters: ~
{s} (string) a string
{suffix} (string) a suffix
{s} string String
{suffix} string Suffix to match
Return: ~
(boolean) true if `suffix` is a suffix of s
boolean `true` if `suffix` is a suffix of `s`
gsplit({s}, {sep}, {plain}) *vim.gsplit()*
Splits a string at each instance of a separator.
Parameters: ~
{s} String to split
{sep} Separator string or pattern
{plain} If `true` use `sep` literally (passed to
String.find)
{s} string String to split
{sep} string Separator or pattern
{plain} boolean If `true` use `sep` literally (passed to
string.find)
Return: ~
Iterator over the split components
function Iterator over the split components
See also: ~
|vim.split()|
@@ -1530,10 +1517,10 @@ is_callable({f}) *vim.is_callable()*
Returns true if object `f` can be called as a function.
Parameters: ~
{f} Any object
{f} any Any object
Return: ~
true if `f` is callable, else false
boolean `true` if `f` is callable, else `false`
list_extend({dst}, {src}, {start}, {finish}) *vim.list_extend()*
Extends a list-like table with the values of another list-like
@@ -1542,13 +1529,14 @@ list_extend({dst}, {src}, {start}, {finish}) *vim.list_extend()*
NOTE: This mutates dst!
Parameters: ~
{dst} list which will be modified and appended to.
{src} list from which values will be inserted.
{start} Start index on src. defaults to 1
{finish} Final index on src. defaults to #src
{dst} table List which will be modified and appended
to
{src} table List from which values will be inserted
{start} number Start index on src. Defaults to 1
{finish} number Final index on src. Defaults to `#src`
Return: ~
dst
table dst
See also: ~
|vim.tbl_extend()|
@@ -1558,21 +1546,22 @@ list_slice({list}, {start}, {finish}) *vim.list_slice()*
to end (inclusive)
Parameters: ~
{list} table table
{start} integer Start range of slice
{finish} integer End range of slice
{list} table Table
{start} number Start range of slice
{finish} number End range of slice
Return: ~
Copy of table sliced from start to finish (inclusive)
table Copy of table sliced from start to finish
(inclusive)
pesc({s}) *vim.pesc()*
Escapes magic chars in a Lua pattern.
Parameters: ~
{s} String to escape
{s} string String to escape
Return: ~
%-escaped pattern string
string %-escaped pattern string
See also: ~
https://github.com/rxi/lume
@@ -1589,16 +1578,16 @@ split({s}, {sep}, {kwargs}) *vim.split()*
<
Parameters: ~
{s} String to split
{sep} Separator string or pattern
{kwargs} Keyword arguments:
{s} string String to split
{sep} string Separator or pattern
{kwargs} table Keyword arguments:
• plain: (boolean) If `true` use `sep` literally
(passed to string.find)
• trimempty: (boolean) If `true` remove empty
items from the front and back of the list
Return: ~
List-like table of the split components.
table List of split components
See also: ~
|vim.gsplit()|
@@ -1607,28 +1596,34 @@ startswith({s}, {prefix}) *vim.startswith()*
Tests if `s` starts with `prefix`.
Parameters: ~
{s} (string) a string
{prefix} (string) a prefix
{s} string String
{prefix} string Prefix to match
Return: ~
(boolean) true if `prefix` is a prefix of s
boolean `true` if `prefix` is a prefix of `s`
tbl_add_reverse_lookup({o}) *vim.tbl_add_reverse_lookup()*
Add the reverse lookup values to an existing table. For
example: `tbl_add_reverse_lookup { A = 1 } == { [1] = 'A', A = 1 }`
example: `tbl_add_reverse_lookup { A = 1 } == { [1] = 'A', A =
1 }`
Note that this modifies the input.
Parameters: ~
{o} table The table to add the reverse to.
{o} table Table to add the reverse to
Return: ~
table o
tbl_contains({t}, {value}) *vim.tbl_contains()*
Checks if a list-like (vector) table contains `value`.
Parameters: ~
{t} Table to check
{value} Value to compare
{t} table Table to check
{value} any Value to compare
Return: ~
true if `t` contains `value`
boolean `true` if `t` contains `value`
tbl_count({t}) *vim.tbl_count()*
Counts the number of non-nil values in table `t`.
@@ -1639,10 +1634,10 @@ tbl_count({t}) *vim.tbl_count()*
<
Parameters: ~
{t} Table
{t} table Table
Return: ~
Number that is the number of the value in table
number Number of non-nil values in table
See also: ~
https://github.com/Tieske/Penlight/blob/master/lua/pl/tablex.lua
@@ -1651,12 +1646,15 @@ tbl_deep_extend({behavior}, {...}) *vim.tbl_deep_extend()*
Merges recursively two or more map-like tables.
Parameters: ~
{behavior} Decides what to do if a key is found in more
than one map:
{behavior} string Decides what to do if a key is found in
more than one map:
• "error": raise an error
• "keep": use value from the leftmost map
• "force": use value from the rightmost map
{...} Two or more map-like tables.
{...} table Two or more map-like tables
Return: ~
table Merged table
See also: ~
|tbl_extend()|
@@ -1665,12 +1663,15 @@ tbl_extend({behavior}, {...}) *vim.tbl_extend()*
Merges two or more map-like tables.
Parameters: ~
{behavior} Decides what to do if a key is found in more
than one map:
{behavior} string Decides what to do if a key is found in
more than one map:
• "error": raise an error
• "keep": use value from the leftmost map
• "force": use value from the rightmost map
{...} Two or more map-like tables.
{...} table Two or more map-like tables
Return: ~
table Merged table
See also: ~
|extend()|
@@ -1679,43 +1680,51 @@ tbl_filter({func}, {t}) *vim.tbl_filter()*
Filter a table using a predicate function
Parameters: ~
{func} function or callable table
{t} table
{func} function|table Function or callable table
{t} table Table
Return: ~
table Table of filtered values
tbl_flatten({t}) *vim.tbl_flatten()*
Creates a copy of a list-like table such that any nested
tables are "unrolled" and appended to the result.
Parameters: ~
{t} List-like table
{t} table List-like table
Return: ~
Flattened copy of the given list-like table.
table Flattened copy of the given list-like table
See also: ~
From https://github.com/premake/premake-core/blob/master/src/base/table.lua
tbl_get({o}, {...}) *vim.tbl_get()*
Index into a table (first argument) via string keys passed as
subsequent arguments. Return `nil` if the key does not exist. Examples: >
subsequent arguments. Return `nil` if the key does not exist.
Examples: >
vim.tbl_get({ key = { nested_key = true }}, 'key', 'nested_key') == true
vim.tbl_get({ key = {}}, 'key', 'nested_key') == nil
<
Parameters: ~
{o} Table to index
{...} Optional strings (0 or more, variadic) via which to
index the table
{o} table Table to index
{...} string Optional strings (0 or more, variadic) via
which to index the table
Return: ~
nested value indexed by key if it exists, else nil
any Nested value indexed by key (if it exists), else nil
tbl_isempty({t}) *vim.tbl_isempty()*
Checks if a table is empty.
Parameters: ~
{t} Table to check
{t} table Table to check
Return: ~
boolean `true` if `t` is empty
See also: ~
https://github.com/premake/premake-core/blob/master/src/base/table.lua
@@ -1729,20 +1738,20 @@ tbl_islist({t}) *vim.tbl_islist()*
|vim.fn|.
Parameters: ~
{t} Table
{t} table Table
Return: ~
`true` if array-like table, else `false`.
boolean `true` if array-like table, else `false`
tbl_keys({t}) *vim.tbl_keys()*
Return a list of all keys used in a table. However, the order
of the return table of keys is not guaranteed.
Parameters: ~
{t} Table
{t} table Table
Return: ~
list of keys
table List of keys
See also: ~
From https://github.com/premake/premake-core/blob/master/src/base/table.lua
@@ -1751,28 +1760,32 @@ tbl_map({func}, {t}) *vim.tbl_map()*
Apply a function to all values of a table.
Parameters: ~
{func} function or callable table
{t} table
{func} function|table Function or callable table
{t} table Table
Return: ~
table Table of transformed values
tbl_values({t}) *vim.tbl_values()*
Return a list of all values used in a table. However, the
order of the return table of values is not guaranteed.
Parameters: ~
{t} Table
{t} table Table
Return: ~
list of values
table List of values
trim({s}) *vim.trim()*
Trim whitespace (Lua pattern "%s") from both sides of a
string.
Parameters: ~
{s} String to trim
{s} string String to trim
Return: ~
String with whitespace removed from its beginning and end
string String with whitespace removed from its beginning
and end
See also: ~
https://www.lua.org/pil/20.2.html
@@ -1814,9 +1827,9 @@ validate({opt}) *vim.validate()*
<
Parameters: ~
{opt} table of parameter names to validations. Each key
is a parameter name; each value is a tuple in one
of these forms:
{opt} table Names of parameters to validate. Each key is
a parameter name; each value is a tuple in one of
these forms:
1. (arg_value, type_name, optional)
• arg_value: argument value
• type_name: string|table type name, one of:

View File

@@ -15,7 +15,7 @@ local vim = vim or {}
--- copied and will throw an error.
---
---@param orig table Table to copy
---@returns New table of copied keys and (nested) values.
---@return table Table of copied keys and (nested) values.
function vim.deepcopy(orig) end -- luacheck: no unused
vim.deepcopy = (function()
local function _id(v)
@@ -59,10 +59,10 @@ end)()
---@see https://www.lua.org/pil/20.2.html
---@see http://lua-users.org/wiki/StringLibraryTutorial
---
---@param s String to split
---@param sep Separator string or pattern
---@param plain If `true` use `sep` literally (passed to String.find)
---@returns Iterator over the split components
---@param s string String to split
---@param sep string Separator or pattern
---@param plain boolean If `true` use `sep` literally (passed to string.find)
---@return function Iterator over the split components
function vim.gsplit(s, sep, plain)
vim.validate({ s = { s, 's' }, sep = { sep, 's' }, plain = { plain, 'b', true } })
@@ -107,13 +107,13 @@ end
---
---@see |vim.gsplit()|
---
---@param s String to split
---@param sep Separator string or pattern
---@param kwargs Keyword arguments:
---@param s string String to split
---@param sep string Separator or pattern
---@param kwargs table Keyword arguments:
--- - plain: (boolean) If `true` use `sep` literally (passed to string.find)
--- - trimempty: (boolean) If `true` remove empty items from the front
--- and back of the list
---@returns List-like table of the split components.
---@return table List of split components
function vim.split(s, sep, kwargs)
local plain
local trimempty = false
@@ -156,8 +156,8 @@ end
---
---@see From https://github.com/premake/premake-core/blob/master/src/base/table.lua
---
---@param t Table
---@returns list of keys
---@param t table Table
---@return table List of keys
function vim.tbl_keys(t)
assert(type(t) == 'table', string.format('Expected table, got %s', type(t)))
@@ -171,8 +171,8 @@ end
--- Return a list of all values used in a table.
--- However, the order of the return table of values is not guaranteed.
---
---@param t Table
---@returns list of values
---@param t table Table
---@return table List of values
function vim.tbl_values(t)
assert(type(t) == 'table', string.format('Expected table, got %s', type(t)))
@@ -185,8 +185,9 @@ end
--- Apply a function to all values of a table.
---
---@param func function or callable table
---@param t table
---@param func function|table Function or callable table
---@param t table Table
---@return table Table of transformed values
function vim.tbl_map(func, t)
vim.validate({ func = { func, 'c' }, t = { t, 't' } })
@@ -199,8 +200,9 @@ end
--- Filter a table using a predicate function
---
---@param func function or callable table
---@param t table
---@param func function|table Function or callable table
---@param t table Table
---@return table Table of filtered values
function vim.tbl_filter(func, t)
vim.validate({ func = { func, 'c' }, t = { t, 't' } })
@@ -215,9 +217,9 @@ end
--- Checks if a list-like (vector) table contains `value`.
---
---@param t Table to check
---@param value Value to compare
---@returns true if `t` contains `value`
---@param t table Table to check
---@param value any Value to compare
---@return boolean `true` if `t` contains `value`
function vim.tbl_contains(t, value)
vim.validate({ t = { t, 't' } })
@@ -233,13 +235,14 @@ end
---
---@see https://github.com/premake/premake-core/blob/master/src/base/table.lua
---
---@param t Table to check
---@param t table Table to check
---@return boolean `true` if `t` is empty
function vim.tbl_isempty(t)
assert(type(t) == 'table', string.format('Expected table, got %s', type(t)))
return next(t) == nil
end
--- we only merge empty tables or tables that are not a list
--- We only merge empty tables or tables that are not a list
---@private
local function can_merge(v)
return type(v) == 'table' and (vim.tbl_isempty(v) or not vim.tbl_islist(v))
@@ -283,11 +286,12 @@ end
---
---@see |extend()|
---
---@param behavior Decides what to do if a key is found in more than one map:
---@param behavior string Decides what to do if a key is found in more than one map:
--- - "error": raise an error
--- - "keep": use value from the leftmost map
--- - "force": use value from the rightmost map
---@param ... Two or more map-like tables.
---@param ... table Two or more map-like tables
---@return table Merged table
function vim.tbl_extend(behavior, ...)
return tbl_extend(behavior, false, ...)
end
@@ -296,22 +300,23 @@ end
---
---@see |tbl_extend()|
---
---@param behavior Decides what to do if a key is found in more than one map:
---@param behavior string Decides what to do if a key is found in more than one map:
--- - "error": raise an error
--- - "keep": use value from the leftmost map
--- - "force": use value from the rightmost map
---@param ... Two or more map-like tables.
---@param ... table Two or more map-like tables
---@return table Merged table
function vim.tbl_deep_extend(behavior, ...)
return tbl_extend(behavior, true, ...)
end
--- Deep compare values for equality
---
--- Tables are compared recursively unless they both provide the `eq` methamethod.
--- Tables are compared recursively unless they both provide the `eq` metamethod.
--- All other types are compared using the equality `==` operator.
---@param a first value
---@param b second value
---@returns `true` if values are equals, else `false`.
---@param a any First value
---@param b any Second value
---@return boolean `true` if values are equals, else `false`
function vim.deep_equal(a, b)
if a == b then
return true
@@ -338,9 +343,10 @@ end
--- Add the reverse lookup values to an existing table.
--- For example:
--- ``tbl_add_reverse_lookup { A = 1 } == { [1] = 'A', A = 1 }``
--
--Do note that it *modifies* the input.
---@param o table The table to add the reverse to.
---
--- Note that this *modifies* the input.
---@param o table Table to add the reverse to
---@return table o
function vim.tbl_add_reverse_lookup(o)
local keys = vim.tbl_keys(o)
for _, k in ipairs(keys) do
@@ -361,17 +367,17 @@ end
--- Index into a table (first argument) via string keys passed as subsequent arguments.
--- Return `nil` if the key does not exist.
--_
---
--- Examples:
--- <pre>
--- vim.tbl_get({ key = { nested_key = true }}, 'key', 'nested_key') == true
--- vim.tbl_get({ key = {}}, 'key', 'nested_key') == nil
--- </pre>
---
---@param o Table to index
---@param ... Optional strings (0 or more, variadic) via which to index the table
---@param o table Table to index
---@param ... string Optional strings (0 or more, variadic) via which to index the table
---
---@returns nested value indexed by key if it exists, else nil
---@return any Nested value indexed by key (if it exists), else nil
function vim.tbl_get(o, ...)
local keys = { ... }
if #keys == 0 then
@@ -395,11 +401,11 @@ end
---
---@see |vim.tbl_extend()|
---
---@param dst list which will be modified and appended to.
---@param src list from which values will be inserted.
---@param start Start index on src. defaults to 1
---@param finish Final index on src. defaults to #src
---@returns dst
---@param dst table List which will be modified and appended to
---@param src table List from which values will be inserted
---@param start number Start index on src. Defaults to 1
---@param finish number Final index on src. Defaults to `#src`
---@return table dst
function vim.list_extend(dst, src, start, finish)
vim.validate({
dst = { dst, 't' },
@@ -418,8 +424,8 @@ end
---
---@see From https://github.com/premake/premake-core/blob/master/src/base/table.lua
---
---@param t List-like table
---@returns Flattened copy of the given list-like table.
---@param t table List-like table
---@return table Flattened copy of the given list-like table
function vim.tbl_flatten(t)
local result = {}
local function _tbl_flatten(_t)
@@ -443,8 +449,8 @@ end
--- |vim.empty_dict()| or returned as a dict-like |API| or Vimscript result,
--- for example from |rpcrequest()| or |vim.fn|.
---
---@param t Table
---@returns `true` if array-like table, else `false`.
---@param t table Table
---@return boolean `true` if array-like table, else `false`
function vim.tbl_islist(t)
if type(t) ~= 'table' then
return false
@@ -480,8 +486,8 @@ end
--- </pre>
---
---@see https://github.com/Tieske/Penlight/blob/master/lua/pl/tablex.lua
---@param t Table
---@returns Number that is the number of the value in table
---@param t table Table
---@return number Number of non-nil values in table
function vim.tbl_count(t)
vim.validate({ t = { t, 't' } })
@@ -494,10 +500,10 @@ end
--- Creates a copy of a table containing only elements from start to end (inclusive)
---
---@param list table table
---@param start integer Start range of slice
---@param finish integer End range of slice
---@returns Copy of table sliced from start to finish (inclusive)
---@param list table Table
---@param start number Start range of slice
---@param finish number End range of slice
---@return table Copy of table sliced from start to finish (inclusive)
function vim.list_slice(list, start, finish)
local new_list = {}
for i = start or 1, finish or #list do
@@ -509,8 +515,8 @@ end
--- Trim whitespace (Lua pattern "%s") from both sides of a string.
---
---@see https://www.lua.org/pil/20.2.html
---@param s String to trim
---@returns String with whitespace removed from its beginning and end
---@param s string String to trim
---@return string String with whitespace removed from its beginning and end
function vim.trim(s)
vim.validate({ s = { s, 's' } })
return s:match('^%s*(.*%S)') or ''
@@ -519,8 +525,8 @@ end
--- Escapes magic chars in a Lua pattern.
---
---@see https://github.com/rxi/lume
---@param s String to escape
---@returns %-escaped pattern string
---@param s string String to escape
---@return string %-escaped pattern string
function vim.pesc(s)
vim.validate({ s = { s, 's' } })
return s:gsub('[%(%)%.%%%+%-%*%?%[%]%^%$]', '%%%1')
@@ -528,9 +534,9 @@ end
--- Tests if `s` starts with `prefix`.
---
---@param s (string) a string
---@param prefix (string) a prefix
---@return (boolean) true if `prefix` is a prefix of s
---@param s string String
---@param prefix string Prefix to match
---@return boolean `true` if `prefix` is a prefix of `s`
function vim.startswith(s, prefix)
vim.validate({ s = { s, 's' }, prefix = { prefix, 's' } })
return s:sub(1, #prefix) == prefix
@@ -538,9 +544,9 @@ end
--- Tests if `s` ends with `suffix`.
---
---@param s (string) a string
---@param suffix (string) a suffix
---@return (boolean) true if `suffix` is a suffix of s
---@param s string String
---@param suffix string Suffix to match
---@return boolean `true` if `suffix` is a suffix of `s`
function vim.endswith(s, suffix)
vim.validate({ s = { s, 's' }, suffix = { suffix, 's' } })
return #suffix == 0 or s:sub(-#suffix) == suffix
@@ -582,7 +588,7 @@ end
---
--- </pre>
---
---@param opt table of parameter names to validations. Each key is a parameter
---@param opt table Names of parameters to validate. Each key is a parameter
--- name; each value is a tuple in one of these forms:
--- 1. (arg_value, type_name, optional)
--- - arg_value: argument value
@@ -632,8 +638,8 @@ do
return false, string.format('opt[%s]: expected table, got %s', param_name, type(spec))
end
local val = spec[1] -- Argument value.
local types = spec[2] -- Type name, or callable.
local val = spec[1] -- Argument value
local types = spec[2] -- Type name, or callable
local optional = (true == spec[3])
if type(types) == 'string' then
@@ -641,7 +647,7 @@ do
end
if vim.is_callable(types) then
-- Check user-provided validation function.
-- Check user-provided validation function
local valid, optional_message = types(val)
if not valid then
local error_message = string.format('%s: expected %s, got %s', param_name, (spec[3] or '?'), tostring(val))
@@ -685,8 +691,8 @@ do
end
--- Returns true if object `f` can be called as a function.
---
---@param f Any object
---@return true if `f` is callable, else false
---@param f any Any object
---@return boolean `true` if `f` is callable, else `false`
function vim.is_callable(f)
if type(f) == 'function' then
return true