diff options
| author | Josh Rahm <joshuarahm@gmail.com> | 2023-11-30 20:35:25 +0000 |
|---|---|---|
| committer | Josh Rahm <joshuarahm@gmail.com> | 2023-11-30 20:35:25 +0000 |
| commit | 1b7b916b7631ddf73c38e3a0070d64e4636cb2f3 (patch) | |
| tree | cd08258054db80bb9a11b1061bb091c70b76926a /runtime/doc/lua.txt | |
| parent | eaa89c11d0f8aefbb512de769c6c82f61a8baca3 (diff) | |
| parent | 4a8bf24ac690004aedf5540fa440e788459e5e34 (diff) | |
| download | rneovim-aucmd_textputpost.tar.gz rneovim-aucmd_textputpost.tar.bz2 rneovim-aucmd_textputpost.zip | |
Merge remote-tracking branch 'upstream/master' into aucmd_textputpostaucmd_textputpost
Diffstat (limited to 'runtime/doc/lua.txt')
| -rw-r--r-- | runtime/doc/lua.txt | 3103 |
1 files changed, 2197 insertions, 906 deletions
diff --git a/runtime/doc/lua.txt b/runtime/doc/lua.txt index 47249a484b..a35d70cae8 100644 --- a/runtime/doc/lua.txt +++ b/runtime/doc/lua.txt @@ -14,7 +14,7 @@ INTRODUCTION *lua-intro* The Lua 5.1 script engine is builtin and always available. Try this command to get an idea of what lurks beneath: >vim - :lua print(vim.inspect(package.loaded)) + :lua vim.print(package.loaded) Nvim includes a "standard library" |lua-stdlib| for Lua. It complements the "editor stdlib" (|builtin-functions| and |Ex-commands|) and the |API|, all of @@ -33,6 +33,22 @@ Lua 5.1, not worry about forward-compatibility with future Lua versions. If Nvim ever ships with Lua 5.4+, a Lua 5.1 compatibility shim will be provided so that old plugins continue to work transparently. + *lua-luajit* +Nvim is built with luajit on platforms which support it, which provides +extra functionality. Lua code in |init.lua| and plugins can assume its presence +on installations on common platforms. For maximum compatibility with less +common platforms, availability can be checked using the `jit` global variable: >lua + if jit then + -- code for luajit + else + -- code for plain lua 5.1 + end +< + *lua-bit* +In particular, the luajit "bit" extension module is _always_ available. +A fallback implementation is included when nvim is built with PUC Lua 5.1, +and will be transparently used when `require("bit")` is invoked. + ============================================================================== LUA CONCEPTS AND IDIOMS *lua-concepts* @@ -46,15 +62,32 @@ programming": tables, closures, and coroutines. https://www.lua.org/doc/cacm2018.pdf - Tables are the "object" or container datastructure: they represent both lists and maps, you can extend them to represent your own datatypes and - change their behavior using |luaref-metatable| (like Python's "datamodel"). + change their behavior using |metatable|s (like Python's "datamodel"). - EVERY scope in Lua is a closure: a function is a closure, a module is - a closure, a `do` block (|luaref-do|) is a closure--and they all work the - same. A Lua module is literally just a big closure discovered on the "path" + a closure, a `do` block (|lua-do|) is a closure--and they all work the same. + A Lua module is literally just a big closure discovered on the "path" (where your modules are found: |package.cpath|). - Stackful coroutines enable cooperative multithreading, generators, and versatile control for both Lua and its host (Nvim). - *lua-call-function* + *iterator* +An iterator is just a function that can be called repeatedly to get the "next" +value of a collection (or any other |iterable|). This interface is expected by +|for-in| loops, produced by |pairs()|, supported by |vim.iter|, etc. +https://www.lua.org/pil/7.1.html + + *iterable* +An "iterable" is anything that |vim.iter()| can consume: tables, dicts, lists, +iterator functions, tables implementing the |__call()| metamethod, and +|vim.iter()| objects. + + *list-iterator* +Iterators on |lua-list| tables have a "middle" and "end", whereas iterators in +general may be logically infinite. Therefore some |vim.iter| operations (e.g. +|Iter:rev()|) make sense only on list-like tables (which are finite by +definition). + + *lua-function-call* Lua functions can be called in multiple ways. Consider the function: >lua local foo = function(a, b) print("A: ", a) @@ -67,21 +100,19 @@ The first way to call this function is: >lua -- A: 1 -- B: 2 -This way of calling a function is familiar from most scripting languages. -In Lua, any missing arguments are passed as `nil`. Example: >lua +This way of calling a function is familiar from most scripting languages. In +Lua, any missing arguments are passed as `nil`, and extra parameters are +silently discarded. Example: >lua foo(1) -- ==== Result ==== -- A: 1 -- B: nil - -Furthermore it is not an error if extra parameters are passed, they are just -discarded. - +< *kwargs* When calling a function, you can omit the parentheses if the function takes exactly one string literal (`"foo"`) or table literal (`{1,2,3}`). The latter -is often used to approximate "named parameters" ("kwargs" or "keyword args") -as in languages like Python and C#. Example: >lua +is often used to mimic "named parameters" ("kwargs" or "keyword args") as in +languages like Python and C#. Example: >lua local func_with_opts = function(opts) local will_do_foo = opts.foo local filename = opts.filename @@ -92,21 +123,16 @@ as in languages like Python and C#. Example: >lua < There's nothing special going on here except that parentheses are treated as whitespace. But visually, this small bit of sugar gets reasonably close to -a "keyword args" interface. - -It is of course also valid to call the function with parentheses: >lua - func_with_opts({ foo = true, filename = "hello.world" }) -< -Nvim tends to prefer the keyword args style. +a "keyword args" interface. Nvim code tends to prefer this style. ------------------------------------------------------------------------------ LUA PATTERNS *lua-patterns* Lua intentionally does not support regular expressions, instead it has limited -"patterns" |luaref-patterns| which avoid the performance pitfalls of extended +"patterns" |lua-pattern| which avoid the performance pitfalls of extended regex. Lua scripts can also use Vim regex via |vim.regex()|. -These examples use |string.match()| to demonstrate Lua patterns: >lua +Examples: >lua print(string.match("foo123bar123", "%d+")) -- 123 @@ -118,7 +144,7 @@ These examples use |string.match()| to demonstrate Lua patterns: >lua -- .bar ============================================================================== -IMPORTING LUA MODULES *require()* *lua-require* +IMPORTING LUA MODULES *lua-module-load* Modules are searched for under the directories specified in 'runtimepath', in the order they appear. Any "." in the module name is treated as a directory @@ -132,7 +158,7 @@ back to Lua's default search mechanism. The first script found is run and The return value is cached after the first call to `require()` for each module, with subsequent calls returning the cached value without searching for, or -executing any script. For further details on `require()`, see |luaref-require()|. +executing any script. For further details see |require()|. For example, if 'runtimepath' is `foo,bar` and |package.cpath| was `./?.so;./?.dll` at startup, `require('mod')` searches these paths in order @@ -217,11 +243,11 @@ command calls. The |lua-stdlib| modules, user modules, and anything else on The Lua print() function redirects its output to the Nvim message area, with arguments separated by " " (space) instead of "\t" (tab). - *:lua* + *:lua=* *:lua* :lua {chunk} Executes Lua chunk {chunk}. If {chunk} starts with "=" the rest of the - chunk is evaluated as an expression and printed. `:lua =expr` is - equivalent to `:lua print(vim.inspect(expr))` + chunk is evaluated as an expression and printed. `:lua =expr` or `:=expr` is + equivalent to `:lua print(vim.inspect(expr))`. Examples: >vim :lua vim.api.nvim_command('echo "Hello, Nvim!"') @@ -231,12 +257,12 @@ arguments separated by " " (space) instead of "\t" (tab). :lua =jit.version < *:lua-heredoc* -:lua << [endmarker] +:lua << [trim] [{endmarker}] {script} {endmarker} - Executes Lua script {script} from within Vimscript. {endmarker} must NOT - be preceded by whitespace. You can omit [endmarker] after the "<<" and use - a dot "." after {script} (similar to |:append|, |:insert|). + Executes Lua script {script} from within Vimscript. You can omit + [endmarker] after the "<<" and use a dot "." after {script} (similar to + |:append|, |:insert|). Refer to |:let-heredoc| for more information. Example: >vim function! CurrentLineInfo() @@ -280,7 +306,7 @@ arguments separated by " " (space) instead of "\t" (tab). < ============================================================================== -luaeval() *lua-eval* *luaeval()* +luaeval() *lua-eval* The (dual) equivalent of "vim.eval" for passing Lua values to Nvim is "luaeval". "luaeval" takes an expression string and an optional argument used @@ -305,14 +331,16 @@ Example: >vim :echo luaeval('string.match(_A, "[a-z]+")', 'XYXfoo123') " foo < + *lua-table-ambiguous* Lua tables are used as both dictionaries and lists, so it is impossible to determine whether empty table is meant to be empty list or empty dictionary. Additionally Lua does not have integer numbers. To distinguish between these cases there is the following agreement: - + *lua-list* 0. Empty table is empty list. -1. Table with N incrementally growing integral numbers, starting from 1 and - ending with N is considered to be a list. +1. Table with N consecutive integer indices starting from 1 and ending with + N is considered a list. See also |list-iterator|. + *lua-dict* 2. Table with string keys, none of which contains NUL byte, is considered to be a dictionary. 3. Table with string keys, at least one of which contains NUL byte, is also @@ -383,7 +411,7 @@ For example consider the following Lua omnifunc handler: >lua return {'stuff', 'steam', 'strange things'} end end - vim.api.nvim_buf_set_option(0, 'omnifunc', 'v:lua.mymod.omnifunc') + vim.bo[buf].omnifunc = 'v:lua.mymod.omnifunc' Note: The module ("mymod" in the above example) must either be a Lua global, or use require() as shown above to access it from a package. @@ -405,7 +433,7 @@ is unnecessary. You can peek at the module properties: >vim - :lua print(vim.inspect(vim)) + :lua vim.print(vim) Result is something like this: > @@ -431,29 +459,24 @@ Note that underscore-prefixed functions (e.g. "_os_proc_children") are internal/private and must not be used by plugins. ------------------------------------------------------------------------------ -VIM.LOOP *lua-loop* *vim.loop* +VIM.UV *lua-loop* *vim.uv* -`vim.loop` exposes all features of the Nvim event-loop. This is a low-level -API that provides functionality for networking, filesystem, and process -management. Try this command to see available functions: >vim - - :lua print(vim.inspect(vim.loop)) -< -Internally, `vim.loop` wraps the "luv" Lua bindings for the LibUV library; -see |luv-intro| for a full reference manual. +`vim.uv` exposes the "luv" Lua bindings for the libUV library that Nvim uses +for networking, filesystem, and process management, see |luvref.txt|. +In particular, it allows interacting with the main Nvim |luv-event-loop|. *E5560* *lua-loop-callbacks* It is an error to directly invoke `vim.api` functions (except |api-fast|) in -`vim.loop` callbacks. For example, this is an error: >lua +`vim.uv` callbacks. For example, this is an error: >lua - local timer = vim.loop.new_timer() + local timer = vim.uv.new_timer() timer:start(1000, 0, function() vim.api.nvim_command('echomsg "test"') end) < To avoid the error use |vim.schedule_wrap()| to defer the callback: >lua - local timer = vim.loop.new_timer() + local timer = vim.uv.new_timer() timer:start(1000, 0, vim.schedule_wrap(function() vim.api.nvim_command('echomsg "test"') end)) @@ -466,7 +489,7 @@ Example: repeating timer 2. Execute it with ":luafile %". >lua -- Create a timer handle (implementation detail: uv_timer_t). - local timer = vim.loop.new_timer() + local timer = vim.uv.new_timer() local i = 0 -- Waits 1000ms, then repeats every 750ms until timer:close(). timer:start(1000, 750, function() @@ -486,7 +509,7 @@ Example: File-change detection *watch-file* 5. Observe that the file reloads in Nvim (because on_change() calls |:checktime|). >lua - local w = vim.loop.new_fs_event() + local w = vim.uv.new_fs_event() local function on_change(err, fname, status) -- Do work... vim.api.nvim_command('checktime') @@ -510,11 +533,11 @@ Example: TCP echo-server *tcp-server* 4. Connect from any TCP client (e.g. "nc 0.0.0.0 36795"): >lua local function create_server(host, port, on_connect) - local server = vim.loop.new_tcp() + local server = vim.uv.new_tcp() server:bind(host, port) server:listen(128, function(err) assert(not err, err) -- Check for errors. - local sock = vim.loop.new_tcp() + local sock = vim.uv.new_tcp() server:accept(sock) -- Accept client connection. on_connect(sock) -- Start reading messages. end) @@ -535,105 +558,139 @@ Example: TCP echo-server *tcp-server* Multithreading *lua-loop-threading* Plugins can perform work in separate (os-level) threads using the threading -APIs in luv, for instance `vim.loop.new_thread`. Note that every thread -gets its own separate lua interpreter state, with no access to lua globals +APIs in luv, for instance `vim.uv.new_thread`. Note that every thread +gets its own separate Lua interpreter state, with no access to Lua globals in the main thread. Neither can the state of the editor (buffers, windows, etc) be directly accessed from threads. A subset of the `vim.*` API is available in threads. This includes: -- `vim.loop` with a separate event loop per thread. +- `vim.uv` with a separate event loop per thread. - `vim.mpack` and `vim.json` (useful for serializing messages between threads) -- `require` in threads can use lua packages from the global |package.path| +- `require` in threads can use Lua packages from the global |package.path| - `print()` and `vim.inspect` - `vim.diff` -- most utility functions in `vim.*` for working with pure lua values +- most utility functions in `vim.*` for working with pure Lua values like `vim.split`, `vim.tbl_*`, `vim.list_*`, and so on. - `vim.is_thread()` returns true from a non-main thread. ------------------------------------------------------------------------------ -VIM.HIGHLIGHT *lua-highlight* +VIM.LPEG *lua-lpeg* + + *vim.lpeg* *vim.re* +The Lpeg library for parsing expression grammars is being included as +`vim.lpeg` (https://www.inf.puc-rio.br/~roberto/lpeg/). In addition, its regex-like +interface is available as `vim.re` (https://www.inf.puc-rio.br/~roberto/lpeg/re.html). -Nvim includes a function for highlighting a selection on yank (see for example -https://github.com/machakann/vim-highlightedyank). To enable it, add ->vim +============================================================================== +VIM.HIGHLIGHT *vim.highlight* + + +Nvim includes a function for highlighting a selection on yank. + +To enable it, add the following to your `init.vim`: >vim au TextYankPost * silent! lua vim.highlight.on_yank() + < -to your `init.vim`. You can customize the highlight group and the duration of -the highlight via ->vim + +You can customize the highlight group and the duration of the highlight +via: >vim au TextYankPost * silent! lua vim.highlight.on_yank {higroup="IncSearch", timeout=150} + < -If you want to exclude visual selections from highlighting on yank, use ->vim + +If you want to exclude visual selections from highlighting on yank, use: >vim au TextYankPost * silent! lua vim.highlight.on_yank {on_visual=false} + < + vim.highlight.on_yank({opts}) *vim.highlight.on_yank()* - Highlights the yanked text. The fields of the optional dict {opts} - control the highlight: - - {higroup} highlight group for yanked region (default |hl-IncSearch|) - - {timeout} time in ms before highlight is cleared (default `150`) - - {on_macro} highlight when executing macro (default `false`) - - {on_visual} highlight when yanking visual selection (default `true`) - - {event} event structure (default |v:event|) - -vim.highlight.range({bufnr}, {ns}, {hlgroup}, {start}, {finish}, {opts}) - *vim.highlight.range()* + Highlight the yanked text + + Parameters: ~ + • {opts} (table|nil) Optional parameters + • higroup highlight group for yanked region (default + "IncSearch") + • timeout time in ms before highlight is cleared (default 150) + • on_macro highlight when executing macro (default false) + • on_visual highlight when yanking visual selection (default + true) + • event event structure (default vim.v.event) + • priority integer priority (default + |vim.highlight.priorities|`.user`) + +vim.highlight.priorities *vim.highlight.priorities* + Table with default priorities used for highlighting: + • `syntax`: `50`, used for standard syntax highlighting + • `treesitter`: `100`, used for tree-sitter-based highlighting + • `semantic_tokens`: `125`, used for LSP semantic token highlighting + • `diagnostics`: `150`, used for code analysis such as diagnostics + • `user`: `200`, used for user-triggered highlights such as LSP document + symbols or `on_yank` autocommands + *vim.highlight.range()* +vim.highlight.range({bufnr}, {ns}, {higroup}, {start}, {finish}, {opts}) Apply highlight group to range of text. - Parameters: ~ - • {bufnr} buffer number - • {ns} namespace for highlights - • {hlgroup} highlight group name - • {start} starting position (tuple {line,col}) - • {finish} finish position (tuple {line,col}) - • {opts} optional parameters: - • `regtype`: type of range (characterwise, linewise, - or blockwise, see |setreg()|), default `'v'` - • `inclusive`: range includes end position, - default `false` - • `priority`: priority of highlight, default - `vim.highlight.user` (see below) + Parameters: ~ + • {bufnr} (integer) Buffer number to apply highlighting to + • {ns} (integer) Namespace to add highlight to + • {higroup} (string) Highlight group to use for highlighting + • {start} integer[]|string Start of region as a (line, column) tuple + or string accepted by |getpos()| + • {finish} integer[]|string End of region as a (line, column) tuple or + string accepted by |getpos()| + • {opts} (table|nil) Optional parameters + • regtype type of range (see |setreg()|, default charwise) + • inclusive boolean indicating whether the range is + end-inclusive (default false) + • priority number indicating priority of highlight (default + priorities.user) -vim.highlight.priorities *vim.highlight.priorities* - Table with default priorities used for highlighting: - • `syntax`: `50`, used for standard syntax highlighting - • `treesitter`: `100`, used for tree-sitter-based highlighting - • `semantic_tokens`: `125`, used for LSP semantic token highlighting - • `diagnostics`: `150`, used for code analysis such as diagnostics - • `user`: `200`, used for user-triggered highlights such as LSP document - symbols or `on_yank` autocommands +============================================================================== +VIM.REGEX *vim.regex* ------------------------------------------------------------------------------- -VIM.REGEX *lua-regex* -Vim regexes can be used directly from lua. Currently they only allow +Vim regexes can be used directly from Lua. Currently they only allow matching within a single line. + vim.regex({re}) *vim.regex()* Parse the Vim regex {re} and return a regex object. Regexes are "magic" and case-sensitive by default, regardless of 'magic' and 'ignorecase'. They can be controlled with flags, see |/magic| and |/ignorecase|. -Methods on the regex object: + Parameters: ~ + • {re} (string) -regex:match_str({str}) *regex:match_str()* - Match the string against the regex. If the string should match the regex - precisely, surround the regex with `^` and `$`. If the was a match, the - byte indices for the beginning and end of the match is returned. When - there is no match, `nil` is returned. As any integer is truth-y, - `regex:match()` can be directly used as a condition in an if-statement. + Return: ~ + vim.regex -regex:match_line({bufnr}, {line_idx} [, {start}, {end}]) *regex:match_line()* + *regex:match_line()* +vim.regex:match_line({bufnr}, {line_idx}, {start}, {end_}) Match line {line_idx} (zero-based) in buffer {bufnr}. If {start} and {end} are supplied, match only this byte index range. Otherwise see |regex:match_str()|. If {start} is used, then the returned byte indices will be relative {start}. ------------------------------------------------------------------------------- -VIM.DIFF *lua-diff* + Parameters: ~ + • {bufnr} (integer) + • {line_idx} (integer) + • {start} (integer|nil) + • {end_} (integer|nil) + +vim.regex:match_str({str}) *regex:match_str()* + Match the string against the regex. If the string should match the regex + precisely, surround the regex with `^` and `$` . If there was a match, the byte indices for the beginning and end of the + match are returned. When there is no match, `nil` is returned. Because any integer is "truthy", `regex:match_str()` can be directly used as a condition in an if-statement. + + Parameters: ~ + • {str} (string) + + +============================================================================== +VIM.DIFF *vim.diff* vim.diff({a}, {b}, {opts}) *vim.diff()* Run diff on strings {a} and {b}. Any indices returned by this function, @@ -653,82 +710,135 @@ vim.diff({a}, {b}, {opts}) *vim.diff()* -- {1, 1, 1, 2} -- } < + Parameters: ~ - • {a} First string to compare - • {b} Second string to compare - • {opts} Optional parameters: - • `on_hunk` (callback): - Invoked for each hunk in the diff. Return a negative number - to cancel the callback for any remaining hunks. - Args: - • `start_a` (integer): Start line of hunk in {a}. - • `count_a` (integer): Hunk size in {a}. - • `start_b` (integer): Start line of hunk in {b}. - • `count_b` (integer): Hunk size in {b}. - • `result_type` (string): Form of the returned diff: - • "unified": (default) String in unified format. - • "indices": Array of hunk locations. - Note: This option is ignored if `on_hunk` is used. - • `linematch` (boolean): Run linematch on the resulting hunks - from xdiff. Requires `result_type = indices`, ignored - otherwise. - • `algorithm` (string): - Diff algorithm to use. Values: - • "myers" the default algorithm - • "minimal" spend extra time to generate the - smallest possible diff - • "patience" patience diff algorithm - • "histogram" histogram diff algorithm - • `ctxlen` (integer): Context length - • `interhunkctxlen` (integer): - Inter hunk context length - • `ignore_whitespace` (boolean): - Ignore whitespace - • `ignore_whitespace_change` (boolean): - Ignore whitespace change - • `ignore_whitespace_change_at_eol` (boolean) - Ignore whitespace change at end-of-line. - • `ignore_cr_at_eol` (boolean) - Ignore carriage return at end-of-line - • `ignore_blank_lines` (boolean) - Ignore blank lines - • `indent_heuristic` (boolean): - Use the indent heuristic for the internal - diff library. - - Return: ~ - See {opts.result_type}. nil if {opts.on_hunk} is given. + • {a} (string) First string to compare + • {b} (string) Second string to compare + • {opts} table<string,any> Optional parameters: + • `on_hunk` (callback): Invoked for each hunk in the diff. Return a + negative number to cancel the callback for any remaining + hunks. Args: + • `start_a` (integer): Start line of hunk in {a}. + • `count_a` (integer): Hunk size in {a}. + • `start_b` (integer): Start line of hunk in {b}. + • `count_b` (integer): Hunk size in {b}. + + • `result_type` (string): Form of the returned diff: + • "unified": (default) String in unified format. + • "indices": Array of hunk locations. Note: This option is + ignored if `on_hunk` is used. + + • `linematch` (boolean|integer): Run linematch on the + resulting hunks from xdiff. When integer, only hunks upto + this size in lines are run through linematch. Requires + `result_type = indices`, ignored otherwise. + • `algorithm` (string): Diff algorithm to use. Values: + • "myers" the default algorithm + • "minimal" spend extra time to generate the smallest + possible diff + • "patience" patience diff algorithm + • "histogram" histogram diff algorithm + + • `ctxlen` (integer): Context length + • `interhunkctxlen` (integer): Inter hunk context length + • `ignore_whitespace` (boolean): Ignore whitespace + • `ignore_whitespace_change` (boolean): Ignore whitespace + change + • `ignore_whitespace_change_at_eol` (boolean) Ignore + whitespace change at end-of-line. + • `ignore_cr_at_eol` (boolean) Ignore carriage return at + end-of-line + • `ignore_blank_lines` (boolean) Ignore blank lines + • `indent_heuristic` (boolean): Use the indent heuristic for + the internal diff library. ------------------------------------------------------------------------------- -VIM.MPACK *lua-mpack* + Return: ~ + string|table|nil See {opts.result_type}. `nil` if {opts.on_hunk} is + given. -The *vim.mpack* module provides encoding and decoding of Lua objects to and -from msgpack-encoded strings. Supports |vim.NIL| and |vim.empty_dict()|. -vim.mpack.encode({obj}) *vim.mpack.encode* - Encodes (or "packs") Lua object {obj} as msgpack in a Lua string. +============================================================================== +VIM.MPACK *vim.mpack* + -vim.mpack.decode({str}) *vim.mpack.decode* +This module provides encoding and decoding of Lua objects to and from +msgpack-encoded strings. Supports |vim.NIL| and |vim.empty_dict()|. + +vim.mpack.decode({str}) *vim.mpack.decode()* Decodes (or "unpacks") the msgpack-encoded {str} to a Lua object. ------------------------------------------------------------------------------- -VIM.JSON *lua-json* + Parameters: ~ + • {str} (string) -The *vim.json* module provides encoding and decoding of Lua objects to and -from JSON-encoded strings. Supports |vim.NIL| and |vim.empty_dict()|. +vim.mpack.encode({obj}) *vim.mpack.encode()* + Encodes (or "packs") Lua object {obj} as msgpack in a Lua string. -vim.json.encode({obj}) *vim.json.encode* - Encodes (or "packs") Lua object {obj} as JSON in a Lua string. -vim.json.decode({str}[, {opts}]) *vim.json.decode* +============================================================================== +VIM.JSON *vim.json* + + +This module provides encoding and decoding of Lua objects to and from +JSON-encoded strings. Supports |vim.NIL| and |vim.empty_dict()|. + +vim.json.decode({str}, {opts}) *vim.json.decode()* Decodes (or "unpacks") the JSON-encoded {str} to a Lua object. - {opts} is a table with the key `luanil = { object: bool, array: bool }` - that controls whether `null` in JSON objects or arrays should be converted - to Lua `nil` instead of `vim.NIL`. + • Decodes JSON "null" as |vim.NIL| (controllable by {opts}, see below). + • Decodes empty object as |vim.empty_dict()|. + • Decodes empty array as `{}` (empty Lua table). ------------------------------------------------------------------------------- -VIM.SPELL *lua-spell* + Example: >lua + vim.print(vim.json.decode('{"bar":[],"foo":{},"zub":null}')) + -- { bar = {}, foo = vim.empty_dict(), zub = vim.NIL } +< + + Parameters: ~ + • {str} (string) Stringified JSON data. + • {opts} table<string,any>|nil Options table with keys: + • luanil: (table) Table with keys: + • object: (boolean) When true, converts `null` in JSON + objects to Lua `nil` instead of |vim.NIL|. + • array: (boolean) When true, converts `null` in JSON arrays + to Lua `nil` instead of |vim.NIL|. + + Return: ~ + any + +vim.json.encode({obj}) *vim.json.encode()* + Encodes (or "packs") Lua object {obj} as JSON in a Lua string. + + Parameters: ~ + • {obj} any + + Return: ~ + (string) + + +============================================================================== +VIM.BASE64 *vim.base64* + +vim.base64.decode({str}) *vim.base64.decode()* + Decode a Base64 encoded string. + + Parameters: ~ + • {str} (string) Base64 encoded string + + Return: ~ + (string) Decoded string + +vim.base64.encode({str}) *vim.base64.encode()* + Encode {str} using Base64. + + Parameters: ~ + • {str} (string) String to encode + + Return: ~ + (string) Encoded string + + +============================================================================== +VIM.SPELL *vim.spell* vim.spell.check({str}) *vim.spell.check()* Check {str} for spelling errors. Similar to the Vimscript function @@ -745,268 +855,359 @@ vim.spell.check({str}) *vim.spell.check()* -- {'quik', 'bad', 5} -- } < + Parameters: ~ - • {str} String to spell check. + • {str} (string) Return: ~ - List of tuples with three items: - - The badly spelled word. - - The type of the spelling error: - "bad" spelling mistake - "rare" rare word - "local" word only valid in another region - "caps" word should start with Capital - - The position in {str} where the word begins. + `{[1]: string, [2]: string, [3]: string}[]` List of tuples with three items: + • The badly spelled word. + • The type of the spelling error: "bad" spelling mistake "rare" rare + word "local" word only valid in another region "caps" word should + start with Capital + • The position in {str} where the word begins. ------------------------------------------------------------------------------- -VIM *lua-builtin* -vim.api.{func}({...}) *vim.api* +============================================================================== +VIM *vim.builtin* + + +vim.api.{func}({...}) *vim.api* Invokes Nvim |API| function {func} with arguments {...}. Example: call the "nvim_get_current_line()" API function: >lua print(tostring(vim.api.nvim_get_current_line())) -vim.version() *vim.version* - Gets the version of the current Nvim build. - -vim.in_fast_event() *vim.in_fast_event()* - Returns true if the code is executing as part of a "fast" event handler, - where most of the API is disabled. These are low-level events (e.g. - |lua-loop-callbacks|) which can be invoked whenever Nvim polls for input. - When this is `false` most API functions are callable (but may be subject - to other restrictions such as |textlock|). - -vim.NIL *vim.NIL* +vim.NIL *vim.NIL* Special value representing NIL in |RPC| and |v:null| in Vimscript conversion, and similar cases. Lua `nil` cannot be used as part of a Lua table representing a Dictionary or Array, because it is treated as missing: `{"foo", nil}` is the same as `{"foo"}`. +vim.type_idx *vim.type_idx* + Type index for use in |lua-special-tbl|. Specifying one of the values from + |vim.types| allows typing the empty table (it is unclear whether empty Lua + table represents empty list or empty array) and forcing integral numbers + to be |Float|. See |lua-special-tbl| for more details. + +vim.val_idx *vim.val_idx* + Value index for tables representing |Float|s. A table representing + floating-point value 1.0 looks like this: >lua + { + [vim.type_idx] = vim.types.float, + [vim.val_idx] = 1.0, + } +< See also |vim.type_idx| and |lua-special-tbl|. + +vim.types *vim.types* + Table with possible values for |vim.type_idx|. Contains two sets of + key-value pairs: first maps possible values for |vim.type_idx| to + human-readable strings, second maps human-readable type names to values + for |vim.type_idx|. Currently contains pairs for `float`, `array` and + `dictionary` types. + + Note: One must expect that values corresponding to `vim.types.float`, + `vim.types.array` and `vim.types.dictionary` fall under only two following + assumptions: + 1. Value may serve both as a key and as a value in a table. Given the + properties of Lua tables this basically means “value is not `nil`”. + 2. For each value in `vim.types` table `vim.types[vim.types[value]]` is the + same as `value`. + No other restrictions are put on types, and it is not guaranteed that + values corresponding to `vim.types.float`, `vim.types.array` and + `vim.types.dictionary` will not change or that `vim.types` table will only + contain values for these three types. + + *log_levels* *vim.log.levels* +Log levels are one of the values defined in `vim.log.levels`: + + vim.log.levels.DEBUG + vim.log.levels.ERROR + vim.log.levels.INFO + vim.log.levels.TRACE + vim.log.levels.WARN + vim.log.levels.OFF + vim.empty_dict() *vim.empty_dict()* - Creates a special empty table (marked with a metatable), which Nvim to an - empty dictionary when translating Lua values to Vimscript or API types. - Nvim by default converts an empty table `{}` without this metatable to an - list/array. + Creates a special empty table (marked with a metatable), which Nvim + converts to an empty dictionary when translating Lua values to Vimscript + or API types. Nvim by default converts an empty table `{}` without this + metatable to an list/array. Note: If numeric keys are present in the table, Nvim ignores the metatable marker and converts the dict to a list/array anyway. -vim.rpcnotify({channel}, { |