Nvim :help
pages, generated
from source
using the tree-sitter-vimdoc parser.
:lua print(vim.inspect(package.loaded))
Nvim includes a "standard library" lua-stdlib for Lua. It complements the
"editor stdlib" (builtin-functions andEx-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 need only consider
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
Neovim 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: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.
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"
(where your modules are found: package.cpath).
lua-call-function
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
. Example: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: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" }
func_with_opts({ foo = true, filename = "hello.world" })
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 on require()
, see luaref-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
or :=expr
is
equivalent to :lua print(vim.inspect(expr))
.
:lua vim.api.nvim_command('echo "Hello, Nvim!"')
:lua print(_VERSION)
:lua =jit.version
: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 tolet-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("Current 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
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.
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 print(vim.inspect(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.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::lua print(vim.inspect(vim.loop))
vim.loop
wraps the "luv" Lua bindings for the LibUV library;
see luv-intro for a full reference manual.
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:local timer = vim.loop.new_timer()
timer:start(1000, 0, function()
vim.api.nvim_command('echomsg "test"')
end)
local timer = vim.loop.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.loop.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.loop.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>'))")
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.loop.new_tcp()
server:bind(host, port)
server:listen(128, function(err)
assert(not err, err) -- Check for errors.
local sock = vim.loop.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)
vim.loop.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.loop
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.
au TextYankPost * silent! lua vim.highlight.on_yank()
init.vim
. You can customize the highlight group and the duration of
the highlight via
au TextYankPost * silent! lua vim.highlight.on_yank {higroup="IncSearch", timeout=150}
au TextYankPost * silent! lua vim.highlight.on_yank {on_visual=false}
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)
{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:
inclusive
: range includes end position,
default false
priority
: priority of highlight, default
vim.highlight.user
(see below)
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()
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.
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.
{line_idx}
[, {start}
, {end}
]) regex:match_line()
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.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).
{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}
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:
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:
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.
{opts.result_type}
. nil if {opts.on_hunk}
is given.
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
Encodes (or "packs") Lua object {obj}
as msgpack in a Lua string.
vim.mpack.decode
Decodes (or "unpacks") the msgpack-encoded {str}
to a Lua object.
vim.json
module provides encoding and decoding of Lua objects to and
from JSON-encoded strings. Supports vim.NIL and vim.empty_dict().
vim.json.encode
Encodes (or "packs") Lua object {obj}
as JSON in a Lua string.
{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
.
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 to spell check.
{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.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
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.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.
{method}
[, {args}
...]) vim.rpcnotify()
Sends {event}
to {channel}
via RPC and returns immediately. If {channel}
is 0, the event is broadcast to all channels.
{method}
[, {args}
...]) vim.rpcrequest()
Sends a request to {channel}
to invoke {method}
via RPC and blocks until
a response is received.
{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.
{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.
{index}
in the middle of a UTF-8 sequence is rounded upwards to the end of
that sequence.
{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.
{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".
{str}
(string) Text to convert
{from}
(string) Encoding of {str}
{to}
(string) Target encoding
nil
otherwise.
vim.schedule()
Schedules {callback}
to be invoked soon by the main event-loop. Useful
to avoid textlock or other temporary restrictions.
{timeout}
) vim.defer_fn
Defers calling {fn}
until {timeout}
ms passes. Use to do a one-shot timer
that calls {fn}
.
{fn}
is vim.schedule_wrap()ped automatically, so API functions are
safe to call.
{fn}
Callback to call once {timeout}
expires
{timeout}
Time in ms to wait before calling {fn}
{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.
{time}
Number of milliseconds to wait
{callback}
Optional callback. Waits until {callback}
returns true
{interval}
(Approximate) number of milliseconds to wait between polls
{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.
---
-- 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
{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)
vim.ui_detach({ns}) vim.ui_detach()
Detach a callback previously attached with vim.ui_attach() for the
given namespace {ns}
.
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.call()
Invokes vim-function or user-function {func}
with arguments {...}
.
See also vim.fn.
Equivalent to:vim.fn[func]({...})
vim.cmd({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.
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:vim.env.FOO = 'bar'
print(vim.env.TERM)
set number
Lua: vim.o.number = true
set wildignore=*.o,*.a,__pycache__
Lua: vim.o.wildignore = '*.o,*.a,__pycache__'
vim.o.cmdheight = 4
print(vim.o.columns)
print(vim.o.foo) -- error: invalid key
vim.go.cmdheight = 4
print(vim.go.columns)
print(vim.go.bar) -- error: invalid key
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.
:set
and :setlocal
.
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
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.
:setlocal
) instead use:nvim_get_option_value(OPTION, { scope = 'local', win = winid })
nvim_set_option_value(OPTION, VALUE, { scope = 'local', win = winid }
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
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.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
vim.opt.formatoptions:append('j')
vim.opt.formatoptions = vim.opt.formatoptions + 'j'
vim.opt.wildignore:prepend('*.o')
vim.opt.wildignore = vim.opt.wildignore ^ '*.o'
vim.opt.wildignore:remove('*.pyc')
vim.opt.wildignore = vim.opt.wildignore - '*.pyc'
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
vim.deprecate()
deprecate({name}
, {alternative}
, {version}
, {plugin}
, {backtrace}
)
Shows a deprecation message to the user.
{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.
{object}
, {options}
) vim.inspect()
Gets a human-readable representation of the given object.
local k = vim.keycode
vim.g.mapleader = k'<bs>'
{str}
string String to be converted.
{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.
{msg}
(string) Content of the notification to show to the user.
{level}
(integer|nil) One of the values from vim.log.levels.
{opts}
(table|nil) Optional parameters. Unused by default.
{msg}
(string) Content of the notification to show to the user.
{level}
(integer|nil) One of the values from vim.log.levels.
{opts}
(table|nil) Optional parameters. Unused by default.
{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}
will not be cleared by nvim_buf_clear_namespace()
{fn}
will receive the keys after mappings have been evaluated
{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}
integer? Namespace ID. If nil or 0, generates and returns a
new nvim_create_namespace() id.
{fn}
. Or count of all callbacks
if on_key() is called without arguments.
{fn}
will be removed if an error occurs while calling.
{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}
paste_phase -1: "non-streaming" paste: the call contains all
lines. If paste is "streamed", phase
indicates the stream state:
local hl_normal = vim.print(vim.api.nvim_get_hl_by_name('Normal', true))
{bufnr}
, {pos1}
, {pos2}
, {regtype}
, {inclusive}
) vim.region()
Get a table of lines with start, end columns for a region marked by two
points. Input and output positions are (0,0)-indexed and indicate byte
positions.
{bufnr}
(integer) number of buffer
{pos1}
integer[]|string start of region as a (line, column)
tuple or string accepted by getpos()
{pos2}
integer[]|string end of region as a (line, column) tuple
or string accepted by getpos()
{regtype}
(string) type of selection, see setreg()
{inclusive}
(boolean) indicating whether column of pos2 is inclusive
{linenr = {startcol,endcol}}
.
endcol
is exclusive, and whole lines are marked with
{startcol,endcol} = {0,-1}
.
{cb}
(function)
{bufnr}
, {row}
, {col}
, {filter}
) vim.inspect_pos()
Get all the items at a given buffer position.
{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
all
,
then extmarks without a hl_group
will also be included
(defaults to true)
{bufnr}
, {row}
, {col}
, {filter}
) vim.show_pos()
Show all the items at a given buffer position.
{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()
eq
metamethod. All other types are compared using the equality ==
operator.
{a}
any First value
{b}
any Second value
true
if values are equals, else false
{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
the same functions as those in the input table. Userdata and threads are
not copied and will throw an error.
{orig}
(table) Table to copy
{create}
) vim.defaulttable()
Creates a table whose members are automatically created when accessed, if
they don't already exist.
{create}
is nil
, this will create a defaulttable whose constructor
function is this function, effectively allowing to create nested tables on
the fly:
local a = vim.defaulttable()
a.b.c = 1
{create}
function?(key:any):any The function called to create a
missing value.
{s}
(string) String
{suffix}
(string) Suffix to match
true
if suffix
is a suffix of s
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
{opts}
(table|nil) Keyword arguments kwargs:
sep
literally (as in string.find).
{f}
any Any object
true
if f
is callable, 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
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|nil) Start index on src. Defaults to 1
{finish}
(integer|nil) Final index on src. Defaults to #src
{list}
, {start}
, {finish}
) vim.list_slice()
Creates a copy of a table containing only elements from start to end
(inclusive)
{list}
(list) Table
{start}
(integer|nil) Start range of slice
{finish}
(integer|nil) End range of slice
{s}
(string) String to escape
{t}
(table) List-like table
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
{s}
(string) String
{prefix}
(string) Prefix to match
true
if prefix
is a prefix of s
{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 }
{o}
(table) Table to add the reverse to
{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
{opts}
(table|nil) Keyword arguments kwargs:
value
is a function reference to be
checked (default false)
true
if t
contains value
vim.tbl_count({ a=1, b=2 }) --> 2
vim.tbl_count({ 1, 2 }) --> 2
{t}
(table) Table
{behavior}
(string) Decides what to do if a key is found in more than
one map:
{...}
(table) Two or more tables
{behavior}
(string) Decides what to do if a key is found in more than
one map:
{...}
(table) Two or more tables
{func}
(function) Function
{t}
(table) Table
{t}
) vim.tbl_flatten()
Creates a copy of a list-like table such that any nested tables are
"unrolled" and appended to the result.
{t}
(table) List-like table
{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
{...}
(string) Optional strings (0 or more, variadic) via which to
index the table
{t}
) vim.tbl_isarray()
Tests if a Lua table can be treated as an array (a table indexed by
integers).
{}
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.
{t}
(table)
true
if array-like table, else false
.
{t}
(table) Table to check
true
if t
is empty
{t}
) vim.tbl_islist()
Tests if a Lua table can be treated as a list (a table indexed by
consecutive integers starting from 1).
{}
is assumed to be an 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)
true
if list-like table, else false
.
{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
{func}
(function) Function
{t}
(table) Table
{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
{s}
(string) String to trim
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
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|nil) Options for finding a module:
true
)
{}
)
{"/init.lua", ".lua"}
)
false
)
modname="*"
{path}
string? path to reset
{bufnr}
(integer)
{path}
(string) Path to file
{uri}
) vim.uri_to_bufnr()
Get the buffer for a uri. Creates a new unloaded buffer if no buffer for
the uri already exists.
{uri}
(string)
{uri}
(string)
{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)
{opts}
(table) Additional options. See input()
{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.
{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}
(table) 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}
(function) ((item|nil, idx|nil) -> ()) Called once the
user made a choice. idx
is the 1-based index of item
within items
. nil
if the user aborted the dialog.
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 = {
['.*'] = {
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,
},
},
}
{filetypes}
(table) A table containing new filetype maps (see
example).
{filetype}
, {option}
) vim.filetype.get_option()
Get the default option value for a {filetype}
.
vim.filetype.get_option('vim', 'commentstring')
{filetype}
string Filetype
{option}
string Option name
-- 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:
{contents}
{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.
{filename}
.
Mutually exclusive with {buf}
.
{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 })
{opts}
(table|nil) A table of optional arguments:
{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|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 be
a Lua function.
{opts}
(table|nil) Table of :map-arguments.
{opts}
, except:
true
if "expr" is true
.
0
or true
for current buffer.
false
.
{file}
(string) File or directory
{file}
{path}
, {opts}
) vim.fs.dir()
Return an iterator over the files and directories located in {path}
{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:
{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".
{file}
(string) File or directory
{file}
{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.
-- location of Cargo.toml from the current buffer's path
local cargo = vim.fs.find('Cargo.toml', {
upward = true,
stop = vim.loop.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'})
{names}
(string|table|fun(name: string, path: string): boolean) Names
of the files and directories 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 file and directory with args:
true
if the given file or directory is considered
a match.
{opts}
(table) Optional keyword arguments:
{names}
are included.
math.huge
to place no limit on the
number of matches.
{...}
) vim.fs.joinpath()
Concatenate directories and/or file into a single path with normalization
(e.g., "foo/"
and "bar"
get joined to "foo/bar"
)
{...}
(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 any
backslash (\) characters are converted to forward slashes (/). Environment
variables are also expanded.
vim.fs.normalize('C:\\Users\\jdoe')
--> 'C:/Users/jdoe'
vim.fs.normalize('~/src/neovim')
--> '/home/jdoe/src/neovim'
vim.fs.normalize('$XDG_CONFIG_HOME/nvim/init.vim')
--> '/Users/jdoe/.config/nvim/init.vim'
{path}
(string) Path to normalize
{opts}
(table|nil) Options:
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 file or directory.
{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.
{opts}
(table)
{bufnr}
. Cannot be used when {action}
is
"allow".
{path}
.
vim.version
module provides functions for comparing versions and
ranges conforming to the
local v = vim.version.parse(vim.fn.system({'tmux', '-V'}), {strict=false})
if vim.version.gt(v, {3, 2, 0}) then
-- ...
end
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}
Version|number[] Version object.
{v2}
Version|number[] Version to compare with v1
.
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}
Version|number[]
{v2}
Version|number[]
{v1}
Version|number[]
{v2}
Version|number[]
{versions}
Version []
{v1}
Version|number[]
{v2}
Version|number[]
{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|nil) 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.
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
). Example: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
.to
and .from
directly: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))
{spec}
string Version range "spec"
vim.iter()
wraps its 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 together to create
iterator "pipelines". Each pipeline stage receives as input the output
values from the prior stage. The values used in the first stage of the
pipeline depend on the type passed to this function:
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 }
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
vim.iter(src):filter(f):totable()
{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
{pred}
) Iter:all()
Return true if all of the items in the iterator match the given predicate.
{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.
{pred}
) Iter:any()
Return true if any of the items in the iterator match the given predicate.
{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.
{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()
Add an iterator stage that returns the current iterator count as well as
the iterator value.
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'
local bufs = vim.iter(vim.api.nvim_list_bufs()):filter(vim.api.nvim_buf_is_loaded)
{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.
{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
-- 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 }
{init}
any Initial value of the accumulator.
{f}
function(acc:any, ...):A Accumulation function.
local it = vim.iter(vim.gsplit('abcdefg', ''))
it:last()
-- 'g'
local it = vim.iter({ 3, 6, 9, 12, 15 })
it:last()
-- 15
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}
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.
local it = vim.iter(string.gmatch('1 2 3', 'd+')):map(tonumber)
it:next()
-- 1
it:next()
-- 2
it:next()
-- 3
local it = vim.iter({1, 2, 3, 4})
it:nextback()
-- 4
it:nextback()
-- 3
local it = vim.iter({ 3, 6, 9, 12 })
it:nth(2)
-- 6
it:nth(2)
-- 12
{n}
(number) The index of the value to return.
local it = vim.iter({ 3, 6, 9, 12 })
it:nthback(2)
-- 9
it:nthback(2)
-- 3
{n}
(number) The index of the value to return.
local it = vim.iter({ 3, 6, 9, 12 })
it:peek()
-- 3
it:peek()
-- 3
it:next()
-- 3
Iter:peekback()
Return the next value from the end of the iterator without consuming it.
local it = vim.iter({1, 2, 3, 4})
it:peekback()
-- 4
it:peekback()
-- 4
it:nextback()
-- 4
local it = vim.iter({ 3, 6, 9, 12 }):rev()
it:totable()
-- { 12, 9, 6, 3 }
{f}
) Iter:rfind()
Find the first value in the iterator that satisfies the given predicate,
starting from the end.
local it = vim.iter({ 1, 2, 3, 2, 1 }):enumerate()
it:rfind(1)
-- 5 1
it:rfind(1)
-- 1 1
local it = vim.iter({ 3, 6, 9, 12 }):skip(2)
it:next()
-- 9
{n}
(number) Number of values to skip.
local it = vim.iter({ 1, 2, 3, 4, 5 }):skipback(2)
it:next()
-- 1
it:nextback()
-- 3
{n}
(number) Number of values to skip.
{first}
, {last}
) Iter:slice()
Slice an iterator, changing its start and end positions.
{first}
(number)
{last}
(number)
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 } }
vim.iter(src):map(f):totable()
{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
vim.iter(f):totable()
{f}
(function) Iterator function