aboutsummaryrefslogtreecommitdiff
path: root/runtime/doc/lua.txt
diff options
context:
space:
mode:
authorJosh Rahm <joshuarahm@gmail.com>2023-11-30 20:35:25 +0000
committerJosh Rahm <joshuarahm@gmail.com>2023-11-30 20:35:25 +0000
commit1b7b916b7631ddf73c38e3a0070d64e4636cb2f3 (patch)
treecd08258054db80bb9a11b1061bb091c70b76926a /runtime/doc/lua.txt
parenteaa89c11d0f8aefbb512de769c6c82f61a8baca3 (diff)
parent4a8bf24ac690004aedf5540fa440e788459e5e34 (diff)
downloadrneovim-1b7b916b7631ddf73c38e3a0070d64e4636cb2f3.tar.gz
rneovim-1b7b916b7631ddf73c38e3a0070d64e4636cb2f3.tar.bz2
rneovim-1b7b916b7631ddf73c38e3a0070d64e4636cb2f3.zip
Merge remote-tracking branch 'upstream/master' into aucmd_textputpostaucmd_textputpost
Diffstat (limited to 'runtime/doc/lua.txt')
-rw-r--r--runtime/doc/lua.txt3103
1 files changed, 2197 insertions, 906 deletions
diff --git a/runtime/doc/lua.txt b/runtime/doc/lua.txt
index 47249a484b..a35d70cae8 100644
--- a/runtime/doc/lua.txt
+++ b/runtime/doc/lua.txt
@@ -14,7 +14,7 @@ INTRODUCTION *lua-intro*
The Lua 5.1 script engine is builtin and always available. Try this command to
get an idea of what lurks beneath: >vim
- :lua print(vim.inspect(package.loaded))
+ :lua vim.print(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
@@ -33,6 +33,22 @@ Lua 5.1, not worry about forward-compatibility with future Lua versions. If
Nvim ever ships with Lua 5.4+, a Lua 5.1 compatibility shim will be provided
so that old plugins continue to work transparently.
+ *lua-luajit*
+Nvim is built with luajit on platforms which support it, which provides
+extra functionality. Lua code in |init.lua| and plugins can assume its presence
+on installations on common platforms. For maximum compatibility with less
+common platforms, availability can be checked using the `jit` global variable: >lua
+ if jit then
+ -- code for luajit
+ else
+ -- code for plain lua 5.1
+ end
+<
+ *lua-bit*
+In particular, the luajit "bit" extension module is _always_ available.
+A fallback implementation is included when nvim is built with PUC Lua 5.1,
+and will be transparently used when `require("bit")` is invoked.
+
==============================================================================
LUA CONCEPTS AND IDIOMS *lua-concepts*
@@ -46,15 +62,32 @@ programming": tables, closures, and coroutines.
https://www.lua.org/doc/cacm2018.pdf
- Tables are the "object" or container datastructure: they represent both
lists and maps, you can extend them to represent your own datatypes and
- change their behavior using |luaref-metatable| (like Python's "datamodel").
+ change their behavior using |metatable|s (like Python's "datamodel").
- EVERY scope in Lua is a closure: a function is a closure, a module is
- a closure, a `do` block (|luaref-do|) is a closure--and they all work the
- same. A Lua module is literally just a big closure discovered on the "path"
+ a closure, a `do` block (|lua-do|) is a closure--and they all work the same.
+ A Lua module is literally just a big closure discovered on the "path"
(where your modules are found: |package.cpath|).
- Stackful coroutines enable cooperative multithreading, generators, and
versatile control for both Lua and its host (Nvim).
- *lua-call-function*
+ *iterator*
+An iterator is just a function that can be called repeatedly to get the "next"
+value of a collection (or any other |iterable|). This interface is expected by
+|for-in| loops, produced by |pairs()|, supported by |vim.iter|, etc.
+https://www.lua.org/pil/7.1.html
+
+ *iterable*
+An "iterable" is anything that |vim.iter()| can consume: tables, dicts, lists,
+iterator functions, tables implementing the |__call()| metamethod, and
+|vim.iter()| objects.
+
+ *list-iterator*
+Iterators on |lua-list| tables have a "middle" and "end", whereas iterators in
+general may be logically infinite. Therefore some |vim.iter| operations (e.g.
+|Iter:rev()|) make sense only on list-like tables (which are finite by
+definition).
+
+ *lua-function-call*
Lua functions can be called in multiple ways. Consider the function: >lua
local foo = function(a, b)
print("A: ", a)
@@ -67,21 +100,19 @@ The first way to call this function is: >lua
-- A: 1
-- B: 2
-This way of calling a function is familiar from most scripting languages.
-In Lua, any missing arguments are passed as `nil`. Example: >lua
+This way of calling a function is familiar from most scripting languages. In
+Lua, any missing arguments are passed as `nil`, and extra parameters are
+silently discarded. Example: >lua
foo(1)
-- ==== Result ====
-- A: 1
-- B: nil
-
-Furthermore it is not an error if extra parameters are passed, they are just
-discarded.
-
+<
*kwargs*
When calling a function, you can omit the parentheses if the function takes
exactly one string literal (`"foo"`) or table literal (`{1,2,3}`). The latter
-is often used to approximate "named parameters" ("kwargs" or "keyword args")
-as in languages like Python and C#. Example: >lua
+is often used to mimic "named parameters" ("kwargs" or "keyword args") as in
+languages like Python and C#. Example: >lua
local func_with_opts = function(opts)
local will_do_foo = opts.foo
local filename = opts.filename
@@ -92,21 +123,16 @@ as in languages like Python and C#. Example: >lua
<
There's nothing special going on here except that parentheses are treated as
whitespace. But visually, this small bit of sugar gets reasonably close to
-a "keyword args" interface.
-
-It is of course also valid to call the function with parentheses: >lua
- func_with_opts({ foo = true, filename = "hello.world" })
-<
-Nvim tends to prefer the keyword args style.
+a "keyword args" interface. Nvim code tends to prefer this style.
------------------------------------------------------------------------------
LUA PATTERNS *lua-patterns*
Lua intentionally does not support regular expressions, instead it has limited
-"patterns" |luaref-patterns| which avoid the performance pitfalls of extended
+"patterns" |lua-pattern| which avoid the performance pitfalls of extended
regex. Lua scripts can also use Vim regex via |vim.regex()|.
-These examples use |string.match()| to demonstrate Lua patterns: >lua
+Examples: >lua
print(string.match("foo123bar123", "%d+"))
-- 123
@@ -118,7 +144,7 @@ These examples use |string.match()| to demonstrate Lua patterns: >lua
-- .bar
==============================================================================
-IMPORTING LUA MODULES *require()* *lua-require*
+IMPORTING LUA MODULES *lua-module-load*
Modules are searched for under the directories specified in 'runtimepath', in
the order they appear. Any "." in the module name is treated as a directory
@@ -132,7 +158,7 @@ back to Lua's default search mechanism. The first script found is run and
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 |luaref-require()|.
+executing any script. For further details see |require()|.
For example, if 'runtimepath' is `foo,bar` and |package.cpath| was
`./?.so;./?.dll` at startup, `require('mod')` searches these paths in order
@@ -217,11 +243,11 @@ command calls. The |lua-stdlib| modules, user modules, and anything else on
The Lua print() function redirects its output to the Nvim message area, with
arguments separated by " " (space) instead of "\t" (tab).
- *:lua*
+ *:lua=* *:lua*
:lua {chunk}
Executes Lua chunk {chunk}. 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))`
+ chunk is evaluated as an expression and printed. `:lua =expr` or `:=expr` is
+ equivalent to `:lua print(vim.inspect(expr))`.
Examples: >vim
:lua vim.api.nvim_command('echo "Hello, Nvim!"')
@@ -231,12 +257,12 @@ arguments separated by " " (space) instead of "\t" (tab).
:lua =jit.version
<
*:lua-heredoc*
-:lua << [endmarker]
+:lua << [trim] [{endmarker}]
{script}
{endmarker}
- Executes Lua script {script} from within Vimscript. {endmarker} must NOT
- be preceded by whitespace. You can omit [endmarker] after the "<<" and use
- a dot "." after {script} (similar to |:append|, |:insert|).
+ Executes Lua script {script} from within Vimscript. You can omit
+ [endmarker] after the "<<" and use a dot "." after {script} (similar to
+ |:append|, |:insert|). Refer to |:let-heredoc| for more information.
Example: >vim
function! CurrentLineInfo()
@@ -280,7 +306,7 @@ arguments separated by " " (space) instead of "\t" (tab).
<
==============================================================================
-luaeval() *lua-eval* *luaeval()*
+luaeval() *lua-eval*
The (dual) equivalent of "vim.eval" for passing Lua values to Nvim is
"luaeval". "luaeval" takes an expression string and an optional argument used
@@ -305,14 +331,16 @@ Example: >vim
:echo luaeval('string.match(_A, "[a-z]+")', 'XYXfoo123')
" foo
<
+ *lua-table-ambiguous*
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
cases there is the following agreement:
-
+ *lua-list*
0. Empty table is empty list.
-1. Table with N incrementally growing integral numbers, starting from 1 and
- ending with N is considered to be a list.
+1. Table with N consecutive integer indices starting from 1 and ending with
+ N is considered a list. See also |list-iterator|.
+ *lua-dict*
2. Table with string keys, none of which contains NUL byte, is considered to
be a dictionary.
3. Table with string keys, at least one of which contains NUL byte, is also
@@ -383,7 +411,7 @@ For example consider the following Lua omnifunc handler: >lua
return {'stuff', 'steam', 'strange things'}
end
end
- vim.api.nvim_buf_set_option(0, 'omnifunc', 'v:lua.mymod.omnifunc')
+ vim.bo[buf].omnifunc = 'v:lua.mymod.omnifunc'
Note: The module ("mymod" in the above example) must either be a Lua global,
or use require() as shown above to access it from a package.
@@ -405,7 +433,7 @@ is unnecessary.
You can peek at the module properties: >vim
- :lua print(vim.inspect(vim))
+ :lua vim.print(vim)
Result is something like this: >
@@ -431,29 +459,24 @@ Note that underscore-prefixed functions (e.g. "_os_proc_children") are
internal/private and must not be used by plugins.
------------------------------------------------------------------------------
-VIM.LOOP *lua-loop* *vim.loop*
+VIM.UV *lua-loop* *vim.uv*
-`vim.loop` exposes all features of the Nvim event-loop. This is a low-level
-API that provides functionality for networking, filesystem, and process
-management. Try this command to see available functions: >vim
-
- :lua print(vim.inspect(vim.loop))
-<
-Internally, `vim.loop` wraps the "luv" Lua bindings for the LibUV library;
-see |luv-intro| for a full reference manual.
+`vim.uv` exposes the "luv" Lua bindings for the libUV library that Nvim uses
+for networking, filesystem, and process management, see |luvref.txt|.
+In particular, it allows interacting with the main Nvim |luv-event-loop|.
*E5560* *lua-loop-callbacks*
It is an error to directly invoke `vim.api` functions (except |api-fast|) in
-`vim.loop` callbacks. For example, this is an error: >lua
+`vim.uv` callbacks. For example, this is an error: >lua
- local timer = vim.loop.new_timer()
+ local timer = vim.uv.new_timer()
timer:start(1000, 0, function()
vim.api.nvim_command('echomsg "test"')
end)
<
To avoid the error use |vim.schedule_wrap()| to defer the callback: >lua
- local timer = vim.loop.new_timer()
+ local timer = vim.uv.new_timer()
timer:start(1000, 0, vim.schedule_wrap(function()
vim.api.nvim_command('echomsg "test"')
end))
@@ -466,7 +489,7 @@ Example: repeating timer
2. Execute it with ":luafile %". >lua
-- Create a timer handle (implementation detail: uv_timer_t).
- local timer = vim.loop.new_timer()
+ local timer = vim.uv.new_timer()
local i = 0
-- Waits 1000ms, then repeats every 750ms until timer:close().
timer:start(1000, 750, function()
@@ -486,7 +509,7 @@ Example: File-change detection *watch-file*
5. Observe that the file reloads in Nvim (because on_change() calls
|:checktime|). >lua
- local w = vim.loop.new_fs_event()
+ local w = vim.uv.new_fs_event()
local function on_change(err, fname, status)
-- Do work...
vim.api.nvim_command('checktime')
@@ -510,11 +533,11 @@ Example: TCP echo-server *tcp-server*
4. Connect from any TCP client (e.g. "nc 0.0.0.0 36795"): >lua
local function create_server(host, port, on_connect)
- local server = vim.loop.new_tcp()
+ local server = vim.uv.new_tcp()
server:bind(host, port)
server:listen(128, function(err)
assert(not err, err) -- Check for errors.
- local sock = vim.loop.new_tcp()
+ local sock = vim.uv.new_tcp()
server:accept(sock) -- Accept client connection.
on_connect(sock) -- Start reading messages.
end)
@@ -535,105 +558,139 @@ Example: TCP echo-server *tcp-server*
Multithreading *lua-loop-threading*
Plugins can perform work in separate (os-level) threads using the threading
-APIs in luv, for instance `vim.loop.new_thread`. Note that every thread
-gets its own separate lua interpreter state, with no access to lua globals
+APIs in luv, for instance `vim.uv.new_thread`. Note that every thread
+gets its own separate Lua interpreter state, with no access to Lua globals
in the main thread. Neither can the state of the editor (buffers, windows,
etc) be directly accessed from threads.
A subset of the `vim.*` API is available in threads. This includes:
-- `vim.loop` with a separate event loop per thread.
+- `vim.uv` with a separate event loop per thread.
- `vim.mpack` and `vim.json` (useful for serializing messages between threads)
-- `require` in threads can use lua packages from the global |package.path|
+- `require` in threads can use Lua packages from the global |package.path|
- `print()` and `vim.inspect`
- `vim.diff`
-- most utility functions in `vim.*` for working with pure lua values
+- most utility functions in `vim.*` for working with pure Lua values
like `vim.split`, `vim.tbl_*`, `vim.list_*`, and so on.
- `vim.is_thread()` returns true from a non-main thread.
------------------------------------------------------------------------------
-VIM.HIGHLIGHT *lua-highlight*
+VIM.LPEG *lua-lpeg*
+
+ *vim.lpeg* *vim.re*
+The Lpeg library for parsing expression grammars is being included as
+`vim.lpeg` (https://www.inf.puc-rio.br/~roberto/lpeg/). In addition, its regex-like
+interface is available as `vim.re` (https://www.inf.puc-rio.br/~roberto/lpeg/re.html).
-Nvim includes a function for highlighting a selection on yank (see for example
-https://github.com/machakann/vim-highlightedyank). To enable it, add
->vim
+==============================================================================
+VIM.HIGHLIGHT *vim.highlight*
+
+
+Nvim includes a function for highlighting a selection on yank.
+
+To enable it, add the following to your `init.vim`: >vim
au TextYankPost * silent! lua vim.highlight.on_yank()
+
<
-to your `init.vim`. You can customize the highlight group and the duration of
-the highlight via
->vim
+
+You can customize the highlight group and the duration of the highlight
+via: >vim
au TextYankPost * silent! lua vim.highlight.on_yank {higroup="IncSearch", timeout=150}
+
<
-If you want to exclude visual selections from highlighting on yank, use
->vim
+
+If you want to exclude visual selections from highlighting on yank, use: >vim
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:
- - {higroup} highlight group for yanked region (default |hl-IncSearch|)
- - {timeout} time in ms before highlight is cleared (default `150`)
- - {on_macro} highlight when executing macro (default `false`)
- - {on_visual} highlight when yanking visual selection (default `true`)
- - {event} event structure (default |v:event|)
-
-vim.highlight.range({bufnr}, {ns}, {hlgroup}, {start}, {finish}, {opts})
- *vim.highlight.range()*
+ Highlight the yanked text
+
+ Parameters: ~
+ • {opts} (table|nil) Optional parameters
+ • higroup highlight group for yanked region (default
+ "IncSearch")
+ • timeout time in ms before highlight is cleared (default 150)
+ • on_macro highlight when executing macro (default false)
+ • on_visual highlight when yanking visual selection (default
+ true)
+ • event event structure (default vim.v.event)
+ • priority integer priority (default
+ |vim.highlight.priorities|`.user`)
+
+vim.highlight.priorities *vim.highlight.priorities*
+ Table with default priorities used for highlighting:
+ • `syntax`: `50`, used for standard syntax highlighting
+ • `treesitter`: `100`, used for tree-sitter-based highlighting
+ • `semantic_tokens`: `125`, used for LSP semantic token highlighting
+ • `diagnostics`: `150`, used for code analysis such as diagnostics
+ • `user`: `200`, used for user-triggered highlights such as LSP document
+ symbols or `on_yank` autocommands
+ *vim.highlight.range()*
+vim.highlight.range({bufnr}, {ns}, {higroup}, {start}, {finish}, {opts})
Apply highlight group to range of text.
- Parameters: ~
- • {bufnr} buffer number
- • {ns} namespace for highlights
- • {hlgroup} highlight group name
- • {start} starting position (tuple {line,col})
- • {finish} finish position (tuple {line,col})
- • {opts} optional parameters:
- • `regtype`: type of range (characterwise, linewise,
- or blockwise, see |setreg()|), default `'v'`
- • `inclusive`: range includes end position,
- default `false`
- • `priority`: priority of highlight, default
- `vim.highlight.user` (see below)
+ Parameters: ~
+ • {bufnr} (integer) Buffer number to apply highlighting to
+ • {ns} (integer) Namespace to add highlight to
+ • {higroup} (string) Highlight group to use for highlighting
+ • {start} integer[]|string Start of region as a (line, column) tuple
+ or string accepted by |getpos()|
+ • {finish} integer[]|string End of region as a (line, column) tuple or
+ string accepted by |getpos()|
+ • {opts} (table|nil) Optional parameters
+ • regtype type of range (see |setreg()|, default charwise)
+ • inclusive boolean indicating whether the range is
+ end-inclusive (default false)
+ • priority number indicating priority of highlight (default
+ priorities.user)
-vim.highlight.priorities *vim.highlight.priorities*
- Table with default priorities used for highlighting:
- • `syntax`: `50`, used for standard syntax highlighting
- • `treesitter`: `100`, used for tree-sitter-based highlighting
- • `semantic_tokens`: `125`, used for LSP semantic token highlighting
- • `diagnostics`: `150`, used for code analysis such as diagnostics
- • `user`: `200`, used for user-triggered highlights such as LSP document
- symbols or `on_yank` autocommands
+==============================================================================
+VIM.REGEX *vim.regex*
-------------------------------------------------------------------------------
-VIM.REGEX *lua-regex*
-Vim regexes can be used directly from lua. Currently they only allow
+Vim regexes can be used directly from Lua. Currently they only allow
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-sensitive by default, regardless of 'magic' and 'ignorecase'.
They can be controlled with flags, see |/magic| and |/ignorecase|.
-Methods on the regex object:
+ Parameters: ~
+ • {re} (string)
-regex:match_str({str}) *regex:match_str()*
- Match the string against the regex. If the string should match the regex
- precisely, surround the regex with `^` and `$`. If the was a match, the
- byte indices for the beginning and end of the match is returned. When
- there is no match, `nil` is returned. As any integer is truth-y,
- `regex:match()` can be directly used as a condition in an if-statement.
+ Return: ~
+ vim.regex
-regex:match_line({bufnr}, {line_idx} [, {start}, {end}]) *regex:match_line()*
+ *regex:match_line()*
+vim.regex:match_line({bufnr}, {line_idx}, {start}, {end_})
Match line {line_idx} (zero-based) in buffer {bufnr}. If {start} and {end}
are supplied, match only this byte index range. Otherwise see
|regex:match_str()|. If {start} is used, then the returned byte indices
will be relative {start}.
-------------------------------------------------------------------------------
-VIM.DIFF *lua-diff*
+ Parameters: ~
+ • {bufnr} (integer)
+ • {line_idx} (integer)
+ • {start} (integer|nil)
+ • {end_} (integer|nil)
+
+vim.regex:match_str({str}) *regex:match_str()*
+ Match the string against the regex. If the string should match the regex
+ precisely, surround the regex with `^` and `$` . If there was a match, the byte indices for the beginning and end of the
+ match are returned. When there is no match, `nil` is returned. Because any integer is "truthy", `regex:match_str()` can be directly used as a condition in an if-statement.
+
+ Parameters: ~
+ • {str} (string)
+
+
+==============================================================================
+VIM.DIFF *vim.diff*
vim.diff({a}, {b}, {opts}) *vim.diff()*
Run diff on strings {a} and {b}. Any indices returned by this function,
@@ -653,82 +710,135 @@ vim.diff({a}, {b}, {opts}) *vim.diff()*
-- {1, 1, 1, 2}
-- }
<
+
Parameters: ~
- • {a} First string to compare
- • {b} Second string to compare
- • {opts} Optional parameters:
- • `on_hunk` (callback):
- Invoked for each hunk in the diff. Return a negative number
- to cancel the callback for any remaining hunks.
- Args:
- • `start_a` (integer): Start line of hunk in {a}.
- • `count_a` (integer): Hunk size in {a}.
- • `start_b` (integer): Start line of hunk in {b}.
- • `count_b` (integer): Hunk size in {b}.
- • `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 used.
- • `linematch` (boolean): Run linematch on the resulting hunks
- from xdiff. Requires `result_type = indices`, ignored
- otherwise.
- • `algorithm` (string):
- Diff algorithm to use. Values:
- • "myers" the default algorithm
- • "minimal" spend extra time to generate the
- smallest possible diff
- • "patience" patience diff algorithm
- • "histogram" histogram diff algorithm
- • `ctxlen` (integer): Context length
- • `interhunkctxlen` (integer):
- Inter hunk context length
- • `ignore_whitespace` (boolean):
- Ignore whitespace
- • `ignore_whitespace_change` (boolean):
- Ignore whitespace change
- • `ignore_whitespace_change_at_eol` (boolean)
- Ignore whitespace change at end-of-line.
- • `ignore_cr_at_eol` (boolean)
- Ignore carriage return at end-of-line
- • `ignore_blank_lines` (boolean)
- Ignore blank lines
- • `indent_heuristic` (boolean):
- Use the indent heuristic for the internal
- diff library.
-
- Return: ~
- See {opts.result_type}. nil if {opts.on_hunk} is given.
+ • {a} (string) First string to compare
+ • {b} (string) Second string to compare
+ • {opts} table<string,any> Optional parameters:
+ • `on_hunk` (callback): Invoked for each hunk in the diff. Return a
+ negative number to cancel the callback for any remaining
+ hunks. Args:
+ • `start_a` (integer): Start line of hunk in {a}.
+ • `count_a` (integer): Hunk size in {a}.
+ • `start_b` (integer): Start line of hunk in {b}.
+ • `count_b` (integer): Hunk size in {b}.
+
+ • `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 used.
+
+ • `linematch` (boolean|integer): Run linematch on the
+ resulting hunks from xdiff. When integer, only hunks upto
+ this size in lines are run through linematch. Requires
+ `result_type = indices`, ignored otherwise.
+ • `algorithm` (string): Diff algorithm to use. Values:
+ • "myers" the default algorithm
+ • "minimal" spend extra time to generate the smallest
+ possible diff
+ • "patience" patience diff algorithm
+ • "histogram" histogram diff algorithm
+
+ • `ctxlen` (integer): Context length
+ • `interhunkctxlen` (integer): Inter hunk context length
+ • `ignore_whitespace` (boolean): Ignore whitespace
+ • `ignore_whitespace_change` (boolean): Ignore whitespace
+ change
+ • `ignore_whitespace_change_at_eol` (boolean) Ignore
+ whitespace change at end-of-line.
+ • `ignore_cr_at_eol` (boolean) Ignore carriage return at
+ end-of-line
+ • `ignore_blank_lines` (boolean) Ignore blank lines
+ • `indent_heuristic` (boolean): Use the indent heuristic for
+ the internal diff library.
-------------------------------------------------------------------------------
-VIM.MPACK *lua-mpack*
+ Return: ~
+ string|table|nil See {opts.result_type}. `nil` if {opts.on_hunk} is
+ given.
-The *vim.mpack* module provides encoding and decoding of Lua objects to and
-from msgpack-encoded strings. Supports |vim.NIL| and |vim.empty_dict()|.
-vim.mpack.encode({obj}) *vim.mpack.encode*
- Encodes (or "packs") Lua object {obj} as msgpack in a Lua string.
+==============================================================================
+VIM.MPACK *vim.mpack*
+
-vim.mpack.decode({str}) *vim.mpack.decode*
+This module provides encoding and decoding of Lua objects to and from
+msgpack-encoded strings. Supports |vim.NIL| and |vim.empty_dict()|.
+
+vim.mpack.decode({str}) *vim.mpack.decode()*
Decodes (or "unpacks") the msgpack-encoded {str} to a Lua object.
-------------------------------------------------------------------------------
-VIM.JSON *lua-json*
+ Parameters: ~
+ • {str} (string)
-The *vim.json* module provides encoding and decoding of Lua objects to and
-from JSON-encoded strings. Supports |vim.NIL| and |vim.empty_dict()|.
+vim.mpack.encode({obj}) *vim.mpack.encode()*
+ Encodes (or "packs") Lua object {obj} as msgpack in a Lua string.
-vim.json.encode({obj}) *vim.json.encode*
- Encodes (or "packs") Lua object {obj} as JSON in a Lua string.
-vim.json.decode({str}[, {opts}]) *vim.json.decode*
+==============================================================================
+VIM.JSON *vim.json*
+
+
+This module provides encoding and decoding of Lua objects to and from
+JSON-encoded strings. Supports |vim.NIL| and |vim.empty_dict()|.
+
+vim.json.decode({str}, {opts}) *vim.json.decode()*
Decodes (or "unpacks") the JSON-encoded {str} to a Lua object.
- {opts} is a table with the key `luanil = { object: bool, array: bool }`
- that controls whether `null` in JSON objects or arrays should be converted
- to Lua `nil` instead of `vim.NIL`.
+ • Decodes JSON "null" as |vim.NIL| (controllable by {opts}, see below).
+ • Decodes empty object as |vim.empty_dict()|.
+ • Decodes empty array as `{}` (empty Lua table).
-------------------------------------------------------------------------------
-VIM.SPELL *lua-spell*
+ Example: >lua
+ vim.print(vim.json.decode('{"bar":[],"foo":{},"zub":null}'))
+ -- { bar = {}, foo = vim.empty_dict(), zub = vim.NIL }
+<
+
+ Parameters: ~
+ • {str} (string) Stringified JSON data.
+ • {opts} table<string,any>|nil Options table with keys:
+ • luanil: (table) Table with keys:
+ • object: (boolean) When true, converts `null` in JSON
+ objects to Lua `nil` instead of |vim.NIL|.
+ • array: (boolean) When true, converts `null` in JSON arrays
+ to Lua `nil` instead of |vim.NIL|.
+
+ Return: ~
+ any
+
+vim.json.encode({obj}) *vim.json.encode()*
+ Encodes (or "packs") Lua object {obj} as JSON in a Lua string.
+
+ Parameters: ~
+ • {obj} any
+
+ Return: ~
+ (string)
+
+
+==============================================================================
+VIM.BASE64 *vim.base64*
+
+vim.base64.decode({str}) *vim.base64.decode()*
+ Decode a Base64 encoded string.
+
+ Parameters: ~
+ • {str} (string) Base64 encoded string
+
+ Return: ~
+ (string) Decoded string
+
+vim.base64.encode({str}) *vim.base64.encode()*
+ Encode {str} using Base64.
+
+ Parameters: ~
+ • {str} (string) String to encode
+
+ Return: ~
+ (string) Encoded string
+
+
+==============================================================================
+VIM.SPELL *vim.spell*
vim.spell.check({str}) *vim.spell.check()*
Check {str} for spelling errors. Similar to the Vimscript function
@@ -745,268 +855,359 @@ vim.spell.check({str}) *vim.spell.check()*
-- {'quik', 'bad', 5}
-- }
<
+
Parameters: ~
- • {str} String to spell check.
+ • {str} (string)
Return: ~
- List of tuples with three items:
- - The badly spelled word.
- - The type of the spelling error:
- "bad" spelling mistake
- "rare" rare word
- "local" word only valid in another region
- "caps" word should start with Capital
- - The position in {str} where the word begins.
+ `{[1]: string, [2]: string, [3]: string}[]` List of tuples with three items:
+ • The badly spelled word.
+ • The type of the spelling error: "bad" spelling mistake "rare" rare
+ word "local" word only valid in another region "caps" word should
+ start with Capital
+ • The position in {str} where the word begins.
-------------------------------------------------------------------------------
-VIM *lua-builtin*
-vim.api.{func}({...}) *vim.api*
+==============================================================================
+VIM *vim.builtin*
+
+
+vim.api.{func}({...}) *vim.api*
Invokes Nvim |API| function {func} with arguments {...}.
Example: call the "nvim_get_current_line()" API function: >lua
print(tostring(vim.api.nvim_get_current_line()))
-vim.version() *vim.version*
- Gets the version of the current Nvim build.
-
-vim.in_fast_event() *vim.in_fast_event()*
- Returns true if the code is executing as part of a "fast" event handler,
- where most of the API is disabled. These are low-level events (e.g.
- |lua-loop-callbacks|) which can be invoked whenever Nvim polls for input.
- When this is `false` most API functions are callable (but may be subject
- to other restrictions such as |textlock|).
-
-vim.NIL *vim.NIL*
+vim.NIL *vim.NIL*
Special value representing NIL in |RPC| and |v:null| in Vimscript
conversion, and similar cases. Lua `nil` cannot be used as part of a Lua
table representing a Dictionary or Array, because it is treated as
missing: `{"foo", nil}` is the same as `{"foo"}`.
+vim.type_idx *vim.type_idx*
+ Type index for use in |lua-special-tbl|. Specifying one of the values from
+ |vim.types| allows typing the empty table (it is unclear whether empty Lua
+ table represents empty list or empty array) and forcing integral numbers
+ to be |Float|. See |lua-special-tbl| for more details.
+
+vim.val_idx *vim.val_idx*
+ Value index for tables representing |Float|s. A table representing
+ floating-point value 1.0 looks like this: >lua
+ {
+ [vim.type_idx] = vim.types.float,
+ [vim.val_idx] = 1.0,
+ }
+< See also |vim.type_idx| and |lua-special-tbl|.
+
+vim.types *vim.types*
+ Table with possible values for |vim.type_idx|. Contains two sets of
+ key-value pairs: first maps possible values for |vim.type_idx| to
+ human-readable strings, second maps human-readable type names to 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`,
+ `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
+ properties of Lua tables this basically means “value is not `nil`”.
+ 2. For each value in `vim.types` table `vim.types[vim.types[value]]` is the
+ same as `value`.
+ No other restrictions are put on types, and it is not guaranteed that
+ values corresponding to `vim.types.float`, `vim.types.array` and
+ `vim.types.dictionary` will not change or that `vim.types` table will only
+ contain values for these three types.
+
+ *log_levels* *vim.log.levels*
+Log levels are one of the values defined in `vim.log.levels`:
+
+ vim.log.levels.DEBUG
+ vim.log.levels.ERROR
+ vim.log.levels.INFO
+ vim.log.levels.TRACE
+ vim.log.levels.WARN
+ vim.log.levels.OFF
+
vim.empty_dict() *vim.empty_dict()*
- Creates a special empty table (marked with a metatable), which Nvim to an
- empty dictionary when translating Lua values to Vimscript or API types.
- Nvim by default converts an empty table `{}` without this metatable to an
- list/array.
+ Creates a special empty table (marked with a metatable), which Nvim
+ converts to an empty dictionary when translating Lua values to 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 metatable
marker and converts the dict to a list/array anyway.
-vim.rpcnotify({channel}, {method} [, {args}...]) *vim.rpcnotify()*
+vim.iconv({str}, {from}, {to}, {opts}) *vim.iconv()*
+ The result is a String, which is the text {str} converted from encoding
+ {from} to encoding {to}. When the conversion fails `nil` is returned. When
+ some characters could not be converted they are replaced with "?". The
+ encoding names are whatever the iconv() library function can accept, see
+ ":Man 3 iconv".
+
+ Parameters: ~
+ • {str} (string) Text to convert
+ • {from} (number) Encoding of {str}
+ • {to} (number) Target encoding
+ • {opts} table<string,any>|nil
+
+ Return: ~
+ (string|nil) Converted string if conversion succeeds, `nil` otherwise.
+
+vim.in_fast_event() *vim.in_fast_event()*
+ Returns true if the code is executing as part of a "fast" event handler,
+ where most of the API is disabled. These are low-level events (e.g.
+ |lua-loop-callbacks|) which can be invoked whenever Nvim polls for input.
+ When this is `false` most API functions are callable (but may be subject
+ to other restrictions such as |textlock|).
+
+vim.rpcnotify({channel}, {method}, {args}, {...}) *vim.rpcnotify()*
Sends {event} to {channel} via |RPC| and returns immediately. If {channel}
is 0, the event is broadcast to all channels.
This function also works in a fast callback |lua-loop-callbacks|.
-vim.rpcrequest({channel}, {method} [, {args}...]) *vim.rpcrequest()*
+ Parameters: ~
+ • {channel} (integer)
+ • {method} (string)
+ • {args} any[]|nil
+ • {...} any|nil
+
+vim.rpcrequest({channel}, {method}, {args}, {...}) *vim.rpcrequest()*
Sends a request to {channel} to invoke {method} via |RPC| and blocks until
a response is received.
Note: NIL values as part of the return value is represented as |vim.NIL|
special value
-vim.stricmp({a}, {b}) *vim.stricmp()*
- Compares strings case-insensitively. Returns 0, 1 or -1 if strings are
- equal, {a} is greater than {b} or {a} is lesser than {b}, respectively.
+ Parameters: ~
+ • {channel} (integer)
+ • {method} (string)
+ • {args} any[]|nil
+ • {...} any|nil
-vim.str_utfindex({str} [, {index}]) *vim.str_utfindex()*
- Convert byte index to UTF-32 and UTF-16 indices. If {index} is not
- supplied, the length of the string is used. All indices are zero-based.
- Returns two values: the UTF-32 and UTF-16 indices respectively.
+vim.schedule({fn}) *vim.schedule()*
+ Schedules {fn} to be invoked soon by the main event-loop. Useful to avoid
+ |textlock| or other temporary restrictions.
- Embedded NUL bytes are treated as terminating the string. Invalid UTF-8
- bytes, and embedded surrogates are counted as one code point each. An
- {index} in the middle of a UTF-8 sequence is rounded upwards to the end of
- that sequence.
+ Parameters: ~
+ • {fn} (function)
-vim.str_byteindex({str}, {index} [, {use_utf16}]) *vim.str_byteindex()*
+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.iconv({str}, {from}, {to}[, {opts}]) *vim.iconv()*
- The result is a String, which is the text {str} converted from
- encoding {from} to encoding {to}. When the conversion fails `nil` is
- returned. When some characters could not be converted they
- are replaced with "?".
- The encoding names are whatever the iconv() library function
- can accept, see ":Man 3 iconv".
+ Parameters: ~
+ • {str} (string)
+ • {index} (number)
+ • {use_utf16} any|nil
+
+vim.str_utf_end({str}, {index}) *vim.str_utf_end()*
+ Gets the distance (in bytes) from the last byte of the codepoint
+ (character) that {index} points to.
- Parameters: ~
- • {str} (string) Text to convert
- • {from} (string) Encoding of {str}
- • {to} (string) Target encoding
+ Examples: >lua
+ -- The character 'æ' is stored as the bytes '\xc3\xa6' (using UTF-8)
- Returns: ~
- Converted string if conversion succeeds, `nil` otherwise.
+ -- Returns 0 because the index is pointing at the last byte of a character
+ vim.str_utf_end('æ', 2)
-vim.schedule({callback}) *vim.schedule()*
- Schedules {callback} to be invoked soon by the main event-loop. Useful
- to avoid |textlock| or other temporary restrictions.
+ -- Returns 1 because the index is pointing at the penultimate byte of a character
+ vim.str_utf_end('æ', 1)
+<
+ Parameters: ~
+ • {str} (string)
+ • {index} (number)
+
+ Return: ~
+ (number)
-vim.defer_fn({fn}, {timeout}) *vim.defer_fn*
- Defers calling {fn} until {timeout} ms passes. Use to do a one-shot timer
- that calls {fn}.
+vim.str_utf_pos({str}) *vim.str_utf_pos()*
+ Gets a list of the starting byte positions of each UTF-8 codepoint in the
+ given string.
- Note: The {fn} is |vim.schedule_wrap()|ped automatically, so API functions are
- safe to call.
+ Embedded NUL bytes are treated as terminating the string.
Parameters: ~
- • {fn} Callback to call once {timeout} expires
- • {timeout} Time in ms to wait before calling {fn}
+ • {str} (string)
- Returns: ~
- |vim.loop|.new_timer() object
+ Return: ~
+ (table)
-vim.wait({time} [, {callback}, {interval}, {fast_only}]) *vim.wait()*
- Wait for {time} in milliseconds until {callback} returns `true`.
+vim.str_utf_start({str}, {index}) *vim.str_utf_start()*
+ Gets the distance (in bytes) from the starting byte of the codepoint
+ (character) that {index} points to.
- Executes {callback} immediately and at approximately {interval}
- milliseconds (default 200). Nvim still processes other events during
- this time.
+ The result can be added to {index} to get the starting byte of a
+ character.
+
+ Examples: >lua
+ -- The character 'æ' is stored as the bytes '\xc3\xa6' (using UTF-8)
+
+ -- Returns 0 because the index is pointing at the first byte of a character
+ vim.str_utf_start('æ', 1)
+
+ -- Returns -1 because the index is pointing at the second byte of a character
+ vim.str_utf_start('æ', 2)
+<
Parameters: ~
- • {time} Number of milliseconds to wait
- • {callback} Optional callback. Waits until {callback} returns true
- • {interval} (Approximate) number of milliseconds to wait between polls
- • {fast_only} If true, only |api-fast| events will be processed.
- If called from while in an |api-fast| event, will
- automatically be set to `true`.
+ • {str} (string)
+ • {index} (number)
- Returns: ~
- If {callback} returns `true` during the {time}:
- `true, nil`
+ Return: ~
+ (number)
- If {callback} never returns `true` during the {time}:
- `false, -1`
+vim.str_utfindex({str}, {index}) *vim.str_utfindex()*
+ Convert byte index to UTF-32 and UTF-16 indices. If {index} is not
+ supplied, the length of the string is used. All indices are zero-based.
- If {callback} is interrupted during the {time}:
- `false, -2`
+ Embedded NUL bytes are treated as terminating the string. Invalid UTF-8
+ bytes, and embedded surrogates are counted as one code point each. An
+ {index} in the middle of a UTF-8 sequence is rounded upwards to the end of
+ that sequence.
- If {callback} errors, the error is raised.
+ Parameters: ~
+ • {str} (string)
+ • {index} (number|nil)
- Examples: >lua
+ Return (multiple): ~
+ (integer) UTF-32 index
+ (integer) UTF-16 index
- ---
- -- Wait for 100 ms, allowing other events to process
- vim.wait(100, function() end)
+vim.stricmp({a}, {b}) *vim.stricmp()*
+ Compares strings case-insensitively.
- ---
- -- Wait for 100 ms or until global variable set.
- vim.wait(100, function() return vim.g.waiting_for_var end)
+ Parameters: ~
+ • {a} (string)
+ • {b} (string)
- ---
- -- Wait for 1 second or until global variable set, checking every ~500 ms
- vim.wait(1000, function() return vim.g.waiting_for_var end, 500)
+ Return: ~
+ 0|1|-1 if strings are equal, {a} is greater than {b} or {a} is lesser
+ than {b}, respectively.
+
+vim.ui_attach({ns}, {options}, {callback}) *vim.ui_attach()*
+ Attach to ui events, similar to |nvim_ui_attach()| but receive events as
+ Lua callback. Can be used to implement screen elements like popupmenu or
+ message handling in Lua.
+
+ {options} should be a dictionary-like table, where `ext_...` options
+ should be set to true to receive events for the respective external
+ element.
+
+ {callback} receives event name plus additional parameters. See
+ |ui-popupmenu| and the sections below for event format for respective
+ events.
+
+ WARNING: This api is considered experimental. Usability will vary for
+ different screen elements. In particular `ext_messages` behavior is
+ subject to further changes and usability improvements. This is expected to
+ be used to handle messages when setting 'cmdheight' to zero (which is
+ likewise experimental).
- ---
- -- Schedule a function to set a value in 100ms
- vim.defer_fn(function() vim.g.timer_result = true end, 100)
+ Example (stub for a |ui-popupmenu| implementation): >lua
+ ns = vim.api.nvim_create_namespace('my_fancy_pum')
- -- Would wait ten seconds if results blocked. Actually only waits 100 ms
- if vim.wait(10000, function() return vim.g.timer_result end) then
- print('Only waiting a little bit of time!')
- end
+ vim.ui_attach(ns, {ext_popupmenu=true}, function(event, ...)
+ if event == "popupmenu_show" then
+ local items, selected, row, col, grid = ...
+ print("display pum ", #items)
+ elseif event == "popupmenu_select" then
+ local selected = ...
+ print("selected", selected)
+ elseif event == "popupmenu_hide" then
+ print("FIN")
+ end
+ end)
<
-vim.ui_attach({ns}, {options}, {callback}) *vim.ui_attach()*
- Attach to ui events, similar to |nvim_ui_attach()| but receive events
- as lua callback. Can be used to implement screen elements like
- popupmenu or message handling in lua.
+ Parameters: ~
+ • {ns} (integer)
+ • {options} table<string, any>
+ • {callback} fun()
- {options} should be a dictionary-like table, where `ext_...` options should
- be set to true to receive events for the respective external element.
+vim.ui_detach({ns}) *vim.ui_detach()*
+ Detach a callback previously attached with |vim.ui_attach()| for the given
+ namespace {ns}.
- {callback} receives event name plus additional parameters. See |ui-popupmenu|
- and the sections below for event format for respective events.
+ Parameters: ~
+ • {ns} (integer)
- WARNING: This api is considered experimental. Usability will vary for
- different screen elements. In particular `ext_messages` behavior is subject
- to further changes and usability improvements. This is expected to be
- used to handle messages when setting 'cmdheight' to zero (which is
- likewise experimental).
+vim.wait({time}, {callback}, {interval}, {fast_only}) *vim.wait()*
+ Wait for {time} in milliseconds until {callback} returns `true`.
- Example (stub for a |ui-popupmenu| implementation): >lua
+ Executes {callback} immediately and at approximately {interval}
+ milliseconds (default 200). Nvim still processes other events during this
+ time.
- ns = vim.api.nvim_create_namespace('my_fancy_pum')
-
- vim.ui_attach(ns, {ext_popupmenu=true}, function(event, ...)
- if event == "popupmenu_show" then
- local items, selected, row, col, grid = ...
- print("display pum ", #items)
- elseif event == "popupmenu_select" then
- local selected = ...
- print("selected", selected)
- elseif event == "popupmenu_hide" then
- print("FIN")
- end
- end)
+ Cannot be called while in an |api-fast| event.
-vim.ui_detach({ns}) *vim.ui_detach()*
- Detach a callback previously attached with |vim.ui_attach()| for the
- given namespace {ns}.
+ Examples: >lua
+ ---
+ -- Wait for 100 ms, allowing other events to process
+ vim.wait(100, function() end)
-vim.type_idx *vim.type_idx*
- Type index for use in |lua-special-tbl|. Specifying one of the values from
- |vim.types| allows typing the empty table (it is unclear whether empty Lua
- table represents empty list or empty array) and forcing integral numbers
- to be |Float|. See |lua-special-tbl| for more details.
+ ---
+ -- Wait for 100 ms or until global variable set.
+ vim.wait(100, function() return vim.g.waiting_for_var end)
-vim.val_idx *vim.val_idx*
- Value index for tables representing |Float|s. A table representing
- floating-point value 1.0 looks like this: >lua
- {
- [vim.type_idx] = vim.types.float,
- [vim.val_idx] = 1.0,
- }
-< See also |vim.type_idx| and |lua-special-tbl|.
+ ---
+ -- Wait for 1 second or until global variable set, checking every ~500 ms
+ vim.wait(1000, function() return vim.g.waiting_for_var end, 500)
-vim.types *vim.types*
- Table with possible values for |vim.type_idx|. Contains two sets of
- key-value pairs: first maps possible values for |vim.type_idx| to
- human-readable strings, second maps human-readable type names to values
- for |vim.type_idx|. Currently contains pairs for `float`, `array` and
- `dictionary` types.
+ ---
+ -- Schedule a function to set a value in 100ms
+ vim.defer_fn(function() vim.g.timer_result = true end, 100)
- 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
- properties of Lua tables this basically means “value is not `nil`”.
- 2. For each value in `vim.types` table `vim.types[vim.types[value]]` is the
- same as `value`.
- No other restrictions are put on types, and it is not guaranteed that
- values corresponding to `vim.types.float`, `vim.types.array` and
- `vim.types.dictionary` will not change or that `vim.types` table will only
- contain values for these three types.
+ -- Would wait ten seconds if results blocked. Actually only waits 100 ms
+ if vim.wait(10000, function() return vim.g.timer_result end) then
+ print('Only waiting a little bit of time!')
+ end
+<
- *log_levels* *vim.log.levels*
-Log levels are one of the values defined in `vim.log.levels`:
+ Parameters: ~
+ • {time} (integer) Number of milliseconds to wait
+ • {callback} fun():|nil boolean Optional callback. Waits until
+ {callback} returns true
+ • {interval} (integer|nil) (Approximate) number of milliseconds to
+ wait between polls
+ • {fast_only} (boolean|nil) If true, only |api-fast| events will be
+ processed.
- vim.log.levels.DEBUG
- vim.log.levels.ERROR
- vim.log.levels.INFO
- vim.log.levels.TRACE
- vim.log.levels.WARN
- vim.log.levels.OFF
+ Return: ~
+ boolean, nil|-1|-2
+ • If {callback} returns `true` during the {time}: `true, nil`
+ • If {callback} never returns `true` during the {time}: `false, -1`
+ • If {callback} is interrupted during the {time}: `false, -2`
+ • If {callback} errors, the error is raised.
-------------------------------------------------------------------------------
+
+==============================================================================
LUA-VIMSCRIPT BRIDGE *lua-vimscript*
-Nvim Lua provides an interface to Vimscript variables and functions, and
-editor commands and options.
-See also https://github.com/nanotee/nvim-lua-guide.
+Nvim Lua provides an interface or "bridge" to Vimscript variables and
+functions, and editor commands and options.
+
+Objects passed over this bridge are COPIED (marshalled): there are no
+"references". |lua-guide-variables| For example, using `vim.fn.remove()`
+on a Lua list copies the list object to Vimscript and does NOT modify the
+Lua list: >lua
+ local list = { 1, 2, 3 }
+ vim.fn.remove(list, 0)
+ vim.print(list) --> "{ 1, 2, 3 }"
+
+<
vim.call({func}, {...}) *vim.call()*
Invokes |vim-function| or |user-function| {func} with arguments {...}.
See also |vim.fn|.
Equivalent to: >lua
vim.fn[func]({...})
-
+<
vim.cmd({command})
See |vim.cmd()|.
@@ -1079,16 +1280,7 @@ vim.v *vim.v*
|v:| variables.
Invalid or unset key returns `nil`.
-vim.env *vim.env*
- Environment variables defined in the editor session.
- See |expand-env| and |:let-environment| for the Vimscript behavior.
- Invalid or unset key returns `nil`.
- Example: >lua
- vim.env.FOO = 'bar'
- print(vim.env.TERM)
-<
-
- *lua-options*
+` ` *lua-options*
*lua-vim-options*
*lua-vim-set*
*lua-vim-setlocal*
@@ -1111,66 +1303,10 @@ window-scoped options. Note that this must NOT be confused with
|local-options| and |:setlocal|. There is also |vim.go| that only accesses the
global value of a |global-local| option, see |:setglobal|.
-vim.o *vim.o*
- Get or set |options|. Like `:set`. Invalid key is an error.
-
- Note: this works on both buffer-scoped and window-scoped options using the
- current buffer and window.
-
- Example: >lua
- vim.o.cmdheight = 4
- print(vim.o.columns)
- print(vim.o.foo) -- error: invalid key
-<
-vim.go *vim.go*
- Get or set global |options|. Like `:setglobal`. Invalid key is
- an error.
-
- Note: this is different from |vim.o| because this accesses the global
- option value and thus is mostly useful for use with |global-local|
- options.
-
- Example: >lua
- vim.go.cmdheight = 4
- print(vim.go.columns)
- print(vim.go.bar) -- error: invalid key
-<
-vim.bo[{bufnr}] *vim.bo*
- Get or set buffer-scoped |options| for the buffer with number {bufnr}.
- Like `:set` and `:setlocal`. If [{bufnr}] is omitted then the current
- buffer is used. Invalid {bufnr} or key is an error.
-
- Note: this is equivalent to both `:set` and `:setlocal`.
-
- Example: >lua
- local bufnr = vim.api.nvim_get_current_buf()
- vim.bo[bufnr].buflisted = true -- same as vim.bo.buflisted = true
- print(vim.bo.comments)
- print(vim.bo.baz) -- error: invalid key
-<
-vim.wo[{winid}] *vim.wo*
- Get or set window-scoped |options| for the window with handle {winid}.
- Like `:set`. If [{winid}] is omitted then the current window is used.
- Invalid {winid} or key is an error.
-
- Note: this does not access |local-options| (`:setlocal`) instead use: >lua
- nvim_get_option_value(OPTION, { scope = 'local', win = winid })
- nvim_set_option_value(OPTION, VALUE, { scope = 'local', win = winid }
-<
- Example: >lua
- local winid = vim.api.nvim_get_current_win()
- vim.wo[winid].number = true -- same as vim.wo.number = true
- print(vim.wo.foldmarker)
- print(vim.wo.quux) -- error: invalid key
-<
-
-
-
- *vim.opt_local*
+` ` *vim.opt_local*
*vim.opt_global*
*vim.opt*
-
A special interface |vim.opt| exists for conveniently interacting with list-
and map-style option from Lua: It allows accessing them as Lua tables and
offers object-oriented method for adding and removing entries.
@@ -1223,26 +1359,33 @@ which is accessed through |vim.opt:get()|:
print(vim.o.wildignore)
<
In Lua using `vim.opt`: >lua
- vim.pretty_print(vim.opt.wildignore:get())
+ vim.print(vim.opt.wildignore:get())
<
In any of the above examples, to replicate the behavior |:setlocal|, use
`vim.opt_local`. Additionally, to replicate the behavior of |:setglobal|, use
`vim.opt_global`.
+Option:append({value}) *vim.opt:append()*
+ Append a value to string-style options. See |:set+=|
+ These are equivalent: >lua
+ vim.opt.formatoptions:append('j')
+ vim.opt.formatoptions = vim.opt.formatoptions + 'j'
+<
- *vim.opt:get()*
-Option:get()
+ Parameters: ~
+ • {value} (string) Value to append
- Returns a lua-representation of the option. Boolean, number and string
+Option:get() *vim.opt:get()*
+ Returns a Lua-representation of the option. Boolean, number and string
values will be returned in exactly the same fashion.
For values that are comma-separated lists, an array will be returned with
the values as entries in the array: >lua
vim.cmd [[set wildignore=*.pyc,*.o]]
- vim.pretty_print(vim.opt.wildignore:get())
+ vim.print(vim.opt.wildignore:get())
-- { "*.pyc", "*.o", }
for _, ignore_pattern in ipairs(vim.opt.wildignore:get()) do
@@ -1251,22 +1394,24 @@ Option:get()
-- Will ignore: *.pyc
-- Will ignore: *.o
<
+
For values that are comma-separated maps, a table will be returned with
the names as keys and the values as entries: >lua
vim.cmd [[set listchars=space:_,tab:>~]]
- vim.pretty_print(vim.opt.listchars:get())
+ vim.print(vim.opt.listchars:get())
-- { space = "_", tab = ">~", }
for char, representation in pairs(vim.opt.listchars:get()) do
print(char, "=>", representation)
end
<
+
For values that are lists of flags, a set will be returned with the flags
as keys and `true` as entries. >lua
vim.cmd [[set formatoptions=njtcroql]]
- vim.pretty_print(vim.opt.formatoptions:get())
+ vim.print(vim.opt.formatoptions:get())
-- { n = true, j = true, c = true, ... }
local format_opts = vim.opt.formatoptions:get()
@@ -1274,27 +1419,22 @@ Option:get()
print("J is enabled!")
end
<
- *vim.opt:append()*
-Option:append(value)
- Append a value to string-style options. See |:set+=|
-
- These are equivalent: >lua
- vim.opt.formatoptions:append('j')
- vim.opt.formatoptions = vim.opt.formatoptions + 'j'
-<
- *vim.opt:prepend()*
-Option:prepend(value)
+ Return: ~
+ string|integer|boolean|nil value of option
+Option:prepend({value}) *vim.opt:prepend()*
Prepend a value to string-style options. See |:set^=|
These are equivalent: >lua
vim.opt.wildignore:prepend('*.o')
vim.opt.wildignore = vim.opt.wildignore ^ '*.o'
<
- *vim.opt:remove()*
-Option:remove(value)
+ Parameters: ~
+ • {value} (string) Value to prepend
+
+Option:remove({value}) *vim.opt:remove()*
Remove a value from string-style options. See |:set-=|
These are equivalent: >lua
@@ -1302,93 +1442,191 @@ Option:remove(value)
vim.opt.wildignore = vim.opt.wildignore - '*.pyc'
<
-==============================================================================
-Lua module: vim *lua-vim*
+ Parameters: ~
+ • {value} (string) Value to remove
-cmd({command}) *vim.cmd()*
- Execute Vim script commands.
+vim.bo *vim.bo*
+ Get or set buffer-scoped |options| for the buffer with number {bufnr}.
+ Like `:set` and `:setlocal`. If [{bufnr}] is omitted then the current
+ buffer is used. Invalid {bufnr} or key is an error.
- Note that `vim.cmd` can be indexed with a command name to return a
- callable function to the command.
+ Note: this is equivalent to both `:set` and `:setlocal`.
+
+ Example: >lua
+ local bufnr = vim.api.nvim_get_current_buf()
+ vim.bo[bufnr].buflisted = true -- same as vim.bo.buflisted = true
+ print(vim.bo.comments)
+ print(vim.bo.baz) -- error: invalid key
+<
+
+vim.env *vim.env*
+ Environment variables defined in the editor session. See |expand-env| and
+ |:let-environment| for the Vimscript behavior. Invalid or unset key
+ returns `nil`.
+
+ Example: >lua
+ vim.env.FOO = 'bar'
+ print(vim.env.TERM)
+<
+
+ Parameters: ~
+ • {var} (string)
+
+vim.go *vim.go*
+ Get or set global |options|. Like `:setglobal`. Invalid key is an error.
+
+ Note: this is different from |vim.o| because this accesses the global
+ option value and thus is mostly useful for use with |global-local|
+ options.
Example: >lua
+ vim.go.cmdheight = 4
+ print(vim.go.columns)
+ print(vim.go.bar) -- error: invalid key
+<
- vim.cmd('echo 42')
- vim.cmd([[
- augroup My_group
- autocmd!
- autocmd FileType c setlocal cindent
- augroup END
- ]])
+vim.o *vim.o*
+ Get or set |options|. Like `:set`. Invalid key is an error.
- -- Ex command :echo "foo"
- -- Note string literals need to be double quoted.
- vim.cmd('echo "foo"')
- vim.cmd { cmd = 'echo', args = { '"foo"' } }
- vim.cmd.echo({ args = { '"foo"' } })
- vim.cmd.echo('"foo"')
+ Note: this works on both buffer-scoped and window-scoped options using the
+ current buffer and window.
- -- Ex command :write! myfile.txt
- vim.cmd('write! myfile.txt')
- vim.cmd { cmd = 'write', args = { "myfile.txt" }, bang = true }
- vim.cmd.write { args = { "myfile.txt" }, bang = true }
- vim.cmd.write { "myfile.txt", bang = true }
+ Example: >lua
+ vim.o.cmdheight = 4
+ print(vim.o.columns)
+ print(vim.o.foo) -- error: invalid key
+<
+
+vim.wo *vim.wo*
+ Get or set window-scoped |options| for the window with handle {winid} and
+ buffer with number {bufnr}. Like `:setlocal` if {bufnr} is provided, like
+ `:set` otherwise. If [{winid}] is omitted then the current window is used.
+ Invalid {winid}, {bufnr} or key is an error.
- -- Ex command :colorscheme blue
- vim.cmd('colorscheme blue')
- vim.cmd.colorscheme('blue')
+ Note: only {bufnr} with value `0` (the current buffer in the window) is
+ supported.
+
+ Example: >lua
+ local winid = vim.api.nvim_get_current_win()
+ vim.wo[winid].number = true -- same as vim.wo.number = true
+ print(vim.wo.foldmarker)
+ print(vim.wo.quux) -- error: invalid key
+ vim.wo[winid][0].spell = false -- like ':setlocal nospell'
+<
+
+
+==============================================================================
+Lua module: vim *lua-vim*
+
+vim.cmd *vim.cmd()*
+ Executes Vim script commands.
+
+ Note that `vim.cmd` can be indexed with a command name to return a
+ callable function to the command.
+
+ Example: >lua
+ vim.cmd('echo 42')
+ vim.cmd([[
+ augroup My_group
+ autocmd!
+ autocmd FileType c setlocal cindent
+ augroup END
+ ]])
+
+ -- Ex command :echo "foo"
+ -- Note string literals need to be double quoted.
+ vim.cmd('echo "foo"')
+ vim.cmd { cmd = 'echo', args = { '"foo"' } }
+ vim.cmd.echo({ args = { '"foo"' } })
+ vim.cmd.echo('"foo"')
+
+ -- Ex command :write! myfile.txt
+ vim.cmd('write! myfile.txt')
+ vim.cmd { cmd = 'write', args = { "myfile.txt" }, bang = true }
+ vim.cmd.write { args = { "myfile.txt" }, bang = true }
+ vim.cmd.write { "myfile.txt", bang = true }
+
+ -- Ex command :colorscheme blue
+ vim.cmd('colorscheme blue')
+ vim.cmd.colorscheme('blue')
<
Parameters: ~
• {command} string|table Command(s) to execute. If a string, executes
multiple lines of Vim script at once. In this case, it is
- an alias to |nvim_exec()|, where `output` is set to false.
- Thus it works identical to |:source|. If a table, executes
- a single command. In this case, it is an alias to
+ an alias to |nvim_exec2()|, where `opts.output` is set to
+ false. Thus it works identical to |:source|. If a table,
+ executes a single command. In this case, it is an alias to
|nvim_cmd()| where `opts` is empty.
See also: ~
- |ex-cmd-index|
-
- *vim.connection_failure_errmsg()*
-connection_failure_errmsg({consequence})
- TODO: Documentation
+ • |ex-cmd-index|
-defer_fn({fn}, {timeout}) *vim.defer_fn()*
- Defers calling `fn` until `timeout` ms passes.
+vim.defer_fn({fn}, {timeout}) *vim.defer_fn()*
+ Defers calling {fn} until {timeout} ms passes.
- Use to do a one-shot timer that calls `fn` Note: The {fn} is |vim.schedule_wrap()|ped automatically, so API functions
- are safe to call.
+ Use to do a one-shot timer that calls {fn} Note: The {fn} is
+ |vim.schedule_wrap()|ped automatically, so API functions are safe to call.
Parameters: ~
• {fn} (function) Callback to call once `timeout` expires
- • {timeout} integer Number of milliseconds to wait before calling `fn`
+ • {timeout} (integer) Number of milliseconds to wait before calling
+ `fn`
Return: ~
(table) timer luv timer object
*vim.deprecate()*
-deprecate({name}, {alternative}, {version}, {plugin}, {backtrace})
- Display a deprecation notification to the user.
+vim.deprecate({name}, {alternative}, {version}, {plugin}, {backtrace})
+ Shows a deprecation message to the user.
Parameters: ~
- • {name} string Deprecated function.
- • {alternative} (string|nil) Preferred alternative function.
- • {version} string Version in which the deprecated function will be
- removed.
- • {plugin} string|nil Plugin name that the function will be
- removed from. Defaults to "Nvim".
+ • {name} string Deprecated feature (function, API, etc.).
+ • {alternative} (string|nil) Suggested alternative feature.
+ • {version} string Version when the deprecated function will be removed.
+ • {plugin} string|nil Name of the plugin that owns the deprecated
+ feature. Defaults to "Nvim".
• {backtrace} boolean|nil Prints backtrace. Defaults to true.
-inspect({object}, {options}) *vim.inspect()*
+ Return: ~
+ (string|nil) Deprecated message, or nil if no message was shown.
+
+vim.inspect *vim.inspect()*
Gets a human-readable representation of the given object.
+ Return: ~
+ (string)
+
See also: ~
- https://github.com/kikito/inspect.lua
- https://github.com/mpeterv/vinspect
+ • |vim.print()|
+ • https://github.com/kikito/inspect.lua
+ • https://github.com/mpeterv/vinspect
-notify({msg}, {level}, {opts}) *vim.notify()*
- Display a notification to the user.
+vim.keycode({str}) *vim.keycode()*
+ Translates keycodes.
+
+ Example: >lua
+ local k = vim.keycode
+ vim.g.mapleader = k'<bs>'
+<
+
+ Parameters: ~
+ • {str} (string) String to be converted.
+
+ Return: ~
+ (string)
+
+ See also: ~
+ • |nvim_replace_termcodes()|
+
+vim.lua_omnifunc({find_start}, {_}) *vim.lua_omnifunc()*
+ Omnifunc for completing Lua values from the runtime Lua interpreter,
+ similar to the builtin completion for the `:lua` command.
+
+ Activate using `set omnifunc=v:lua.vim.lua_omnifunc` in a Lua buffer.
+
+vim.notify({msg}, {level}, {opts}) *vim.notify()*
+ Displays a notification to the user.
This function can be overridden by plugins to display notifications using
a custom provider (such as the system notification provider). By default,
@@ -1396,66 +1634,60 @@ notify({msg}, {level}, {opts}) *vim.notify()*
Parameters: ~
• {msg} (string) Content of the notification to show to the user.
- • {level} (number|nil) One of the values from |vim.log.levels|.
+ • {level} (integer|nil) One of the values from |vim.log.levels|.
• {opts} (table|nil) Optional parameters. Unused by default.
-notify_once({msg}, {level}, {opts}) *vim.notify_once()*
- Display a notification only one time.
+vim.notify_once({msg}, {level}, {opts}) *vim.notify_once()*
+ Displays a notification only one time.
Like |vim.notify()|, but subsequent calls with the same message will not
display a notification.
Parameters: ~
• {msg} (string) Content of the notification to show to the user.
- • {level} (number|nil) One of the values from |vim.log.levels|.
+ • {level} (integer|nil) One of the values from |vim.log.levels|.
• {opts} (table|nil) Optional parameters. Unused by default.
Return: ~
(boolean) true if message was displayed, else false
-on_key({fn}, {ns_id}) *vim.on_key()*
+vim.on_key({fn}, {ns_id}) *vim.on_key()*
Adds Lua function {fn} with namespace id {ns_id} as a listener to every,
yes every, input key.
The Nvim command-line option |-w| is related but does not support
callbacks and cannot be toggled dynamically.
- Note:
- {fn} will not be cleared by |nvim_buf_clear_namespace()|
-
- Note:
- {fn} will receive the keys after mappings have been evaluated
+ Note: ~
+ • {fn} will be removed on error.
+ • {fn} will not be cleared by |nvim_buf_clear_namespace()|
+ • {fn} will receive the keys after mappings have been evaluated
Parameters: ~
- • {fn} (function) Callback function. It should take one string
- argument. On each key press, Nvim passes the key char to
- fn(). |i_CTRL-V| If {fn} is nil, it removes the callback for
- the associated {ns_id}
- • {ns_id} number? Namespace ID. If nil or 0, generates and returns a
+ • {fn} fun(key: string) Function invoked on every key press.
+ |i_CTRL-V| Returning nil removes the callback associated with
+ namespace {ns_id}.
+ • {ns_id} integer? Namespace ID. If nil or 0, generates and returns a
new |nvim_create_namespace()| id.
Return: ~
- (number) Namespace id associated with {fn}. Or count of all callbacks
+ (integer) Namespace id associated with {fn}. Or count of all callbacks
if on_key() is called without arguments.
- Note:
- {fn} will be removed if an error occurs while calling.
-
-paste({lines}, {phase}) *vim.paste()*
+vim.paste({lines}, {phase}) *vim.paste()*
Paste handler, invoked by |nvim_paste()| when a conforming UI (such as the
|TUI|) pastes text into the editor.
Example: To remove ANSI color codes when pasting: >lua
-
- vim.paste = (function(overridden)
- return function(lines, phase)
- for i,line in ipairs(lines) do
- -- Scrub ANSI color codes from paste input.
- lines[i] = line:gsub('\27%[[0-9;mK]+', '')
- end
- overridden(lines, phase)
- end
- end)(vim.paste)
+ vim.paste = (function(overridden)
+ return function(lines, phase)
+ for i,line in ipairs(lines) do
+ -- Scrub ANSI color codes from paste input.
+ lines[i] = line:gsub('\27%[[0-9;mK]+', '')
+ end
+ overridden(lines, phase)
+ end
+ end)(vim.paste)
<
Parameters: ~
@@ -1468,68 +1700,163 @@ paste({lines}, {phase}) *vim.paste()*
• 3: ends the paste (exactly once)
Return: ~
- (boolean) # false if client should cancel the paste.
+ (boolean) result false if client should cancel the paste.
See also: ~
- |paste| @alias paste_phase -1 | 1 | 2 | 3
+ • |paste| @alias paste_phase -1 | 1 | 2 | 3
-pretty_print({...}) *vim.pretty_print()*
- Prints given arguments in human-readable format. Example: >lua
- -- Print highlight group Normal and store it's contents in a variable.
- local hl_normal = vim.pretty_print(vim.api.nvim_get_hl_by_name("Normal", true))
+vim.print({...}) *vim.print()*
+ "Pretty prints" the given arguments and returns them unmodified.
+
+ Example: >lua
+ local hl_normal = vim.print(vim.api.nvim_get_hl(0, { name = 'Normal' }))
<
Return: ~
- any # given arguments.
+ any given arguments.
See also: ~
- |vim.inspect()|
+ • |vim.inspect()|
+ • |:=|
-region({bufnr}, {pos1}, {pos2}, {regtype}, {inclusive}) *vim.region()*
- Get a table of lines with start, end columns for a region marked by two
- points
+ *vim.region()*
+vim.region({bufnr}, {pos1}, {pos2}, {regtype}, {inclusive})
+ Gets a dict of line segment ("chunk") positions for the region from `pos1`
+ to `pos2`.
+
+ Input and output positions are byte positions, (0,0)-indexed. "End of
+ line" column position (for example, |linewise| visual selection) is
+ returned as |v:maxcol| (big number).
Parameters: ~
- • {bufnr} (number) of buffer
- • {pos1} integer[] (line, column) tuple marking beginning of
- region
- • {pos2} integer[] (line, column) tuple marking end of region
- • {regtype} (string) type of selection, see |setreg()|
- • {inclusive} (boolean) indicating whether the selection is
- end-inclusive
+ • {bufnr} (integer) Buffer number, or 0 for current buffer
+ • {pos1} integer[]|string Start of region as a (line, column)
+ tuple or |getpos()|-compatible string
+ • {pos2} integer[]|string End of region as a (line, column) tuple
+ or |getpos()|-compatible string
+ • {regtype} (string) |setreg()|-style selection type
+ • {inclusive} (boolean) Controls whether the ending column is inclusive
+ (see also 'selection').
Return: ~
- (table) region Table of the form `{linenr = {startcol,endcol}}`
+ (table) region Dict of the form `{linenr = {startcol,endcol}}`.
+ `endcol` is exclusive, and whole lines are returned as
+ `{startcol,endcol} = {0,-1}`.
+
+vim.schedule_wrap({fn}) *vim.schedule_wrap()*
+ Returns a function which calls {fn} via |vim.schedule()|.
-schedule_wrap({cb}) *vim.schedule_wrap()*
- Defers callback `cb` until the Nvim API is safe to call.
+ The returned function passes all arguments to {fn}.
+
+ Example: >lua
+ function notify_readable(_err, readable)
+ vim.notify("readable? " .. tostring(readable))
+ end
+ vim.uv.fs_access(vim.fn.stdpath("config"), "R", vim.schedule_wrap(notify_readable))
+<
Parameters: ~
- • {cb} (function)
+ • {fn} (function)
Return: ~
(function)
See also: ~
- |lua-loop-callbacks|
- |vim.schedule()|
- |vim.in_fast_event()|
+ • |lua-loop-callbacks|
+ • |vim.schedule()|
+ • |vim.in_fast_event()|
+
+vim.system({cmd}, {opts}, {on_exit}) *vim.system()*
+ Runs a system command or throws an error if {cmd} cannot be run.
+
+ Examples: >lua
+ local on_exit = function(obj)
+ print(obj.code)
+ print(obj.signal)
+ print(obj.stdout)
+ print(obj.stderr)
+ end
+
+ -- Runs asynchronously:
+ vim.system({'echo', 'hello'}, { text = true }, on_exit)
+
+ -- Runs synchronously:
+ local obj = vim.system({'echo', 'hello'}, { text = true }):wait()
+ -- { code = 0, signal = 0, stdout = 'hello', stderr = '' }
+<
+
+ See |uv.spawn()| for more details. Note: unlike |uv.spawn()|, vim.system
+ throws an error if {cmd} cannot be run.
+
+ Parameters: ~
+ • {cmd} (string[]) Command to execute
+ • {opts} (SystemOpts|nil) Options:
+ • cwd: (string) Set the current working directory for the
+ sub-process.
+ • env: table<string,string> Set environment variables for
+ the new process. Inherits the current environment with
+ `NVIM` set to |v:servername|.
+ • clear_env: (boolean) `env` defines the job environment
+ exactly, instead of merging current environment.
+ • stdin: (string|string[]|boolean) If `true`, then a pipe
+ to stdin is opened and can be written to via the
+ `write()` method to SystemObj. If string or string[] then
+ will be written to stdin and closed. Defaults to `false`.
+ • stdout: (boolean|function) Handle output from stdout.
+ When passed as a function must have the signature
+ `fun(err: string, data: string)`. Defaults to `true`
+ • stderr: (boolean|function) Handle output from stderr.
+ When passed as a function must have the signature
+ `fun(err: string, data: string)`. Defaults to `true`.
+ • text: (boolean) Handle stdout and stderr as text.
+ Replaces `\r\n` with `\n`.
+ • timeout: (integer) Run the command with a time limit.
+ Upon timeout the process is sent the TERM signal (15) and
+ the exit code is set to 124.
+ • detach: (boolean) If true, spawn the child process in a
+ detached state - this will make it a process group
+ leader, and will effectively enable the child to keep
+ running after the parent exits. Note that the child
+ process will still keep the parent's event loop alive
+ unless the parent process calls |uv.unref()| on the
+ child's process handle.
+ • {on_exit} (function|nil) Called when subprocess exits. When provided,
+ the command runs asynchronously. Receives SystemCompleted
+ object, see return of SystemObj:wait().
+
+ Return: ~
+ vim.SystemObj Object with the fields:
+ • pid (integer) Process ID
+ • wait (fun(timeout: integer|nil): SystemCompleted) Wait for the
+ process to complete. Upon timeout the process is sent the KILL
+ signal (9) and the exit code is set to 124. Cannot be called in
+ |api-fast|.
+ • SystemCompleted is an object with the fields:
+ • code: (integer)
+ • signal: (integer)
+ • stdout: (string), nil if stdout argument is passed
+ • stderr: (string), nil if stderr argument is passed
+
+ • kill (fun(signal: integer|string))
+ • write (fun(data: string|nil)) Requires `stdin=true`. Pass `nil` to
+ close the stream.
+ • is_closing (fun(): boolean)
==============================================================================
-Lua module: inspector *lua-inspector*
+Lua module: vim.inspector *vim.inspector*
-inspect_pos({bufnr}, {row}, {col}, {filter}) *vim.inspect_pos()*
+vim.inspect_pos({bufnr}, {row}, {col}, {filter}) *vim.inspect_pos()*
Get all the items at a given buffer position.
Can also be pretty-printed with `:Inspect!`. *:Inspect!*
Parameters: ~
- • {bufnr} (number|nil) defaults to the current buffer
- • {row} (number|nil) row to inspect, 0-based. Defaults to the row of
- the current cursor
- • {col} (number|nil) col to inspect, 0-based. Defaults to the col of
- the current cursor
+ • {bufnr} (integer|nil) defaults to the current buffer
+ • {row} (integer|nil) row to inspect, 0-based. Defaults to the row
+ of the current cursor
+ • {col} (integer|nil) col to inspect, 0-based. Defaults to the col
+ of the current cursor
• {filter} (table|nil) a table with key-value pairs to filter the items
• syntax (boolean): include syntax based highlight groups
(defaults to true)
@@ -1552,23 +1879,23 @@ inspect_pos({bufnr}, {row}, {col}, {filter}) *vim.inspect_pos()*
• row: the row used to get the items
• col: the col used to get the items
-show_pos({bufnr}, {row}, {col}, {filter}) *vim.show_pos()*
+vim.show_pos({bufnr}, {row}, {col}, {filter}) *vim.show_pos()*
Show all the items at a given buffer position.
Can also be shown with `:Inspect`. *:Inspect*
Parameters: ~
- • {bufnr} (number|nil) defaults to the current buffer
- • {row} (number|nil) row to inspect, 0-based. Defaults to the row of
- the current cursor
- • {col} (number|nil) col to inspect, 0-based. Defaults to the col of
- the current cursor
+ • {bufnr} (integer|nil) defaults to the current buffer
+ • {row} (integer|nil) row to inspect, 0-based. Defaults to the row
+ of the current cursor
+ • {col} (integer|nil) col to inspect, 0-based. Defaults to the col
+ of the current cursor
• {filter} (table|nil) see |vim.inspect_pos()|
-deep_equal({a}, {b}) *vim.deep_equal()*
+vim.deep_equal({a}, {b}) *vim.deep_equal()*
Deep compare values for equality
Tables are compared recursively unless they both provide the `eq` metamethod. All other types are compared using the equality `==` operator.
@@ -1580,7 +1907,7 @@ deep_equal({a}, {b}) *vim.deep_equal()*
Return: ~
(boolean) `true` if values are equals, else `false`
-deepcopy({orig}) *vim.deepcopy()*
+vim.deepcopy({orig}) *vim.deepcopy()*
Returns a deep copy of the given object. Non-table objects are copied as
in a typical Lua assignment, whereas table objects are copied recursively.
Functions are naively copied, so functions in the copied table point to
@@ -1593,30 +1920,24 @@ deepcopy({orig}) *vim.deepcopy()*
Return: ~
(table) Table of copied keys and (nested) values.
-defaulttable({create}) *vim.defaulttable()*
- Creates a table whose members are automatically created when accessed, if
- they don't already exist.
-
- They mimic defaultdict in python.
+vim.defaulttable({createfn}) *vim.defaulttable()*
+ Creates a table whose missing keys are provided by {createfn} (like
+ Python's "defaultdict").
- If {create} is `nil`, this will create a defaulttable whose constructor
- function is this function, effectively allowing to create nested tables on
- the fly:
-
- >lua
-
- local a = vim.defaulttable()
- a.b.c = 1
+ If {createfn} is `nil` it defaults to defaulttable() itself, so accessing
+ nested keys creates nested tables: >lua
+ local a = vim.defaulttable()
+ a.b.c = 1
<
Parameters: ~
- • {create} (function|nil) The function called to create a missing
- value.
+ • {createfn} function?(key:any):any Provides the value for a missing
+ `key`.
Return: ~
- (table) Empty table with metamethod
+ (table) Empty table with `__index` metamethod.
-endswith({s}, {suffix}) *vim.endswith()*
+vim.endswith({s}, {suffix}) *vim.endswith()*
Tests if `s` ends with `suffix`.
Parameters: ~
@@ -1626,25 +1947,42 @@ endswith({s}, {suffix}) *vim.endswith()*
Return: ~
(boolean) `true` if `suffix` is a suffix of `s`
-gsplit({s}, {sep}, {plain}) *vim.gsplit()*
- Splits a string at each instance of a separator.
+vim.gsplit({s}, {sep}, {opts}) *vim.gsplit()*
+ Gets an |iterator| that splits a string at each instance of a separator,
+ in "lazy" fashion (as opposed to |vim.split()| which is "eager").
+
+ Example: >lua
+ for s in vim.gsplit(':aa::b:', ':', {plain=true}) do
+ print(s)
+ end
+<
+
+ If you want to also inspect the separator itself (instead of discarding
+ it), use |string.gmatch()|. Example: >lua
+ for word, num in ('foo111bar222'):gmatch('([^0-9]*)(%d*)') do
+ print(('word: %s num: %s'):format(word, num))
+ end
+<
Parameters: ~
- • {s} (string) String to split
- • {sep} (string) Separator or pattern
- • {plain} (boolean|nil) If `true` use `sep` literally (passed to
- string.find)
+ • {s} (string) String to split
+ • {sep} (string) Separator or pattern
+ • {opts} (table|nil) Keyword arguments |kwargs|:
+ • plain: (boolean) Use `sep` literally (as in string.find).
+ • trimempty: (boolean) Discard empty segments at start and end
+ of the sequence.
Return: ~
(function) Iterator over the split components
See also: ~
- |vim.split()|
- |luaref-patterns|
- https://www.lua.org/pil/20.2.html
- http://lua-users.org/wiki/StringLibraryTutorial
+ • |string.gmatch()|
+ • |vim.split()|
+ • |lua-patterns|
+ • https://www.lua.org/pil/20.2.html
+ • http://lua-users.org/wiki/StringLibraryTutorial
-is_callable({f}) *vim.is_callable()*
+vim.is_callable({f}) *vim.is_callable()*
Returns true if object `f` can be called as a function.
Parameters: ~
@@ -1653,7 +1991,20 @@ is_callable({f}) *vim.is_callable()*
Return: ~
(boolean) `true` if `f` is callable, else `false`
-list_extend({dst}, {src}, {start}, {finish}) *vim.list_extend()*
+vim.list_contains({t}, {value}) *vim.list_contains()*
+ Checks if a list-like table (integer keys without gaps) contains `value`.
+
+ Parameters: ~
+ • {t} (table) Table to check (must be list-like, not validated)
+ • {value} any Value to compare
+
+ Return: ~
+ (boolean) `true` if `t` contains `value`
+
+ See also: ~
+ • |vim.tbl_contains()| for checking values in general tables
+
+vim.list_extend({dst}, {src}, {start}, {finish}) *vim.list_extend()*
Extends a list-like table with the values of another list-like table.
NOTE: This mutates dst!
@@ -1661,28 +2012,28 @@ list_extend({dst}, {src}, {start}, {finish}) *vim.list_extend()*
Parameters: ~
• {dst} (table) List which will be modified and appended to
• {src} (table) List from which values will be inserted
- • {start} (number|nil) Start index on src. Defaults to 1
- • {finish} (number|nil) Final index on src. Defaults to `#src`
+ • {start} (integer|nil) Start index on src. Defaults to 1
+ • {finish} (integer|nil) Final index on src. Defaults to `#src`
Return: ~
(table) dst
See also: ~
- |vim.tbl_extend()|
+ • |vim.tbl_extend()|
-list_slice({list}, {start}, {finish}) *vim.list_slice()*
+vim.list_slice({list}, {start}, {finish}) *vim.list_slice()*
Creates a copy of a table containing only elements from start to end
(inclusive)
Parameters: ~
• {list} (list) Table
- • {start} (number|nil) Start range of slice
- • {finish} (number|nil) End range of slice
+ • {start} (integer|nil) Start range of slice
+ • {finish} (integer|nil) End range of slice
Return: ~
(list) Copy of table sliced from start to finish (inclusive)
-pesc({s}) *vim.pesc()*
+vim.pesc({s}) *vim.pesc()*
Escapes magic chars in |lua-patterns|.
Parameters: ~
@@ -1692,47 +2043,97 @@ pesc({s}) *vim.pesc()*
(string) %-escaped pattern string
See also: ~
- https://github.com/rxi/lume
+ • https://github.com/rxi/lume
+
+vim.ringbuf({size}) *vim.ringbuf()*
+ Create a ring buffer limited to a maximal number of items. Once the buffer
+ is full, adding a new entry overrides the oldest entry. >lua
+ local ringbuf = vim.ringbuf(4)
+ ringbuf:push("a")
+ ringbuf:push("b")
+ ringbuf:push("c")
+ ringbuf:push("d")
+ ringbuf:push("e") -- overrides "a"
+ print(ringbuf:pop()) -- returns "b"
+ print(ringbuf:pop()) -- returns "c"
+
+ -- Can be used as iterator. Pops remaining items:
+ for val in ringbuf do
+ print(val)
+ end
+<
+
+ Returns a Ringbuf instance with the following methods:
-spairs({t}) *vim.spairs()*
- Enumerate a table sorted by its keys.
+ • |Ringbuf:push()|
+ • |Ringbuf:pop()|
+ • |Ringbuf:peek()|
+ • |Ringbuf:clear()|
Parameters: ~
- • {t} (table) List-like table
+ • {size} (integer)
+
+ Return: ~
+ (table)
+
+vim.Ringbuf:clear() *Ringbuf:clear()*
+ Clear all items.
+
+vim.Ringbuf:peek() *Ringbuf:peek()*
+ Returns the first unread item without removing it
+
+ Return: ~
+ any?|nil
+
+vim.Ringbuf:pop() *Ringbuf:pop()*
+ Removes and returns the first unread item
+
+ Return: ~
+ any?|nil
+
+vim.Ringbuf:push({item}) *Ringbuf:push()*
+ Adds an item, overriding the oldest item if the buffer is full.
+
+ Parameters: ~
+ • {item} any
+
+vim.spairs({t}) *vim.spairs()*
+ Enumerates key-value pairs of a table, ordered by key.
+
+ Parameters: ~
+ • {t} (table) Dict-like table
Return: ~
- iterator over sorted keys and their values
+ (function) |for-in| iterator over sorted keys and their values
See also: ~
- Based on https://github.com/premake/premake-core/blob/master/src/base/table.lua
+ • Based on https://github.com/premake/premake-core/blob/master/src/base/table.lua
-split({s}, {sep}, {kwargs}) *vim.split()*
- Splits a string at each instance of a separator.
+vim.split({s}, {sep}, {opts}) *vim.split()*
+ Splits a string at each instance of a separator and returns the result as
+ a table (unlike |vim.gsplit()|).
Examples: >lua
-
- split(":aa::b:", ":") --> {'','aa','','b',''}
- split("axaby", "ab?") --> {'','x','y'}
- split("x*yz*o", "*", {plain=true}) --> {'x','yz','o'}
- split("|x|y|z|", "|", {trimempty=true}) --> {'x', 'y', 'z'}
+ split(":aa::b:", ":") --> {'','aa','','b',''}
+ split("axaby", "ab?") --> {'','x','y'}
+ split("x*yz*o", "*", {plain=true}) --> {'x','yz','o'}
+ split("|x|y|z|", "|", {trimempty=true}) --> {'x', 'y', 'z'}
<
Parameters: ~
- • {s} (string) String to split
- • {sep} (string) Separator or pattern
- • {kwargs} (table|nil) 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
+ • {s} (string) String to split
+ • {sep} (string) Separator or pattern
+ • {opts} (table|nil) Keyword arguments |kwargs| accepted by
+ |vim.gsplit()|
Return: ~
string[] List of split components
See also: ~
- |vim.gsplit()|
+ • |vim.gsplit()|
+ • |string.gmatch()|
-startswith({s}, {prefix}) *vim.startswith()*
+vim.startswith({s}, {prefix}) *vim.startswith()*
Tests if `s` starts with `prefix`.
Parameters: ~
@@ -1742,7 +2143,7 @@ startswith({s}, {prefix}) *vim.startswith()*
Return: ~
(boolean) `true` if `prefix` is a prefix of `s`
-tbl_add_reverse_lookup({o}) *vim.tbl_add_reverse_lookup()*
+vim.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 }`
@@ -1754,36 +2155,47 @@ tbl_add_reverse_lookup({o}) *vim.tbl_add_reverse_lookup()*
Return: ~
(table) o
-tbl_contains({t}, {value}) *vim.tbl_contains()*
- Checks if a list-like (vector) table contains `value`.
+vim.tbl_contains({t}, {value}, {opts}) *vim.tbl_contains()*
+ Checks if a table contains a given value, specified either directly or via
+ a predicate that is checked for each value.
+
+ Example: >lua
+ vim.tbl_contains({ 'a', { 'b', 'c' } }, function(v)
+ return vim.deep_equal(v, { 'b', 'c' })
+ end, { predicate = true })
+ -- true
+<
Parameters: ~
• {t} (table) Table to check
- • {value} any Value to compare
+ • {value} any Value to compare or predicate function reference
+ • {opts} (table|nil) Keyword arguments |kwargs|:
+ • predicate: (boolean) `value` is a function reference to be
+ checked (default false)
Return: ~
(boolean) `true` if `t` contains `value`
-tbl_count({t}) *vim.tbl_count()*
- Counts the number of non-nil values in table `t`.
-
- >lua
+ See also: ~
+ • |vim.list_contains()| for checking values in list-like tables
- vim.tbl_count({ a=1, b=2 }) --> 2
- vim.tbl_count({ 1, 2 }) --> 2
+vim.tbl_count({t}) *vim.tbl_count()*
+ Counts the number of non-nil values in table `t`. >lua
+ vim.tbl_count({ a=1, b=2 }) --> 2
+ vim.tbl_count({ 1, 2 }) --> 2
<
Parameters: ~
• {t} (table) Table
Return: ~
- (number) Number of non-nil values in table
+ (integer) Number of non-nil values in table
See also: ~
- https://github.com/Tieske/Penlight/blob/master/lua/pl/tablex.lua
+ • https://github.com/Tieske/Penlight/blob/master/lua/pl/tablex.lua
-tbl_deep_extend({behavior}, {...}) *vim.tbl_deep_extend()*
- Merges recursively two or more map-like tables.
+vim.tbl_deep_extend({behavior}, {...}) *vim.tbl_deep_extend()*
+ Merges recursively two or more tables.
Parameters: ~
• {behavior} (string) Decides what to do if a key is found in more than
@@ -1791,16 +2203,16 @@ tbl_deep_extend({behavior}, {...}) *vim.tbl_deep_extend()*
• "error": raise an error
• "keep": use value from the leftmost map
• "force": use value from the rightmost map
- • {...} (table) Two or more map-like tables
+ • {...} (table) Two or more tables
Return: ~
(table) Merged table
See also: ~
- |vim.tbl_extend()|
+ • |vim.tbl_extend()|
-tbl_extend({behavior}, {...}) *vim.tbl_extend()*
- Merges two or more map-like tables.
+vim.tbl_extend({behavior}, {...}) *vim.tbl_extend()*
+ Merges two or more tables.
Parameters: ~
• {behavior} (string) Decides what to do if a key is found in more than
@@ -1808,15 +2220,15 @@ tbl_extend({behavior}, {...}) *vim.tbl_extend()*
• "error": raise an error
• "keep": use value from the leftmost map
• "force": use value from the rightmost map
- • {...} (table) Two or more map-like tables
+ • {...} (table) Two or more tables
Return: ~
(table) Merged table
See also: ~
- |extend()|
+ • |extend()|
-tbl_filter({func}, {t}) *vim.tbl_filter()*
+vim.tbl_filter({func}, {t}) *vim.tbl_filter()*
Filter a table using a predicate function
Parameters: ~
@@ -1826,7 +2238,7 @@ tbl_filter({func}, {t}) *vim.tbl_filter()*
Return: ~
(table) Table of filtered values
-tbl_flatten({t}) *vim.tbl_flatten()*
+vim.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.
@@ -1837,27 +2249,45 @@ tbl_flatten({t}) *vim.tbl_flatten()*
(table) Flattened copy of the given list-like table
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()*
+vim.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: >lua
-
- vim.tbl_get({ key = { nested_key = true }}, 'key', 'nested_key') == true
- vim.tbl_get({ key = {}}, 'key', 'nested_key') == nil
+ vim.tbl_get({ key = { nested_key = true }}, 'key', 'nested_key') == true
+ vim.tbl_get({ key = {}}, 'key', 'nested_key') == nil
<
Parameters: ~
• {o} (table) Table to index
- • {...} (string) Optional strings (0 or more, variadic) via which to
- index the table
+ • {...} any Optional keys (0 or more, variadic) via which to index the
+ table
Return: ~
any Nested value indexed by key (if it exists), else nil
-tbl_isempty({t}) *vim.tbl_isempty()*
+vim.tbl_isarray({t}) *vim.tbl_isarray()*
+ Tests if `t` is an "array": a table indexed only by integers (potentially non-contiguous).
+
+ If the indexes start from 1 and are contiguous then the array is also a
+ list. |vim.tbl_islist()|
+
+ Empty table `{}` is an array, unless it was created by |vim.empty_dict()|
+ or returned as a dict-like |API| or Vimscript result, for example from
+ |rpcrequest()| or |vim.fn|.
+
+ Parameters: ~
+ • {t} (table)
+
+ Return: ~
+ (boolean) `true` if array-like table, else `false`.
+
+ See also: ~
+ • https://github.com/openresty/luajit2#tableisarray
+
+vim.tbl_isempty({t}) *vim.tbl_isempty()*
Checks if a table is empty.
Parameters: ~
@@ -1867,22 +2297,26 @@ tbl_isempty({t}) *vim.tbl_isempty()*
(boolean) `true` if `t` is empty
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
-tbl_islist({t}) *vim.tbl_islist()*
- Tests if a Lua table can be treated as an array.
+vim.tbl_islist({t}) *vim.tbl_islist()*
+ Tests if `t` is a "list": a table indexed only by contiguous integers starting from 1 (what |lua-length| calls a "regular
+ array").
- Empty table `{}` is assumed to be an array, unless it was created by
- |vim.empty_dict()| or returned as a dict-like |API| or Vimscript result,
- for example from |rpcrequest()| or |vim.fn|.
+ Empty table `{}` is a list, unless it was created by |vim.empty_dict()| or
+ returned as a dict-like |API| or Vimscript result, for example from
+ |rpcrequest()| or |vim.fn|.
Parameters: ~
- • {t} (table) Table
+ • {t} (table)
Return: ~
- (boolean) `true` if array-like table, else `false`
+ (boolean) `true` if list-like table, else `false`.
+
+ See also: ~
+ • |vim.tbl_isarray()|
-tbl_keys({t}) *vim.tbl_keys()*
+vim.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.
@@ -1893,9 +2327,9 @@ tbl_keys({t}) *vim.tbl_keys()*
(list) List of keys
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_map({func}, {t}) *vim.tbl_map()*
+vim.tbl_map({func}, {t}) *vim.tbl_map()*
Apply a function to all values of a table.
Parameters: ~
@@ -1905,7 +2339,7 @@ tbl_map({func}, {t}) *vim.tbl_map()*
Return: ~
(table) Table of transformed values
-tbl_values({t}) *vim.tbl_values()*
+vim.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.
@@ -1915,7 +2349,7 @@ tbl_values({t}) *vim.tbl_values()*
Return: ~
(list) List of values
-trim({s}) *vim.trim()*
+vim.trim({s}) *vim.trim()*
Trim whitespace (Lua pattern "%s") from both sides of a string.
Parameters: ~
@@ -1925,43 +2359,40 @@ trim({s}) *vim.trim()*
(string) String with whitespace removed from its beginning and end
See also: ~
- |luaref-patterns|
- https://www.lua.org/pil/20.2.html
+ • |lua-patterns|
+ • https://www.lua.org/pil/20.2.html
-validate({opt}) *vim.validate()*
+vim.validate({opt}) *vim.validate()*
Validates a parameter specification (types and values).
Usage example: >lua
-
- function user.new(name, age, hobbies)
- vim.validate{
- name={name, 'string'},
- age={age, 'number'},
- hobbies={hobbies, 'table'},
- }
- ...
- end
+ function user.new(name, age, hobbies)
+ vim.validate{
+ name={name, 'string'},
+ age={age, 'number'},
+ hobbies={hobbies, 'table'},
+ }
+ ...
+ end
<
Examples with explicit argument values (can be run directly): >lua
+ vim.validate{arg1={{'foo'}, 'table'}, arg2={'foo', 'string'}}
+ --> NOP (success)
- vim.validate{arg1={{'foo'}, 'table'}, arg2={'foo', 'string'}}
- --> NOP (success)
-
- vim.validate{arg1={1, 'table'}}
- --> error('arg1: expected table, got number')
+ vim.validate{arg1={1, 'table'}}
+ --> error('arg1: expected table, got number')
- vim.validate{arg1={3, function(a) return (a % 2) == 0 end, 'even number'}}
- --> error('arg1: expected even number, got 3')
+ vim.validate{arg1={3, function(a) return (a % 2) == 0 end, 'even number'}}
+ --> error('arg1: expected even number, got 3')
<
If multiple types are valid they can be given as a list. >lua
+ vim.validate{arg1={{'foo'}, {'table', 'string'}}, arg2={'foo', {'table', 'string'}}}
+ -- NOP (success)
- vim.validate{arg1={{'foo'}, {'table', 'string'}}, arg2={'foo', {'table', 'string'}}}
- --> NOP (success)
-
- vim.validate{arg1={1, {'string', table'}}}
- --> error('arg1: expected string|table, got number')
+ vim.validate{arg1={1, {'string', 'table'}}}
+ -- error('arg1: expected string|table, got number')
<
Parameters: ~
@@ -1984,19 +2415,85 @@ validate({opt}) *vim.validate()*
==============================================================================
-Lua module: uri *lua-uri*
+Lua module: vim.loader *vim.loader*
+
+vim.loader.disable() *vim.loader.disable()*
+ Disables the experimental Lua module loader:
+ • removes the loaders
+ • adds the default Nvim loader
+
+vim.loader.enable() *vim.loader.enable()*
+ Enables the experimental Lua module loader:
+ • overrides loadfile
+ • adds the Lua loader using the byte-compilation cache
+ • adds the libs loader
+ • removes the default Nvim loader
+
+vim.loader.find({modname}, {opts}) *vim.loader.find()*
+ Finds Lua modules for the given module name.
+
+ Parameters: ~
+ • {modname} (string) Module name, or `"*"` to find the top-level
+ modules instead
+ • {opts} (table|nil) Options for finding a module:
+ • rtp: (boolean) Search for modname in the runtime path
+ (defaults to `true`)
+ • paths: (string[]) Extra paths to search for modname
+ (defaults to `{}`)
+ • patterns: (string[]) List of patterns to use when
+ searching for modules. A pattern is a string added to the
+ basename of the Lua module being searched. (defaults to
+ `{"/init.lua", ".lua"}`)
+ • all: (boolean) Return all matches instead of just the
+ first one (defaults to `false`)
+
+ Return: ~
+ (list) A list of results with the following properties:
+ • modpath: (string) the path to the module
+ • modname: (string) the name of the module
+ • stat: (table|nil) the fs_stat of the module path. Won't be returned
+ for `modname="*"`
+
+vim.loader.reset({path}) *vim.loader.reset()*
+ Resets the cache for the path, or all the paths if path is nil.
+
+ Parameters: ~
+ • {path} string? path to reset
+
+
+==============================================================================
+Lua module: vim.uri *vim.uri*
+
+vim.uri_decode({str}) *vim.uri_decode()*
+ URI-decodes a string containing percent escapes.
+
+ Parameters: ~
+ • {str} (string) string to decode
+
+ Return: ~
+ (string) decoded string
+
+vim.uri_encode({str}, {rfc}) *vim.uri_encode()*
+ URI-encodes a string using percent escapes.
+
+ Parameters: ~
+ • {str} (string) string to encode
+ • {rfc} "rfc2396" | "rfc2732" | "rfc3986" | nil
+
+ Return: ~
+ (string) encoded string
-uri_from_bufnr({bufnr}) *vim.uri_from_bufnr()*
- Get a URI from a bufnr
+vim.uri_from_bufnr({bufnr}) *vim.uri_from_bufnr()*
+ Gets a URI from a bufnr.
Parameters: ~
- • {bufnr} (number)
+ • {bufnr} (integer)
Return: ~
(string) URI
-uri_from_fname({path}) *vim.uri_from_fname()*
- Get a URI from a file path.
+vim.uri_from_fname({path}) *vim.uri_from_fname()*
+ Gets a URI from a file path.
Parameters: ~
• {path} (string) Path to file
@@ -2004,18 +2501,18 @@ uri_from_fname({path}) *vim.uri_from_fname()*
Return: ~
(string) URI
-uri_to_bufnr({uri}) *vim.uri_to_bufnr()*
- Get the buffer for a uri. Creates a new unloaded buffer if no buffer for
+vim.uri_to_bufnr({uri}) *vim.uri_to_bufnr()*
+ Gets the buffer for a uri. Creates a new unloaded buffer if no buffer for
the uri already exists.
Parameters: ~
• {uri} (string)
Return: ~
- (number) bufnr
+ (integer) bufnr
-uri_to_fname({uri}) *vim.uri_to_fname()*
- Get a filename from a URI
+vim.uri_to_fname({uri}) *vim.uri_to_fname()*
+ Gets a filename from a URI.
Parameters: ~
• {uri} (string)
@@ -2025,16 +2522,16 @@ uri_to_fname({uri}) *vim.uri_to_fname()*
==============================================================================
-Lua module: ui *lua-ui*
+Lua module: vim.ui *vim.ui*
-input({opts}, {on_confirm}) *vim.ui.input()*
- Prompts the user for input
+vim.ui.input({opts}, {on_confirm}) *vim.ui.input()*
+ Prompts the user for input, allowing arbitrary (potentially asynchronous)
+ work until `on_confirm`.
Example: >lua
-
- vim.ui.input({ prompt = 'Enter value for shiftwidth: ' }, function(input)
- vim.o.shiftwidth = tonumber(input)
- end)
+ vim.ui.input({ prompt = 'Enter value for shiftwidth: ' }, function(input)
+ vim.o.shiftwidth = tonumber(input)
+ end)
<
Parameters: ~
@@ -2052,23 +2549,46 @@ input({opts}, {on_confirm}) *vim.ui.input()*
typed (it might be an empty string if nothing was
entered), or `nil` if the user aborted the dialog.
-select({items}, {opts}, {on_choice}) *vim.ui.select()*
- Prompts the user to pick a single item from a collection of entries
+vim.ui.open({path}) *vim.ui.open()*
+ Opens `path` with the system default handler (macOS `open`, Windows
+ `explorer.exe`, Linux `xdg-open`, …), or returns (but does not show) an
+ error message on failure.
- Example: >lua
+ Expands "~/" and environment variables in filesystem paths.
- vim.ui.select({ 'tabs', 'spaces' }, {
- prompt = 'Select tabs or spaces:',
- format_item = function(item)
- return "I'd like to choose " .. item
- end,
- }, function(choice)
- if choice == 'spaces' then
- vim.o.expandtab = true
- else
- vim.o.expandtab = false
- end
- end)
+ Examples: >lua
+ vim.ui.open("https://neovim.io/")
+ vim.ui.open("~/path/to/file")
+ vim.ui.open("$VIMRUNTIME")
+<
+
+ Parameters: ~
+ • {path} (string) Path or URL to open
+
+ Return (multiple): ~
+ vim.SystemCompleted|nil Command result, or nil if not found.
+ (string|nil) Error message on failure
+
+ See also: ~
+ • |vim.system()|
+
+vim.ui.select({items}, {opts}, {on_choice}) *vim.ui.select()*
+ Prompts the user to pick from a list of items, allowing arbitrary
+ (potentially asynchronous) work until `on_choice`.
+
+ Example: >lua
+ vim.ui.select({ 'tabs', 'spaces' }, {
+ prompt = 'Select tabs or spaces:',
+ format_item = function(item)
+ return "I'd like to choose " .. item
+ end,
+ }, function(choice)
+ if choice == 'spaces' then
+ vim.o.expandtab = true
+ else
+ vim.o.expandtab = false
+ end
+ end)
<
Parameters: ~
@@ -2089,9 +2609,9 @@ select({items}, {opts}, {on_choice}) *vim.ui.select()*
==============================================================================
-Lua module: filetype *lua-filetype*
+Lua module: vim.filetype *vim.filetype*
-add({filetypes}) *vim.filetype.add()*
+vim.filetype.add({filetypes}) *vim.filetype.add()*
Add new filetype mappings.
Filetype mappings can be added either by extension or by filename (either
@@ -2107,7 +2627,8 @@ add({filetypes}) *vim.filetype.add()*
matched pattern, if any) and should return a string that will be used as
the buffer's filetype. Optionally, the function can return a second
function value which, when called, modifies the state of the buffer. This
- can be used to, for example, set filetype-specific buffer variables.
+ can be used to, for example, set filetype-specific buffer variables. This
+ function will be called by Nvim before setting the buffer's filetype.
Filename patterns can specify an optional priority to resolve cases when a
file path matches multiple patterns. Higher priorities are matched first.
@@ -2119,65 +2640,86 @@ add({filetypes}) *vim.filetype.add()*
See $VIMRUNTIME/lua/vim/filetype.lua for more examples.
Example: >lua
-
- vim.filetype.add({
- extension = {
- foo = 'fooscript',
- bar = function(path, bufnr)
- if some_condition() then
- return 'barscript', function(bufnr)
- -- Set a buffer variable
- vim.b[bufnr].barscript_version = 2
+ vim.filetype.add({
+ extension = {
+ foo = 'fooscript',
+ bar = function(path, bufnr)
+ if some_condition() then
+ return 'barscript', function(bufnr)
+ -- Set a buffer variable
+ vim.b[bufnr].barscript_version = 2
+ end
end
- end
- return 'bar'
- end,
- },
- filename = {
- ['.foorc'] = 'toml',
- ['/etc/foo/config'] = 'toml',
- },
- pattern = {
- ['.*/etc/foo/.*'] = 'fooscript',
- -- Using an optional priority
- ['.*/etc/foo/.*%.conf'] = { 'dosini', { priority = 10 } },
- -- A pattern containing an environment variable
- ['${XDG_CONFIG_HOME}/foo/git'] = 'git',
- ['README.(a+)$'] = function(path, bufnr, ext)
- if ext == 'md' then
- return 'markdown'
- elseif ext == 'rst' then
- return 'rst'
- end
- end,
- },
- })
+ return 'bar'
+ end,
+ },
+ filename = {
+ ['.foorc'] = 'toml',
+ ['/etc/foo/config'] = 'toml',
+ },
+ pattern = {
+ ['.*&zwj;/etc/foo/.*'] = 'fooscript',
+ -- Using an optional priority
+ ['.*&zwj;/etc/foo/.*%.conf'] = { 'dosini', { priority = 10 } },
+ -- A pattern containing an environment variable
+ ['${XDG_CONFIG_HOME}/foo/git'] = 'git',
+ ['README.(%a+)$'] = function(path, bufnr, ext)
+ if ext == 'md' then
+ return 'markdown'
+ elseif ext == 'rst' then
+ return 'rst'
+ end
+ end,
+ },
+ })
<
To add a fallback match on contents, use >lua
-
- vim.filetype.add {
- pattern = {
- ['.*'] = {
- priority = -math.huge,
- function(path, bufnr)
- local content = vim.filetype.getlines(bufnr, 1)
- if vim.filetype.matchregex(content, [[^#!.*\<mine\>]]) then
- return 'mine'
- elseif vim.filetype.matchregex(content, [[\<drawing\>]]) then
- return 'drawing'
- end
- end,
- },
- },
- }
+ vim.filetype.add {
+ pattern = {
+ ['.*'] = {
+ priority = -math.huge,
+ function(path, bufnr)
+ local content = vim.api.nvim_buf_get_lines(bufnr, 0, 1, false)[1] or ''
+ if vim.regex([[^#!.*\\<mine\\>]]):match_str(content) ~= nil then
+ return 'mine'
+ elseif vim.regex([[\\<drawing\\>]]):match_str(content) ~= nil then
+ return 'drawing'
+ end
+ end,
+ },
+ },
+ }
<
Parameters: ~
• {filetypes} (table) A table containing new filetype maps (see
example).
-match({args}) *vim.filetype.match()*
+ *vim.filetype.get_option()*
+vim.filetype.get_option({filetype}, {option})
+ Get the default option value for a {filetype}.
+
+ The returned value is what would be set in a new buffer after 'filetype'
+ is set, meaning it should respect all FileType autocmds and ftplugin
+ files.
+
+ Example: >lua
+ vim.filetype.get_option('vim', 'commentstring')
+<
+
+ Note: this uses |nvim_get_option_value()| but caches the result. This
+ means |ftplugin| and |FileType| autocommands are only triggered once and
+ may not reflect later changes.
+
+ Parameters: ~
+ • {filetype} (string) Filetype
+ • {option} (string) Option name
+
+ Return: ~
+ string|boolean|integer: Option value
+
+vim.filetype.match({args}) *vim.filetype.match()*
Perform filetype detection.
The filetype can be detected using one of three methods:
@@ -2192,21 +2734,18 @@ match({args}) *vim.filetype.match()*
the filetype.
Each of the three options is specified using a key to the single argument
- of this function. Example:
-
- >lua
-
- -- Using a buffer number
- vim.filetype.match({ buf = 42 })
+ of this function. Example: >lua
+ -- Using a buffer number
+ vim.filetype.match({ buf = 42 })
- -- Override the filename of the given buffer
- vim.filetype.match({ buf = 42, filename = 'foo.c' })
+ -- Override the filename of the given buffer
+ vim.filetype.match({ buf = 42, filename = 'foo.c' })
- -- Using a filename without a buffer
- vim.filetype.match({ filename = 'main.lua' })
+ -- Using a filename without a buffer
+ vim.filetype.match({ filename = 'main.lua' })
- -- Using file contents
- vim.filetype.match({ contents = {'#!/usr/bin/env bash'} })
+ -- Using file contents
+ vim.filetype.match({ contents = {'#!/usr/bin/env bash'} })
<
Parameters: ~
@@ -2225,7 +2764,7 @@ match({args}) *vim.filetype.match()*
contents to use for matching. Can be used with {filename}.
Mutually exclusive with {buf}.
- Return: ~
+ Return (multiple): ~
(string|nil) If a match was found, the matched filetype.
(function|nil) A function that modifies buffer state when called (for
example, to set some filetype specific buffer variables). The function
@@ -2233,138 +2772,145 @@ match({args}) *vim.filetype.match()*
==============================================================================
-Lua module: keymap *lua-keymap*
+Lua module: vim.keymap *vim.keymap*
-del({modes}, {lhs}, {opts}) *vim.keymap.del()*
+vim.keymap.del({modes}, {lhs}, {opts}) *vim.keymap.del()*
Remove an existing mapping. Examples: >lua
+ vim.keymap.del('n', 'lhs')
- vim.keymap.del('n', 'lhs')
-
- vim.keymap.del({'n', 'i', 'v'}, '<leader>w', { buffer = 5 })
+ vim.keymap.del({'n', 'i', 'v'}, '<leader>w', { buffer = 5 })
<
Parameters: ~
• {opts} (table|nil) A table of optional arguments:
- • buffer: (number or boolean) Remove a mapping from the given
- buffer. When "true" or 0, use the current buffer.
+ • "buffer": (integer|boolean) Remove a mapping from the given
+ buffer. When `0` or `true`, use the current buffer.
See also: ~
- |vim.keymap.set()|
-
-set({mode}, {lhs}, {rhs}, {opts}) *vim.keymap.set()*
- Add a new |mapping|. Examples: >lua
-
- -- Can add mapping to Lua functions
- vim.keymap.set('n', 'lhs', function() print("real lua function") end)
-
- -- Can use it to map multiple modes
- vim.keymap.set({'n', 'v'}, '<leader>lr', vim.lsp.buf.references, { buffer=true })
-
- -- Can add mapping for specific buffer
- vim.keymap.set('n', '<leader>w', "<cmd>w<cr>", { silent = true, buffer = 5 })
-
- -- Expr mappings
- vim.keymap.set('i', '<Tab>', function()
- return vim.fn.pumvisible() == 1 and "<C-n>" or "<Tab>"
- end, { expr = true })
- -- <Plug> mappings
- vim.keymap.set('n', '[%', '<Plug>(MatchitNormalMultiBackward)')
-<
-
- Note that in a mapping like: >lua
-
- vim.keymap.set('n', 'asdf', require('jkl').my_fun)
-<
-
- the `require('jkl')` gets evaluated during this call in order to access the function. If you
- want to avoid this cost at startup you can wrap it in a function, for
- example: >lua
-
- vim.keymap.set('n', 'asdf', function() return require('jkl').my_fun() end)
+ • |vim.keymap.set()|
+
+vim.keymap.set({mode}, {lhs}, {rhs}, {opts}) *vim.keymap.set()*
+ Adds a new |mapping|. Examples: >lua
+ -- Map to a Lua function:
+ vim.keymap.set('n', 'lhs', function() print("real lua function") end)
+ -- Map to multiple modes:
+ vim.keymap.set({'n', 'v'}, '<leader>lr', vim.lsp.buf.references, { buffer = true })
+ -- Buffer-local mapping:
+ vim.keymap.set('n', '<leader>w', "<cmd>w<cr>", { silent = true, buffer = 5 })
+ -- Expr mapping:
+ vim.keymap.set('i', '<Tab>', function()
+ return vim.fn.pumvisible() == 1 and "<C-n>" or "<Tab>"
+ end, { expr = true })
+ -- <Plug> mapping:
+ vim.keymap.set('n', '[%%', '<Plug>(MatchitNormalMultiBackward)')
<
Parameters: ~
- • {mode} string|table Same mode short names as |nvim_set_keymap()|. Can
+ • {mode} string|table Mode short-name, see |nvim_set_keymap()|. Can
also be list of modes to create mapping on multiple modes.
• {lhs} (string) Left-hand side |{lhs}| of the mapping.
- • {rhs} string|function Right-hand side |{rhs}| of the mapping. Can
- also be a Lua function.
- • {opts} (table|nil) A table of |:map-arguments|.
- • Accepts options accepted by the {opts} parameter in
- |nvim_set_keymap()|, with the following notable differences:
- • replace_keycodes: Defaults to `true` if "expr" is `true`.
- • noremap: Always overridden with the inverse of "remap"
- (see below).
-
- • In addition to those options, the table accepts the
- following keys:
- • buffer: (number or boolean) Add a mapping to the given
- buffer. When `0` or `true`, use the current buffer.
- • remap: (boolean) Make the mapping recursive. This is the
- inverse of the "noremap" option from |nvim_set_keymap()|.
- Defaults to `false`.
+ • {rhs} string|function Right-hand side |{rhs}| of the mapping, can be
+ a Lua function.
+ • {opts} (table|nil) Table of |:map-arguments|.
+ • Same as |nvim_set_keymap()| {opts}, except:
+ • "replace_keycodes" defaults to `true` if "expr" is `true`.
+ • "noremap": inverse of "remap" (see below).
+
+ • Also accepts:
+ • "buffer": (integer|boolean) Creates buffer-local mapping,
+ `0` or `true` for current buffer.
+ • "remap": (boolean) Make the mapping recursive. Inverse of
+ "noremap". Defaults to `false`.
See also: ~
- |nvim_set_keymap()|
+ • |nvim_set_keymap()|
+ • |maparg()|
+ • |mapcheck()|
+ • |mapset()|
==============================================================================
-Lua module: fs *lua-fs*
+Lua module: vim.fs *vim.fs*
-basename({file}) *vim.fs.basename()*
- Return the basename of the given file or directory
+vim.fs.basename({file}) *vim.fs.basename()*
+ Return the basename of the given path
Parameters: ~
- • {file} (string) File or directory
+ • {file} (string) Path
Return: ~
- (string) Basename of {file}
+ (string|nil) Basename of {file}
-dir({path}, {opts}) *vim.fs.dir()*
- Return an iterator over the files and directories located in {path}
+vim.fs.dir({path}, {opts}) *vim.fs.dir()*
+ Return an iterator over the items located in {path}
Parameters: ~
• {path} (string) An absolute or relative path to the directory to
iterate over. The path is first normalized
|vim.fs.normalize()|.
- • {opts} table|nil Optional keyword arguments:
+ • {opts} (table|nil) Optional keyword arguments:
• depth: integer|nil How deep the traverse (default 1)
• skip: (fun(dir_name: string): boolean)|nil Predicate to
control traversal. Return false to stop searching the
current directory. Only useful when depth > 1
Return: ~
- Iterator over files and directories in {path}. Each iteration yields
- two values: name and type. Each "name" is the basename of the file or
- directory relative to {path}. Type is one of "file" or "directory".
+ Iterator over items in {path}. Each iteration yields two values:
+ "name" and "type". "name" is the basename of the item relative to
+ {path}. "type" is one of the following: "file", "directory", "link",
+ "fifo", "socket", "char", "block", "unknown".
-dirname({file}) *vim.fs.dirname()*
- Return the parent directory of the given file or directory
+vim.fs.dirname({file}) *vim.fs.dirname()*
+ Return the parent directory of the given path
Parameters: ~
- • {file} (string) File or directory
+ • {file} (string) Path
Return: ~
- (string) Parent directory of {file}
+ (string|nil) Parent directory of {file}
-find({names}, {opts}) *vim.fs.find()*
- Find files or directories in the given path.
+vim.fs.find({names}, {opts}) *vim.fs.find()*
+ Find files or directories (or other items as specified by `opts.type`) in
+ the given path.
- Finds any files or directories given in {names} starting from {path}. If
- {upward} is "true" then the search traverses upward through parent
- directories; otherwise, the search traverses downward. Note that downward
- searches are recursive and may search through many directories! If {stop}
- is non-nil, then the search stops when the directory given in {stop} is
- reached. The search terminates when {limit} (default 1) matches are found.
- The search can be narrowed to find only files or only directories by
- specifying {type} to be "file" or "directory", respectively.
+ Finds items given in {names} starting from {path}. If {upward} is "true"
+ then the search traverses upward through parent directories; otherwise,
+ the search traverses downward. Note that downward searches are recursive
+ and may search through many directories! If {stop} is non-nil, then the
+ search stops when the directory given in {stop} is reached. The search
+ terminates when {limit} (default 1) matches are found. You can set {type}
+ to "file", "directory", "link", "socket", "char", "block", or "fifo" to
+ narrow the search to find only that type.
+
+ Examples: >lua
+ -- location of Cargo.toml from the current buffer's path
+ local cargo = vim.fs.find('Cargo.toml', {
+ upward = true,
+ stop = vim.uv.os_homedir(),
+ path = vim.fs.dirname(vim.api.nvim_buf_get_name(0)),
+ })
+
+ -- list all test directories under the runtime directory
+ local test_dirs = vim.fs.find(
+ {'test', 'tst', 'testdir'},
+ {limit = math.huge, type = 'directory', path = './runtime/'}
+ )
+
+ -- get all files ending with .cpp or .hpp inside lib/
+ local cpp_hpp = vim.fs.find(function(name, path)
+ return name:match('.*%.[ch]pp$') and path:match('[/\\\\]lib$')
+ end, {limit = math.huge, type = 'file'})
+<
Parameters: ~
- • {names} (string|table|fun(name: string): boolean) Names of the files
- and directories to find. Must be base names, paths and globs
- are not supported. The function is called per file and
- directory within the traversed directories to test if they
- match {names}.
+ • {names} (string|string[]|fun(name: string, path: string): boolean)
+ Names of the items to find. Must be base names, paths and
+ globs are not supported when {names} is a string or a table.
+ If {names} is a function, it is called for each traversed
+ item with args:
+ • name: base name of the current item
+ • path: full path of the current item The function should
+ return `true` if the given item is considered a match.
• {opts} (table) Optional keyword arguments:
• path (string): Path to begin searching from. If omitted,
the |current-directory| is used.
@@ -2373,70 +2919,81 @@ find({names}, {opts}) *vim.fs.find()*
directories (recursively).
• stop (string): Stop searching when this directory is
reached. The directory itself is not searched.
- • type (string): Find only files ("file") or directories
- ("directory"). If omitted, both files and directories that
- match {names} are included.
+ • type (string): Find only items of the given type. If
+ omitted, all items that match {names} are included.
• limit (number, default 1): Stop the search after finding
this many matches. Use `math.huge` to place no limit on the
number of matches.
Return: ~
- (table) Normalized paths |vim.fs.normalize()| of all matching files or
- directories
+ (string[]) Normalized paths |vim.fs.normalize()| of all matching items
+
+vim.fs.joinpath({...}) *vim.fs.joinpath()*
+ Concatenate directories and/or file paths into a single path with
+ normalization (e.g., `"foo/"` and `"bar"` get joined to `"foo/bar"`)
+
+ Parameters: ~
+ • {...} (string)
+
+ Return: ~
+ (string)
-normalize({path}) *vim.fs.normalize()*
+vim.fs.normalize({path}, {opts}) *vim.fs.normalize()*
Normalize a path to a standard format. A tilde (~) character at the
beginning of the path is expanded to the user's home directory and any
backslash (\) characters are converted to forward slashes (/). Environment
variables are also expanded.
Examples: >lua
+ vim.fs.normalize('C:\\\\Users\\\\jdoe')
+ -- 'C:/Users/jdoe'
- vim.fs.normalize('C:\\Users\\jdoe')
- --> 'C:/Users/jdoe'
-
- vim.fs.normalize('~/src/neovim')
- --> '/home/jdoe/src/neovim'
+ vim.fs.normalize('~/src/neovim')
+ -- '/home/jdoe/src/neovim'
- vim.fs.normalize('$XDG_CONFIG_HOME/nvim/init.vim')
- --> '/Users/jdoe/.config/nvim/init.vim'
+ vim.fs.normalize('$XDG_CONFIG_HOME/nvim/init.vim')
+ -- '/Users/jdoe/.config/nvim/init.vim'
<
Parameters: ~
• {path} (string) Path to normalize
+ • {opts} (table|nil) Options:
+ • expand_env: boolean Expand environment variables (default:
+ true)
Return: ~
(string) Normalized path
-parents({start}) *vim.fs.parents()*
- Iterate over all the parents of the given file or directory.
+vim.fs.parents({start}) *vim.fs.parents()*
+ Iterate over all the parents of the given path.
Example: >lua
+ local root_dir
+ for dir in vim.fs.parents(vim.api.nvim_buf_get_name(0)) do
+ if vim.fn.isdirectory(dir .. "/.git") == 1 then
+ root_dir = dir
+ break
+ end
+ end
- local root_dir
- for dir in vim.fs.parents(vim.api.nvim_buf_get_name(0)) do
- if vim.fn.isdirectory(dir .. "/.git") == 1 then
- root_dir = dir
- break
- end
- end
-
- if root_dir then
- print("Found git repository at", root_dir)
- end
+ if root_dir then
+ print("Found git repository at", root_dir)
+ end
<
Parameters: ~
- • {start} (string) Initial file or directory.
+ • {start} (string) Initial path.
- Return: ~
- (function) Iterator
+ Return (multiple): ~
+ fun(_, dir: string): string? Iterator
+ nil
+ (string|nil)
==============================================================================
-Lua module: secure *lua-secure*
+Lua module: vim.secure *vim.secure*
-read({path}) *vim.secure.read()*
+vim.secure.read({path}) *vim.secure.read()*
Attempt to read the file at {path} prompting the user if the file should
be trusted. The user's choice is persisted in a trust database at
$XDG_STATE_HOME/nvim/trust.
@@ -2449,9 +3006,9 @@ read({path}) *vim.secure.read()*
trusted, or nil otherwise.
See also: ~
- |:trust|
+ • |:trust|
-trust({opts}) *vim.secure.trust()*
+vim.secure.trust({opts}) *vim.secure.trust()*
Manage the trust database.
The trust database is located at |$XDG_STATE_HOME|/nvim/trust.
@@ -2467,9 +3024,743 @@ trust({opts}) *vim.secure.trust()*
• bufnr (number|nil): Buffer number to update. Mutually
exclusive with {path}.
+ Return (multiple): ~
+ (boolean) success true if operation was successful
+ (string) msg full path if operation was successful, else error message
+
+
+==============================================================================
+Lua module: vim.version *vim.version*
+
+
+The `vim.version` module provides functions for comparing versions and
+ranges conforming to the
+
+https://semver.org
+
+spec. Plugins, and plugin managers, can use this to check available tools
+and dependencies on the current system.
+
+Example: >lua
+ local v = vim.version.parse(vim.fn.system({'tmux', '-V'}), {strict=false})
+ if vim.version.gt(v, {3, 2, 0}) then
+ -- ...
+ end
+
+<
+
+*vim.version()* returns the version of the current Nvim process.
+
+VERSION RANGE SPEC *version-range*
+
+A version "range spec" defines a semantic version range which can be
+tested against a version, using |vim.version.range()|.
+
+Supported range specs are shown in the following table. Note: suffixed
+versions (1.2.3-rc1) are not matched. >
+ 1.2.3 is 1.2.3
+ =1.2.3 is 1.2.3
+ >1.2.3 greater than 1.2.3
+ <1.2.3 before 1.2.3
+ >=1.2.3 at least 1.2.3
+ ~1.2.3 is >=1.2.3 <1.3.0 "reasonably close to 1.2.3"
+ ^1.2.3 is >=1.2.3 <2.0.0 "compatible with 1.2.3"
+ ^0.2.3 is >=0.2.3 <0.3.0 (0.x.x is special)
+ ^0.0.1 is =0.0.1 (0.0.x is special)
+ ^1.2 is >=1.2.0 <2.0.0 (like ^1.2.0)
+ ~1.2 is >=1.2.0 <1.3.0 (like ~1.2.0)
+ ^1 is >=1.0.0 <2.0.0 "compatible with 1"
+ ~1 same "reasonably close to 1"
+ 1.x same
+ 1.* same
+ 1 same
+ * any version
+ x same
+
+ 1.2.3 - 2.3.4 is >=1.2.3 <=2.3.4
+
+ Partial right: missing pieces treated as x (2.3 => 2.3.x).
+ 1.2.3 - 2.3 is >=1.2.3 <2.4.0
+ 1.2.3 - 2 is >=1.2.3 <3.0.0
+
+ Partial left: missing pieces treated as 0 (1.2 => 1.2.0).
+ 1.2 - 2.3.0 is 1.2.0 - 2.3.0
+
+<
+
+vim.version.cmp({v1}, {v2}) *vim.version.cmp()*
+ Parses and compares two version objects (the result of
+ |vim.version.parse()|, or specified literally as a `{major, minor, patch}`
+ tuple, e.g. `{1, 0, 3}`).
+
+ Example: >lua
+ if vim.version.cmp({1,0,3}, {0,2,1}) == 0 then
+ -- ...
+ end
+ local v1 = vim.version.parse('1.0.3-pre')
+ local v2 = vim.version.parse('0.2.1')
+ if vim.version.cmp(v1, v2) == 0 then
+ -- ...
+ end
+<
+
+ Note: ~
+ • Per semver, build metadata is ignored when comparing two
+ otherwise-equivalent versions.
+
+ Parameters: ~
+ • {v1} Version|number[] Version object.
+ • {v2} Version|number[] Version to compare with `v1` .
+
+ Return: ~
+ (integer) -1 if `v1 < v2`, 0 if `v1 == v2`, 1 if `v1 > v2`.
+
+vim.version.eq({v1}, {v2}) *vim.version.eq()*
+ Returns `true` if the given versions are equal. See |vim.version.cmp()| for usage.
+
+ Parameters: ~
+ • {v1} Version|number[]
+ • {v2} Version|number[]
+
+ Return: ~
+ (boolean)
+
+vim.version.gt({v1}, {v2}) *vim.version.gt()*
+ Returns `true` if `v1 > v2` . See |vim.version.cmp()| for usage.
+
+ Parameters: ~
+ • {v1} Version|number[]
+ • {v2} Version|number[]
+
+ Return: ~
+ (boolean)
+
+vim.version.last({versions}) *vim.version.last()*
+ TODO: generalize this, move to func.lua
+
+ Parameters: ~
+ • {versions} Version []
+
+ Return: ~
+ Version ?|nil
+
+vim.version.lt({v1}, {v2}) *vim.version.lt()*
+ Returns `true` if `v1 < v2` . See |vim.version.cmp()| for usage.
+
+ Parameters: ~
+ • {v1} Version|number[]
+ • {v2} Version|number[]
+
+ Return: ~
+ (boolean)
+
+vim.version.parse({version}, {opts}) *vim.version.parse()*
+ Parses a semantic version string and returns a version object which can be
+ used with other `vim.version` functions. For example "1.0.1-rc1+build.2"
+ returns: >
+ { major = 1, minor = 0, patch = 1, prerelease = "rc1", build = "build.2" }
+<
+
+ Parameters: ~
+ • {version} (string) Version string to parse.
+ • {opts} (table|nil) Optional keyword arguments:
+ • strict (boolean): Default false. If `true`, no coercion
+ is attempted on input not conforming to semver v2.0.0. If
+ `false`, `parse()` attempts to coerce input such as
+ "1.0", "0-x", "tmux 3.2a" into valid versions.
+
+ Return: ~
+ (table|nil) parsed_version Version object or `nil` if input is invalid.
+
+ See also: ~
+ • # https://semver.org/spec/v2.0.0.html
+
+vim.version.range({spec}) *vim.version.range()*
+ Parses a semver |version-range| "spec" and returns a range object: >
+ {
+ from: Version
+ to: Version
+ has(v: string|Version)
+ }
+<
+
+ `:has()` checks if a version is in the range (inclusive `from`, exclusive
+ `to`).
+
+ Example: >lua
+ local r = vim.version.range('1.0.0 - 2.0.0')
+ print(r:has('1.9.9')) -- true
+ print(r:has('2.0.0')) -- false
+ print(r:has(vim.version())) -- check against current Nvim version
+<
+
+ Or use cmp(), eq(), lt(), and gt() to compare `.to` and `.from` directly: >lua
+ local r = vim.version.range('1.0.0 - 2.0.0')
+ print(vim.version.gt({1,0,3}, r.from) and vim.version.lt({1,0,3}, r.to))
+<
+
+ Parameters: ~
+ • {spec} (string) Version range "spec"
+
+ See also: ~
+ • # https://github.com/npm/node-semver#ranges
+
+
+==============================================================================
+Lua module: vim.iter *vim.iter*
+
+
+*vim.iter()* is an interface for |iterable|s: it wraps a table or function
+argument into an *Iter* object with methods (such as |Iter:filter()| and
+|Iter:map()|) that transform the underlying source data. These methods can
+be chained to create iterator "pipelines": the output of each pipeline
+stage is input to the next stage. The first stage depends on the type
+passed to `vim.iter()`:
+
+• List tables (arrays, |lua-list|) yield only the value of each element.
+ • Use |Iter:enumerate()| to also pass the index to the next stage.
+ • Or initialize with ipairs(): `vim.iter(ipairs(…))`.
+
+• Non-list tables (|lua-dict|) yield both the key and value of each
+ element.
+• Function |iterator|s yield all values returned by the underlying
+ function.
+• Tables with a |__call()| metamethod are treated as function iterators.
+
+The iterator pipeline terminates when the underlying |iterable| is
+exhausted (for function iterators this means it returned nil).
+
+Note: `vim.iter()` scans table input to decide if it is a list or a dict;
+to avoid this cost you can wrap the table with an iterator e.g.
+`vim.iter(ipairs({…}))`, but that precludes the use of |list-iterator|
+operations such as |Iter:rev()|).
+
+Examples: >lua
+ local it = vim.iter({ 1, 2, 3, 4, 5 })
+ it:map(function(v)
+ return v * 3
+ end)
+ it:rev()
+ it:skip(2)
+ it:totable()
+ -- { 9, 6, 3 }
+
+ -- ipairs() is a function iterator which returns both the index (i) and the value (v)
+ vim.iter(ipairs({ 1, 2, 3, 4, 5 })):map(function(i, v)
+ if i > 2 then return v end
+ end):totable()
+ -- { 3, 4, 5 }
+
+ local it = vim.iter(vim.gsplit('1,2,3,4,5', ','))
+ it:map(function(s) return tonumber(s) end)
+ for i, d in it:enumerate() do
+ print(string.format("Column %d is %d", i, d))
+ end
+ -- Column 1 is 1
+ -- Column 2 is 2
+ -- Column 3 is 3
+ -- Column 4 is 4
+ -- Column 5 is 5
+
+ vim.iter({ a = 1, b = 2, c = 3, z = 26 }):any(function(k, v)
+ return k == 'z'
+ end)
+ -- true
+
+ local rb = vim.ringbuf(3)
+ rb:push("a")
+ rb:push("b")
+ vim.iter(rb):totable()
+ -- { "a", "b" }
+
+<
+
+In addition to the |vim.iter()| function, the |vim.iter| module provides
+convenience functions like |vim.iter.filter()| and |vim.iter.totable()|.
+
+filter({f}, {src}, {...}) *vim.iter.filter()*
+ Filters a table or other |iterable|. >lua
+ -- Equivalent to:
+ vim.iter(src):filter(f):totable()
+<
+
+ Parameters: ~
+ • {f} function(...):bool Filter function. Accepts the current
+ iterator or table values as arguments and returns true if those
+ values should be kept in the final table
+ • {src} table|function Table or iterator function to filter
+
+ Return: ~
+ (table)
+
+ See also: ~
+ • |Iter:filter()|
+
+Iter:all({pred}) *Iter:all()*
+ Returns true if all items in the iterator match the given predicate.
+
+ Parameters: ~
+ • {pred} function(...):bool Predicate function. Takes all values
+ returned from the previous stage in the pipeline as arguments
+ and returns true if the predicate matches.
+
+Iter:any({pred}) *Iter:any()*
+ Returns true if any of the items in the iterator match the given
+ predicate.
+
+ Parameters: ~
+ • {pred} function(...):bool Predicate function. Takes all values
+ returned from the previous stage in the pipeline as arguments
+ and returns true if the predicate matches.
+
+Iter:each({f}) *Iter:each()*
+ Calls a function once for each item in the pipeline, draining the
+ iterator.
+
+ For functions with side effects. To modify the values in the iterator, use
+ |Iter:map()|.
+
+ Parameters: ~
+ • {f} function(...) Function to execute for each item in the pipeline.
+ Takes all of the values returned by the previous stage in the
+ pipeline as arguments.
+
+Iter:enumerate() *Iter:enumerate()*
+ Yields the item index (count) and value for each item of an iterator
+ pipeline.
+
+ For list tables, this is more efficient: >lua
+ vim.iter(ipairs(t))
+<
+
+ instead of: >lua
+ vim.iter(t):enumerate()
+<
+
+ Example: >lua
+ local it = vim.iter(vim.gsplit('abc', '')):enumerate()
+ it:next()
+ -- 1 'a'
+ it:next()
+ -- 2 'b'
+ it:next()
+ -- 3 'c'
+<
+
+ Return: ~
+ Iter
+
+Iter:filter({f}) *Iter:filter()*
+ Filters an iterator pipeline.
+
+ Example: >lua
+ local bufs = vim.iter(vim.api.nvim_list_bufs()):filter(vim.api.nvim_buf_is_loaded)
+<
+
+ Parameters: ~
+ • {f} function(...):bool Takes all values returned from the previous
+ stage in the pipeline and returns false or nil if the current
+ iterator element should be removed.
+
+ Return: ~
+ Iter
+
+Iter:find({f}) *Iter:find()*
+ Find the first value in the iterator that satisfies the given predicate.
+
+ Advances the iterator. Returns nil and drains the iterator if no value is
+ found.
+
+ Examples: >lua
+ local it = vim.iter({ 3, 6, 9, 12 })
+ it:find(12)
+ -- 12
+
+ local it = vim.iter({ 3, 6, 9, 12 })
+ it:find(20)
+ -- nil
+
+ local it = vim.iter({ 3, 6, 9, 12 })
+ it:find(function(v) return v % 4 == 0 end)
+ -- 12
+<
+
+ Return: ~
+ any
+
+Iter:fold({init}, {f}) *Iter:fold()*
+ Folds ("reduces") an iterator into a single value.
+
+ Examples: >lua
+ -- Create a new table with only even values
+ local t = { a = 1, b = 2, c = 3, d = 4 }
+ local it = vim.iter(t)
+ it:filter(function(k, v) return v % 2 == 0 end)
+ it:fold({}, function(t, k, v)
+ t[k] = v
+ return t
+ end)
+ -- { b = 2, d = 4 }
+<
+
+ Parameters: ~
+ • {init} any Initial value of the accumulator.
+ • {f} function(acc:any, ...):A Accumulation function.
+
+ Return: ~
+ any
+
+Iter:last() *Iter:last()*
+ Drains the iterator and returns the last item.
+
+ Example: >lua
+ local it = vim.iter(vim.gsplit('abcdefg', ''))
+ it:last()
+ -- 'g'
+
+ local it = vim.iter({ 3, 6, 9, 12, 15 })
+ it:last()
+ -- 15
+<
+
+ Return: ~
+ any
+
+Iter:map({f}) *Iter:map()*
+ Maps the items of an iterator pipeline to the values returned by `f`.
+
+ If the map function returns nil, the value is filtered from the iterator.
+
+ Example: >lua
+ local it = vim.iter({ 1, 2, 3, 4 }):map(function(v)
+ if v % 2 == 0 then
+ return v * 3
+ end
+ end)
+ it:totable()
+ -- { 6, 12 }
+<
+
+ Parameters: ~
+ • {f} function(...):any Mapping function. Takes all values returned
+ from the previous stage in the pipeline as arguments and returns
+ one or more new values, which are used in the next pipeline
+ stage. Nil return values are filtered from the output.
+
+ Return: ~
+ Iter
+
+Iter:next() *Iter:next()*
+ Gets the next value from the iterator.
+
+ Example: >lua
+ local it = vim.iter(string.gmatch('1 2 3', '%d+')):map(tonumber)
+ it:next()
+ -- 1
+ it:next()
+ -- 2
+ it:next()
+ -- 3
+<
+
+ Return: ~
+ any
+
+Iter:nextback() *Iter:nextback()*
+ "Pops" a value from a |list-iterator| (gets the last value and decrements
+ the tail).
+
+ Example: >lua
+ local it = vim.iter({1, 2, 3, 4})
+ it:nextback()
+ -- 4
+ it:nextback()
+ -- 3
+<
+
+ Return: ~
+ any
+
+Iter:nth({n}) *Iter:nth()*
+ Gets the nth value of an iterator (and advances to it).
+
+ Example: >lua
+ local it = vim.iter({ 3, 6, 9, 12 })
+ it:nth(2)
+ -- 6
+ it:nth(2)
+ -- 12
+<
+
+ Parameters: ~
+ • {n} (number) The index of the value to return.
+
+ Return: ~
+ any
+
+Iter:nthback({n}) *Iter:nthback()*
+ Gets the nth value from the end of a |list-iterator| (and advances to it).
+
+ Example: >lua
+ local it = vim.iter({ 3, 6, 9, 12 })
+ it:nthback(2)
+ -- 9
+ it:nthback(2)
+ -- 3
+<
+
+ Parameters: ~
+ • {n} (number) The index of the value to return.
+
+ Return: ~
+ any
+
+Iter:peek() *Iter:peek()*
+ Gets the next value in a |list-iterator| without consuming it.
+
+ Example: >lua
+ local it = vim.iter({ 3, 6, 9, 12 })
+ it:peek()
+ -- 3
+ it:peek()
+ -- 3
+ it:next()
+ -- 3
+<
+
+ Return: ~
+ any
+
+Iter:peekback() *Iter:peekback()*
+ Gets the last value of a |list-iterator| without consuming it.
+
+ See also |Iter:last()|.
+
+ Example: >lua
+ local it = vim.iter({1, 2, 3, 4})
+ it:peekback()
+ -- 4
+ it:peekback()
+ -- 4
+ it:nextback()
+ -- 4
+<
+
+ Return: ~
+ any
+
+Iter:rev() *Iter:rev()*
+ Reverses a |list-iterator| pipeline.
+
+ Example: >lua
+ local it = vim.iter({ 3, 6, 9, 12 }):rev()
+ it:totable()
+ -- { 12, 9, 6, 3 }
+<
+
+ Return: ~
+ Iter
+
+Iter:rfind({f}) *Iter:rfind()*
+ Gets the first value in a |list-iterator| that satisfies a predicate,
+ starting from the end.
+
+ Advances the iterator. Returns nil and drains the iterator if no value is
+ found.
+
+ Examples: >lua
+ local it = vim.iter({ 1, 2, 3, 2, 1 }):enumerate()
+ it:rfind(1)
+ -- 5 1
+ it:rfind(1)
+ -- 1 1
+<
+
+ Return: ~
+ any
+
+ See also: ~
+ • Iter.find
+
+Iter:skip({n}) *Iter:skip()*
+ Skips `n` values of an iterator pipeline.
+
+ Example: >lua
+ local it = vim.iter({ 3, 6, 9, 12 }):skip(2)
+ it:next()
+ -- 9
+<
+
+ Parameters: ~
+ • {n} (number) Number of values to skip.
+
+ Return: ~
+ Iter
+
+Iter:skipback({n}) *Iter:skipback()*
+ Skips `n` values backwards from the end of a |list-iterator| pipeline.
+
+ Example: >lua
+ local it = vim.iter({ 1, 2, 3, 4, 5 }):skipback(2)
+ it:next()
+ -- 1
+ it:nextback()
+ -- 3
+<
+
+ Parameters: ~
+ • {n} (number) Number of values to skip.
+
+ Return: ~
+ Iter
+
+Iter:slice({first}, {last}) *Iter:slice()*
+ Sets the start and end of a |list-iterator| pipeline.
+
+ Equivalent to `:skip(first - 1):skipback(len - last + 1)`.
+
+ Parameters: ~
+ • {first} (number)
+ • {last} (number)
+
+ Return: ~
+ Iter
+
+Iter:totable() *Iter:totable()*
+ Collect the iterator into a table.
+
+ The resulting table depends on the initial source in the iterator
+ pipeline. List-like tables and function iterators will be collected into a
+ list-like table. If multiple values are returned from the final stage in
+ the iterator pipeline, each value will be included in a table.
+
+ Examples: >lua
+ vim.iter(string.gmatch('100 20 50', '%d+')):map(tonumber):totable()
+ -- { 100, 20, 50 }
+
+ vim.iter({ 1, 2, 3 }):map(function(v) return v, 2 * v end):totable()
+ -- { { 1, 2 }, { 2, 4 }, { 3, 6 } }
+
+ vim.iter({ a = 1, b = 2, c = 3 }):filter(function(k, v) return v % 2 ~= 0 end):totable()
+ -- { { 'a', 1 }, { 'c', 3 } }
+<
+
+ The generated table is a list-like table with consecutive, numeric
+ indices. To create a map-like table with arbitrary keys, use
+ |Iter:fold()|.
+
+ Return: ~
+ (table)
+
+map({f}, {src}, {...}) *vim.iter.map()*
+ Maps a table or other |iterable|. >lua
+ -- Equivalent to:
+ vim.iter(src):map(f):totable()
+<
+
+ Parameters: ~
+ • {f} function(...):?any Map function. Accepts the current iterator
+ or table values as arguments and returns one or more new
+ values. Nil values are removed from the final table.
+ • {src} table|function Table or iterator function to filter
+
+ Return: ~
+ (table)
+
+ See also: ~
+ • |Iter:map()|
+
+totable({f}, {...}) *vim.iter.totable()*
+ Collects an |iterable| into a table. >lua
+ -- Equivalent to:
+ vim.iter(f):totable()
+<
+
+ Parameters: ~
+ • {f} (function) Iterator function
+
+ Return: ~
+ (table)
+
+
+==============================================================================
+Lua module: vim.snippet *vim.snippet*
+
+vim.snippet.active() *vim.snippet.active()*
+ Returns `true` if there's an active snippet in the current buffer.
+
+ Return: ~
+ (boolean)
+
+vim.snippet.exit() *vim.snippet.exit()*
+ Exits the current snippet.
+
+vim.snippet.expand({input}) *vim.snippet.expand()*
+ Expands the given snippet text. Refer to https://microsoft.github.io/language-server-protocol/specification/#snippet_syntax for the specification of valid input.
+
+ Tabstops are highlighted with hl-SnippetTabstop.
+
+ Parameters: ~
+ • {input} (string)
+
+vim.snippet.jump({direction}) *vim.snippet.jump()*
+ Jumps within the active snippet in the given direction. If the jump isn't
+ possible, the function call does nothing.
+
+ You can use this function to navigate a snippet as follows: >lua
+ vim.keymap.set({ 'i', 's' }, '<Tab>', function()
+ if vim.snippet.jumpable(1) then
+ return '<cmd>lua vim.snippet.jump(1)<cr>'
+ else
+ return '<Tab>'
+ end
+ end, { expr = true })
+<
+
+ Parameters: ~
+ • {direction} (vim.snippet.Direction) Navigation direction. -1 for
+ previous, 1 for next.
+
+vim.snippet.jumpable({direction}) *vim.snippet.jumpable()*
+ Returns `true` if there is an active snippet which can be jumped in the
+ given direction. You can use this function to navigate a snippet as
+ follows: >lua
+ vim.keymap.set({ 'i', 's' }, '<Tab>', function()
+ if vim.snippet.jumpable(1) then
+ return '<cmd>lua vim.snippet.jump(1)<cr>'
+ else
+ return '<Tab>'
+ end
+ end, { expr = true })
+<
+
+ Parameters: ~
+ • {direction} (vim.snippet.Direction) Navigation direction. -1 for
+ previous, 1 for next.
+
+ Return: ~
+ (boolean)
+
+
+==============================================================================
+Lua module: vim.text *vim.text*
+
+vim.text.hexdecode({enc}) *vim.text.hexdecode()*
+ Hex decode a string.
+
+ Parameters: ~
+ • {enc} (string) String to decode
+
+ Return: ~
+ (string) Decoded string
+
+vim.text.hexencode({str}) *vim.text.hexencode()*
+ Hex encode a string.
+
+ Parameters: ~
+ • {str} (string) String to encode
+
Return: ~
- (boolean, string) success, msg:
- • true and full path of target file if operation was successful
- • false and error message on failure
+ (string) Hex encoded string
vim:tw=78:ts=8:sw=4:sts=4:et:ft=help:norl: