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

View File

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