aboutsummaryrefslogtreecommitdiff
path: root/runtime/doc/lua.txt
diff options
context:
space:
mode:
authorJosh Rahm <rahm@google.com>2022-10-11 19:00:52 +0000
committerJosh Rahm <rahm@google.com>2022-10-11 19:00:52 +0000
commit21e2e46242033c7aaa6ccfb23e256680816c063c (patch)
treef089522cfb145d6e9c8a86a01d8e454ce5501e20 /runtime/doc/lua.txt
parent179d3ed87b17988f5fe00d8b99f2611a28212be7 (diff)
parent760b399f6c0c6470daa0663752bd22886997f9e6 (diff)
downloadrneovim-floattitle.tar.gz
rneovim-floattitle.tar.bz2
rneovim-floattitle.zip
Merge remote-tracking branch 'upstream/master' into floattitlefloattitle
Diffstat (limited to 'runtime/doc/lua.txt')
-rw-r--r--runtime/doc/lua.txt942
1 files changed, 494 insertions, 448 deletions
diff --git a/runtime/doc/lua.txt b/runtime/doc/lua.txt
index 42f3a5e432..7330453778 100644
--- a/runtime/doc/lua.txt
+++ b/runtime/doc/lua.txt
@@ -11,30 +11,126 @@ Lua engine *lua* *Lua*
==============================================================================
INTRODUCTION *lua-intro*
-The Lua 5.1 language is builtin and always available. Try this command to get
-an idea of what lurks beneath: >
+The Lua 5.1 script engine is builtin and always available. Try this command to
+get an idea of what lurks beneath: >
:lua print(vim.inspect(package.loaded))
+
+Nvim includes a "standard library" |lua-stdlib| for Lua. It complements the
+"editor stdlib" (|builtin-functions| and |Ex-commands|) and the |API|, all of
+which can be used from Lua code (|lua-vimscript| |vim.api|). Together these
+"namespaces" form the Nvim programming interface.
+
+The |:source| and |:runtime| commands can run Lua scripts. Lua modules can be
+loaded with `require('name')`, which by convention usually returns a table.
+See |lua-require| for how Nvim finds and loads Lua modules.
+
+See this page for more insight into Nvim Lua:
+ https://github.com/nanotee/nvim-lua-guide
+
+ *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 CONCEPTS AND IDIOMS *lua-concepts*
+
+Lua is very simple: this means that, while there are some quirks, once you
+internalize those quirks, everything works the same everywhere. Scopes
+(closures) in particular are very consistent, unlike JavaScript or most other
+languages.
+
+Lua has three fundamental mechanisms—one for "each major aspect of
+programming": tables, closures, and coroutines.
+https://www.lua.org/doc/cacm2018.pdf
+- Tables are the "object" or container datastructure: they represent both
+ lists and maps, you can extend them to represent your own datatypes and
+ change their behavior using |luaref-metatable| (like Python's "datamodel").
+- EVERY scope in Lua is a closure: a function is a closure, a module is
+ a closure, a `do` block (|luaref-do|) is a closure--and they all work the
+ same. A Lua module is literally just a big closure discovered on the "path"
+ (where your modules are found: |package.cpath|).
+- Stackful coroutines enable cooperative multithreading, generators, and
+ versatile control for both Lua and its host (Nvim).
+
+ *lua-call-function*
+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.
+
+It is also allowed to omit the parentheses (only) if the function takes
+exactly one string (`"foo"`) or table literal (`{1,2,3}`). The latter is often
+used to approximate the "named parameters" feature of languages like Python
+("kwargs" or "keyword args"). 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" }
<
-Nvim includes a "standard library" |lua-stdlib| for Lua. It complements the
-"editor stdlib" (|builtin-functions| and Ex commands) and the |API|, all of
-which can be used from Lua code. A good overview of using Lua in neovim is
-given by https://github.com/nanotee/nvim-lua-guide.
+There is nothing special going on here except that parentheses are treated as
+whitespace. But visually, this small bit of sugar gets reasonably close to
+a "keyword args" interface.
-The |:source| and |:runtime| commands can run Lua scripts as well as Vim
-scripts. Lua modules can be loaded with `require('name')`, which
-conventionally returns a table but can return any value.
+It is of course also valid to call the function with parentheses: >
-See |lua-require| for details on how Nvim finds and loads Lua modules.
-See |lua-require-example| for an example of how to write and use a module.
+ func_with_opts({ foo = true, filename = "hello.world" })
+<
+Nvim tends to prefer the keyword args style.
+
+------------------------------------------------------------------------------
+LUA PATTERNS *lua-patterns*
+
+Lua intentionally does not support regular expressions, instead it has limited
+"patterns" which avoid the performance pitfalls of extended regex.
+|luaref-patterns|
+
+Examples using |string.match()|: >
+
+ 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
+
+For more complex matching you can use Vim regex from Lua via |vim.regex()|.
==============================================================================
IMPORTING LUA MODULES *lua-require*
Modules are searched for under the directories specified in 'runtimepath', in
-the order they appear. Any `.` in the module name is treated as a directory
-separator when searching. For a module `foo.bar`, each directory is searched
-for `lua/foo/bar.lua`, then `lua/foo/bar/init.lua`. If no files are found,
+the order they appear. Any "." in the module name is treated as a directory
+separator when searching. For a module `foo.bar`, each directory is searched
+for `lua/foo/bar.lua`, then `lua/foo/bar/init.lua`. If no files are found,
the directories are searched again for a shared library with a name matching
`lua/foo/bar.?`, where `?` is a list of suffixes (such as `so` or `dll`) derived from
the initial value of |package.cpath|. If still no files are found, Nvim falls
@@ -48,8 +144,7 @@ documentation at https://www.lua.org/manual/5.1/manual.html#pdf-require.
For example, if 'runtimepath' is `foo,bar` and |package.cpath| was
`./?.so;./?.dll` at startup, `require('mod')` searches these paths in order
-and loads the first module found:
-
+and loads the first module found ("first wins"): >
foo/lua/mod.lua
foo/lua/mod/init.lua
bar/lua/mod.lua
@@ -58,10 +153,11 @@ and loads the first module found:
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
+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`).
@@ -70,37 +166,33 @@ added to |package.cpath|. In this case, instead of appending `/lua/?.lua` and
`/lua/?/init.lua` to each runtimepath, all unique `?`-containing suffixes of
the existing |package.cpath| are used. Example:
-1. Given that
+- 1. Given that
- 'runtimepath' contains `/foo/bar,/xxx;yyy/baz,/abc`;
- - initial (defined at compile-time or derived from
- `$LUA_CPATH`/`$LUA_INIT`) |package.cpath| contains
- `./?.so;/def/ghi/a?d/j/g.elf;/def/?.so`.
-2. It finds `?`-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.
-3. The suffix of `/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.
-4. 'runtimepath' has three paths: `/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.
-5. The cartesian product of paths from 4. and suffixes from 3. is taken,
- giving four variants. In each variant, a `/lua` path segment is inserted
- between path and suffix, leaving:
-
- - `/foo/bar/lua/?.so`
- - `/foo/bar/lua/a?d/j/g.elf`
- - `/abc/lua/?.so`
- - `/abc/lua/a?d/j/g.elf`
-
-6. New paths are prepended to the original |package.cpath|.
-
-The result will look like this:
-
- `/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/?.so`
+ - initial |package.cpath| (defined at compile-time or derived from
+ `$LUA_CPATH` / `$LUA_INIT`) contains `./?.so;/def/ghi/a?d/j/g.elf;/def/?.so`.
+- 2. It finds `?`-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.
+- 3. The suffix of `/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.
+- 4. 'runtimepath' has three paths: `/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.
+- 5. The cartesian product of paths from 4. and suffixes from 3. is taken,
+ giving four variants. In each variant a `/lua` path segment is inserted
+ between path and suffix, leaving:
+ - `/foo/bar/lua/?.so`
+ - `/foo/bar/lua/a?d/j/g.elf`
+ - `/abc/lua/?.so`
+ - `/abc/lua/a?d/j/g.elf`
+- 6. New paths are prepended to the original |package.cpath|.
+
+The result will look like this: >
+
+ /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/?.so
Note:
@@ -122,170 +214,13 @@ Note:
it is better to not have them in 'runtimepath' at all.
==============================================================================
-Lua Syntax Information *lua-syntax-help*
-
-While Lua has a simple syntax, there are a few things to understand,
-particularly when looking at the documentation above.
-
- *lua-syntax-call-function*
-
-Lua functions can be called in multiple ways. Consider the function: >
-
- local example_func = function(a, b)
- print("A is: ", a)
- print("B is: ", b)
- end
-<
-The first way to call this function is: >
-
- example_func(1, 2)
- -- ==== Result ====
- -- A is: 1
- -- B is: 2
-<
-This way of calling a function is familiar from most scripting languages.
-In Lua, it's important to understand that any function arguments that are
-not supplied are automatically set to `nil`. For example: >
-
- example_func(1)
- -- ==== Result ====
- -- A is: 1
- -- B is: nil
-<
-Additionally, if any extra parameters are passed, they are discarded
-completely.
-
-In Lua, it is also possible to omit the parentheses (only) if the function
-takes a single string or table literal (`"foo"` or "`{1,2,3}`", respectively).
-The latter is most often used to approximate "keyword-style" arguments with a
-single dictionary, for 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" }
-<
-In this style, each "parameter" is passed via keyword. It is still valid
-to call the function in the standard style: >
-
- func_with_opts({ foo = true, filename = "hello.world" })
-<
-But often in the documentation, you will see the former rather than the
-latter style due to its brevity.
-
-==============================================================================
-Lua Patterns *lua-patterns*
-
-For performance reasons, Lua does not support regular expressions natively.
-Instead, the Lua `string` standard library allows manipulations using a
-restricted set of "patterns", see |luaref-patterns|.
-
-Examples (`string.match` extracts the first match): >
-
- 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
-
-For more complex matching, Vim regular expressions can be used from Lua
-through |vim.regex()|.
-
-------------------------------------------------------------------------------
-LUA PLUGIN EXAMPLE *lua-require-example*
-
-The following example plugin adds a command `:MakeCharBlob` which transforms
-current buffer into a long `unsigned char` array. Lua contains transformation
-function in a module `lua/charblob.lua` which is imported in
-`autoload/charblob.vim` (`require("charblob")`). Example plugin is supposed
-to be put into any directory from 'runtimepath', e.g. `~/.config/nvim` (in
-this case `lua/charblob.lua` means `~/.config/nvim/lua/charblob.lua`).
-
-autoload/charblob.vim: >
-
- function charblob#encode_buffer()
- call setline(1, luaeval(
- \ 'require("charblob").encode(unpack(_A))',
- \ [getline(1, '$'), &textwidth, ' ']))
- endfunction
-<
-plugin/charblob.vim: >
-
- if exists('g:charblob_loaded')
- finish
- endif
- let g:charblob_loaded = 1
-
- command MakeCharBlob :call charblob#encode_buffer()
-<
-lua/charblob.lua: >
-
- local function charblob_bytes_iter(lines)
- local init_s = {
- next_line_idx = 1,
- next_byte_idx = 1,
- lines = lines,
- }
- local function next(s, _)
- if lines[s.next_line_idx] == nil then
- return nil
- end
- if s.next_byte_idx > #(lines[s.next_line_idx]) then
- s.next_line_idx = s.next_line_idx + 1
- s.next_byte_idx = 1
- return ('\n'):byte()
- end
- local ret = lines[s.next_line_idx]:byte(s.next_byte_idx)
- if ret == ('\n'):byte() then
- ret = 0 -- See :h NL-used-for-NUL.
- end
- s.next_byte_idx = s.next_byte_idx + 1
- return ret
- end
- return next, init_s, nil
- end
-
- local function charblob_encode(lines, textwidth, indent)
- local ret = {
- 'const unsigned char blob[] = {',
- indent,
- }
- for byte in charblob_bytes_iter(lines) do
- -- .- space + number (width 3) + comma
- if #(ret[#ret]) + 5 > textwidth then
- ret[#ret + 1] = indent
- else
- ret[#ret] = ret[#ret] .. ' '
- end
- ret[#ret] = ret[#ret] .. (('%3u,'):format(byte))
- end
- ret[#ret + 1] = '};'
- return ret
- end
-
- return {
- bytes_iter = charblob_bytes_iter,
- encode = charblob_encode,
- }
-<
-==============================================================================
COMMANDS *lua-commands*
These commands execute a Lua chunk from either the command line (:lua, :luado)
or a file (:luafile) on the given line [range]. As always in Lua, each chunk
has its own scope (closure), so only global variables are shared between
command calls. The |lua-stdlib| modules, user modules, and anything else on
-|lua-package-path| are available.
+|package.path| are available.
The Lua print() function redirects its output to the Nvim message area, with
arguments separated by " " (space) instead of "\t" (tab).
@@ -339,7 +274,7 @@ arguments separated by " " (space) instead of "\t" (tab).
: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
+ :luado if bp:match(line) then return "=>\t" .. line end
<
*:luafile*
:luafile {file}
@@ -617,7 +552,7 @@ A subset of the `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 |lua-package-path|
+- `require` in threads can use lua packages from the global |package.path|
- `print()` and `vim.inspect`
- `vim.diff`
- most utility functions in `vim.*` for working with pure lua values
@@ -656,14 +591,14 @@ vim.highlight.range({bufnr}, {ns}, {hlgroup}, {start}, {finish}, {opts})
Apply highlight group to range of text.
Parameters: ~
- {bufnr} buffer number
- {ns} namespace for highlights
- {hlgroup} highlight group name
- {start} starting position (tuple {line,col})
- {finish} finish position (tuple {line,col})
- {opts} optional parameters:
+ • {bufnr} buffer number
+ • {ns} namespace for highlights
+ • {hlgroup} highlight group name
+ • {start} starting position (tuple {line,col})
+ • {finish} finish position (tuple {line,col})
+ • {opts} optional parameters:
• `regtype`: type of range (characterwise, linewise,
- or blockwise, see |setreg|), default `'v'`
+ or blockwise, see |setreg()|), default `'v'`
• `inclusive`: range includes end position,
default `false`
• `priority`: priority of highlight, default
@@ -714,22 +649,22 @@ vim.diff({a}, {b}, {opts}) *vim.diff()*
Examples: >
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}
}
<
Parameters: ~
- {a} First string to compare
- {b} Second string to compare
- {opts} Optional parameters:
+ • {a} First string to compare
+ • {b} Second string to compare
+ • {opts} Optional parameters:
• `on_hunk` (callback):
Invoked for each hunk in the diff. Return a negative number
to cancel the callback for any remaining hunks.
@@ -795,13 +730,13 @@ vim.spell.check({str}) *vim.spell.check()*
Example: >
vim.spell.check("the quik brown fox")
- -->
+ =>
{
{'quik', 'bad', 4}
}
<
Parameters: ~
- {str} String to spell check.
+ • {str} String to spell check.
Return: ~
List of tuples with three items:
@@ -881,6 +816,22 @@ vim.str_byteindex({str}, {index} [, {use_utf16}]) *vim.str_byteindex()*
An {index} in the middle of a UTF-16 sequence is rounded upwards to
the end of that sequence.
+vim.iconv({str}, {from}, {to}[, {opts}]) *vim.iconv()*
+ The result is a String, which is the text {str} converted from
+ encoding {from} to encoding {to}. When the conversion fails `nil` is
+ returned. When some characters could not be converted they
+ are replaced with "?".
+ The encoding names are whatever the iconv() library function
+ can accept, see ":Man 3 iconv".
+
+ Parameters: ~
+ • {str} (string) Text to convert
+ • {from} (string) Encoding of {str}
+ • {to} (string) Target encoding
+
+ Returns: ~
+ Converted string if conversion succeeds, `nil` otherwise.
+
vim.schedule({callback}) *vim.schedule()*
Schedules {callback} to be invoked soon by the main event-loop. Useful
to avoid |textlock| or other temporary restrictions.
@@ -890,12 +841,12 @@ vim.defer_fn({fn}, {timeout}) *vim.defer_fn*
Defers calling {fn} until {timeout} ms passes. Use to do a one-shot timer
that calls {fn}.
- Note: The {fn} is |schedule_wrap|ped automatically, so API functions are
+ Note: The {fn} is |vim.schedule_wrap()|ped automatically, so API functions are
safe to call.
Parameters: ~
- {fn} Callback to call once {timeout} expires
- {timeout} Time in ms to wait before calling {fn}
+ • {fn} Callback to call once {timeout} expires
+ • {timeout} Time in ms to wait before calling {fn}
Returns: ~
|vim.loop|.new_timer() object
@@ -908,10 +859,10 @@ vim.wait({time} [, {callback}, {interval}, {fast_only}]) *vim.wait()*
this time.
Parameters: ~
- {time} Number of milliseconds to wait
- {callback} Optional callback. Waits until {callback} returns true
- {interval} (Approximate) number of milliseconds to wait between polls
- {fast_only} If true, only |api-fast| events will be processed.
+ • {time} Number of milliseconds to wait
+ • {callback} Optional callback. Waits until {callback} returns true
+ • {interval} (Approximate) number of milliseconds to wait between polls
+ • {fast_only} If true, only |api-fast| events will be processed.
If called from while in an |api-fast| event, will
automatically be set to `true`.
@@ -951,6 +902,43 @@ vim.wait({time} [, {callback}, {interval}, {fast_only}]) *vim.wait()*
end
<
+vim.ui_attach({ns}, {options}, {callback}) *vim.ui_attach()*
+ Attach to ui events, similar to |nvim_ui_attach()| but receive events
+ as lua callback. Can be used to implement screen elements like
+ popupmenu or message handling in lua.
+
+ {options} should be a dictionary-like table, where `ext_...` options should
+ be set to true to receive events for the respective external element.
+
+ {callback} receives event name plus additional parameters. See |ui-popupmenu|
+ and the sections below for event format for respective events.
+
+ WARNING: This api is considered experimental. Usability will vary for
+ different screen elements. In particular `ext_messages` behavior is subject
+ to further changes and usability improvements. This is expected to be
+ used to handle messages when setting 'cmdheight' to zero (which is
+ likewise experimental).
+
+ Example (stub for a |ui-popupmenu| implementation): >
+
+ 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 *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
@@ -1000,6 +988,7 @@ LUA-VIMSCRIPT BRIDGE *lua-vimscript*
Nvim Lua provides an interface to Vimscript variables and functions, and
editor commands and options.
+
See also https://github.com/nanotee/nvim-lua-guide.
vim.call({func}, {...}) *vim.call()*
@@ -1043,6 +1032,20 @@ Example: >
vim.g.foo = nil -- Delete (:unlet) the Vimscript variable.
vim.b[2].foo = 6 -- Set b:foo for buffer 2
<
+
+Note that setting dictionary fields directly will not write them back into
+Nvim. This is because the index into the namespace simply returns a copy.
+Instead the whole dictionary must be written as one. This can be achieved by
+creating a short-lived temporary.
+
+Example: >
+
+ 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`.
@@ -1075,81 +1078,149 @@ vim.env *vim.env*
print(vim.env.TERM)
<
+ *lua-options*
*lua-vim-options*
- *lua-vim-opt*
*lua-vim-set*
- *lua-vim-optlocal*
*lua-vim-setlocal*
-In Vimscript, there is a way to set options |set-option|. In Lua, the
-corresponding method is `vim.opt`.
-
-`vim.opt` provides several conveniences for setting and controlling options
-from within Lua.
+Vim options can be accessed through |vim.o|, which behaves like Vimscript
+|:set|.
Examples: ~
To set a boolean toggle:
- In Vimscript:
- `set number`
+ Vimscript: `set number`
+ Lua: `vim.o.number = true`
+
+ To set a string value:
+ Vimscript: `set wildignore=*.o,*.a,__pycache__`
+ Lua: `vim.o.wildignore = '*.o,*.a,__pycache__'`
+
+Similarly, there is |vim.bo| and |vim.wo| for setting buffer-scoped and
+window-scoped options. Note that this must NOT be confused with
+|local-options| and |:setlocal|. There is also |vim.go| that only accesses the
+global value of a |global-local| option, see |:setglobal|.
+
+vim.o *vim.o*
+ Get or set |options|. Like `:set`. Invalid key is an error.
- In Lua:
- `vim.opt.number = true`
+ Note: this works on both buffer-scoped and window-scoped options using the
+ current buffer and window.
+
+ Example: >
+ vim.o.cmdheight = 4
+ print(vim.o.columns)
+ print(vim.o.foo) -- error: invalid key
+<
+vim.go *vim.go*
+ Get or set global |options|. Like `:setglobal`. Invalid key is
+ an error.
- To set an array of values:
+ Note: this is different from |vim.o| because this accesses the global
+ option value and thus is mostly useful for use with |global-local|
+ options.
+
+ Example: >
+ vim.go.cmdheight = 4
+ print(vim.go.columns)
+ print(vim.go.bar) -- error: invalid key
+<
+vim.bo[{bufnr}] *vim.bo*
+ Get or set buffer-scoped |options| for the buffer with number {bufnr}.
+ Like `:set` and `:setlocal`. If [{bufnr}] is omitted then the current
+ buffer is used. Invalid {bufnr} or key is an error.
+
+ Note: this is equivalent to both `:set` and `:setlocal`.
+
+ Example: >
+ local bufnr = vim.api.nvim_get_current_buf()
+ vim.bo[bufnr].buflisted = true -- same as vim.bo.buflisted = true
+ print(vim.bo.comments)
+ print(vim.bo.baz) -- error: invalid key
+<
+vim.wo[{winid}] *vim.wo*
+ Get or set window-scoped |options| for the window with handle {winid}.
+ Like `:set`. If [{winid}] is omitted then the current window is used.
+ Invalid {winid} or key is an error.
+
+ Note: this does not access |local-options| (`:setlocal`) instead use: >
+ nvim_get_option_value(OPTION, { scope = 'local', win = winid })
+ nvim_set_option_value(OPTION, VALUE, { scope = 'local', win = winid }
+<
+ Example: >
+ 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
+<
+
+
+
+ *lua-vim-opt*
+ *lua-vim-optlocal*
+ *lua-vim-optglobal*
+ *vim.opt*
+
+
+A special interface |vim.opt| exists for conveniently interacting with list-
+and map-style option from Lua: It allows accessing them as Lua tables and
+offers object-oriented method for adding and removing entries.
+
+ Examples: ~
+
+ The following methods of setting a list-style option are equivalent:
In Vimscript:
`set wildignore=*.o,*.a,__pycache__`
- In Lua, there are two ways you can do this now. One is very similar to
- the Vimscript form:
- `vim.opt.wildignore = '*.o,*.a,__pycache__'`
+ In Lua using `vim.o`:
+ `vim.o.wildignore = '*.o,*.a,__pycache__'`
- However, vim.opt also supports a more elegent way of setting
- list-style options by using lua tables:
+ In Lua using `vim.opt`:
`vim.opt.wildignore = { '*.o', '*.a', '__pycache__' }`
To replicate the behavior of |:set+=|, use: >
- -- vim.opt supports appending options via the "+" operator
- vim.opt.wildignore = vim.opt.wildignore + { "*.pyc", "node_modules" }
-
- -- or using the `:append(...)` method
vim.opt.wildignore:append { "*.pyc", "node_modules" }
<
To replicate the behavior of |:set^=|, use: >
- -- vim.opt supports prepending options via the "^" operator
- vim.opt.wildignore = vim.opt.wildignore ^ { "new_first_value" }
-
- -- or using the `:prepend(...)` method
vim.opt.wildignore:prepend { "new_first_value" }
<
To replicate the behavior of |:set-=|, use: >
- -- vim.opt supports removing options via the "-" operator
- vim.opt.wildignore = vim.opt.wildignore - { "node_modules" }
-
- -- or using the `:remove(...)` method
vim.opt.wildignore:remove { "node_modules" }
<
- To set a map of values:
+ The following methods of setting a map-style option are equivalent:
In Vimscript:
`set listchars=space:_,tab:>~`
- In Lua:
+ In Lua using `vim.o`:
+ `vim.o.listchars = 'space:_,tab:>~'`
+
+ In Lua using `vim.opt`:
`vim.opt.listchars = { space = '_', tab = '>~' }`
-In any of the above examples, to replicate the behavior |setlocal|, use
-`vim.opt_local`. Additionally, to replicate the behavior of |setglobal|, use
-`vim.opt_global`.
- *vim.opt*
+Note that |vim.opt| returns an `Option` object, not the value of the option,
+which is accessed through |vim.opt:get()|:
-|vim.opt| returns an Option object.
+ Examples: ~
-For example: `local listchar_object = vim.opt.listchars`
+ The following methods of getting a list-style option are equivalent:
+ In Vimscript:
+ `echo wildignore`
+
+ In Lua using `vim.o`:
+ `print(vim.o.wildignore)`
+
+ In Lua using `vim.opt`:
+ `vim.pretty_print(vim.opt.wildignore:get())`
+
+
+In any of the above examples, to replicate the behavior |:setlocal|, use
+`vim.opt_local`. Additionally, to replicate the behavior of |:setglobal|, use
+`vim.opt_global`.
-An `Option` has the following methods:
*vim.opt:get()*
@@ -1162,7 +1233,7 @@ Option:get()
the values as entries in the array: >
vim.cmd [[set wildignore=*.pyc,*.o]]
- print(vim.inspect(vim.opt.wildignore:get()))
+ vim.pretty_print(vim.opt.wildignore:get())
-- { "*.pyc", "*.o", }
for _, ignore_pattern in ipairs(vim.opt.wildignore:get()) do
@@ -1175,18 +1246,18 @@ Option:get()
the names as keys and the values as entries: >
vim.cmd [[set listchars=space:_,tab:>~]]
- print(vim.inspect(vim.opt.listchars:get()))
+ vim.pretty_print(vim.opt.listchars:get())
-- { space = "_", tab = ">~", }
for char, representation in pairs(vim.opt.listchars:get()) do
- print(char, "->", representation)
+ print(char, "=>", representation)
end
<
For values that are lists of flags, a set will be returned with the flags
as keys and `true` as entries. >
vim.cmd [[set formatoptions=njtcroql]]
- print(vim.inspect(vim.opt.formatoptions:get()))
+ vim.pretty_print(vim.opt.formatoptions:get())
-- { n = true, j = true, c = true, ... }
local format_opts = vim.opt.formatoptions:get()
@@ -1222,71 +1293,6 @@ Option:remove(value)
`vim.opt.wildignore = vim.opt.wildignore - '*.pyc'`
-In general, using `vim.opt` will provide the expected result when the user is
-used to interacting with editor |options| via `set`. There are still times
-where the user may want to set particular options via a shorthand in Lua,
-which is where |vim.o|, |vim.bo|, |vim.wo|, and |vim.go| come into play.
-
-The behavior of |vim.o|, |vim.bo|, |vim.wo|, and |vim.go| is designed to
-follow that of |:set|, |:setlocal|, and |:setglobal| which can be seen in the
-table below:
-
- lua command global_value local_value ~
-vim.o :set set set
-vim.bo/vim.wo :setlocal - set
-vim.go :setglobal set -
-
-vim.o *vim.o*
- Get or set editor options, like |:set|. Invalid key is an error.
-
- Example: >
- vim.o.cmdheight = 4
- print(vim.o.columns)
- print(vim.o.foo) -- error: invalid key
-<
-vim.go *vim.go*
- Get or set an |option|. Invalid key is an error.
-
- This is a wrapper around |nvim_set_option_value()| and
- |nvim_get_option_value()|.
-
- NOTE: This is different from |vim.o| because this ONLY sets the global
- option, which generally produces confusing behavior for options with
- |global-local| values.
-
- Example: >
- vim.go.cmdheight = 4
- print(vim.go.columns)
- print(vim.go.bar) -- error: invalid key
-<
-vim.bo[{bufnr}] *vim.bo*
- Get or set buffer-scoped |local-options| for the buffer with number {bufnr}.
- If [{bufnr}] is omitted, use the current buffer. Invalid {bufnr} or key is
- an error.
-
- This is a wrapper around |nvim_set_option_value()| and
- |nvim_get_option_value()| with `opts = {scope = local, buf = bufnr}` .
-
- Example: >
- local bufnr = vim.api.nvim_get_current_buf()
- vim.bo[bufnr].buflisted = true -- same as vim.bo.buflisted = true
- print(vim.bo.comments)
- print(vim.bo.baz) -- error: invalid key
-<
-vim.wo[{winid}] *vim.wo*
- Get or set window-scoped |local-options| for the window with handle {winid}.
- If [{winid}] is omitted, use the current window. Invalid {winid} or key
- is an error.
-
- This is a wrapper around |nvim_set_option_value()| and
- |nvim_get_option_value()| with `opts = {scope = local, win = winid}` .
-
- Example: >
- 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
-<
==============================================================================
Lua module: vim *lua-vim*
@@ -1325,7 +1331,7 @@ cmd({command}) *vim.cmd()*
<
Parameters: ~
- {command} string|table Command(s) to execute. If a string, executes
+ • {command} string|table Command(s) to execute. If a string, executes
multiple lines of Vim script at once. In this case, it is
an alias to |nvim_exec()|, where `output` is set to false.
Thus it works identical to |:source|. If a table, executes
@@ -1342,31 +1348,31 @@ connection_failure_errmsg({consequence})
defer_fn({fn}, {timeout}) *vim.defer_fn()*
Defers calling `fn` until `timeout` ms passes.
- Use to do a one-shot timer that calls `fn` Note: The {fn} is |schedule_wrap|ped automatically, so API functions are
- safe to call.
+ Use to do a one-shot timer that calls `fn` Note: The {fn} is |vim.schedule_wrap()|ped automatically, so API functions
+ are safe to call.
Parameters: ~
- {fn} Callback to call once `timeout` expires
- {timeout} Number of milliseconds to wait before calling `fn`
+ • {fn} (function) Callback to call once `timeout` expires
+ • {timeout} integer Number of milliseconds to wait before calling `fn`
Return: ~
- timer luv timer object
+ (table) timer luv timer object
*vim.deprecate()*
deprecate({name}, {alternative}, {version}, {plugin}, {backtrace})
Display a deprecation notification to the user.
Parameters: ~
- {name} string Deprecated function.
- {alternative} (string|nil) Preferred alternative function.
- {version} string Version in which the deprecated function will be
+ • {name} string Deprecated function.
+ • {alternative} (string|nil) Preferred alternative function.
+ • {version} string Version in which the deprecated function will be
removed.
- {plugin} string|nil Plugin name that the function will be
+ • {plugin} string|nil Plugin name that the function will be
removed from. Defaults to "Nvim".
- {backtrace} boolean|nil Prints backtrace. Defaults to true.
+ • {backtrace} boolean|nil Prints backtrace. Defaults to true.
inspect({object}, {options}) *vim.inspect()*
- Return a human-readable representation of the given object.
+ Gets a human-readable representation of the given object.
See also: ~
https://github.com/kikito/inspect.lua
@@ -1380,9 +1386,9 @@ notify({msg}, {level}, {opts}) *vim.notify()*
writes to |:messages|.
Parameters: ~
- {msg} (string) Content of the notification to show to the user.
- {level} (number|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} (number|nil) One of the values from |vim.log.levels|.
+ • {opts} (table|nil) Optional parameters. Unused by default.
notify_once({msg}, {level}, {opts}) *vim.notify_once()*
Display a notification only one time.
@@ -1391,9 +1397,9 @@ notify_once({msg}, {level}, {opts}) *vim.notify_once()*
display a notification.
Parameters: ~
- {msg} (string) Content of the notification to show to the user.
- {level} (number|nil) One of the values from |vim.log.levels|.
- {opts} (table|nil) Optional parameters. Unused by default.
+ • {msg} (string) Content of the notification to show to the user.
+ • {level} (number|nil) One of the values from |vim.log.levels|.
+ • {opts} (table|nil) Optional parameters. Unused by default.
Return: ~
(boolean) true if message was displayed, else false
@@ -1412,11 +1418,11 @@ on_key({fn}, {ns_id}) *vim.on_key()*
{fn} will receive the keys after mappings have been evaluated
Parameters: ~
- {fn} function: Callback function. It should take one string
+ • {fn} (function) Callback function. It should take one string
argument. On each key press, Nvim passes the key char to
fn(). |i_CTRL-V| If {fn} is nil, it removes the callback for
the associated {ns_id}
- {ns_id} number? Namespace ID. If nil or 0, generates and returns a
+ • {ns_id} number? Namespace ID. If nil or 0, generates and returns a
new |nvim_create_namespace()| id.
Return: ~
@@ -1444,18 +1450,19 @@ paste({lines}, {phase}) *vim.paste()*
<
Parameters: ~
- {lines} |readfile()|-style list of lines to paste. |channel-lines|
- {phase} -1: "non-streaming" paste: the call contains all lines. If
- paste is "streamed", `phase` indicates the stream state:
+ • {lines} string[] # |readfile()|-style list of lines to paste.
+ |channel-lines|
+ • {phase} paste_phase -1: "non-streaming" paste: the call contains all
+ lines. If paste is "streamed", `phase` indicates the stream state:
• 1: starts the paste (exactly once)
• 2: continues the paste (zero or more times)
• 3: ends the paste (exactly once)
Return: ~
- false if client should cancel the paste.
+ (boolean) # false if client should cancel the paste.
See also: ~
- |paste|
+ |paste| @alias paste_phase -1 | 1 | 2 | 3
pretty_print({...}) *vim.pretty_print()*
Prints given arguments in human-readable format. Example: >
@@ -1464,7 +1471,7 @@ pretty_print({...}) *vim.pretty_print()*
<
Return: ~
- given arguments.
+ any # given arguments.
See also: ~
|vim.inspect()|
@@ -1474,19 +1481,27 @@ region({bufnr}, {pos1}, {pos2}, {regtype}, {inclusive}) *vim.region()*
points
Parameters: ~
- {bufnr} (number) of buffer
- {pos1} (line, column) tuple marking beginning of region
- {pos2} (line, column) tuple marking end of region
- {regtype} type of selection (:help setreg)
- {inclusive} (boolean) indicating whether the selection is
+ • {bufnr} (number) of buffer
+ • {pos1} integer[] (line, column) tuple marking beginning of
+ region
+ • {pos2} integer[] (line, column) tuple marking end of region
+ • {regtype} (string) type of selection, see |setreg()|
+ • {inclusive} (boolean) indicating whether the selection is
end-inclusive
Return: ~
- region lua table of the form {linenr = {startcol,endcol}}
+ table<integer, {}> region lua table of the form {linenr =
+ {startcol,endcol}}
schedule_wrap({cb}) *vim.schedule_wrap()*
Defers callback `cb` until the Nvim API is safe to call.
+ Parameters: ~
+ • {cb} (function)
+
+ Return: ~
+ (function)
+
See also: ~
|lua-loop-callbacks|
|vim.schedule()|
@@ -1501,8 +1516,8 @@ deep_equal({a}, {b}) *vim.deep_equal()*
Tables are compared recursively unless they both provide the `eq` metamethod. All other types are compared using the equality `==` operator.
Parameters: ~
- {a} any First value
- {b} any Second value
+ • {a} any First value
+ • {b} any Second value
Return: ~
(boolean) `true` if values are equals, else `false`
@@ -1515,17 +1530,39 @@ deepcopy({orig}) *vim.deepcopy()*
not copied and will throw an error.
Parameters: ~
- {orig} (table) Table to copy
+ • {orig} (table) Table to copy
Return: ~
(table) Table of copied keys and (nested) values.
+defaulttable({create}) *vim.defaulttable()*
+ Creates a table whose members are automatically created when accessed, if
+ they don't already exist.
+
+ They mimic defaultdict in python.
+
+ If {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
+<
+
+ Parameters: ~
+ • {create} (function|nil) The function called to create a missing
+ value.
+
+ Return: ~
+ (table) Empty table with metamethod
+
endswith({s}, {suffix}) *vim.endswith()*
Tests if `s` ends with `suffix`.
Parameters: ~
- {s} (string) String
- {suffix} (string) Suffix to match
+ • {s} (string) String
+ • {suffix} (string) Suffix to match
Return: ~
(boolean) `true` if `suffix` is a suffix of `s`
@@ -1534,9 +1571,9 @@ gsplit({s}, {sep}, {plain}) *vim.gsplit()*
Splits a string at each instance of a separator.
Parameters: ~
- {s} (string) String to split
- {sep} (string) Separator or pattern
- {plain} (boolean) If `true` use `sep` literally (passed to
+ • {s} (string) String to split
+ • {sep} (string) Separator or pattern
+ • {plain} (boolean) If `true` use `sep` literally (passed to
string.find)
Return: ~
@@ -1551,7 +1588,7 @@ is_callable({f}) *vim.is_callable()*
Returns true if object `f` can be called as a function.
Parameters: ~
- {f} any Any object
+ • {f} any Any object
Return: ~
(boolean) `true` if `f` is callable, else `false`
@@ -1562,10 +1599,10 @@ list_extend({dst}, {src}, {start}, {finish}) *vim.list_extend()*
NOTE: This mutates dst!
Parameters: ~
- {dst} (table) List which will be modified and appended to
- {src} (table) List from which values will be inserted
- {start} (number) Start index on src. Defaults to 1
- {finish} (number) Final index on src. Defaults to `#src`
+ • {dst} (table) List which will be modified and appended to
+ • {src} (table) List from which values will be inserted
+ • {start} (number|nil) Start index on src. Defaults to 1
+ • {finish} (number|nil) Final index on src. Defaults to `#src`
Return: ~
(table) dst
@@ -1578,18 +1615,18 @@ list_slice({list}, {start}, {finish}) *vim.list_slice()*
(inclusive)
Parameters: ~
- {list} (table) Table
- {start} (number) Start range of slice
- {finish} (number) End range of slice
+ • {list} (list) Table
+ • {start} (number) Start range of slice
+ • {finish} (number) End range of slice
Return: ~
- (table) Copy of table sliced from start to finish (inclusive)
+ (list) Copy of table sliced from start to finish (inclusive)
pesc({s}) *vim.pesc()*
Escapes magic chars in |lua-patterns|.
Parameters: ~
- {s} (string) String to escape
+ • {s} (string) String to escape
Return: ~
(string) %-escaped pattern string
@@ -1602,33 +1639,35 @@ split({s}, {sep}, {kwargs}) *vim.split()*
Examples: >
- split(":aa::b:", ":") --> {'','aa','','b',''}
- split("axaby", "ab?") --> {'','x','y'}
- split("x*yz*o", "*", {plain=true}) --> {'x','yz','o'}
- split("|x|y|z|", "|", {trimempty=true}) --> {'x', 'y', 'z'}
+ split(":aa::b:", ":") => {'','aa','','b',''}
+ split("axaby", "ab?") => {'','x','y'}
+ split("x*yz*o", "*", {plain=true}) => {'x','yz','o'}
+ split("|x|y|z|", "|", {trimempty=true}) => {'x', 'y', 'z'}
<
+ @alias split_kwargs {plain: boolean, trimempty: boolean} | boolean | nil
+
+ See also: ~
+ |vim.gsplit()|
+
Parameters: ~
- {s} (string) String to split
- {sep} (string) Separator or pattern
- {kwargs} (table) Keyword arguments:
+ • {s} (string) String to split
+ • {sep} (string) Separator or pattern
+ • {kwargs} (table|nil) Keyword arguments:
• plain: (boolean) If `true` use `sep` literally (passed to
string.find)
• trimempty: (boolean) If `true` remove empty items from the
front and back of the list
Return: ~
- (table) List of split components
-
- See also: ~
- |vim.gsplit()|
+ string[] List of split components
startswith({s}, {prefix}) *vim.startswith()*
Tests if `s` starts with `prefix`.
Parameters: ~
- {s} (string) String
- {prefix} (string) Prefix to match
+ • {s} (string) String
+ • {prefix} (string) Prefix to match
Return: ~
(boolean) `true` if `prefix` is a prefix of `s`
@@ -1640,7 +1679,7 @@ tbl_add_reverse_lookup({o}) *vim.tbl_add_reverse_lookup()*
Note that this modifies the input.
Parameters: ~
- {o} (table) Table to add the reverse to
+ • {o} (table) Table to add the reverse to
Return: ~
(table) o
@@ -1649,8 +1688,8 @@ tbl_contains({t}, {value}) *vim.tbl_contains()*
Checks if a list-like (vector) table contains `value`.
Parameters: ~
- {t} (table) Table to check
- {value} any Value to compare
+ • {t} (table) Table to check
+ • {value} any Value to compare
Return: ~
(boolean) `true` if `t` contains `value`
@@ -1664,7 +1703,7 @@ tbl_count({t}) *vim.tbl_count()*
<
Parameters: ~
- {t} (table) Table
+ • {t} (table) Table
Return: ~
(number) Number of non-nil values in table
@@ -1676,29 +1715,29 @@ tbl_deep_extend({behavior}, {...}) *vim.tbl_deep_extend()*
Merges recursively two or more map-like tables.
Parameters: ~
- {behavior} (string) Decides what to do if a key is found in more than
+ • {behavior} (string) Decides what to do if a key is found in more than
one map:
• "error": raise an error
• "keep": use value from the leftmost map
• "force": use value from the rightmost map
- {...} (table) Two or more map-like tables
+ • {...} (table) Two or more map-like tables
Return: ~
(table) Merged table
See also: ~
- |tbl_extend()|
+ |vim.tbl_extend()|
tbl_extend({behavior}, {...}) *vim.tbl_extend()*
Merges two or more map-like tables.
Parameters: ~
- {behavior} (string) Decides what to do if a key is found in more than
+ • {behavior} (string) Decides what to do if a key is found in more than
one map:
• "error": raise an error
• "keep": use value from the leftmost map
• "force": use value from the rightmost map
- {...} (table) Two or more map-like tables
+ • {...} (table) Two or more map-like tables
Return: ~
(table) Merged table
@@ -1710,8 +1749,8 @@ tbl_filter({func}, {t}) *vim.tbl_filter()*
Filter a table using a predicate function
Parameters: ~
- {func} function|table Function or callable table
- {t} (table) Table
+ • {func} (function) Function
+ • {t} (table) Table
Return: ~
(table) Table of filtered values
@@ -1721,7 +1760,7 @@ tbl_flatten({t}) *vim.tbl_flatten()*
"unrolled" and appended to the result.
Parameters: ~
- {t} (table) List-like table
+ • {t} (table) List-like table
Return: ~
(table) Flattened copy of the given list-like table
@@ -1740,8 +1779,8 @@ tbl_get({o}, {...}) *vim.tbl_get()*
<
Parameters: ~
- {o} (table) Table to index
- {...} (string) Optional strings (0 or more, variadic) via which to
+ • {o} (table) Table to index
+ • {...} (string) Optional strings (0 or more, variadic) via which to
index the table
Return: ~
@@ -1751,7 +1790,7 @@ tbl_isempty({t}) *vim.tbl_isempty()*
Checks if a table is empty.
Parameters: ~
- {t} (table) Table to check
+ • {t} (table) Table to check
Return: ~
(boolean) `true` if `t` is empty
@@ -1767,7 +1806,7 @@ tbl_islist({t}) *vim.tbl_islist()*
for example from |rpcrequest()| or |vim.fn|.
Parameters: ~
- {t} (table) Table
+ • {t} (table) Table
Return: ~
(boolean) `true` if array-like table, else `false`
@@ -1777,10 +1816,10 @@ tbl_keys({t}) *vim.tbl_keys()*
return table of keys is not guaranteed.
Parameters: ~
- {t} (table) Table
+ • {t} (table) Table
Return: ~
- (table) List of keys
+ (list) List of keys
See also: ~
From https://github.com/premake/premake-core/blob/master/src/base/table.lua
@@ -1789,8 +1828,8 @@ tbl_map({func}, {t}) *vim.tbl_map()*
Apply a function to all values of a table.
Parameters: ~
- {func} function|table Function or callable table
- {t} (table) Table
+ • {func} (function) Function
+ • {t} (table) Table
Return: ~
(table) Table of transformed values
@@ -1800,16 +1839,16 @@ tbl_values({t}) *vim.tbl_values()*
return table of values is not guaranteed.
Parameters: ~
- {t} (table) Table
+ • {t} (table) Table
Return: ~
- (table) List of values
+ (list) List of values
trim({s}) *vim.trim()*
Trim whitespace (Lua pattern "%s") from both sides of a string.
Parameters: ~
- {s} (string) String to trim
+ • {s} (string) String to trim
Return: ~
(string) String with whitespace removed from its beginning and end
@@ -1854,7 +1893,7 @@ validate({opt}) *vim.validate()*
<
Parameters: ~
- {opt} (table) Names of parameters to validate. Each key is a
+ • {opt} (table) Names of parameters to validate. Each key is a
parameter name; each value is a tuple in one of these forms:
1. (arg_value, type_name, optional)
• arg_value: argument value
@@ -1879,7 +1918,7 @@ uri_from_bufnr({bufnr}) *vim.uri_from_bufnr()*
Get a URI from a bufnr
Parameters: ~
- {bufnr} (number)
+ • {bufnr} (number)
Return: ~
(string) URI
@@ -1888,7 +1927,7 @@ uri_from_fname({path}) *vim.uri_from_fname()*
Get a URI from a file path.
Parameters: ~
- {path} (string) Path to file
+ • {path} (string) Path to file
Return: ~
(string) URI
@@ -1898,7 +1937,7 @@ uri_to_bufnr({uri}) *vim.uri_to_bufnr()*
the uri already exists.
Parameters: ~
- {uri} (string)
+ • {uri} (string)
Return: ~
(number) bufnr
@@ -1907,7 +1946,7 @@ uri_to_fname({uri}) *vim.uri_to_fname()*
Get a filename from a URI
Parameters: ~
- {uri} (string)
+ • {uri} (string)
Return: ~
(string) filename or unchanged URI for non-file URIs
@@ -1927,7 +1966,7 @@ input({opts}, {on_confirm}) *vim.ui.input()*
<
Parameters: ~
- {opts} (table) Additional options. See |input()|
+ • {opts} (table) Additional options. See |input()|
• prompt (string|nil) Text of the prompt
• default (string|nil) Default reply to the input
• completion (string|nil) Specifies type of completion
@@ -1936,7 +1975,7 @@ input({opts}, {on_confirm}) *vim.ui.input()*
"-complete=" argument. See |:command-completion|
• highlight (function) Function that will be used for
highlighting user inputs.
- {on_confirm} (function) ((input|nil) -> ()) Called once the user
+ • {on_confirm} (function) ((input|nil) -> ()) Called once the user
confirms or abort the input. `input` is what the user
typed. `nil` if the user aborted the dialog.
@@ -1960,8 +1999,8 @@ select({items}, {opts}, {on_choice}) *vim.ui.select()*
<
Parameters: ~
- {items} (table) Arbitrary items
- {opts} (table) Additional options
+ • {items} (table) Arbitrary items
+ • {opts} (table) Additional options
• prompt (string|nil) Text of the prompt. Defaults to
`Select one of:`
• format_item (function item -> text) Function to format
@@ -1971,7 +2010,7 @@ select({items}, {opts}, {on_choice}) *vim.ui.select()*
item shape. Plugins reimplementing `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
+ • {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.
@@ -1999,7 +2038,10 @@ add({filetypes}) *vim.filetype.add()*
Filename patterns can specify an optional priority to resolve cases when a
file path matches multiple patterns. Higher priorities are matched first.
- When omitted, the priority defaults to 0.
+ When omitted, the priority defaults to 0. A pattern can contain
+ environment variables of the form "${SOME_VAR}" that will be automatically
+ expanded. If the environment variable is not set, the pattern won't be
+ matched.
See $VIMRUNTIME/lua/vim/filetype.lua for more examples.
@@ -2029,6 +2071,8 @@ add({filetypes}) *vim.filetype.add()*
['.*/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'
@@ -2060,7 +2104,7 @@ add({filetypes}) *vim.filetype.add()*
<
Parameters: ~
- {filetypes} (table) A table containing new filetype maps (see
+ • {filetypes} (table) A table containing new filetype maps (see
example).
match({args}) *vim.filetype.match()*
@@ -2095,7 +2139,7 @@ match({args}) *vim.filetype.match()*
<
Parameters: ~
- {args} (table) Table specifying which matching strategy to use.
+ • {args} (table) Table specifying which matching strategy to use.
Accepted keys are:
• buf (number): Buffer number to use for matching. Mutually
exclusive with {contents}
@@ -2129,7 +2173,7 @@ del({modes}, {lhs}, {opts}) *vim.keymap.del()*
<
Parameters: ~
- {opts} (table) A table of optional arguments:
+ • {opts} (table|nil) A table of optional arguments:
• buffer: (number or boolean) Remove a mapping from the given
buffer. When "true" or 0, use the current buffer.
@@ -2169,12 +2213,12 @@ set({mode}, {lhs}, {rhs}, {opts}) *vim.keymap.set()*
<
Parameters: ~
- {mode} string|table Same mode short names as |nvim_set_keymap()|. Can
+ • {mode} string|table Same mode short names as |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
+ • {lhs} (string) Left-hand side |{lhs}| of the mapping.
+ • {rhs} string|function Right-hand side |{rhs}| of the mapping. Can
also be a Lua function.
- {opts} (table) A table of |:map-arguments|.
+ • {opts} (table|nil) A table of |:map-arguments|.
• Accepts options accepted by the {opts} parameter in
|nvim_set_keymap()|, with the following notable differences:
• replace_keycodes: Defaults to `true` if "expr" is `true`.
@@ -2200,7 +2244,7 @@ basename({file}) *vim.fs.basename()*
Return the basename of the given file or directory
Parameters: ~
- {file} (string) File or directory
+ • {file} (string) File or directory
Return: ~
(string) Basename of {file}
@@ -2209,7 +2253,7 @@ dir({path}) *vim.fs.dir()*
Return an iterator over the files and directories located in {path}
Parameters: ~
- {path} (string) An absolute or relative path to the directory to
+ • {path} (string) An absolute or relative path to the directory to
iterate over. The path is first normalized
|vim.fs.normalize()|.
@@ -2222,7 +2266,7 @@ dirname({file}) *vim.fs.dirname()*
Return the parent directory of the given file or directory
Parameters: ~
- {file} (string) File or directory
+ • {file} (string) File or directory
Return: ~
(string) Parent directory of {file}
@@ -2240,9 +2284,11 @@ find({names}, {opts}) *vim.fs.find()*
specifying {type} to be "file" or "directory", respectively.
Parameters: ~
- {names} (string|table) Names of the files and directories to find.
- Must be base names, paths and globs are not supported.
- {opts} (table) Optional keyword arguments:
+ • {names} (string|table|fun(name: string): boolean) Names of the files
+ and directories to find. Must be base names, paths and globs
+ are not supported. If a function it is called per file and
+ dir within the traversed directories to test if they match.
+ • {opts} (table) Optional keyword arguments:
• path (string): Path to begin searching from. If omitted,
the current working directory is used.
• upward (boolean, default false): If true, search upward
@@ -2279,7 +2325,7 @@ normalize({path}) *vim.fs.normalize()*
<
Parameters: ~
- {path} (string) Path to normalize
+ • {path} (string) Path to normalize
Return: ~
(string) Normalized path
@@ -2303,7 +2349,7 @@ parents({start}) *vim.fs.parents()*
<
Parameters: ~
- {start} (string) Initial file or directory.
+ • {start} (string) Initial file or directory.
Return: ~
(function) Iterator