Nvim :help
pages, generated
from source
using the tree-sitter-vimdoc parser.
Lua
: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
which can be used from Lua code (lua-vimscript vim.api). Together these
"namespaces" form the Nvim programming interface.
nvim -l foo.lua [args...]
lua-compat
Lua 5.1 is the permanent interface for Nvim Lua. Plugins should target Lua 5.1
as specified in luaref; later versions (which are essentially different,
incompatible, dialects) are not supported. This includes extensions such as
goto
that some Lua 5.1 interpreters like LuaJIT may support.
lua-luajit
While Nvim officially only requires Lua 5.1 support, it should be built with
LuaJIT or a compatible fork on supported platforms for performance reasons.
LuaJIT also comes with useful extensions such as ffi
, lua-profile, and
enhanced standard library functions; these cannot be assumed to be available,
and Lua code in init.lua or plugins should check the jit
global variable
before using them:if jit then
-- code for luajit
else
-- code for plain lua 5.1
end
lua-bit
One exception is the LuaJIT bit
extension, which is always available: when
built with PUC Lua, Nvim includes a fallback implementation which provides
require("bit")
.
lua-profile
If Nvim is built with LuaJIT, Lua code can be profiled via-- Start a profiling session:
require('jit.p').start('ri1', '/tmp/profile')
-- Perform arbitrary tasks (use plugins, scripts, etc.) ...
-- Stop the session. Profile is written to /tmp/profile.
require('jit.p').stop()
See https://luajit.org/ext_profiler.html or the p.lua
source for details::lua vim.cmd.edit(package.searchpath('jit.p', package.path))
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).
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:local foo = function(a, b)
print("A: ", a)
print("B: ", b)
end
The first way to call this function is:foo(1, 2)
-- ==== Result ====
-- 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
, and extra parameters are
silently discarded. Example:foo(1)
-- ==== Result ====
-- A: 1
-- B: nil
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 mimic "named parameters" ("kwargs" or "keyword args") as in
languages like Python and C#. Example:local func_with_opts = function(opts)
local will_do_foo = opts.foo
local filename = opts.filename
...
end
func_with_opts { foo = true, filename = "hello.world" }
lua-regex
Lua intentionally does not support regular expressions, instead it has limited
lua-patterns which avoid the performance pitfalls of extended regex. Lua
scripts can also use Vim regex via vim.regex().
print(string.match("foo123bar123", "%d+"))
-- 123
print(string.match("foo123bar123", "[^%d]+"))
-- foo
print(string.match("foo123bar123", "[abc]+"))
-- ba
print(string.match("foo.bar", "%.bar"))
-- .bar
foo.bar
, each directory is searched
for lua/foo/bar.lua
, then lua/foo/bar/init.lua
. If no files are found,
the directories are searched again for a shared library with a name matching
lua/foo/bar.?
, where ?
is a list of suffixes (such as so
or dll
) derived from
the initial value of package.cpath. If still no files are found, Nvim falls
back to Lua's default search mechanism. The first script found is run and
require()
returns the value returned by the script if any, else true
.
require()
for each module,
with subsequent calls returning the cached value without searching for, or
executing any script. For further details see require().
foo,bar
and package.cpath was
./?.so;./?.dll
at startup, require('mod')
searches these paths in order
and loads the first module found ("first wins"):foo/lua/mod.lua foo/lua/mod/init.lua bar/lua/mod.lua bar/lua/mod/init.lua foo/lua/mod.so foo/lua/mod.dll bar/lua/mod.so bar/lua/mod.dll
lua-package-path
Nvim automatically adjusts package.path and package.cpath according to the
effective 'runtimepath' value. Adjustment happens whenever 'runtimepath' is
changed. package.path
is adjusted by simply appending /lua/?.lua
and
/lua/?/init.lua
to each directory from 'runtimepath' (/
is actually the
first character of package.config
).
/lua/?.lua
and
/lua/?/init.lua
to each runtimepath, all unique ?
-containing suffixes of
the existing package.cpath are used. Example:
/foo/bar,/xxx;yyy/baz,/abc
;
$LUA_CPATH
/ $LUA_INIT
) contains ./?.so;/def/ghi/a?d/j/g.elf;/def/?.so
.
?
-containing suffixes /?.so
, /a?d/j/g.elf
and /?.so
, in
order: parts of the path starting from the first path component containing
question mark and preceding path separator.
/def/?.so
, namely /?.so
is not unique, as it’s the same
as the suffix of the first path from package.path (i.e. ./?.so
). Which
leaves /?.so
and /a?d/j/g.elf
, in this order.
/foo/bar
, /xxx;yyy/baz
and /abc
. The
second one contains a semicolon which is a paths separator so it is out,
leaving only /foo/bar
and /abc
, in order.
/lua
path segment is inserted
between path and suffix, leaving:
/foo/bar/lua/?.so
/foo/bar/lua/a?d/j/g.elf
/abc/lua/?.so
/abc/lua/a?d/j/g.elf
/foo/bar,/xxx;yyy/baz,/abc ('runtimepath') × ./?.so;/def/ghi/a?d/j/g.elf;/def/?.so (package.cpath) = /foo/bar/lua/?.so;/foo/bar/lua/a?d/j/g.elf;/abc/lua/?.so;/abc/lua/a?d/j/g.elf;./?.so;/def/ghi/a?d/j/g.elf;/def/?.soNote:
let &runtimepath = &runtimepath
: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
and :=expr
are equivalent to :lua vim.print(expr)
.
:lua vim.api.nvim_command('echo "Hello, Nvim!"')
:lua print(_VERSION)
:lua =jit.version
{range}
as Lua code. Unlike :source, this
always treats the lines as Lua code.
print(string.format(
'unix time: %s', os.time()))
:lua-heredoc
:lua << [trim] [{endmarker}
]
{script}
{endmarker}
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.
function! CurrentLineInfo()
lua << EOF
local linenr = vim.api.nvim_win_get_cursor(0)[1]
local curline = vim.api.nvim_buf_get_lines(0, linenr - 1, linenr, false)[1]
print(string.format('Line [%d] has %d bytes', linenr, #curline))
EOF
endfunction
local
variables will disappear when the block finishes.
But not globals.
:luado
:[range]luado {body}
Executes Lua chunk "function(line, linenr) {body}
end" for each buffer
line in [range], where line
is the current line text (without <EOL>
),
and linenr
is the current line number. If the function returns a string
that becomes the text of the corresponding buffer line. Default [range] is
the whole file: "1,$".
:luado return string.format("%s\t%d", line:reverse(), #line)
:lua require"lpeg"
:lua -- balanced parenthesis grammar:
:lua bp = lpeg.P{ "(" * ((1 - lpeg.S"()") + lpeg.V(1))^0 * ")" }
:luado if bp:match(line) then return "=>\t" .. line end
:luafile
:luafile {file}
Execute Lua script in {file}
.
The whole argument is used as the filename (like :edit), spaces do not
need to be escaped. Alternatively you can :source Lua files.
:luafile script.lua
:luafile %
local chunkheader = "local _A = select(1, ...) return "
function luaeval (expstr, arg)
local chunk = assert(loadstring(chunkheader .. expstr, "luaeval"))
return chunk(arg) -- return typval
end
:echo luaeval('_A[1] + _A[2]', [40, 2])
" 42
: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 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
considered to be a dictionary, but this time it is converted to
a msgpack-special-map.
lua-special-tbl
4. Table with vim.type_idx
key may be a dictionary, a list or floating-point
value:
{[vim.type_idx]=vim.types.float, [vim.val_idx]=1}
is converted to
a floating-point 1.0. Note that by default integral Lua numbers are
converted to Numbers, non-integral are converted to Floats. This
variant allows integral Floats.
{[vim.type_idx]=vim.types.dictionary}
is converted to an empty
dictionary, {[vim.type_idx]=vim.types.dictionary, [42]=1, a=2}
is
converted to a dictionary {'a': 42}
: non-string keys are ignored.
Without vim.type_idx
key tables with keys not fitting in 1., 2. or 3.
are errors.
{[vim.type_idx]=vim.types.array}
is converted to an empty list. As well
as {[vim.type_idx]=vim.types.array, [42]=1}
: integral keys that do not
form a 1-step sequence from 1 to N are ignored, as well as all
non-integral keys.
:echo luaeval('math.pi')
:function Rand(x,y) " random uniform between x and y
: return luaeval('(_A.y-_A.x)*math.random()+_A.x', {'x':a:x,'y':a:y})
: endfunction
:echo Rand(1,10)
luaeval
is converted ("marshalled") from Vimscript
to Lua, so changes to Lua containers do not affect values in Vimscript. Return
value is also always converted. When converting, msgpack-special-dicts are
treated specially.
v:lua
prefix can be used to call Lua functions
which are global or accessible from global tables. The expressioncall v:lua.func(arg1, arg2)
is equivalent to the Lua chunkreturn func(...)
where the args are converted to Lua values. The expressioncall v:lua.somemod.func(args)
is equivalent to the Lua chunkreturn somemod.func(...)
In addition, functions of packages can be accessed likecall v:lua.require'mypack'.func(arg1, arg2)
call v:lua.require'mypack.submod'.func(arg1, arg2)
Note: Only single quote form without parens is allowed. Using
require"mypack"
or require('mypack')
as prefixes do NOT work (the latter
is still valid as a function call of itself, in case require returns a useful
value).
v:lua
prefix may be used to call Lua functions as methods. For
example::eval arg1->v:lua.somemod.func(arg2)
v:lua
in "func" options like 'tagfunc', 'omnifunc', etc.
For example consider the following Lua omnifunc handler:function mymod.omnifunc(findstart, base)
if findstart == 1 then
return 0
else
return {'stuff', 'steam', 'strange things'}
end
end
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.
v:lua
without a call is not allowed in a Vimscript expression:
Funcrefs cannot represent Lua functions. The following are errors:let g:Myvar = v:lua.myfunc " Error
call SomeFunc(v:lua.mycallback) " Error
let g:foo = v:lua " Error
let g:foo = v:['lua'] " Error
vim
module, which exposes
various functions and sub-modules. It is always loaded, thus require("vim")
is unnecessary.
:lua vim.print(vim)
Result is something like this:{ _os_proc_children = <function 1>, _os_proc_info = <function 2>, ... api = { nvim__id = <function 5>, nvim__id_array = <function 6>, ... }, deepcopy = <function 106>, gsplit = <function 107>, ... }To find documentation on e.g. the "deepcopy" function:
:help vim.deepcopy()
Note that underscore-prefixed functions (e.g. "_os_proc_children") are
internal/private and must not be used by plugins.
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.uv
callbacks. For example, this is an error:local timer = vim.uv.new_timer()
timer:start(1000, 0, function()
vim.api.nvim_command('echomsg "test"')
end)
local timer = vim.uv.new_timer()
timer:start(1000, 0, vim.schedule_wrap(function()
vim.api.nvim_command('echomsg "test"')
end))
-- Create a timer handle (implementation detail: uv_timer_t).
local timer = vim.uv.new_timer()
local i = 0
-- Waits 1000ms, then repeats every 750ms until timer:close().
timer:start(1000, 750, function()
print('timer invoked! i='..tostring(i))
if i > 4 then
timer:close() -- Always close handles to avoid leaks.
end
i = i + 1
end)
print('sleeping');
watch-file
1. Save this code to a file.
2. Execute it with ":luafile %".
3. Use ":Watch %" to watch any file.
4. Try editing the file from another text editor.
5. Observe that the file reloads in Nvim (because on_change() calls
:checktime).local w = vim.uv.new_fs_event()
local function on_change(err, fname, status)
-- Do work...
vim.api.nvim_command('checktime')
-- Debounce: stop/start.
w:stop()
watch_file(fname)
end
function watch_file(fname)
local fullpath = vim.api.nvim_call_function(
'fnamemodify', {fname, ':p'})
w:start(fullpath, {}, vim.schedule_wrap(function(...)
on_change(...) end))
end
vim.api.nvim_command(
"command! -nargs=1 Watch call luaeval('watch_file(_A)', expand('<args>'))")
inotify-limitations
When on Linux you may need to increase the maximum number of inotify
watches
and queued events as the default limit can be too low. To increase the limit,
run:sysctl fs.inotify.max_user_watches=494462
/etc/sysctl.conf
to make the changes persistent.
tcp-server
1. Save this code to a file.
2. Execute it with ":luafile %".
3. Note the port number.
4. Connect from any TCP client (e.g. "nc 0.0.0.0 36795"):local function create_server(host, port, on_connect)
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.uv.new_tcp()
server:accept(sock) -- Accept client connection.
on_connect(sock) -- Start reading messages.
end)
return server
end
local server = create_server('0.0.0.0', 0, function(sock)
sock:read_start(function(err, chunk)
assert(not err, err) -- Check for errors.
if chunk then
sock:write(chunk) -- Echo received messages to the channel.
else -- EOF (stream closed).
sock:close() -- Always close handles to avoid leaks.
end
end)
end)
print('TCP echo-server listening on port: '..server:getsockname().port)
lua-loop-threading
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.
vim.*
API is available in threads. This includes:
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
print()
and vim.inspect
vim.diff
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.
{opts}
) vim.highlight.on_yank()
Highlight the yanked text during a TextYankPost event.
init.vim
:autocmd TextYankPost * silent! lua vim.highlight.on_yank {higroup='Visual', timeout=300}
{opts}
(table?
) Optional parameters
.user
)
vim.highlight.priorities
Table with default priorities used for highlighting:
syntax
: 50
, used for standard syntax highlighting
treesitter
: 100
, used for treesitter-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.
{bufnr}
(integer
) Buffer number to apply highlighting to
{ns}
(integer
) Namespace to add highlight to
{higroup}
(string
) Highlight group to use for highlighting
{opts}
(table?
) A table with the following fields:
{inclusive}
(boolean
, default: false
) Indicates
whether the range is end-inclusive
{priority}
(integer
, default:
vim.highlight.priorities.user
) Indicates priority of
highlight
{a}
, {b}
, {opts}
) vim.diff()
Run diff on strings {a}
and {b}
. Any indices returned by this function,
either directly or via callback arguments, are 1-based.
vim.diff('a\n', 'b\nc\n')
-- =>
-- @@ -1 +1,2 @@
-- -a
-- +b
-- +c
vim.diff('a\n', 'b\nc\n', {result_type = 'indices'})
-- =>
-- {
-- {1, 1, 1, 2}
-- }
{a}
(string
) First string to compare
{b}
(string
) Second string to compare
{opts}
(table
) Optional parameters:
{on_hunk}
(fun(start_a: integer, count_a: integer, start_b: integer, count_b: integer): integer
)
Invoked for each hunk in the diff. Return a negative number
to cancel the callback for any remaining hunks. Arguments:
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}
('unified'|'indices'
, default: 'unified'
)
Form of the returned diff:
unified
: 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}
('myers'|'minimal'|'patience'|'histogram'
,
default: 'myers'
) 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.
string|integer[]
) See {opts.result_type}
. nil
if {opts.on_hunk}
is given.
{str}
) vim.mpack.decode()
Decodes (or "unpacks") the msgpack-encoded {str}
to a Lua object.
{str}
(string
)
any
)
{obj}
) vim.mpack.encode()
Encodes (or "packs") Lua object {obj}
as msgpack in a Lua string.
{obj}
(any
)
string
)
{str}
, {opts}
) vim.json.decode()
Decodes (or "unpacks") the JSON-encoded {str}
to a Lua object.
{opts}
, see below).
{}
(empty Lua table).
vim.print(vim.json.decode('{"bar":[],"foo":{},"zub":null}'))
-- { bar = {}, foo = vim.empty_dict(), zub = vim.NIL }
{str}
(string
) Stringified JSON data.
{opts}
(table<string,any>?
) Options table with keys:
any
)
{obj}
) vim.json.encode()
Encodes (or "packs") Lua object {obj}
as JSON in a Lua string.
{obj}
(any
)
string
)
{str}
) vim.base64.decode()
Decode a Base64 encoded string.
{str}
(string
) Base64 encoded string
string
) Decoded string
{str}
(string
) String to encode
string
) Encoded string
{str}
) vim.spell.check()
Check {str}
for spelling errors. Similar to the Vimscript function
spellbadword().
vim.spell.check("the quik brown fox")
-- =>
-- {
-- {'quik', 'bad', 5}
-- }
{str}
(string
)
[string, 'bad'|'rare'|'local'|'caps', integer][]
) List of tuples
with three items:
{str}
where the word begins.
{...}
) vim.api
Invokes Nvim API function {func}
with arguments {...}
.
Example: call the "nvim_get_current_line()" API function:print(tostring(vim.api.nvim_get_current_line()))
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
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
Value index for tables representing Floats. A table representing
floating-point value 1.0 looks like this:{
[vim.type_idx] = vim.types.float,
[vim.val_idx] = 1.0,
}
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.
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.
vim.empty_dict()
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.
table
)
{str}
, {from}
, {to}
) 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".
{str}
(string
) Text to convert
{from}
(string
) Encoding of {str}
{to}
(string
) Target encoding
string?
) Converted string if conversion succeeds, nil
otherwise.
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).
{channel}
, {method}
, {...}
) vim.rpcnotify()
Sends {event}
to {channel}
via RPC and returns immediately. If {channel}
is 0, the event is broadcast to all channels.
{channel}
(integer
)
{method}
(string
)
{...}
(any?
)
{channel}
, {method}
, {...}
) vim.rpcrequest()
Sends a request to {channel}
to invoke {method}
via RPC and blocks until
a response is received.
{channel}
(integer
)
{method}
(string
)
{...}
(any?
)
{fn}
) vim.schedule()
Schedules {fn}
to be invoked soon by the main event-loop. Useful to avoid
textlock or other temporary restrictions.
{fn}
(fun()
)
{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.
{index}
in the middle of a UTF-16 sequence is rounded upwards to the end of that
sequence.
{str}
(string
)
{index}
(integer
)
{use_utf16}
(boolean?
)
integer
)
{str}
, {index}
) vim.str_utf_end()
Gets the distance (in bytes) from the last byte of the codepoint
(character) that {index}
points to.
-- The character 'æ' is stored as the bytes '\xc3\xa6' (using UTF-8)
-- Returns 0 because the index is pointing at the last byte of a character
vim.str_utf_end('æ', 2)
-- Returns 1 because the index is pointing at the penultimate byte of a character
vim.str_utf_end('æ', 1)
{str}
(string
)
{index}
(integer
)
integer
)
{str}
) vim.str_utf_pos()
Gets a list of the starting byte positions of each UTF-8 codepoint in the
given string.
{str}
(string
)
integer[]
)
{str}
, {index}
) vim.str_utf_start()
Gets the distance (in bytes) from the starting byte of the codepoint
(character) that {index}
points to.
{index}
to get the starting byte of a
character.
-- 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)
{str}
(string
)
{index}
(integer
)
integer
)
{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.
{index}
in the middle of a UTF-8 sequence is rounded upwards to the end of
that sequence.
{str}
(string
)
{index}
(integer?
)
integer
) UTF-32 index
(integer
) UTF-16 index
{a}
(string
)
{b}
(string
)
0|1|-1
) if strings are equal, {a}
is greater than {b}
or {a}
is
lesser than {b}
, respectively.
{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.
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).
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)
{ns}
(integer
)
{options}
(table<string, any>
)
{callback}
(fun()
)
{ns}
) vim.ui_detach()
Detach a callback previously attached with vim.ui_attach() for the given
namespace {ns}
.
{ns}
(integer
)
{time}
, {callback}
, {interval}
, {fast_only}
) vim.wait()
Wait for {time}
in milliseconds until {callback}
returns true
.
{callback}
immediately and at approximately {interval}
milliseconds (default 200). Nvim still processes other events during this
time.
---
-- Wait for 100 ms, allowing other events to process
vim.wait(100, function() end)
---
-- Wait for 100 ms or until global variable set.
vim.wait(100, function() return vim.g.waiting_for_var end)
---
-- 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)
---
-- Schedule a function to set a value in 100ms
vim.defer_fn(function() vim.g.timer_result = true end, 100)
-- 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
{time}
(integer
) Number of milliseconds to wait
{callback}
(fun(): boolean?
) Optional callback. Waits until
{callback}
returns true
{interval}
(integer?
) (Approximate) number of milliseconds to wait
between polls
boolean
)
(-1|-2?
)
{callback}
returns true
during the {time}
: true, nil
{callback}
never returns true
during the {time}
: false, -1
{callback}
is interrupted during the {time}
: false, -2
{callback}
errors, the error is raised.
vim.fn.remove()
on a
Lua list copies the list object to Vimscript and does NOT modify the Lua list:local list = { 1, 2, 3 }
vim.fn.remove(list, 0)
vim.print(list) --> "{ 1, 2, 3 }"
{func}
, {...}
) vim.call()
Invokes vim-function or user-function {func}
with arguments {...}
.
See also vim.fn.
Equivalent to:vim.fn[func]({...})
{command}
)
See vim.cmd().
{...}
) vim.fn
Invokes vim-function or user-function {func}
with arguments {...}
.
To call autoload functions, use the syntax:vim.fn['some#function']({...})
pairs(vim.fn)
only
enumerates functions that were called at least once.
lua-vim-variables
The Vim editor global dictionaries g: w: b: t: v: can be accessed
from Lua conveniently and idiomatically by referencing the vim.*
Lua tables
described below. In this way you can easily read and modify global Vimscript
variables from Lua.
vim.g.foo = 5 -- Set the g:foo Vimscript variable.
print(vim.g.foo) -- Get and print the g:foo Vimscript variable.
vim.g.foo = nil -- Delete (:unlet) the Vimscript variable.
vim.b[2].foo = 6 -- Set b:foo for buffer 2
vim.g.my_dict.field1 = 'value' -- Does not work
local my_dict = vim.g.my_dict --
my_dict.field1 = 'value' -- Instead do
vim.g.my_dict = my_dict --
vim.g vim.g
Global (g:) editor variables.
Key with no value returns nil
.
vim.b
Buffer-scoped (b:) variables for the current buffer.
Invalid or unset key returns nil
. Can be indexed with
an integer to access variables for a specific buffer.
vim.w
Window-scoped (w:) variables for the current window.
Invalid or unset key returns nil
. Can be indexed with
an integer to access variables for a specific window.
vim.t
Tabpage-scoped (t:) variables for the current tabpage.
Invalid or unset key returns nil
. Can be indexed with
an integer to access variables for a specific tabpage.
set number
Lua: vim.o.number = true
set wildignore=*.o,*.a,__pycache__
Lua: vim.o.wildignore = '*.o,*.a,__pycache__'
set wildignore=*.o,*.a,__pycache__
vim.o
:vim.o.wildignore = '*.o,*.a,__pycache__'
vim.opt
:vim.opt.wildignore = { '*.o', '*.a', '__pycache__' }
vim.opt.wildignore:append { "*.pyc", "node_modules" }
vim.opt.wildignore:prepend { "new_first_value" }
vim.opt.wildignore:remove { "node_modules" }
set listchars=space:_,tab:>~
vim.o
:vim.o.listchars = 'space:_,tab:>~'
vim.opt
:vim.opt.listchars = { space = '_', tab = '>~' }
Option
object, not the value of the option,
which is accessed through vim.opt:get():
echo wildignore
vim.o
:print(vim.o.wildignore)
vim.opt
:vim.print(vim.opt.wildignore:get())
vim.opt_local
. Additionally, to replicate the behavior of :setglobal, use
vim.opt_global
.
vim.opt.formatoptions:append('j')
vim.opt.formatoptions = vim.opt.formatoptions + 'j'
{value}
(string
) Value to append
vim.opt:get()
Returns a Lua-representation of the option. Boolean, number and string
values will be returned in exactly the same fashion.
vim.cmd [[set wildignore=*.pyc,*.o]]
vim.print(vim.opt.wildignore:get())
-- { "*.pyc", "*.o", }
for _, ignore_pattern in ipairs(vim.opt.wildignore:get()) do
print("Will ignore:", ignore_pattern)
end
-- Will ignore: *.pyc
-- Will ignore: *.o
vim.cmd [[set listchars=space:_,tab:>~]]
vim.print(vim.opt.listchars:get())
-- { space = "_", tab = ">~", }
for char, representation in pairs(vim.opt.listchars:get()) do
print(char, "=>", representation)
end
true
as entries.vim.cmd [[set formatoptions=njtcroql]]
vim.print(vim.opt.formatoptions:get())
-- { n = true, j = true, c = true, ... }
local format_opts = vim.opt.formatoptions:get()
if format_opts.j then
print("J is enabled!")
end
string|integer|boolean?
) value of option
vim.opt.wildignore:prepend('*.o')
vim.opt.wildignore = vim.opt.wildignore ^ '*.o'
{value}
(string
) Value to prepend
vim.opt.wildignore:remove('*.pyc')
vim.opt.wildignore = vim.opt.wildignore - '*.pyc'
{value}
(string
) Value to remove
{bufnr}
] vim.bo
Get or set buffer-scoped options for the buffer with number {bufnr}
. If
{bufnr}
is omitted then the current buffer is used. Invalid {bufnr}
or key
is an error.
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
Environment variables defined in the editor session. See expand-env and
:let-environment for the Vimscript behavior. Invalid or unset key
returns nil
.
vim.env.FOO = 'bar'
print(vim.env.TERM)
vim.go.cmdheight = 4
print(vim.go.columns)
print(vim.go.bar) -- error: invalid key
vim.o.cmdheight = 4
print(vim.o.columns)
print(vim.o.foo) -- error: invalid key
{winid}
][{bufnr}
] vim.wo
Get or set window-scoped options for the window with handle {winid}
and
buffer with number {bufnr}
. Like :setlocal
if setting a global-local
option or 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.
{bufnr}
with value 0
(the current buffer in the window) is
supported.
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'
{command}
) vim.cmd()
Executes Vim script commands.
vim.cmd
can be indexed with a command name to return a
callable function to the command.
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')
{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_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.
{fn}
Note: The {fn}
is
vim.schedule_wrap()ped automatically, so API functions are safe to call.
{fn}
(function
) Callback to call once timeout
expires
{timeout}
(integer
) Number of milliseconds to wait before calling
fn
table
) timer luv timer object
vim.deprecate()
vim.deprecate({name}
, {alternative}
, {version}
, {plugin}
, {backtrace}
)
Shows a deprecation message to the user.
{name}
(string
) Deprecated feature (function, API, etc.).
{alternative}
(string?
) Suggested alternative feature.
{version}
(string
) Version when the deprecated function will be
removed.
{plugin}
(string?
) Name of the plugin that owns the deprecated
feature. Defaults to "Nvim".
{backtrace}
(boolean?
) Prints backtrace. Defaults to true.
string?
) Deprecated message, or nil if no message was shown.
vim.inspect()
Gets a human-readable representation of the given object.
string
)
{str}
) vim.keycode()
Translates keycodes.
local k = vim.keycode
vim.g.mapleader = k'<bs>'
{str}
(string
) String to be converted.
string
)
{find_start}
) vim.lua_omnifunc()
Omnifunc for completing Lua values from the runtime Lua interpreter,
similar to the builtin completion for the :lua
command.
set omnifunc=v:lua.vim.lua_omnifunc
in a Lua buffer.
{find_start}
(1|0
)
{msg}
(string
) Content of the notification to show to the user.
{opts}
(table?
) Optional parameters. Unused by default.
{msg}
(string
) Content of the notification to show to the user.
{opts}
(table?
) Optional parameters. Unused by default.
boolean
) true if message was displayed, else false
{fn}
, {ns_id}
) vim.on_key()
Adds Lua function {fn}
with namespace id {ns_id}
as a listener to every,
yes every, input key.
{fn}
(fun(key: string, typed: string)?
) Function invoked on
every key press. i_CTRL-V {key}
is the key after mappings
have been applied, and {typed}
is the key(s) before mappings
are applied, which may be empty if {key}
is produced by
non-typed keys. When {fn}
is nil and {ns_id}
is specified,
the callback associated with namespace {ns_id}
is removed.
{ns_id}
(integer?
) Namespace ID. If nil or 0, generates and returns
a new nvim_create_namespace() id.
integer
) Namespace id associated with {fn}
. Or count of all
callbacks if on_key() is called without arguments.
{lines}
, {phase}
) vim.paste()
Paste handler, invoked by nvim_paste() when a conforming UI (such as the
TUI) pastes text into the editor.
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)
{phase}
(-1|1|2|3
) -1: "non-streaming" paste: the call contains all
lines. If paste is "streamed", phase
indicates the stream
state:
boolean
) result false if client should cancel the paste.
{...}
) vim.print()
"Pretty prints" the given arguments and returns them unmodified.
local hl_normal = vim.print(vim.api.nvim_get_hl(0, { name = 'Normal' }))
{...}
(any
)
any
) given arguments.
{fn}
.
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))
{fn}
(function
)
function
)
{cmd}
, {opts}
, {on_exit}
) vim.system()
Runs a system command or throws an error if {cmd}
cannot be run.
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 = '' }
{cmd}
cannot be run.
{cmd}
(string[]
) Command to execute
{opts}
(vim.SystemOpts?
) Options:
NVIM
set to v:servername.
env
defines the job environment
exactly, instead of merging current environment.
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
.
fun(err: string, data: string)
. Defaults to true
fun(err: string, data: string)
. Defaults to true
.
\r\n
with \n
.
{on_exit}
(fun(out: vim.SystemCompleted)?
) Called when subprocess
exits. When provided, the command runs asynchronously.
Receives SystemCompleted object, see return of
SystemObj:wait().
vim.SystemObj
) Object with the fields:
stdin=true
. Pass nil
to
close the stream.
{bufnr}
, {row}
, {col}
, {filter}
) vim.inspect_pos()
Get all the items at a given buffer position.
:Inspect!
. :Inspect!
{bufnr}
(integer?
) defaults to the current buffer
{row}
(integer?
) row to inspect, 0-based. Defaults to the row of
the current cursor
{col}
(integer?
) col to inspect, 0-based. Defaults to the col of
the current cursor
{filter}
(table?
) Table with key-value pairs to filter the items
{syntax}
(boolean
, default: true
) Include syntax based
highlight groups.
{treesitter}
(boolean
, default: true
) Include
treesitter based highlight groups.
{extmarks}
(boolean|"all"
, default: true) Include
extmarks. When all
, then extmarks without a hl_group
will also be included.
{semantic_tokens}
(boolean
, default: true) Include
semantic token highlights.
table
) a table with the following key-value pairs. Items are in
"traversal order":
{bufnr}
, {row}
, {col}
, {filter}
) vim.show_pos()
Show all the items at a given buffer position.
:Inspect
. :Inspect
{bufnr}
(integer?
) defaults to the current buffer
{row}
(integer?
) row to inspect, 0-based. Defaults to the row of
the current cursor
{col}
(integer?
) col to inspect, 0-based. Defaults to the col of
the current cursor
{filter}
(table?
) A table with the following fields:
{syntax}
(boolean
, default: true
) Include syntax based
highlight groups.
{treesitter}
(boolean
, default: true
) Include
treesitter based highlight groups.
{extmarks}
(boolean|"all"
, default: true) Include
extmarks. When all
, then extmarks without a hl_group
will also be included.
{semantic_tokens}
(boolean
, default: true) Include
semantic token highlights.
{clear}
(fun()
) Clear all items
{push}
(fun(item: T)
) Adds an item, overriding the oldest item if
the buffer is full.
{pop}
(fun(): T?
) Removes and returns the first unread item
{peek}
(fun(): T?
) Returns the first unread item without removing
it
Ringbuf:clear()
Clear all items
Ringbuf:peek()
Returns the first unread item without removing it
any?
)
Ringbuf:pop()
Removes and returns the first unread item
any?
)
{item}
) Ringbuf:push()
Adds an item, overriding the oldest item if the buffer is full.
{item}
(any
)
eq
metamethod. All other types are compared using the equality ==
operator.
{a}
(any
) First value
{b}
(any
) Second value
boolean
) true
if values are equals, else false
{orig}
, {noref}
) 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
the same functions as those in the input table. Userdata and threads are
not copied and will throw an error.
noref=true
is much more performant on tables with unique table
fields, while noref=false
is more performant on tables that reuse table
fields.
{orig}
(table
) Table to copy
{noref}
(boolean?
) When false
(default) a contained table is only
copied once and all references point to this single copy.
When true
every occurrence of a table results in a new
copy. This also means that a cyclic reference can cause
deepcopy()
to fail.
table
) Table of copied keys and (nested) values.
{createfn}
) vim.defaulttable()
Creates a table whose missing keys are provided by {createfn}
(like
Python's "defaultdict").
{createfn}
is nil
it defaults to defaulttable() itself, so accessing
nested keys creates nested tables:local a = vim.defaulttable()
a.b.c = 1
{createfn}
(fun(key:any):any?
) Provides the value for a missing
key
.
table
) Empty table with __index
metamethod.
{s}
(string
) String
{suffix}
(string
) Suffix to match
boolean
) true
if suffix
is a suffix of s
{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").
for s in vim.gsplit(':aa::b:', ':', {plain=true}) do
print(s)
end
for word, num in ('foo111bar222'):gmatch('([^0-9]*)(%d*)') do
print(('word: %s num: %s'):format(word, num))
end
{s}
(string
) String to split
{sep}
(string
) Separator or pattern
{plain}
(boolean
) Use sep
literally (as in
string.find).
{trimempty}
(boolean
) Discard empty segments at start and
end of the sequence.
fun():string?
) Iterator over the split components
{f}
(any
) Any object
boolean
) true
if f
is callable, else false
{t}
) vim.isarray()
Tests if t
is an "array": a table indexed only by integers (potentially
non-contiguous).
{}
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.
{t}
(table?
)
boolean
) true
if array-like table, else false
.
{t}
) vim.islist()
Tests if t
is a "list": a table indexed only by contiguous integers
starting from 1 (what lua-length calls a "regular array").
{}
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.
{t}
(table?
)
boolean
) true
if list-like table, else false
.
{t}
, {value}
) vim.list_contains()
Checks if a list-like table (integer keys without gaps) contains value
.
{t}
(table
) Table to check (must be list-like, not validated)
{value}
(any
) Value to compare
boolean
) true
if t
contains value
{dst}
, {src}
, {start}
, {finish}
) vim.list_extend()
Extends a list-like table with the values of another list-like table.
{dst}
(table
) List which will be modified and appended to
{src}
(table
) List from which values will be inserted
{start}
(integer?
) Start index on src. Defaults to 1
{finish}
(integer?
) Final index on src. Defaults to #src
table
) dst
{list}
, {start}
, {finish}
) vim.list_slice()
Creates a copy of a table containing only elements from start to end
(inclusive)
{list}
(any[]
) Table
{start}
(integer?
) Start range of slice
{finish}
(integer?
) End range of slice
any[]
) Copy of table sliced from start to finish (inclusive)
{s}
(string
) String to escape
string
) %-escaped pattern string
{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.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
{size}
(integer
)
{t}
) vim.spairs()
Enumerates key-value pairs of a table, ordered by key.
{t}
(table
) Dict-like table
fun(table: table<K, V>, index?: K):K, V
) for-in iterator over
sorted keys and their values
(table
)
{s}
, {sep}
, {opts}
) vim.split()
Splits a string at each instance of a separator and returns the result as
a table (unlike vim.gsplit()).
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'}
{s}
(string
) String to split
{sep}
(string
) Separator or pattern
{plain}
(boolean
) Use sep
literally (as in
string.find).
{trimempty}
(boolean
) Discard empty segments at start and
end of the sequence.
string[]
) List of split components
{s}
(string
) String
{prefix}
(string
) Prefix to match
boolean
) true
if prefix
is a prefix of s
{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.
vim.tbl_contains({ 'a', { 'b', 'c' } }, function(v)
return vim.deep_equal(v, { 'b', 'c' })
end, { predicate = true })
-- true
{t}
(table
) Table to check
{value}
(any
) Value to compare or predicate function reference
{predicate}
(boolean
) value
is a function reference to
be checked (default false)
boolean
) true
if t
contains value
{t}
) vim.tbl_count()
Counts the number of non-nil values in table t
.vim.tbl_count({ a=1, b=2 }) --> 2
vim.tbl_count({ 1, 2 }) --> 2
{t}
(table
) Table
integer
) Number of non-nil values in table
{behavior}
('error'|'keep'|'force'
) Decides what to do if a key is
found in more than one map:
{...}
(table
) Two or more tables
table
) Merged table
{behavior}
('error'|'keep'|'force'
) Decides what to do if a key is
found in more than one map:
{...}
(table
) Two or more tables
table
) Merged table
{func}
(function
) Function
{t}
(table
) Table
any[]
) Table of filtered values
{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.
vim.tbl_get({ key = { nested_key = true }}, 'key', 'nested_key') == true
vim.tbl_get({ key = {}}, 'key', 'nested_key') == nil
{o}
(table
) Table to index
{...}
(any
) Optional keys (0 or more, variadic) via which to index
the table
any
) Nested value indexed by key (if it exists), else nil
{t}
) vim.tbl_isempty()
Checks if a table is empty.
{t}
(table
) Table to check
boolean
) true
if t
is empty
{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.
{t}
(table
) Table
any[]
) List of keys
{func}
(fun(value: T): any
) Function
{t}
(table<any, T>
) Table
table
) Table of transformed 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.
{t}
(table
) Table
any[]
) List of values
{s}
) vim.trim()
Trim whitespace (Lua pattern "%s") from both sides of a string.
{s}
(string
) String to trim
string
) String with whitespace removed from its beginning and end
{opt}
) vim.validate()
Validate function arguments.
{name}
with value {value}
has the type
{type}
. {type}
must be a value returned by lua-type(). If {optional}
is
true, then {value}
may be null. This form is significantly faster and
should be preferred for simple cases.
function vim.startswith(s, prefix)
vim.validate('s', s, 'string')
vim.validate('prefix', prefix, 'string')
...
end
function user.new(name, age, hobbies)
vim.validate{
name={name, 'string'},
age={age, 'number'},
hobbies={hobbies, 'table'},
}
...
end
vim.validate{arg1={{'foo'}, 'table'}, arg2={'foo', 'string'}}
--> NOP (success)
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={{'foo'}, {'table', 'string'}}, arg2={'foo', {'table', 'string'}}}
-- NOP (success)
vim.validate{arg1={1, {'string', 'table'}}}
-- error('arg1: expected string|table, got number')
{opt}
(table
) Names of parameters to validate. Each key is a
parameter name; each value is a tuple in one of these forms:
1. (arg_value, type_name, optional)
nil
is valid
2. (arg_value, fn, msg)
vim.loader.disable()
Disables the experimental Lua module loader:
vim.loader.enable()
Enables the experimental Lua module loader:
{modname}
(string
) Module name, or "*"
to find the top-level
modules instead
{opts}
(table?
) Options for finding a module:
{rtp}
(boolean
, default: true
) Search for modname in
the runtime path.
{paths}
(string[]
, default: {}
) Extra paths to
search for modname
{patterns}
(string[]
, default:
{"/init.lua", ".lua"}
) List of patterns to use when
searching for modules. A pattern is a string added to the
basename of the Lua module being searched.
{all}
(boolean
, default: false
) Search for all
matches.
table[]
) A list of objects with the following fields:
{modpath}
(string
) Path of the module
{modname}
(string
) Name of the module
{stat}
(uv.uv_fs_t
) The fs_stat of the module path. Won't be
returned for modname="*"
{path}
) vim.loader.reset()
Resets the cache for the path, or all the paths if path is nil.
{path}
(string?
) path to reset
{str}
) vim.uri_decode()
URI-decodes a string containing percent escapes.
{str}
(string
) string to decode
string
) decoded string
{str}
(string
) string to encode
{rfc}
("rfc2396"|"rfc2732"|"rfc3986"?
)
string
) encoded string
{bufnr}
) vim.uri_from_bufnr()
Gets a URI from a bufnr.
{bufnr}
(integer
)
string
) URI
{path}
) vim.uri_from_fname()
Gets a URI from a file path.
{path}
(string
) Path to file
string
) URI
{uri}
) vim.uri_to_bufnr()
Gets the buffer for a uri. Creates a new unloaded buffer if no buffer for
the uri already exists.
{uri}
(string
)
integer
) bufnr
{uri}
) vim.uri_to_fname()
Gets a filename from a URI.
{uri}
(string
)
string
) filename or unchanged URI for non-file URIs
{opts}
, {on_confirm}
) vim.ui.input()
Prompts the user for input, allowing arbitrary (potentially asynchronous)
work until on_confirm
.
vim.ui.input({ prompt = 'Enter value for shiftwidth: ' }, function(input)
vim.o.shiftwidth = tonumber(input)
end)
{on_confirm}
(function
) ((input|nil) -> ()) Called once the user
confirms or abort the input. input
is what the user
typed (it might be an empty string if nothing was
entered), or nil
if the user aborted the dialog.
{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.
-- Asynchronous.
vim.ui.open("https://neovim.io/")
vim.ui.open("~/path/to/file")
-- Synchronous (wait until the process exits).
local cmd, err = vim.ui.open("$VIMRUNTIME")
if cmd then
cmd:wait()
end
{path}
(string
) Path or URL to open
vim.SystemObj?
) Command object, or nil if not found.
(string?
) Error message on failure, or nil on success.
{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
.
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)
{items}
(any[]
) Arbitrary items
{opts}
(table
) Additional options
Select one of:
items
. Defaults to
tostring
.
vim.ui.select
may
wish to use this to infer the structure or semantics of
items
, or the context in which select() was called.
{on_choice}
(fun(item: any?, idx: integer?)
) Called once the user
made a choice. idx
is the 1-based index of item
within items
. nil
if the user aborted the dialog.
{filetypes}
) vim.filetype.add()
Add new filetype mappings.
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
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,
},
})
vim.filetype.add {
pattern = {
['.*'] = {
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,
{ priority = -math.huge },
},
},
}
{filetypes}
(table
) A table containing new filetype maps (see
example).
{pattern}
(vim.filetype.mapping
)
{extension}
(vim.filetype.mapping
)
{filename}
(vim.filetype.mapping
)
vim.filetype.get_option()
vim.filetype.get_option({filetype}
, {option}
)
Get the default option value for a {filetype}
.
vim.filetype.get_option('vim', 'commentstring')
{filetype}
(string
) Filetype
{option}
(string
) Option name
string|boolean|integer
) Option value
{args}
) vim.filetype.match()
Perform filetype detection.
-- Using a buffer number
vim.filetype.match({ buf = 42 })
-- 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 file contents
vim.filetype.match({ contents = {'#!/usr/bin/env bash'} })
{args}
(table
) Table specifying which matching strategy to use.
Accepted keys are:
{buf}
(integer
) Buffer number to use for matching.
Mutually exclusive with {contents}
{filename}
(string
) Filename to use for matching. When
{buf}
is given, defaults to the filename of the given buffer
number. The file need not actually exist in the filesystem.
When used without {buf}
only the name of the file is used
for filetype matching. This may result in failure to detect
the filetype in cases where the filename alone is not enough
to disambiguate the filetype.
{contents}
(string[]
) An array of lines representing file
contents to use for matching. Can be used with {filename}
.
Mutually exclusive with {buf}
.
string?
) If a match was found, the matched filetype.
(function?
) A function that modifies buffer state when called (for
example, to set some filetype specific buffer variables). The function
accepts a buffer number as its only argument.
{modes}
, {lhs}
, {opts}
) vim.keymap.del()
Remove an existing mapping. Examples:vim.keymap.del('n', 'lhs')
vim.keymap.del({'n', 'i', 'v'}, '<leader>w', { buffer = 5 })
{modes}
(string|string[]
)
{lhs}
(string
)
{opts}
(table?
) A table with the following fields:
{buffer}
(integer|boolean
) Remove a mapping from the
given buffer. When 0
or true
, use the current buffer.
{mode}
, {lhs}
, {rhs}
, {opts}
) vim.keymap.set()
Adds a new mapping. Examples:-- 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)')
{mode}
(string|string[]
) Mode short-name, see nvim_set_keymap().
Can also be list of modes to create mapping on multiple modes.
{replace_keycodes}
defaults to true
if "expr" is true
.
{buffer}
(integer|boolean
) Creates buffer-local mapping,
0
or true
for current buffer.
{remap}
(boolean
, default: false
) Make the mapping
recursive. Inverse of {noremap}
.
{file}
) vim.fs.basename()
Return the basename of the given path
{file}
(string?
) Path
string?
) Basename of {file}
{path}
(string
) An absolute or relative path to the directory to
iterate over. The path is first normalized
vim.fs.normalize().
{opts}
(table?
) Optional keyword arguments:
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".
{file}
) vim.fs.dirname()
Return the parent directory of the given path
{file}
(string?
) Path
string?
) Parent directory of {file}
{names}
, {opts}
) vim.fs.find()
Find files or directories (or other items as specified by opts.type
) in
the given path.
{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.
-- 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'})
{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:
true
if the given item is considered a match.
{opts}
(table
) Optional keyword arguments:
{upward}
(boolean
, default: false
) Search upward
through parent directories. Otherwise, search through child
directories (recursively).
{stop}
(string
) Stop searching when this directory is
reached. The directory itself is not searched.
{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.
{...}
) 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"
)
{...}
(string
)
string
)
{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
environment variables are also expanded. "." and ".." components are also
resolved, except when the path is relative and trying to resolve it would
result in an absolute path.
[[C:\Users\jdoe]] => "C:/Users/jdoe"
"~/src/neovim" => "/home/jdoe/src/neovim"
"$XDG_CONFIG_HOME/nvim/init.vim" => "/Users/jdoe/.config/nvim/init.vim"
"~/src/nvim/api/../tui/./tui.c" => "/home/jdoe/src/nvim/tui/tui.c"
"./foo/bar" => "foo/bar"
"foo/../../../bar" => "../../bar"
"/home/jdoe/../../../bar" => "/bar"
"C:foo/../../baz" => "C:../baz"
"C:/foo/../../baz" => "C:/baz"
[[\\?\UNC\server\share\foo\..\..\..\bar]] => "//?/UNC/server/share/bar"
{path}
(string
) Path to normalize
{opts}
(table?
) A table with the following fields:
{expand_env}
(boolean
, default: true
) Expand
environment variables.
{win}
(boolean
, default: true
in Windows, false
otherwise) Path is a Windows path.
string
) Normalized path
{start}
) vim.fs.parents()
Iterate over all the parents of the given path.
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
{start}
(string
) Initial path.
fun(_, dir: string): string?
) Iterator
(nil
)
(string?
)
{source}
, {marker}
) vim.fs.root()
Find the first parent directory containing a specific "marker", relative
to a file path or buffer.
-- Find the root of a Python project, starting from file 'main.py'
vim.fs.root(vim.fs.joinpath(vim.env.PWD, 'main.py'), {'pyproject.toml', 'setup.py' })
-- Find the root of a git repository
vim.fs.root(0, '.git')
-- Find the parent directory containing any file with a .csproj extension
vim.fs.root(0, function(name, path)
return name:match('%.csproj$') ~= nil
end)
{source}
(integer|string
) Buffer number (0 for current buffer) or
file path (absolute or relative to the current-directory)
to begin the search from.
{marker}
(string|string[]|fun(name: string, path: string): boolean
)
A marker, or list of markers, to search for. If a function,
the function is called for each evaluated item and should
return true if {name}
and {path}
are a match.
string?
) Directory path containing one of the given markers, or nil
if no directory was found.
*
to match one or more characters in a path segment
?
to match on one character in a path segment
**
to match any number of path segments, including none
{}
to group conditions (e.g. *.{ts,js}
matches TypeScript and
JavaScript files)
[]
to declare a range of characters to match in a path segment (e.g.,
example.[0-9]
to match on example.0
, example.1
, …)
[!...]
to negate a range of characters to match in a path segment
(e.g., example.[!0-9]
to match on example.a
, example.b
, but not
example.0
)
{pattern}
(string
) The raw glob pattern
lua-lpeg
vim.lpeg.Pattern
The LPeg library for parsing expression grammars is included as vim.lpeg
(https://www.inf.puc-rio.br/~roberto/lpeg/).
{subject}
, {init}
, {...}
) Pattern:match()
Matches the given pattern
against the subject
string. If the match
succeeds, returns the index in the subject of the first character after
the match, or the captured values (if the pattern captured any value). An
optional numeric argument init
makes the match start at that position in
the subject string. As usual in Lua libraries, a negative value counts
from the end. Unlike typical pattern-matching functions, match
works
only in anchored mode; that is, it tries to match the pattern with a
prefix of the given subject string (at position init
), not with an
arbitrary substring of the subject. So, if we want to find a pattern
anywhere in a string, we must either write a loop in Lua or write a
pattern that matches anywhere.
local pattern = lpeg.R('az') ^ 1 * -1
assert(pattern:match('hello') == 6)
assert(lpeg.match(pattern, 'hello') == 6)
assert(pattern:match('1 hello') == nil)
{subject}
(string
)
{init}
(integer?
)
{...}
(any
)
any
) ...
{pattern}
) vim.lpeg.B()
Returns a pattern that matches only if the input string at the current
position is preceded by patt
. Pattern patt
must match only strings
with some fixed length, and it cannot contain captures. Like the and
predicate, this pattern never consumes any input, independently of success
or failure.
{pattern}
(vim.lpeg.Pattern|string|integer|boolean|table
)
vim.lpeg.Pattern
)
{patt}
) vim.lpeg.C()
Creates a simple capture, which captures the substring of the subject that
matches patt
. The captured value is a string. If patt
has other
captures, their values are returned after this one.
local function split (s, sep)
sep = lpeg.P(sep)
local elem = lpeg.C((1 - sep) ^ 0)
local p = elem * (sep * elem) ^ 0
return lpeg.match(p, s)
end
local a, b, c = split('a,b,c', ',')
assert(a == 'a')
assert(b == 'b')
assert(c == 'c')
{patt}
(vim.lpeg.Pattern|string|integer|boolean|table|function
)
vim.lpeg.Capture
)
{n}
) vim.lpeg.Carg()
Creates an argument capture. This pattern matches the empty string and
produces the value given as the nth extra argument given in the call to
lpeg.match
.
{n}
(integer
)
vim.lpeg.Capture
)
{name}
) vim.lpeg.Cb()
Creates a back capture. This pattern matches the empty string and produces
the values produced by the most recent group capture named name
(where
name
can be any Lua value). Most recent means the last complete
outermost group capture with the given name. A Complete capture means that
the entire pattern corresponding to the capture has matched. An Outermost
capture means that the capture is not inside another complete capture. In
the same way that LPeg does not specify when it evaluates captures, it
does not specify whether it reuses values previously produced by the group
or re-evaluates them.
{name}
(any
)
vim.lpeg.Capture
)
{...}
) vim.lpeg.Cc()
Creates a constant capture. This pattern matches the empty string and
produces all given values as its captured values.
{...}
(any
)
vim.lpeg.Capture
)
{patt}
, {func}
) vim.lpeg.Cf()
Creates a fold capture. If patt
produces a list of captures C1 C2 ...
Cn, this capture will produce the value
func(...func(func(C1, C2), C3)...,Cn)
, that is, it will fold (or
accumulate, or reduce) the captures from patt
using function func
.
This capture assumes that patt
should produce at least one capture with
at least one value (of any type), which becomes the initial value of an
accumulator. (If you need a specific initial value, you may prefix a
constant capture to patt
.) For each subsequent capture, LPeg calls
func
with this accumulator as the first argument and all values produced
by the capture as extra arguments; the first result from this call becomes
the new value for the accumulator. The final value of the accumulator
becomes the captured value.
local number = lpeg.R('09') ^ 1 / tonumber
local list = number * (',' * number) ^ 0
local function add(acc, newvalue) return acc + newvalue end
local sum = lpeg.Cf(list, add)
assert(sum:match('10,30,43') == 83)
{patt}
(vim.lpeg.Pattern|string|integer|boolean|table|function
)
{func}
(fun(acc, newvalue)
)
vim.lpeg.Capture
)
{patt}
, {name}
) vim.lpeg.Cg()
Creates a group capture. It groups all values returned by patt
into a
single capture. The group may be anonymous (if no name is given) or named
with the given name (which can be any non-nil Lua value).
{patt}
(vim.lpeg.Pattern|string|integer|boolean|table|function
)
{name}
(string?
)
vim.lpeg.Capture
)
{patt}
, {fn}
) vim.lpeg.Cmt()
Creates a match-time capture. Unlike all other captures, this one is
evaluated immediately when a match occurs (even if it is part of a larger
pattern that fails later). It forces the immediate evaluation of all its
nested captures and then calls function
. The given function gets as
arguments the entire subject, the current position (after the match of
patt
), plus any capture values produced by patt
. The first value
returned by function
defines how the match happens. If the call returns
a number, the match succeeds and the returned number becomes the new
current position. (Assuming a subject sand current position i
, the
returned number must be in the range [i, len(s) + 1]
.) If the call
returns true
, the match succeeds without consuming any input (so, to
return true is equivalent to return i
). If the call returns false
,
nil
, or no value, the match fails. Any extra values returned by the
function become the values produced by the capture.
{patt}
(vim.lpeg.Pattern|string|integer|boolean|table|function
)
{fn}
(fun(s: string, i: integer, ...: any)
) (position:
boolean|integer, ...: any)
vim.lpeg.Capture
)
vim.lpeg.Cp()
Creates a position capture. It matches the empty string and captures the
position in the subject where the match occurs. The captured value is a
number.
local I = lpeg.Cp()
local function anywhere(p) return lpeg.P({I * p * I + 1 * lpeg.V(1)}) end
local match_start, match_end = anywhere('world'):match('hello world!')
assert(match_start == 7)
assert(match_end == 12)
vim.lpeg.Capture
)
{patt}
) vim.lpeg.Cs()
Creates a substitution capture. This function creates a substitution
capture, which captures the substring of the subject that matches patt
,
with substitutions. For any capture inside patt
with a value, the
substring that matched the capture is replaced by the capture value (which
should be a string). The final captured value is the string resulting from
all replacements.
local function gsub (s, patt, repl)
patt = lpeg.P(patt)
patt = lpeg.Cs((patt / repl + 1) ^ 0)
return lpeg.match(patt, s)
end
assert(gsub('Hello, xxx!', 'xxx', 'World') == 'Hello, World!')
{patt}
(vim.lpeg.Pattern|string|integer|boolean|table|function
)
vim.lpeg.Capture
)
{patt}
) vim.lpeg.Ct()
Creates a table capture. This capture returns a table with all values from
all anonymous captures made by patt
inside this table in successive
integer keys, starting at 1. Moreover, for each named capture group
created by patt
, the first value of the group is put into the table with
the group name as its key. The captured value is only the table.
{patt}
(vim.lpeg.Pattern|string|integer|boolean|table|function
)
vim.lpeg.Capture
)
{tab}
) vim.lpeg.locale()
Returns a table with patterns for matching some character classes
according to the current locale. The table has fields named alnum
,
alpha
, cntrl
, digit
, graph
, lower
, print
, punct
, space
,
upper
, and xdigit
, each one containing a correspondent pattern. Each
pattern matches any single character that belongs to its class. If called
with an argument table
, then it creates those fields inside the given
table and returns that table.
lpeg.locale(lpeg)
local space = lpeg.space ^ 0
local name = lpeg.C(lpeg.alpha ^ 1) * space
local sep = lpeg.S(',;') * space
local pair = lpeg.Cg(name * '=' * space * name) * sep ^ -1
local list = lpeg.Cf(lpeg.Ct('') * pair ^ 0, rawset)
local t = list:match('a=b, c = hi; next = pi')
assert(t.a == 'b')
assert(t.c == 'hi')
assert(t.next == 'pi')
local locale = lpeg.locale()
assert(type(locale.digit) == 'userdata')
{tab}
(table?
)
vim.lpeg.Locale
)
{pattern}
, {subject}
, {init}
, {...}
) vim.lpeg.match()
Matches the given pattern
against the subject
string. If the match
succeeds, returns the index in the subject of the first character after
the match, or the captured values (if the pattern captured any value). An
optional numeric argument init
makes the match start at that position in
the subject string. As usual in Lua libraries, a negative value counts
from the end. Unlike typical pattern-matching functions, match
works
only in anchored mode; that is, it tries to match the pattern with a
prefix of the given subject string (at position init
), not with an
arbitrary substring of the subject. So, if we want to find a pattern
anywhere in a string, we must either write a loop in Lua or write a
pattern that matches anywhere.
local pattern = lpeg.R('az') ^ 1 * -1
assert(pattern:match('hello') == 6)
assert(lpeg.match(pattern, 'hello') == 6)
assert(pattern:match('1 hello') == nil)
{pattern}
(vim.lpeg.Pattern|string|integer|boolean|table|function
)
{subject}
(string
)
{init}
(integer?
)
{...}
(any
)
any
) ...
{value}
) vim.lpeg.P()
Converts the given value into a proper pattern. The following rules are
applied:
n
, the result is a pattern
that matches exactly n
characters.
-n
, the result is a pattern that
succeeds only if the input string has less than n
characters left:
lpeg.P(-n)
is equivalent to -lpeg.P(n)
(see the unary minus
operation).
{value}
(vim.lpeg.Pattern|string|integer|boolean|table|function
)
vim.lpeg.Pattern
)
{...}
) vim.lpeg.R()
Returns a pattern that matches any single character belonging to one of
the given ranges. Each range
is a string xy
of length 2, representing
all characters with code between the codes of x
and y
(both
inclusive). As an example, the pattern lpeg.R('09')
matches any digit,
and lpeg.R('az', 'AZ')
matches any ASCII letter.
local pattern = lpeg.R('az') ^ 1 * -1
assert(pattern:match('hello') == 6)
{...}
(string
)
vim.lpeg.Pattern
)
{string}
) vim.lpeg.S()
Returns a pattern that matches any single character that appears in the
given string (the S
stands for Set). As an example, the pattern
lpeg.S('+-*/')
matches any arithmetic operator. Note that, if s
is a
character (that is, a string of length 1), then lpeg.P(s)
is equivalent
to lpeg.S(s)
which is equivalent to lpeg.R(s..s)
. Note also that both
lpeg.S('')
and lpeg.R()
are patterns that always fail.
{string}
(string
)
vim.lpeg.Pattern
)
{max}
) vim.lpeg.setmaxstack()
Sets a limit for the size of the backtrack stack used by LPeg to track
calls and choices. The default limit is 400
. Most well-written patterns
need little backtrack levels and therefore you seldom need to change this
limit; before changing it you should try to rewrite your pattern to avoid
the need for extra space. Nevertheless, a few useful patterns may
overflow. Also, with recursive grammars, subjects with deep recursion may
also need larger limits.
{max}
(integer
)
{value}
) vim.lpeg.type()
Returns the string "pattern"
if the given value is a pattern, otherwise
nil
.
{value}
(vim.lpeg.Pattern|string|integer|boolean|table|function
)
"pattern"?
)
{v}
) vim.lpeg.V()
Creates a non-terminal (a variable) for a grammar. This operation creates
a non-terminal (a variable) for a grammar. The created non-terminal refers
to the rule indexed by v
in the enclosing grammar.
local b = lpeg.P({'(' * ((1 - lpeg.S '()') + lpeg.V(1)) ^ 0 * ')'})
assert(b:match('((string))') == 11)
assert(b:match('(') == nil)
{v}
(boolean|string|number|function|table|thread|userdata|lightuserdata
)
vim.lpeg.Pattern
)
vim.lpeg.version()
Returns a string with the running version of LPeg.
string
)
vim.re
module provides a conventional regex-like syntax for pattern
usage within LPeg vim.lpeg. (Unrelated to vim.regex which provides Vim
regexp from Lua.)
{string}
, {defs}
) vim.re.compile()
Compiles the given {string}
and returns an equivalent LPeg pattern. The
given string may define either an expression or a grammar. The optional
{defs}
table provides extra Lua values to be used by the pattern.
{string}
(string
)
{defs}
(table?
)
vim.lpeg.Pattern
)
{subject}
, {pattern}
, {init}
) vim.re.find()
Searches the given {pattern}
in the given {subject}
. If it finds a match,
returns the index where this occurrence starts and the index where it
ends. Otherwise, returns nil.
{init}
makes the search starts at that
position in the subject string. As usual in Lua libraries, a negative
value counts from the end.
{subject}
(string
)
{pattern}
(vim.lpeg.Pattern|string
)
{init}
(integer?
)
integer?
) the index where the occurrence starts, nil if no match
(integer?
) the index where the occurrence ends, nil if no match
{subject}
, {pattern}
, {replacement}
) vim.re.gsub()
Does a global substitution, replacing all occurrences of {pattern}
in the
given {subject}
by {replacement}
.
{subject}
(string
)
{pattern}
(vim.lpeg.Pattern|string
)
{replacement}
(string
)
string
)
{subject}
, {pattern}
, {init}
) vim.re.match()
Matches the given {pattern}
against the given {subject}
, returning all
captures.
{subject}
(string
)
{pattern}
(vim.lpeg.Pattern|string
)
{init}
(integer?
)
integer|vim.lpeg.Capture?
)
vim.re.updatelocale()
Updates the pre-defined character classes to the current locale.
regex:match_line()
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}
.
{bufnr}
(integer
)
{line_idx}
(integer
)
{start}
(integer?
)
{end_}
(integer?
)
{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.
{str}
(string
)
{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.
{re}
(string
)
vim.regex
)
{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.
{path}
(string
) Path to a file to read.
string?
) The contents of the given file if it exists and is
trusted, or nil otherwise.
{opts}
) vim.secure.trust()
Manage the trust database.
{opts}
(table
) A table with the following fields:
{action}
('allow'|'deny'|'remove'
) - 'allow'
to add a
file to the trust database and trust it,
'deny'
to add a file to the trust database and deny it,
'remove'
to remove file from the trust database
{path}
(string
) Path to a file to update. Mutually
exclusive with {bufnr}
. Cannot be used when {action}
is
"allow".
{bufnr}
(integer
) Buffer number to update. Mutually
exclusive with {path}
.
boolean
) success true if operation was successful
(string
) msg full path if operation was successful, else error
message
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.
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.
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
{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}
).
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
{v1}
(vim.Version|number[]|string
) Version object.
{v2}
(vim.Version|number[]|string
) Version to compare with v1
.
integer
) -1 if v1 < v2
, 0 if v1 == v2
, 1 if v1 > v2
.
{v1}
, {v2}
) vim.version.eq()
Returns true
if the given versions are equal. See vim.version.cmp()
for usage.
{v1}
(vim.Version|number[]|string
)
{v2}
(vim.Version|number[]|string
)
boolean
)
{v1}
, {v2}
) vim.version.ge()
Returns true
if v1 >= v2
. See vim.version.cmp() for usage.
{v1}
(vim.Version|number[]|string
)
{v2}
(vim.Version|number[]|string
)
boolean
)
{v1}
, {v2}
) vim.version.gt()
Returns true
if v1 > v2
. See vim.version.cmp() for usage.
{v1}
(vim.Version|number[]|string
)
{v2}
(vim.Version|number[]|string
)
boolean
)
{versions}
) vim.version.last()
TODO: generalize this, move to func.lua
{versions}
(vim.Version[]
)
vim.Version?
)
{v1}
, {v2}
) vim.version.le()
Returns true
if v1 <= v2
. See vim.version.cmp() for usage.
{v1}
(vim.Version|number[]|string
)
{v2}
(vim.Version|number[]|string
)
boolean
)
{v1}
, {v2}
) vim.version.lt()
Returns true
if v1 < v2
. See vim.version.cmp() for usage.
{v1}
(vim.Version|number[]|string
)
{v2}
(vim.Version|number[]|string
)
boolean
)
{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" }
{version}
(string
) Version string to parse.
{opts}
(table?
) Optional keyword arguments:
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.
vim.Version?
) parsed_version Version object or nil
if input is
invalid.
{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
).
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
.to
and .from
directly:local r = vim.version.range('1.0.0 - 2.0.0') -- >=1.0, <2.0
print(vim.version.ge({1,0,3}, r.from) and vim.version.lt({1,0,3}, r.to))
{spec}
(string
) Version range "spec"
table?
) A table with the following fields:
{from}
(vim.Version
)
{to}
(vim.Version
)
vim.iter()
is an interface for iterables: 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()
:
vim.iter(ipairs(…))
.
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()).
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" }
{pred}
) Iter:all()
Returns true if all items in the iterator match the given predicate.
{pred}
(fun(...):boolean
) Predicate function. Takes all values
returned from the previous stage in the pipeline as arguments
and returns true if the predicate matches.
{pred}
) Iter:any()
Returns true if any of the items in the iterator match the given
predicate.
{pred}
(fun(...):boolean
) Predicate function. Takes all values
returned from the previous stage in the pipeline as arguments
and returns true if the predicate matches.
{f}
) Iter:each()
Calls a function once for each item in the pipeline, draining the
iterator.
{f}
(fun(...)
) 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()
Yields the item index (count) and value for each item of an iterator
pipeline.
vim.iter(ipairs(t))
vim.iter(t):enumerate()
local it = vim.iter(vim.gsplit('abc', '')):enumerate()
it:next()
-- 1 'a'
it:next()
-- 2 'b'
it:next()
-- 3 'c'
Iter
)
{f}
) Iter:filter()
Filters an iterator pipeline.
local bufs = vim.iter(vim.api.nvim_list_bufs()):filter(vim.api.nvim_buf_is_loaded)
{f}
(fun(...):boolean
) Takes all values returned from the previous
stage in the pipeline and returns false or nil if the current
iterator element should be removed.
Iter
)
{f}
) Iter:find()
Find the first value in the iterator that satisfies the given predicate.
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
{f}
(any
)
any
)
{depth}
) Iter:flatten()
Flattens a list-iterator, un-nesting nested values up to the given
{depth}
. Errors if it attempts to flatten a dict-like value.
vim.iter({ 1, { 2 }, { { 3 } } }):flatten():totable()
-- { 1, 2, { 3 } }
vim.iter({1, { { a = 2 } }, { 3 } }):flatten():totable()
-- { 1, { a = 2 }, 3 }
vim.iter({ 1, { { a = 2 } }, { 3 } }):flatten(math.huge):totable()
-- error: attempt to flatten a dict-like table
Iter
)
-- Create a new table with only even values
vim.iter({ a = 1, b = 2, c = 3, d = 4 })
:filter(function(k, v) return v % 2 == 0 end)
:fold({}, function(acc, k, v)
acc[k] = v
return acc
end) --> { b = 2, d = 4 }
-- Get the "maximum" item of an iterable.
vim.iter({ -99, -4, 3, 42, 0, 0, 7 })
:fold({}, function(acc, v)
acc.max = math.max(v, acc.max or v)
return acc
end) --> { max = 42 }
{init}
(any
) Initial value of the accumulator.
{f}
(fun(acc:A, ...):A
) Accumulation function.
any
)
{delim}
) Iter:join()
Collect the iterator into a delimited string.
{delim}
.
{delim}
(string
) Delimiter
string
)
Iter:last()
Drains the iterator and returns the last item.
local it = vim.iter(vim.gsplit('abcdefg', ''))
it:last()
-- 'g'
local it = vim.iter({ 3, 6, 9, 12, 15 })
it:last()
-- 15
any
)
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 }
{f}
(fun(...):...: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.
Iter
)
Iter:next()
Gets the next value from the iterator.
local it = vim.iter(string.gmatch('1 2 3', '%d+')):map(tonumber)
it:next()
-- 1
it:next()
-- 2
it:next()
-- 3
any
)
{n}
) Iter:nth()
Gets the nth value of an iterator (and advances to it).
n
is negative, offsets from the end of a list-iterator.
local it = vim.iter({ 3, 6, 9, 12 })
it:nth(2)
-- 6
it:nth(2)
-- 12
local it2 = vim.iter({ 3, 6, 9, 12 })
it2:nth(-2)
-- 9
it2:nth(-2)
-- 3
any
)
Iter:peek()
Gets the next value in a list-iterator without consuming it.
local it = vim.iter({ 3, 6, 9, 12 })
it:peek()
-- 3
it:peek()
-- 3
it:next()
-- 3
any
)
Iter:pop()
"Pops" a value from a list-iterator (gets the last value and decrements
the tail).
local it = vim.iter({1, 2, 3, 4})
it:pop()
-- 4
it:pop()
-- 3
any
)
Iter:rev()
Reverses a list-iterator pipeline.
local it = vim.iter({ 3, 6, 9, 12 }):rev()
it:totable()
-- { 12, 9, 6, 3 }
Iter
)
{f}
) Iter:rfind()
Gets the first value satisfying a predicate, from the end of a
list-iterator.
local it = vim.iter({ 1, 2, 3, 2, 1 }):enumerate()
it:rfind(1)
-- 5 1
it:rfind(1)
-- 1 1
{f}
(any
)
any
)
Iter:rpeek()
Gets the last value of a list-iterator without consuming it.
local it = vim.iter({1, 2, 3, 4})
it:rpeek()
-- 4
it:rpeek()
-- 4
it:pop()
-- 4
any
)
local it = vim.iter({ 1, 2, 3, 4, 5 }):rskip(2)
it:next()
-- 1
it:pop()
-- 3
{n}
(number
) Number of values to skip.
Iter
)
local it = vim.iter({ 3, 6, 9, 12 }):skip(2)
it:next()
-- 9
{n}
(number
) Number of values to skip.
Iter
)
:skip(first - 1):rskip(len - last + 1)
.
{first}
(number
)
{last}
(number
)
Iter
)
{n}
) Iter:take()
Transforms an iterator to yield only the first n values.
local it = vim.iter({ 1, 2, 3, 4 }):take(2)
it:next()
-- 1
it:next()
-- 2
it:next()
-- nil
{n}
(integer
)
Iter
)
Iter:totable()
Collect the iterator into a table.
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 } }
table
)
{direction}
(vim.snippet.Direction
) Navigation direction. -1 for
previous, 1 for next.
{filter}
) vim.snippet.active()
Returns true
if there's an active snippet in the current buffer,
applying the given filter if provided.
vim.keymap.set({ 'i', 's' }, '<Tab>', function()
if vim.snippet.active({ direction = 1 }) then
return '<Cmd>lua vim.snippet.jump(1)<CR>'
else
return '<Tab>'
end
end, { expr = true })
{filter}
(vim.snippet.ActiveFilter?
) Filter to constrain the search
with:
direction
(vim.snippet.Direction): Navigation direction.
Will return true
if the snippet can be jumped in the
given direction. See vim.snippet.ActiveFilter.
boolean
)
{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.
{input}
(string
)
{direction}
) vim.snippet.jump()
Jumps to the next (or previous) placeholder in the current snippet, if
possible.
<Tab>
to jump while a snippet is active:vim.keymap.set({ 'i', 's' }, '<Tab>', function()
if vim.snippet.active({ direction = 1 }) then
return '<Cmd>lua vim.snippet.jump(1)<CR>'
else
return '<Tab>'
end
end, { expr = true })
{direction}
(vim.snippet.Direction
) Navigation direction. -1 for
previous, 1 for next.
vim.snippet.stop()
Exits the current snippet.
{enc}
) vim.text.hexdecode()
Hex decode a string.
{enc}
(string
) String to decode
string?
) Decoded string
(string?
) Error message, if any
{str}
) vim.text.hexencode()
Hex encode a string.
{str}
(string
) String to encode
string
) Hex encoded string
{file}
:TOhtml
Converts the buffer shown in the current window to HTML, opens the generated
HTML in a new split window, and saves its contents to {file}
. If {file}
is not
given, a temporary file (created by tempname()) is used.
{winid}
, {opt}
) tohtml.tohtml.tohtml()
Converts the buffer shown in the window {winid}
to HTML and returns the
output as a list of string.
{winid}
(integer?
) Window to convert (defaults to current window)
{opt}
(table?
) Optional parameters.
{title}
(string|false
, default: buffer name) Title tag
to set in the generated HTML code.
{number_lines}
(boolean
, default: false
) Show line
numbers.
{font}
(string[]|string
, default: guifont
) Fonts to
use.
{width}
(integer
, default: 'textwidth' if non-zero or
window width otherwise) Width used for items which are
either right aligned or repeat a character infinitely.
{range}
(integer[]
, default: entire buffer) Range of
rows to use.
string[]
)