diff options
Diffstat (limited to 'runtime/doc/lua.txt')
-rw-r--r-- | runtime/doc/lua.txt | 1859 |
1 files changed, 1256 insertions, 603 deletions
diff --git a/runtime/doc/lua.txt b/runtime/doc/lua.txt index a35d70cae8..367b5c36d2 100644 --- a/runtime/doc/lua.txt +++ b/runtime/doc/lua.txt @@ -121,16 +121,14 @@ languages like Python and C#. Example: >lua func_with_opts { foo = true, filename = "hello.world" } < -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. Nvim code tends to prefer this style. - ------------------------------------------------------------------------------- -LUA PATTERNS *lua-patterns* +There's nothing special going on here except that parentheses are implicitly +added. But visually, this small bit of sugar gets reasonably close to a +"keyword args" interface. + *lua-regex* Lua intentionally does not support regular expressions, instead it has limited -"patterns" |lua-pattern| which avoid the performance pitfalls of extended -regex. Lua scripts can also use Vim regex via |vim.regex()|. +|lua-patterns| which avoid the performance pitfalls of extended regex. Lua +scripts can also use Vim regex via |vim.regex()|. Examples: >lua @@ -256,6 +254,14 @@ arguments separated by " " (space) instead of "\t" (tab). < To see the LuaJIT version: >vim :lua =jit.version < +:{range}lua + Executes buffer lines in {range} as Lua code. Unlike |:source|, this + always treats the lines as Lua code. + + Example: select the following code and type ":lua<Enter>" to execute it: >lua + print(string.format( + 'unix time: %s', os.time())) +< *:lua-heredoc* :lua << [trim] [{endmarker}] {script} @@ -268,10 +274,8 @@ arguments separated by " " (space) instead of "\t" (tab). 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)) + local curline = vim.api.nvim_buf_get_lines(0, linenr - 1, linenr, false)[1] + print(string.format('Line [%d] has %d bytes', linenr, #curline)) EOF endfunction < @@ -574,41 +578,30 @@ A subset of the `vim.*` API is available in threads. This includes: like `vim.split`, `vim.tbl_*`, `vim.list_*`, and so on. - `vim.is_thread()` returns true from a non-main thread. ------------------------------------------------------------------------------- -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). ============================================================================== 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() - < -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 au TextYankPost * silent! lua vim.highlight.on_yank {on_visual=false} - < + vim.highlight.on_yank({opts}) *vim.highlight.on_yank()* Highlight the yanked text Parameters: ~ - • {opts} (table|nil) Optional parameters + • {opts} (`table?`) Optional parameters • higroup highlight group for yanked region (default "IncSearch") • timeout time in ms before highlight is cleared (default 150) @@ -622,7 +615,7 @@ vim.highlight.on_yank({opts}) *vim.highlight.on_yank()* 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 + • `treesitter`: `100`, used for treesitter-based highlighting • `semantic_tokens`: `125`, used for LSP semantic token highlighting • `diagnostics`: `150`, used for code analysis such as diagnostics • `user`: `200`, used for user-triggered highlights such as LSP document @@ -633,14 +626,14 @@ vim.highlight.range({bufnr}, {ns}, {higroup}, {start}, {finish}, {opts}) Apply highlight group to range of text. 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 + • {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?`) Optional parameters • regtype type of range (see |setreg()|, default charwise) • inclusive boolean indicating whether the range is end-inclusive (default false) @@ -649,47 +642,6 @@ vim.highlight.range({bufnr}, {ns}, {higroup}, {start}, {finish}, {opts}) ============================================================================== -VIM.REGEX *vim.regex* - - -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|. - - Parameters: ~ - • {re} (string) - - Return: ~ - vim.regex - - *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}. - - 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()* @@ -712,22 +664,20 @@ vim.diff({a}, {b}, {opts}) *vim.diff()* < Parameters: ~ - • {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: + • {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 @@ -738,7 +688,6 @@ vim.diff({a}, {b}, {opts}) *vim.diff()* 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 @@ -753,37 +702,45 @@ vim.diff({a}, {b}, {opts}) *vim.diff()* the internal diff library. Return: ~ - string|table|nil See {opts.result_type}. `nil` if {opts.on_hunk} is + (`string|table?`) See {opts.result_type}. `nil` if {opts.on_hunk} is given. ============================================================================== VIM.MPACK *vim.mpack* - 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. Parameters: ~ - • {str} (string) + • {str} (`string`) + + Return: ~ + (`any`) vim.mpack.encode({obj}) *vim.mpack.encode()* Encodes (or "packs") Lua object {obj} as msgpack in a Lua string. + Parameters: ~ + • {obj} (`any`) + + Return: ~ + (`string`) + ============================================================================== 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. - • 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). @@ -794,8 +751,8 @@ vim.json.decode({str}, {opts}) *vim.json.decode()* < Parameters: ~ - • {str} (string) Stringified JSON data. - • {opts} table<string,any>|nil Options table with keys: + • {str} (`string`) Stringified JSON data. + • {opts} (`table<string,any>?`) 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|. @@ -803,16 +760,16 @@ vim.json.decode({str}, {opts}) *vim.json.decode()* to Lua `nil` instead of |vim.NIL|. Return: ~ - any + (`any`) vim.json.encode({obj}) *vim.json.encode()* Encodes (or "packs") Lua object {obj} as JSON in a Lua string. Parameters: ~ - • {obj} any + • {obj} (`any`) Return: ~ - (string) + (`string`) ============================================================================== @@ -822,19 +779,19 @@ vim.base64.decode({str}) *vim.base64.decode()* Decode a Base64 encoded string. Parameters: ~ - • {str} (string) Base64 encoded string + • {str} (`string`) Base64 encoded string Return: ~ - (string) Decoded string + (`string`) Decoded string vim.base64.encode({str}) *vim.base64.encode()* Encode {str} using Base64. Parameters: ~ - • {str} (string) String to encode + • {str} (`string`) String to encode Return: ~ - (string) Encoded string + (`string`) Encoded string ============================================================================== @@ -857,10 +814,11 @@ vim.spell.check({str}) *vim.spell.check()* < Parameters: ~ - • {str} (string) + • {str} (`string`) Return: ~ - `{[1]: string, [2]: string, [3]: string}[]` List of tuples with three items: + (`{[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 @@ -872,24 +830,24 @@ vim.spell.check({str}) *vim.spell.check()* VIM *vim.builtin* -vim.api.{func}({...}) *vim.api* +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.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* +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* +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 { @@ -898,7 +856,7 @@ vim.val_idx *vim.val_id } < See also |vim.type_idx| and |lua-special-tbl|. -vim.types *vim.types* +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 @@ -927,6 +885,8 @@ Log levels are one of the values defined in `vim.log.levels`: 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 converts to an empty dictionary when translating Lua values to Vimscript @@ -936,6 +896,9 @@ vim.empty_dict() *vim.empty_dict()* Note: If numeric keys are present in the table, Nvim ignores the metatable marker and converts the dict to a list/array anyway. + Return: ~ + (`table`) + 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 @@ -944,13 +907,13 @@ vim.iconv({str}, {from}, {to}, {opts}) *vim.iconv()* ":Man 3 iconv". Parameters: ~ - • {str} (string) Text to convert - • {from} (number) Encoding of {str} - • {to} (number) Target encoding - • {opts} table<string,any>|nil + • {str} (`string`) Text to convert + • {from} (`number`) Encoding of {str} + • {to} (`number`) Target encoding + • {opts} (`table<string,any>?`) Return: ~ - (string|nil) Converted string if conversion succeeds, `nil` otherwise. + (`string?`) Converted string if conversion succeeds, `nil` otherwise. vim.in_fast_event() *vim.in_fast_event()* Returns true if the code is executing as part of a "fast" event handler, @@ -959,19 +922,18 @@ vim.in_fast_event() *vim.in_fast_event()* When this is `false` most API functions are callable (but may be subject to other restrictions such as |textlock|). -vim.rpcnotify({channel}, {method}, {args}, {...}) *vim.rpcnotify()* +vim.rpcnotify({channel}, {method}, {...}) *vim.rpcnotify()* Sends {event} to {channel} via |RPC| and returns immediately. If {channel} is 0, the event is broadcast to all channels. This function also works in a fast callback |lua-loop-callbacks|. Parameters: ~ - • {channel} (integer) - • {method} (string) - • {args} any[]|nil - • {...} any|nil + • {channel} (`integer`) + • {method} (`string`) + • {...} (`any?`) -vim.rpcrequest({channel}, {method}, {args}, {...}) *vim.rpcrequest()* +vim.rpcrequest({channel}, {method}, {...}) *vim.rpcrequest()* Sends a request to {channel} to invoke {method} via |RPC| and blocks until a response is received. @@ -979,17 +941,16 @@ vim.rpcrequest({channel}, {method}, {args}, {...}) *vim.rpcrequest()* special value Parameters: ~ - • {channel} (integer) - • {method} (string) - • {args} any[]|nil - • {...} any|nil + • {channel} (`integer`) + • {method} (`string`) + • {...} (`any?`) vim.schedule({fn}) *vim.schedule()* Schedules {fn} to be invoked soon by the main event-loop. Useful to avoid |textlock| or other temporary restrictions. Parameters: ~ - • {fn} (function) + • {fn} (`function`) vim.str_byteindex({str}, {index}, {use_utf16}) *vim.str_byteindex()* Convert UTF-32 or UTF-16 {index} to byte index. If {use_utf16} is not @@ -1000,9 +961,9 @@ vim.str_byteindex({str}, {index}, {use_utf16}) *vim.str_byteindex()* sequence. Parameters: ~ - • {str} (string) - • {index} (number) - • {use_utf16} any|nil + • {str} (`string`) + • {index} (`number`) + • {use_utf16} (`any?`) vim.str_utf_end({str}, {index}) *vim.str_utf_end()* Gets the distance (in bytes) from the last byte of the codepoint @@ -1019,11 +980,11 @@ vim.str_utf_end({str}, {index}) *vim.str_utf_end()* < Parameters: ~ - • {str} (string) - • {index} (number) + • {str} (`string`) + • {index} (`number`) Return: ~ - (number) + (`number`) vim.str_utf_pos({str}) *vim.str_utf_pos()* Gets a list of the starting byte positions of each UTF-8 codepoint in the @@ -1032,10 +993,10 @@ vim.str_utf_pos({str}) *vim.str_utf_pos()* Embedded NUL bytes are treated as terminating the string. Parameters: ~ - • {str} (string) + • {str} (`string`) Return: ~ - (table) + (`table`) vim.str_utf_start({str}, {index}) *vim.str_utf_start()* Gets the distance (in bytes) from the starting byte of the codepoint @@ -1055,11 +1016,11 @@ vim.str_utf_start({str}, {index}) *vim.str_utf_start()* < Parameters: ~ - • {str} (string) - • {index} (number) + • {str} (`string`) + • {index} (`number`) Return: ~ - (number) + (`number`) vim.str_utfindex({str}, {index}) *vim.str_utfindex()* Convert byte index to UTF-32 and UTF-16 indices. If {index} is not @@ -1071,23 +1032,23 @@ vim.str_utfindex({str}, {index}) *vim.str_utfindex()* that sequence. Parameters: ~ - • {str} (string) - • {index} (number|nil) + • {str} (`string`) + • {index} (`number?`) Return (multiple): ~ - (integer) UTF-32 index - (integer) UTF-16 index + (`integer`) UTF-32 index + (`integer`) UTF-16 index vim.stricmp({a}, {b}) *vim.stricmp()* Compares strings case-insensitively. Parameters: ~ - • {a} (string) - • {b} (string) + • {a} (`string`) + • {b} (`string`) Return: ~ - 0|1|-1 if strings are equal, {a} is greater than {b} or {a} is lesser - than {b}, respectively. + (`0|1|-1`) if strings are equal, {a} is greater than {b} or {a} is + lesser than {b}, respectively. vim.ui_attach({ns}, {options}, {callback}) *vim.ui_attach()* Attach to ui events, similar to |nvim_ui_attach()| but receive events as @@ -1125,16 +1086,16 @@ vim.ui_attach({ns}, {options}, {callback}) *vim.ui_attach()* < Parameters: ~ - • {ns} (integer) - • {options} table<string, any> - • {callback} fun() + • {ns} (`integer`) + • {options} (`table<string, any>`) + • {callback} (`fun()`) vim.ui_detach({ns}) *vim.ui_detach()* Detach a callback previously attached with |vim.ui_attach()| for the given namespace {ns}. Parameters: ~ - • {ns} (integer) + • {ns} (`integer`) vim.wait({time}, {callback}, {interval}, {fast_only}) *vim.wait()* Wait for {time} in milliseconds until {callback} returns `true`. @@ -1169,16 +1130,17 @@ vim.wait({time}, {callback}, {interval}, {fast_only}) *vim.wait()* < Parameters: ~ - • {time} (integer) Number of milliseconds to wait - • {callback} fun():|nil boolean Optional callback. Waits until + • {time} (`integer`) Number of milliseconds to wait + • {callback} (`fun(): boolean?`) Optional callback. Waits until {callback} returns true - • {interval} (integer|nil) (Approximate) number of milliseconds to - wait between polls - • {fast_only} (boolean|nil) If true, only |api-fast| events will be + • {interval} (`integer?`) (Approximate) number of milliseconds to wait + between polls + • {fast_only} (`boolean?`) If true, only |api-fast| events will be processed. - Return: ~ - boolean, nil|-1|-2 + Return (multiple): ~ + (`boolean`) + (`-1|-2?`) • If {callback} returns `true` during the {time}: `true, nil` • If {callback} never returns `true` during the {time}: `false, -1` • If {callback} is interrupted during the {time}: `false, -2` @@ -1188,18 +1150,15 @@ vim.wait({time}, {callback}, {interval}, {fast_only}) *vim.wait()* ============================================================================== LUA-VIMSCRIPT BRIDGE *lua-vimscript* - Nvim Lua provides an interface or "bridge" to Vimscript variables and functions, and editor commands and options. Objects passed over this bridge are COPIED (marshalled): there are no -"references". |lua-guide-variables| For example, using `vim.fn.remove()` -on a Lua list copies the list object to Vimscript and does NOT modify the -Lua list: >lua +"references". |lua-guide-variables| For example, using `vim.fn.remove()` on a +Lua list copies the list object to Vimscript and does NOT modify the Lua list: >lua local list = { 1, 2, 3 } vim.fn.remove(list, 0) vim.print(list) --> "{ 1, 2, 3 }" - < vim.call({func}, {...}) *vim.call()* @@ -1280,7 +1239,7 @@ vim.v *vim.v* |v:| variables. Invalid or unset key returns `nil`. -` ` *lua-options* + *lua-options* *lua-vim-options* *lua-vim-set* *lua-vim-setlocal* @@ -1303,9 +1262,10 @@ window-scoped options. Note that this must NOT be confused with |local-options| and |:setlocal|. There is also |vim.go| that only accesses the global value of a |global-local| option, see |:setglobal|. -` ` *vim.opt_local* - *vim.opt_global* - *vim.opt* + *vim.opt_local* + *vim.opt_global* + *vim.opt* + A special interface |vim.opt| exists for conveniently interacting with list- and map-style option from Lua: It allows accessing them as Lua tables and @@ -1366,6 +1326,7 @@ In any of the above examples, to replicate the behavior |:setlocal|, use `vim.opt_local`. Additionally, to replicate the behavior of |:setglobal|, use `vim.opt_global`. + Option:append({value}) *vim.opt:append()* Append a value to string-style options. See |:set+=| @@ -1375,7 +1336,7 @@ Option:append({value}) *vim.opt:append()* < Parameters: ~ - • {value} (string) Value to append + • {value} (`string`) Value to append Option:get() *vim.opt:get()* Returns a Lua-representation of the option. Boolean, number and string @@ -1421,7 +1382,7 @@ Option:get() *vim.opt:get()* < Return: ~ - string|integer|boolean|nil value of option + (`string|integer|boolean?`) value of option Option:prepend({value}) *vim.opt:prepend()* Prepend a value to string-style options. See |:set^=| @@ -1432,7 +1393,7 @@ Option:prepend({value}) *vim.opt:prepend()* < Parameters: ~ - • {value} (string) Value to prepend + • {value} (`string`) Value to prepend Option:remove({value}) *vim.opt:remove()* Remove a value from string-style options. See |:set-=| @@ -1443,14 +1404,15 @@ Option:remove({value}) *vim.opt:remove()* < Parameters: ~ - • {value} (string) Value to remove + • {value} (`string`) Value to remove vim.bo *vim.bo* - Get or set buffer-scoped |options| for the buffer with number {bufnr}. - Like `:set` and `:setlocal`. If [{bufnr}] is omitted then the current - buffer is used. Invalid {bufnr} or key is an error. + Get or set buffer-scoped |options| for the buffer with number {bufnr}. If + {bufnr} is omitted then the current buffer is used. Invalid {bufnr} or key + is an error. - Note: this is equivalent to both `:set` and `:setlocal`. + Note: this is equivalent to `:setlocal` for |global-local| options and + `:set` otherwise. Example: >lua local bufnr = vim.api.nvim_get_current_buf() @@ -1469,9 +1431,6 @@ vim.env *vim.env* print(vim.env.TERM) < - Parameters: ~ - • {var} (string) - vim.go *vim.go* Get or set global |options|. Like `:setglobal`. Invalid key is an error. @@ -1499,9 +1458,10 @@ vim.o *vim.o* vim.wo *vim.wo* Get or set window-scoped |options| for the window with handle {winid} and - buffer with number {bufnr}. Like `:setlocal` if {bufnr} is provided, like - `:set` otherwise. If [{winid}] is omitted then the current window is used. - Invalid {winid}, {bufnr} or key is an error. + buffer with number {bufnr}. Like `:setlocal` if setting a |global-local| + option or if {bufnr} is provided, like `:set` otherwise. If {winid} is + omitted then the current window is used. Invalid {winid}, {bufnr} or key + is an error. Note: only {bufnr} with value `0` (the current buffer in the window) is supported. @@ -1518,7 +1478,7 @@ vim.wo *vim.wo* ============================================================================== Lua module: vim *lua-vim* -vim.cmd *vim.cmd()* +vim.cmd({command}) *vim.cmd()* Executes Vim script commands. Note that `vim.cmd` can be indexed with a command name to return a @@ -1552,12 +1512,12 @@ vim.cmd *vim.cmd()* < Parameters: ~ - • {command} string|table Command(s) to execute. If a string, executes - multiple lines of Vim script at once. In this case, it is - an alias to |nvim_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. + • {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. See also: ~ • |ex-cmd-index| @@ -1569,33 +1529,34 @@ vim.defer_fn({fn}, {timeout}) *vim.defer_fn()* |vim.schedule_wrap()|ped automatically, so API functions are safe to call. Parameters: ~ - • {fn} (function) Callback to call once `timeout` expires - • {timeout} (integer) Number of milliseconds to wait before calling + • {fn} (`function`) Callback to call once `timeout` expires + • {timeout} (`integer`) Number of milliseconds to wait before calling `fn` Return: ~ - (table) timer luv timer object + (`table`) timer luv timer object *vim.deprecate()* vim.deprecate({name}, {alternative}, {version}, {plugin}, {backtrace}) Shows a deprecation message to the user. Parameters: ~ - • {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 + • {name} (`string`) Deprecated feature (function, API, etc.). + • {alternative} (`string?`) Suggested alternative feature. + • {version} (`string`) Version when the deprecated function will be + removed. + • {plugin} (`string?`) Name of the plugin that owns the deprecated feature. Defaults to "Nvim". - • {backtrace} boolean|nil Prints backtrace. Defaults to true. + • {backtrace} (`boolean?`) Prints backtrace. Defaults to true. Return: ~ - (string|nil) Deprecated message, or nil if no message was shown. + (`string?`) Deprecated message, or nil if no message was shown. -vim.inspect *vim.inspect()* +vim.inspect() *vim.inspect()* Gets a human-readable representation of the given object. Return: ~ - (string) + (`string`) See also: ~ • |vim.print()| @@ -1611,20 +1572,23 @@ vim.keycode({str}) *vim.keycode()* < Parameters: ~ - • {str} (string) String to be converted. + • {str} (`string`) String to be converted. Return: ~ - (string) + (`string`) See also: ~ • |nvim_replace_termcodes()| -vim.lua_omnifunc({find_start}, {_}) *vim.lua_omnifunc()* +vim.lua_omnifunc({find_start}) *vim.lua_omnifunc()* Omnifunc for completing Lua values from the runtime Lua interpreter, similar to the builtin completion for the `:lua` command. Activate using `set omnifunc=v:lua.vim.lua_omnifunc` in a Lua buffer. + Parameters: ~ + • {find_start} (`1|0`) + vim.notify({msg}, {level}, {opts}) *vim.notify()* Displays a notification to the user. @@ -1633,9 +1597,9 @@ vim.notify({msg}, {level}, {opts}) *vim.notify()* writes to |:messages|. Parameters: ~ - • {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?`) One of the values from |vim.log.levels|. + • {opts} (`table?`) Optional parameters. Unused by default. vim.notify_once({msg}, {level}, {opts}) *vim.notify_once()* Displays a notification only one time. @@ -1644,12 +1608,12 @@ vim.notify_once({msg}, {level}, {opts}) *vim.notify_once()* display a notification. Parameters: ~ - • {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?`) One of the values from |vim.log.levels|. + • {opts} (`table?`) Optional parameters. Unused by default. Return: ~ - (boolean) true if message was displayed, else false + (`boolean`) true if message was displayed, else false vim.on_key({fn}, {ns_id}) *vim.on_key()* Adds Lua function {fn} with namespace id {ns_id} as a listener to every, @@ -1664,15 +1628,15 @@ vim.on_key({fn}, {ns_id}) *vim.on_key()* • {fn} will receive the keys after mappings have been evaluated Parameters: ~ - • {fn} fun(key: string) Function invoked on every key press. - |i_CTRL-V| Returning nil removes the callback associated with - namespace {ns_id}. - • {ns_id} integer? Namespace ID. If nil or 0, generates and returns a - new |nvim_create_namespace()| id. + • {fn} (`fun(key: string)?`) Function invoked on every key press. + |i_CTRL-V| Passing in nil when {ns_id} is specified removes + the callback associated with namespace {ns_id}. + • {ns_id} (`integer?`) Namespace ID. If nil or 0, generates and returns + a new |nvim_create_namespace()| id. Return: ~ - (integer) Namespace id associated with {fn}. Or count of all callbacks - if on_key() is called without arguments. + (`integer`) Namespace id associated with {fn}. Or count of all + callbacks if on_key() is called without arguments. vim.paste({lines}, {phase}) *vim.paste()* Paste handler, invoked by |nvim_paste()| when a conforming UI (such as the @@ -1691,19 +1655,20 @@ vim.paste({lines}, {phase}) *vim.paste()* < Parameters: ~ - • {lines} string[] # |readfile()|-style list of lines to paste. + • {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: + • {phase} (`-1|1|2|3`) -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: ~ - (boolean) result false if client should cancel the paste. + (`boolean`) result false if client should cancel the paste. See also: ~ - • |paste| @alias paste_phase -1 | 1 | 2 | 3 + • |paste| vim.print({...}) *vim.print()* "Pretty prints" the given arguments and returns them unmodified. @@ -1712,8 +1677,11 @@ vim.print({...}) *vim.print()* local hl_normal = vim.print(vim.api.nvim_get_hl(0, { name = 'Normal' })) < + Parameters: ~ + • {...} (`any`) + Return: ~ - any given arguments. + (`any`) given arguments. See also: ~ • |vim.inspect()| @@ -1729,17 +1697,17 @@ vim.region({bufnr}, {pos1}, {pos2}, {regtype}, {inclusive}) returned as |v:maxcol| (big number). Parameters: ~ - • {bufnr} (integer) Buffer number, or 0 for current buffer - • {pos1} integer[]|string Start of region as a (line, column) + • {bufnr} (`integer`) Buffer number, or 0 for current buffer + • {pos1} (`integer[]|string`) Start of region as a (line, column) tuple or |getpos()|-compatible string - • {pos2} integer[]|string End of region as a (line, column) tuple - or |getpos()|-compatible string - • {regtype} (string) |setreg()|-style selection type - • {inclusive} (boolean) Controls whether the ending column is inclusive - (see also 'selection'). + • {pos2} (`integer[]|string`) End of region as a (line, column) + tuple or |getpos()|-compatible string + • {regtype} (`string`) |setreg()|-style selection type + • {inclusive} (`boolean`) Controls whether the ending column is + inclusive (see also 'selection'). Return: ~ - (table) region Dict of the form `{linenr = {startcol,endcol}}`. + (`table`) region Dict of the form `{linenr = {startcol,endcol}}`. `endcol` is exclusive, and whole lines are returned as `{startcol,endcol} = {0,-1}`. @@ -1756,10 +1724,10 @@ vim.schedule_wrap({fn}) *vim.schedule_wrap()* < Parameters: ~ - • {fn} (function) + • {fn} (`function`) Return: ~ - (function) + (`function`) See also: ~ • |lua-loop-callbacks| @@ -1789,8 +1757,8 @@ vim.system({cmd}, {opts}, {on_exit}) *vim.system()* throws an error if {cmd} cannot be run. Parameters: ~ - • {cmd} (string[]) Command to execute - • {opts} (SystemOpts|nil) Options: + • {cmd} (`string[]`) Command to execute + • {opts} (`vim.SystemOpts?`) Options: • cwd: (string) Set the current working directory for the sub-process. • env: table<string,string> Set environment variables for @@ -1820,12 +1788,13 @@ vim.system({cmd}, {opts}, {on_exit}) *vim.system()* process will still keep the parent's event loop alive unless the parent process calls |uv.unref()| on the child's process handle. - • {on_exit} (function|nil) Called when subprocess exits. When provided, - the command runs asynchronously. Receives SystemCompleted - object, see return of SystemObj:wait(). + • {on_exit} (`fun(out: vim.SystemCompleted)?`) Called when subprocess + exits. When provided, the command runs asynchronously. + Receives SystemCompleted object, see return of + SystemObj:wait(). Return: ~ - vim.SystemObj Object with the fields: + (`vim.SystemObj`) Object with the fields: • pid (integer) Process ID • wait (fun(timeout: integer|nil): SystemCompleted) Wait for the process to complete. Upon timeout the process is sent the KILL @@ -1836,7 +1805,6 @@ vim.system({cmd}, {opts}, {on_exit}) *vim.system()* • signal: (integer) • stdout: (string), nil if stdout argument is passed • stderr: (string), nil if stderr argument is passed - • kill (fun(signal: integer|string)) • write (fun(data: string|nil)) Requires `stdin=true`. Pass `nil` to close the stream. @@ -1852,24 +1820,24 @@ vim.inspect_pos({bufnr}, {row}, {col}, {filter}) *vim.inspect_pos()* Can also be pretty-printed with `:Inspect!`. *:Inspect!* Parameters: ~ - • {bufnr} (integer|nil) defaults to the current buffer - • {row} (integer|nil) row to inspect, 0-based. Defaults to the row - of the current cursor - • {col} (integer|nil) col to inspect, 0-based. Defaults to the col - of the current cursor - • {filter} (table|nil) a table with key-value pairs to filter the items - • syntax (boolean): include syntax based highlight groups - (defaults to true) - • treesitter (boolean): include treesitter based highlight - groups (defaults to true) - • extmarks (boolean|"all"): include extmarks. When `all`, - then extmarks without a `hl_group` will also be included - (defaults to true) - • semantic_tokens (boolean): include semantic tokens - (defaults to true) - - Return: ~ - (table) a table with the following key-value pairs. Items are in + • {bufnr} (`integer?`) defaults to the current buffer + • {row} (`integer?`) row to inspect, 0-based. Defaults to the row of + the current cursor + • {col} (`integer?`) col to inspect, 0-based. Defaults to the col of + the current cursor + • {filter} (`table?`) Table with key-value pairs to filter the items + • {syntax} (`boolean`, default: `true`) Include syntax based + highlight groups. + • {treesitter} (`boolean`, default: `true`) Include + treesitter based highlight groups. + • {extmarks} (`boolean|"all"`, default: true) Include + extmarks. When `all`, then extmarks without a `hl_group` + will also be included. + • {semantic_tokens} (`boolean`, default: true) Include + semantic token highlights. + + Return: ~ + (`table`) a table with the following key-value pairs. Items are in "traversal order": • treesitter: a list of treesitter captures • syntax: a list of syntax groups @@ -1885,40 +1853,91 @@ vim.show_pos({bufnr}, {row}, {col}, {filter}) *vim.show_pos()* Can also be shown with `:Inspect`. *:Inspect* Parameters: ~ - • {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()| + • {bufnr} (`integer?`) defaults to the current buffer + • {row} (`integer?`) row to inspect, 0-based. Defaults to the row of + the current cursor + • {col} (`integer?`) col to inspect, 0-based. Defaults to the col of + the current cursor + • {filter} (`table?`) A table with the following fields: + • {syntax} (`boolean`, default: `true`) Include syntax based + highlight groups. + • {treesitter} (`boolean`, default: `true`) Include + treesitter based highlight groups. + • {extmarks} (`boolean|"all"`, default: true) Include + extmarks. When `all`, then extmarks without a `hl_group` + will also be included. + • {semantic_tokens} (`boolean`, default: true) Include + semantic token highlights. + + + + +*vim.Ringbuf* + + Fields: ~ + • {clear} (`fun()`) Clear all items + • {push} (`fun(item: T)`) Adds an item, overriding the oldest item if + the buffer is full. + • {pop} (`fun(): T?`) Removes and returns the first unread item + • {peek} (`fun(): T?`) Returns the first unread item without removing + it + + +Ringbuf:clear() *Ringbuf:clear()* + Clear all items + +Ringbuf:peek() *Ringbuf:peek()* + Returns the first unread item without removing it + + Return: ~ + (`any?`) +Ringbuf:pop() *Ringbuf:pop()* + Removes and returns the first unread item + + Return: ~ + (`any?`) +Ringbuf:push({item}) *Ringbuf:push()* + Adds an item, overriding the oldest item if the buffer is full. + Parameters: ~ + • {item} (`any`) vim.deep_equal({a}, {b}) *vim.deep_equal()* Deep compare values for equality - Tables are compared recursively unless they both provide the `eq` metamethod. All other types are compared using the equality `==` operator. + 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` + (`boolean`) `true` if values are equals, else `false` -vim.deepcopy({orig}) *vim.deepcopy()* +vim.deepcopy({orig}, {noref}) *vim.deepcopy()* Returns a deep copy of the given object. Non-table objects are copied as in a typical Lua assignment, whereas table objects are copied recursively. Functions are naively copied, so functions in the copied table point to the same functions as those in the input table. Userdata and threads are not copied and will throw an error. + Note: `noref=true` is much more performant on tables with unique table + fields, while `noref=false` is more performant on tables that reuse table + fields. + Parameters: ~ - • {orig} (table) Table to copy + • {orig} (`table`) Table to copy + • {noref} (`boolean?`) When `false` (default) a contained table is only + copied once and all references point to this single copy. + When `true` every occurrence of a table results in a new + copy. This also means that a cyclic reference can cause + `deepcopy()` to fail. Return: ~ - (table) Table of copied keys and (nested) values. + (`table`) Table of copied keys and (nested) values. vim.defaulttable({createfn}) *vim.defaulttable()* Creates a table whose missing keys are provided by {createfn} (like @@ -1931,21 +1950,21 @@ vim.defaulttable({createfn}) *vim.defaulttable()* < Parameters: ~ - • {createfn} function?(key:any):any Provides the value for a missing + • {createfn} (`fun(key:any):any?`) Provides the value for a missing `key`. Return: ~ - (table) Empty table with `__index` metamethod. + (`table`) Empty table with `__index` metamethod. vim.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` + (`boolean`) `true` if `suffix` is a suffix of `s` vim.gsplit({s}, {sep}, {opts}) *vim.gsplit()* Gets an |iterator| that splits a string at each instance of a separator, @@ -1965,15 +1984,16 @@ vim.gsplit({s}, {sep}, {opts}) *vim.gsplit()* < Parameters: ~ - • {s} (string) String to split - • {sep} (string) Separator or pattern - • {opts} (table|nil) Keyword arguments |kwargs|: - • plain: (boolean) Use `sep` literally (as in string.find). - • trimempty: (boolean) Discard empty segments at start and end - of the sequence. + • {s} (`string`) String to split + • {sep} (`string`) Separator or pattern + • {opts} (`table?`) Keyword arguments |kwargs|: + • {plain}? (`boolean`) Use `sep` literally (as in + string.find). + • {trimempty}? (`boolean`) Discard empty segments at start and + end of the sequence. Return: ~ - (function) Iterator over the split components + (`fun():string?`) Iterator over the split components See also: ~ • |string.gmatch()| @@ -1986,20 +2006,20 @@ vim.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` + (`boolean`) `true` if `f` is callable, else `false` vim.list_contains({t}, {value}) *vim.list_contains()* Checks if a list-like table (integer keys without gaps) contains `value`. Parameters: ~ - • {t} (table) Table to check (must be list-like, not validated) - • {value} any Value to compare + • {t} (`table`) Table to check (must be list-like, not validated) + • {value} (`any`) Value to compare Return: ~ - (boolean) `true` if `t` contains `value` + (`boolean`) `true` if `t` contains `value` See also: ~ • |vim.tbl_contains()| for checking values in general tables @@ -2010,13 +2030,13 @@ vim.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} (integer|nil) Start index on src. Defaults to 1 - • {finish} (integer|nil) 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} (`integer?`) Start index on src. Defaults to 1 + • {finish} (`integer?`) Final index on src. Defaults to `#src` Return: ~ - (table) dst + (`table`) dst See also: ~ • |vim.tbl_extend()| @@ -2026,21 +2046,21 @@ vim.list_slice({list}, {start}, {finish}) *vim.list_slice()* (inclusive) Parameters: ~ - • {list} (list) Table - • {start} (integer|nil) Start range of slice - • {finish} (integer|nil) End range of slice + • {list} (`any[]`) Table + • {start} (`integer?`) Start range of slice + • {finish} (`integer?`) End range of slice Return: ~ - (list) Copy of table sliced from start to finish (inclusive) + (`any[]`) Copy of table sliced from start to finish (inclusive) vim.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 + (`string`) %-escaped pattern string See also: ~ • https://github.com/rxi/lume @@ -2064,50 +2084,31 @@ vim.ringbuf({size}) *vim.ringbuf()* < Returns a Ringbuf instance with the following methods: - • |Ringbuf:push()| • |Ringbuf:pop()| • |Ringbuf:peek()| • |Ringbuf:clear()| Parameters: ~ - • {size} (integer) - - Return: ~ - (table) - -vim.Ringbuf:clear() *Ringbuf:clear()* - Clear all items. - -vim.Ringbuf:peek() *Ringbuf:peek()* - Returns the first unread item without removing it + • {size} (`integer`) Return: ~ - any?|nil - -vim.Ringbuf:pop() *Ringbuf:pop()* - Removes and returns the first unread item - - Return: ~ - any?|nil - -vim.Ringbuf:push({item}) *Ringbuf:push()* - Adds an item, overriding the oldest item if the buffer is full. - - Parameters: ~ - • {item} any + (`vim.Ringbuf`) ringbuf See |vim.Ringbuf|. vim.spairs({t}) *vim.spairs()* Enumerates key-value pairs of a table, ordered by key. Parameters: ~ - • {t} (table) Dict-like table + • {t} (`table`) Dict-like table - Return: ~ - (function) |for-in| iterator over sorted keys and their values + Return (multiple): ~ + (`fun(table: table<K, V>, index?: K):K, V`) |for-in| iterator over + sorted keys and their values + (`table`) See also: ~ - • Based on https://github.com/premake/premake-core/blob/master/src/base/table.lua + • Based on + https://github.com/premake/premake-core/blob/master/src/base/table.lua vim.split({s}, {sep}, {opts}) *vim.split()* Splits a string at each instance of a separator and returns the result as @@ -2121,13 +2122,16 @@ vim.split({s}, {sep}, {opts}) *vim.split()* < Parameters: ~ - • {s} (string) String to split - • {sep} (string) Separator or pattern - • {opts} (table|nil) Keyword arguments |kwargs| accepted by - |vim.gsplit()| + • {s} (`string`) String to split + • {sep} (`string`) Separator or pattern + • {opts} (`table?`) Keyword arguments |kwargs|: + • {plain}? (`boolean`) Use `sep` literally (as in + string.find). + • {trimempty}? (`boolean`) Discard empty segments at start and + end of the sequence. Return: ~ - string[] List of split components + (`string[]`) List of split components See also: ~ • |vim.gsplit()| @@ -2137,23 +2141,11 @@ vim.startswith({s}, {prefix}) *vim.startswith()* Tests if `s` starts with `prefix`. Parameters: ~ - • {s} (string) String - • {prefix} (string) Prefix to match - - Return: ~ - (boolean) `true` if `prefix` is a prefix of `s` - -vim.tbl_add_reverse_lookup({o}) *vim.tbl_add_reverse_lookup()* - Add the reverse lookup values to an existing table. For example: - `tbl_add_reverse_lookup { A = 1 } == { [1] = 'A', A = 1 }` - - Note that this modifies the input. - - Parameters: ~ - • {o} (table) Table to add the reverse to + • {s} (`string`) String + • {prefix} (`string`) Prefix to match Return: ~ - (table) o + (`boolean`) `true` if `prefix` is a prefix of `s` vim.tbl_contains({t}, {value}, {opts}) *vim.tbl_contains()* Checks if a table contains a given value, specified either directly or via @@ -2167,14 +2159,14 @@ vim.tbl_contains({t}, {value}, {opts}) *vim.tbl_contains()* < Parameters: ~ - • {t} (table) Table to check - • {value} any Value to compare or predicate function reference - • {opts} (table|nil) Keyword arguments |kwargs|: - • predicate: (boolean) `value` is a function reference to be - checked (default false) + • {t} (`table`) Table to check + • {value} (`any`) Value to compare or predicate function reference + • {opts} (`table?`) Keyword arguments |kwargs|: + • {predicate}? (`boolean`) `value` is a function reference to + be checked (default false) Return: ~ - (boolean) `true` if `t` contains `value` + (`boolean`) `true` if `t` contains `value` See also: ~ • |vim.list_contains()| for checking values in list-like tables @@ -2186,10 +2178,10 @@ vim.tbl_count({t}) *vim.tbl_count()* < Parameters: ~ - • {t} (table) Table + • {t} (`table`) Table Return: ~ - (integer) Number of non-nil values in table + (`integer`) Number of non-nil values in table See also: ~ • https://github.com/Tieske/Penlight/blob/master/lua/pl/tablex.lua @@ -2198,15 +2190,15 @@ vim.tbl_deep_extend({behavior}, {...}) *vim.tbl_deep_extend()* Merges recursively two or more tables. Parameters: ~ - • {behavior} (string) Decides what to do if a key is found in more than - one map: + • {behavior} (`"error"|"keep"|"force"`) (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 tables + • {...} (`table`) Two or more tables Return: ~ - (table) Merged table + (`table`) Merged table See also: ~ • |vim.tbl_extend()| @@ -2215,15 +2207,15 @@ vim.tbl_extend({behavior}, {...}) *vim.tbl_extend()* Merges two or more tables. Parameters: ~ - • {behavior} (string) Decides what to do if a key is found in more than - one map: + • {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 tables + • {...} (`table`) Two or more tables Return: ~ - (table) Merged table + (`table`) Merged table See also: ~ • |extend()| @@ -2232,24 +2224,25 @@ vim.tbl_filter({func}, {t}) *vim.tbl_filter()* Filter a table using a predicate function Parameters: ~ - • {func} (function) Function - • {t} (table) Table + • {func} (`function`) Function + • {t} (`table`) Table Return: ~ - (table) Table of filtered values + (`any[]`) Table of filtered values vim.tbl_flatten({t}) *vim.tbl_flatten()* Creates a copy of a list-like table such that any nested tables are "unrolled" and appended to the result. Parameters: ~ - • {t} (table) List-like table + • {t} (`table`) List-like table Return: ~ - (table) Flattened copy of the given list-like table + (`table`) Flattened copy of the given list-like table See also: ~ - • From https://github.com/premake/premake-core/blob/master/src/base/table.lua + • From + https://github.com/premake/premake-core/blob/master/src/base/table.lua vim.tbl_get({o}, {...}) *vim.tbl_get()* Index into a table (first argument) via string keys passed as subsequent @@ -2261,15 +2254,16 @@ vim.tbl_get({o}, {...}) *vim.tbl_get()* < Parameters: ~ - • {o} (table) Table to index - • {...} any Optional keys (0 or more, variadic) via which to index the - table + • {o} (`table`) Table to index + • {...} (`any`) Optional keys (0 or more, variadic) via which to index + the table Return: ~ - any Nested value indexed by key (if it exists), else nil + (`any`) Nested value indexed by key (if it exists), else nil vim.tbl_isarray({t}) *vim.tbl_isarray()* - Tests if `t` is an "array": a table indexed only by integers (potentially non-contiguous). + Tests if `t` is an "array": a table indexed only by integers (potentially + non-contiguous). If the indexes start from 1 and are contiguous then the array is also a list. |vim.tbl_islist()| @@ -2279,10 +2273,10 @@ vim.tbl_isarray({t}) *vim.tbl_isarray()* |rpcrequest()| or |vim.fn|. Parameters: ~ - • {t} (table) + • {t} (`table`) Return: ~ - (boolean) `true` if array-like table, else `false`. + (`boolean`) `true` if array-like table, else `false`. See also: ~ • https://github.com/openresty/luajit2#tableisarray @@ -2291,27 +2285,27 @@ vim.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 + (`boolean`) `true` if `t` is empty See also: ~ • https://github.com/premake/premake-core/blob/master/src/base/table.lua vim.tbl_islist({t}) *vim.tbl_islist()* - Tests if `t` is a "list": a table indexed only by contiguous integers starting from 1 (what |lua-length| calls a "regular - array"). + Tests if `t` is a "list": a table indexed only by contiguous integers + starting from 1 (what |lua-length| calls a "regular array"). Empty table `{}` is a list, unless it was created by |vim.empty_dict()| or returned as a dict-like |API| or Vimscript result, for example from |rpcrequest()| or |vim.fn|. Parameters: ~ - • {t} (table) + • {t} (`table`) Return: ~ - (boolean) `true` if list-like table, else `false`. + (`boolean`) `true` if list-like table, else `false`. See also: ~ • |vim.tbl_isarray()| @@ -2321,42 +2315,43 @@ vim.tbl_keys({t}) *vim.tbl_keys()* return table of keys is not guaranteed. Parameters: ~ - • {t} (table) Table + • {t} (`table`) Table Return: ~ - (list) List of keys + (`any[]`) List of keys See also: ~ - • From https://github.com/premake/premake-core/blob/master/src/base/table.lua + • From + https://github.com/premake/premake-core/blob/master/src/base/table.lua vim.tbl_map({func}, {t}) *vim.tbl_map()* Apply a function to all values of a table. Parameters: ~ - • {func} (function) Function - • {t} (table) Table + • {func} (`fun(value: T): any`) Function + • {t} (`table<any, T>`) Table Return: ~ - (table) Table of transformed values + (`table`) Table of transformed values vim.tbl_values({t}) *vim.tbl_values()* Return a list of all values used in a table. However, the order of the return table of values is not guaranteed. Parameters: ~ - • {t} (table) Table + • {t} (`table`) Table Return: ~ - (list) List of values + (`any[]`) List of values vim.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 + (`string`) String with whitespace removed from its beginning and end See also: ~ • |lua-patterns| @@ -2396,7 +2391,7 @@ vim.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 @@ -2404,7 +2399,6 @@ vim.validate({opt}) *vim.validate()* "string", "s", "number", "n", "boolean", "b", "function", "f", "nil", "thread", "userdata") or list of them. • optional: (optional) boolean, if true, `nil` is valid - 2. (arg_value, fn, msg) • arg_value: argument value • fn: any function accepting one argument, returns true if @@ -2433,32 +2427,32 @@ vim.loader.find({modname}, {opts}) *vim.loader.find()* Finds Lua modules for the given module name. Parameters: ~ - • {modname} (string) Module name, or `"*"` to find the top-level + • {modname} (`string`) Module name, or `"*"` to find the top-level modules instead - • {opts} (table|nil) Options for finding a module: - • rtp: (boolean) Search for modname in the runtime path - (defaults to `true`) - • paths: (string[]) Extra paths to search for modname - (defaults to `{}`) - • patterns: (string[]) List of patterns to use when + • {opts} (`table?`) Options for finding a module: + • {rtp}? (`boolean`, default: `true`) Search for modname in + the runtime path. + • {paths}? (`string[]`, default: `{}`) Extra paths to + search for modname + • {patterns}? (`string[]`, default: + `{"/init.lua", ".lua"}`) List of patterns to use when searching for modules. A pattern is a string added to the - basename of the Lua module being searched. (defaults to - `{"/init.lua", ".lua"}`) - • all: (boolean) Return all matches instead of just the - first one (defaults to `false`) + basename of the Lua module being searched. + • {all}? (`boolean`, default: `false`) Search for all + matches. Return: ~ - (list) A list of results with the following properties: - • modpath: (string) the path to the module - • modname: (string) the name of the module - • stat: (table|nil) the fs_stat of the module path. Won't be returned - for `modname="*"` + (`table[]`) A list of objects with the following fields: + • {modpath} (`string`) Path of the module + • {modname} (`string`) Name of the module + • {stat}? (`uv.uv_fs_t`) The fs_stat of the module path. Won't be + returned for `modname="*"` vim.loader.reset({path}) *vim.loader.reset()* Resets the cache for the path, or all the paths if path is nil. Parameters: ~ - • {path} string? path to reset + • {path} (`string?`) path to reset ============================================================================== @@ -2468,57 +2462,57 @@ vim.uri_decode({str}) *vim.uri_decode()* URI-decodes a string containing percent escapes. Parameters: ~ - • {str} (string) string to decode + • {str} (`string`) string to decode Return: ~ - (string) decoded string + (`string`) decoded string vim.uri_encode({str}, {rfc}) *vim.uri_encode()* URI-encodes a string using percent escapes. Parameters: ~ - • {str} (string) string to encode - • {rfc} "rfc2396" | "rfc2732" | "rfc3986" | nil + • {str} (`string`) string to encode + • {rfc} (`"rfc2396"|"rfc2732"|"rfc3986"?`) Return: ~ - (string) encoded string + (`string`) encoded string vim.uri_from_bufnr({bufnr}) *vim.uri_from_bufnr()* Gets a URI from a bufnr. Parameters: ~ - • {bufnr} (integer) + • {bufnr} (`integer`) Return: ~ - (string) URI + (`string`) URI vim.uri_from_fname({path}) *vim.uri_from_fname()* Gets a URI from a file path. Parameters: ~ - • {path} (string) Path to file + • {path} (`string`) Path to file Return: ~ - (string) URI + (`string`) URI vim.uri_to_bufnr({uri}) *vim.uri_to_bufnr()* Gets the buffer for a uri. Creates a new unloaded buffer if no buffer for the uri already exists. Parameters: ~ - • {uri} (string) + • {uri} (`string`) Return: ~ - (integer) bufnr + (`integer`) bufnr vim.uri_to_fname({uri}) *vim.uri_to_fname()* Gets a filename from a URI. Parameters: ~ - • {uri} (string) + • {uri} (`string`) Return: ~ - (string) filename or unchanged URI for non-file URIs + (`string`) filename or unchanged URI for non-file URIs ============================================================================== @@ -2535,7 +2529,7 @@ vim.ui.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 @@ -2544,7 +2538,7 @@ vim.ui.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 (it might be an empty string if nothing was entered), or `nil` if the user aborted the dialog. @@ -2563,11 +2557,11 @@ vim.ui.open({path}) *vim.ui.open()* < Parameters: ~ - • {path} (string) Path or URL to open + • {path} (`string`) Path or URL to open Return (multiple): ~ - vim.SystemCompleted|nil Command result, or nil if not found. - (string|nil) Error message on failure + (`vim.SystemCompleted?`) Command result, or nil if not found. + (`string?`) Error message on failure See also: ~ • |vim.system()| @@ -2592,8 +2586,8 @@ vim.ui.select({items}, {opts}, {on_choice}) *vim.ui.select()* < Parameters: ~ - • {items} (table) Arbitrary items - • {opts} (table) Additional options + • {items} (`any[]`) 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 @@ -2603,8 +2597,8 @@ vim.ui.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 - user made a choice. `idx` is the 1-based index of `item` + • {on_choice} (`fun(item: any?, idx: integer?)`) Called once the user + made a choice. `idx` is the 1-based index of `item` within `items`. `nil` if the user aborted the dialog. @@ -2658,9 +2652,9 @@ vim.filetype.add({filetypes}) *vim.filetype.add()* ['/etc/foo/config'] = 'toml', }, pattern = { - ['.*‍/etc/foo/.*'] = 'fooscript', + ['.*/etc/foo/.*'] = 'fooscript', -- Using an optional priority - ['.*‍/etc/foo/.*%.conf'] = { 'dosini', { priority = 10 } }, + ['.*/etc/foo/.*%.conf'] = { 'dosini', { priority = 10 } }, -- A pattern containing an environment variable ['${XDG_CONFIG_HOME}/foo/git'] = 'git', ['README.(%a+)$'] = function(path, bufnr, ext) @@ -2693,8 +2687,11 @@ vim.filetype.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). + • {pattern}? (`vim.filetype.mapping`) + • {extension}? (`vim.filetype.mapping`) + • {filename}? (`vim.filetype.mapping`) *vim.filetype.get_option()* vim.filetype.get_option({filetype}, {option}) @@ -2713,11 +2710,11 @@ vim.filetype.get_option({filetype}, {option}) may not reflect later changes. Parameters: ~ - • {filetype} (string) Filetype - • {option} (string) Option name + • {filetype} (`string`) Filetype + • {option} (`string`) Option name Return: ~ - string|boolean|integer: Option value + (`string|boolean|integer`) Option value vim.filetype.match({args}) *vim.filetype.match()* Perform filetype detection. @@ -2749,24 +2746,24 @@ vim.filetype.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} - • filename (string): Filename to use for matching. When {buf} - is given, defaults to the filename of the given buffer + • {buf}? (`integer`) Buffer number to use for matching. + Mutually exclusive with {contents} + • {filename}? (`string`) Filename to use for matching. When + {buf} is given, defaults to the filename of the given buffer number. The file need not actually exist in the filesystem. When used without {buf} only the name of the file is used for filetype matching. This may result in failure to detect the filetype in cases where the filename alone is not enough to disambiguate the filetype. - • contents (table): An array of lines representing file + • {contents}? (`string[]`) An array of lines representing file contents to use for matching. Can be used with {filename}. Mutually exclusive with {buf}. Return (multiple): ~ - (string|nil) If a match was found, the matched filetype. - (function|nil) A function that modifies buffer state when called (for + (`string?`) If a match was found, the matched filetype. + (`function?`) A function that modifies buffer state when called (for example, to set some filetype specific buffer variables). The function accepts a buffer number as its only argument. @@ -2782,9 +2779,11 @@ vim.keymap.del({modes}, {lhs}, {opts}) *vim.keymap.del()* < Parameters: ~ - • {opts} (table|nil) A table of optional arguments: - • "buffer": (integer|boolean) Remove a mapping from the given - buffer. When `0` or `true`, use the current buffer. + • {modes} (`string|string[]`) + • {lhs} (`string`) + • {opts} (`table?`) A table of optional arguments: + • "buffer": (integer|boolean) Remove a mapping from the given + buffer. When `0` or `true`, use the current buffer. See also: ~ • |vim.keymap.set()| @@ -2806,16 +2805,15 @@ vim.keymap.set({mode}, {lhs}, {rhs}, {opts}) *vim.keymap.set()* < Parameters: ~ - • {mode} string|table Mode short-name, see |nvim_set_keymap()|. Can + • {mode} (`string|table`) Mode short-name, see |nvim_set_keymap()|. Can also be list of modes to create mapping on multiple modes. - • {lhs} (string) Left-hand side |{lhs}| of the mapping. - • {rhs} string|function Right-hand side |{rhs}| of the mapping, can be - a Lua function. - • {opts} (table|nil) Table of |:map-arguments|. + • {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?`) Table of |:map-arguments|. • Same as |nvim_set_keymap()| {opts}, except: • "replace_keycodes" defaults to `true` if "expr" is `true`. • "noremap": inverse of "remap" (see below). - • Also accepts: • "buffer": (integer|boolean) Creates buffer-local mapping, `0` or `true` for current buffer. @@ -2836,26 +2834,26 @@ vim.fs.basename({file}) *vim.fs.basename()* Return the basename of the given path Parameters: ~ - • {file} (string) Path + • {file} (`string?`) Path Return: ~ - (string|nil) Basename of {file} + (`string?`) Basename of {file} vim.fs.dir({path}, {opts}) *vim.fs.dir()* Return an iterator over the items located in {path} Parameters: ~ - • {path} (string) An absolute or relative path to the directory to + • {path} (`string`) An absolute or relative path to the directory to iterate over. The path is first normalized |vim.fs.normalize()|. - • {opts} (table|nil) Optional keyword arguments: + • {opts} (`table?`) Optional keyword arguments: • depth: integer|nil How deep the traverse (default 1) • skip: (fun(dir_name: string): boolean)|nil Predicate to control traversal. Return false to stop searching the current directory. Only useful when depth > 1 Return: ~ - Iterator over items in {path}. Each iteration yields two values: + (`Iterator`) over items in {path}. Each iteration yields two values: "name" and "type". "name" is the basename of the item relative to {path}. "type" is one of the following: "file", "directory", "link", "fifo", "socket", "char", "block", "unknown". @@ -2864,10 +2862,10 @@ vim.fs.dirname({file}) *vim.fs.dirname()* Return the parent directory of the given path Parameters: ~ - • {file} (string) Path + • {file} (`string?`) Path Return: ~ - (string|nil) Parent directory of {file} + (`string?`) Parent directory of {file} vim.fs.find({names}, {opts}) *vim.fs.find()* Find files or directories (or other items as specified by `opts.type`) in @@ -2903,7 +2901,7 @@ vim.fs.find({names}, {opts}) *vim.fs.find()* < Parameters: ~ - • {names} (string|string[]|fun(name: string, path: string): boolean) + • {names} (`string|string[]|fun(name: string, path: string): boolean`) Names of the items to find. Must be base names, paths and globs are not supported when {names} is a string or a table. If {names} is a function, it is called for each traversed @@ -2911,32 +2909,33 @@ vim.fs.find({names}, {opts}) *vim.fs.find()* • name: base name of the current item • path: full path of the current item The function should return `true` if the given item is considered a match. - • {opts} (table) Optional keyword arguments: - • path (string): Path to begin searching from. If omitted, - the |current-directory| is used. - • upward (boolean, default false): If true, search upward + • {opts} (`table`) Optional keyword arguments: + • {path}? (`string`) Path to begin searching from. If + omitted, the |current-directory| is used. + • {upward}? (`boolean`, default: `false`) Search upward through parent directories. Otherwise, search through child directories (recursively). - • stop (string): Stop searching when this directory is + • {stop}? (`string`) Stop searching when this directory is reached. The directory itself is not searched. - • type (string): Find only items of the given type. If + • {type}? (`string`) Find only items of the given type. If omitted, all items that match {names} are included. - • limit (number, default 1): Stop the search after finding - this many matches. Use `math.huge` to place no limit on the - number of matches. + • {limit}? (`number`, default: `1`) Stop the search after + finding this many matches. Use `math.huge` to place no + limit on the number of matches. Return: ~ - (string[]) Normalized paths |vim.fs.normalize()| of all matching items + (`string[]`) Normalized paths |vim.fs.normalize()| of all matching + items vim.fs.joinpath({...}) *vim.fs.joinpath()* Concatenate directories and/or file paths into a single path with normalization (e.g., `"foo/"` and `"bar"` get joined to `"foo/bar"`) Parameters: ~ - • {...} (string) + • {...} (`string`) Return: ~ - (string) + (`string`) vim.fs.normalize({path}, {opts}) *vim.fs.normalize()* Normalize a path to a standard format. A tilde (~) character at the @@ -2956,13 +2955,13 @@ vim.fs.normalize({path}, {opts}) *vim.fs.normalize()* < Parameters: ~ - • {path} (string) Path to normalize - • {opts} (table|nil) Options: - • expand_env: boolean Expand environment variables (default: - true) + • {path} (`string`) Path to normalize + • {opts} (`table?`) A table with the following fields: + • {expand_env} (`boolean`, default: `true`) Expand environment + variables. Return: ~ - (string) Normalized path + (`string`) Normalized path vim.fs.parents({start}) *vim.fs.parents()* Iterate over all the parents of the given path. @@ -2982,12 +2981,552 @@ vim.fs.parents({start}) *vim.fs.parents()* < Parameters: ~ - • {start} (string) Initial path. + • {start} (`string`) Initial path. + + Return (multiple): ~ + (`fun(_, dir: string): string?`) Iterator + (`nil`) + (`string?`) + + +============================================================================== +Lua module: vim.glob *vim.glob* + +vim.glob.to_lpeg({pattern}) *vim.glob.to_lpeg()* + Parses a raw glob into an |lua-lpeg| pattern. + + This uses glob semantics from LSP 3.17.0: + https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#pattern + + Glob patterns can have the following syntax: + • `*` to match one or more characters in a path segment + • `?` to match on one character in a path segment + • `**` to match any number of path segments, including none + • `{}` to group conditions (e.g. `*.{ts,js}` matches TypeScript and + JavaScript files) + • `[]` to declare a range of characters to match in a path segment (e.g., + `example.[0-9]` to match on `example.0`, `example.1`, …) + • `[!...]` to negate a range of characters to match in a path segment + (e.g., `example.[!0-9]` to match on `example.a`, `example.b`, but not + `example.0`) + + Parameters: ~ + • {pattern} (`string`) The raw glob pattern + + Return: ~ + (`vim.lpeg.Pattern`) pattern An |lua-lpeg| representation of the + pattern + + +============================================================================== +VIM.LPEG *vim.lpeg* + + +LPeg is a pattern-matching library for Lua, based on +Parsing Expression Grammars (https://bford.info/packrat/) (PEGs). + + *lua-lpeg* + *vim.lpeg.Pattern* +The LPeg library for parsing expression grammars is included as `vim.lpeg` +(https://www.inf.puc-rio.br/~roberto/lpeg/). + +In addition, its regex-like interface is available as |vim.re| +(https://www.inf.puc-rio.br/~roberto/lpeg/re.html). + + + +Pattern:match({subject}, {init}) *Pattern:match()* + Matches the given `pattern` against the `subject` string. If the match + succeeds, returns the index in the subject of the first character after + the match, or the captured values (if the pattern captured any value). An + optional numeric argument `init` makes the match start at that position in + the subject string. As usual in Lua libraries, a negative value counts + from the end. Unlike typical pattern-matching functions, `match` works + only in anchored mode; that is, it tries to match the pattern with a + prefix of the given subject string (at position `init`), not with an + arbitrary substring of the subject. So, if we want to find a pattern + anywhere in a string, we must either write a loop in Lua or write a + pattern that matches anywhere. + + Example: >lua + local pattern = lpeg.R('az') ^ 1 * -1 + assert(pattern:match('hello') == 6) + assert(lpeg.match(pattern, 'hello') == 6) + assert(pattern:match('1 hello') == nil) +< + + Parameters: ~ + • {subject} (`string`) + • {init} (`integer?`) + + Return: ~ + (`integer|vim.lpeg.Capture?`) + +vim.lpeg.B({pattern}) *vim.lpeg.B()* + Returns a pattern that matches only if the input string at the current + position is preceded by `patt`. Pattern `patt` must match only strings + with some fixed length, and it cannot contain captures. Like the `and` + predicate, this pattern never consumes any input, independently of success + or failure. + + Parameters: ~ + • {pattern} (`vim.lpeg.Pattern`) + + Return: ~ + (`vim.lpeg.Pattern`) + +vim.lpeg.C({patt}) *vim.lpeg.C()* + Creates a simple capture, which captures the substring of the subject that + matches `patt`. The captured value is a string. If `patt` has other + captures, their values are returned after this one. + + Example: >lua + local function split (s, sep) + sep = lpeg.P(sep) + local elem = lpeg.C((1 - sep) ^ 0) + local p = elem * (sep * elem) ^ 0 + return lpeg.match(p, s) + end + local a, b, c = split('a,b,c', ',') + assert(a == 'a') + assert(b == 'b') + assert(c == 'c') +< + + Parameters: ~ + • {patt} (`vim.lpeg.Pattern`) + + Return: ~ + (`vim.lpeg.Capture`) + +vim.lpeg.Carg({n}) *vim.lpeg.Carg()* + Creates an argument capture. This pattern matches the empty string and + produces the value given as the nth extra argument given in the call to + `lpeg.match`. + + Parameters: ~ + • {n} (`integer`) + + Return: ~ + (`vim.lpeg.Capture`) + +vim.lpeg.Cb({name}) *vim.lpeg.Cb()* + Creates a back capture. This pattern matches the empty string and produces + the values produced by the most recent group capture named `name` (where + `name` can be any Lua value). Most recent means the last complete + outermost group capture with the given name. A Complete capture means that + the entire pattern corresponding to the capture has matched. An Outermost + capture means that the capture is not inside another complete capture. In + the same way that LPeg does not specify when it evaluates captures, it + does not specify whether it reuses values previously produced by the group + or re-evaluates them. + + Parameters: ~ + • {name} (`any`) + + Return: ~ + (`vim.lpeg.Capture`) + +vim.lpeg.Cc({...}) *vim.lpeg.Cc()* + Creates a constant capture. This pattern matches the empty string and + produces all given values as its captured values. + + Parameters: ~ + • {...} (`any`) + + Return: ~ + (`vim.lpeg.Capture`) + +vim.lpeg.Cf({patt}, {func}) *vim.lpeg.Cf()* + Creates a fold capture. If `patt` produces a list of captures C1 C2 ... + Cn, this capture will produce the value + `func(...func(func(C1, C2), C3)...,Cn)`, that is, it will fold (or + accumulate, or reduce) the captures from `patt` using function `func`. + This capture assumes that `patt` should produce at least one capture with + at least one value (of any type), which becomes the initial value of an + accumulator. (If you need a specific initial value, you may prefix a + constant captureto `patt`.) For each subsequent capture, LPeg calls `func` + with this accumulator as the first argument and all values produced by the + capture as extra arguments; the first result from this call becomes the + new value for the accumulator. The final value of the accumulator becomes + the captured value. + + Example: >lua + local number = lpeg.R('09') ^ 1 / tonumber + local list = number * (',' * number) ^ 0 + local function add(acc, newvalue) return acc + newvalue end + local sum = lpeg.Cf(list, add) + assert(sum:match('10,30,43') == 83) +< + + Parameters: ~ + • {patt} (`vim.lpeg.Pattern`) + • {func} (`fun(acc, newvalue)`) + + Return: ~ + (`vim.lpeg.Capture`) + +vim.lpeg.Cg({patt}, {name}) *vim.lpeg.Cg()* + Creates a group capture. It groups all values returned by `patt` into a + single capture. The group may be anonymous (if no name is given) or named + with the given name (which can be any non-nil Lua value). + + Parameters: ~ + • {patt} (`vim.lpeg.Pattern`) + • {name} (`string?`) + + Return: ~ + (`vim.lpeg.Capture`) + +vim.lpeg.Cmt({patt}, {fn}) *vim.lpeg.Cmt()* + Creates a match-time capture. Unlike all other captures, this one is + evaluated immediately when a match occurs (even if it is part of a larger + pattern that fails later). It forces the immediate evaluation of all its + nested captures and then calls `function`. The given function gets as + arguments the entire subject, the current position (after the match of + `patt`), plus any capture values produced by `patt`. The first value + returned by `function` defines how the match happens. If the call returns + a number, the match succeeds and the returned number becomes the new + current position. (Assuming a subject sand current position `i`, the + returned number must be in the range `[i, len(s) + 1]`.) If the call + returns `true`, the match succeeds without consuming any input (so, to + return true is equivalent to return `i`). If the call returns `false`, + `nil`, or no value, the match fails. Any extra values returned by the + function become the values produced by the capture. + + Parameters: ~ + • {patt} (`vim.lpeg.Pattern`) + • {fn} (`function`) + + Return: ~ + (`vim.lpeg.Capture`) + +vim.lpeg.Cp() *vim.lpeg.Cp()* + Creates a position capture. It matches the empty string and captures the + position in the subject where the match occurs. The captured value is a + number. + + Example: >lua + local I = lpeg.Cp() + local function anywhere(p) return lpeg.P({I * p * I + 1 * lpeg.V(1)}) end + local match_start, match_end = anywhere('world'):match('hello world!') + assert(match_start == 7) + assert(match_end == 12) +< + + Return: ~ + (`vim.lpeg.Capture`) + +vim.lpeg.Cs({patt}) *vim.lpeg.Cs()* + Creates a substitution capture. This function creates a substitution + capture, which captures the substring of the subject that matches `patt`, + with substitutions. For any capture inside `patt` with a value, the + substring that matched the capture is replaced by the capture value (which + should be a string). The final captured value is the string resulting from + all replacements. + + Example: >lua + local function gsub (s, patt, repl) + patt = lpeg.P(patt) + patt = lpeg.Cs((patt / repl + 1) ^ 0) + return lpeg.match(patt, s) + end + assert(gsub('Hello, xxx!', 'xxx', 'World') == 'Hello, World!') +< + + Parameters: ~ + • {patt} (`vim.lpeg.Pattern`) + + Return: ~ + (`vim.lpeg.Capture`) + +vim.lpeg.Ct({patt}) *vim.lpeg.Ct()* + Creates a table capture. This capture returns a table with all values from + all anonymous captures made by `patt` inside this table in successive + integer keys, starting at 1. Moreover, for each named capture group + created by `patt`, the first value of the group is put into the table with + the group name as its key. The captured value is only the table. + + Parameters: ~ + • {patt} (`vim.lpeg.Pattern|''`) + + Return: ~ + (`vim.lpeg.Capture`) + +vim.lpeg.locale({tab}) *vim.lpeg.locale()* + Returns a table with patterns for matching some character classes + according to the current locale. The table has fields named `alnum`, + `alpha`, `cntrl`, `digit`, `graph`, `lower`, `print`, `punct`, `space`, + `upper`, and `xdigit`, each one containing a correspondent pattern. Each + pattern matches any single character that belongs to its class. If called + with an argument `table`, then it creates those fields inside the given + table and returns that table. + + Example: >lua + lpeg.locale(lpeg) + local space = lpeg.space ^ 0 + local name = lpeg.C(lpeg.alpha ^ 1) * space + local sep = lpeg.S(',;') * space + local pair = lpeg.Cg(name * '=' * space * name) * sep ^ -1 + local list = lpeg.Cf(lpeg.Ct('') * pair ^ 0, rawset) + local t = list:match('a=b, c = hi; next = pi') + assert(t.a == 'b') + assert(t.c == 'hi') + assert(t.next == 'pi') + local locale = lpeg.locale() + assert(type(locale.digit) == 'userdata') +< + + Parameters: ~ + • {tab} (`table?`) + + Return: ~ + (`vim.lpeg.Locale`) + +vim.lpeg.match({pattern}, {subject}, {init}) *vim.lpeg.match()* + Matches the given `pattern` against the `subject` string. If the match + succeeds, returns the index in the subject of the first character after + the match, or the captured values (if the pattern captured any value). An + optional numeric argument `init` makes the match start at that position in + the subject string. As usual in Lua libraries, a negative value counts + from the end. Unlike typical pattern-matching functions, `match` works + only in anchored mode; that is, it tries to match the pattern with a + prefix of the given subject string (at position `init`), not with an + arbitrary substring of the subject. So, if we want to find a pattern + anywhere in a string, we must either write a loop in Lua or write a + pattern that matches anywhere. + + Example: >lua + local pattern = lpeg.R('az') ^ 1 * -1 + assert(pattern:match('hello') == 6) + assert(lpeg.match(pattern, 'hello') == 6) + assert(pattern:match('1 hello') == nil) +< + + Parameters: ~ + • {pattern} (`vim.lpeg.Pattern`) + • {subject} (`string`) + • {init} (`integer?`) + + Return: ~ + (`integer|vim.lpeg.Capture?`) + +vim.lpeg.P({value}) *vim.lpeg.P()* + Converts the given value into a proper pattern. The following rules are + applied: + • If the argument is a pattern, it is returned unmodified. + • If the argument is a string, it is translated to a pattern that matches + the string literally. + • If the argument is a non-negative number `n`, the result is a pattern + that matches exactly `n` characters. + • If the argument is a negative number `-n`, the result is a pattern that + succeeds only if the input string has less than `n` characters left: + `lpeg.P(-n)` is equivalent to `-lpeg.P(n)` (see the unary minus + operation). + • If the argument is a boolean, the result is a pattern that always + succeeds or always fails (according to the boolean value), without + consuming any input. + • If the argument is a table, it is interpreted as a grammar (see + Grammars). + • If the argument is a function, returns a pattern equivalent to a + match-time capture over the empty string. + + Parameters: ~ + • {value} (`vim.lpeg.Pattern|string|integer|boolean|table|function`) + + Return: ~ + (`vim.lpeg.Pattern`) + +vim.lpeg.R({...}) *vim.lpeg.R()* + Returns a pattern that matches any single character belonging to one of + the given ranges. Each `range` is a string `xy` of length 2, representing + all characters with code between the codes of `x` and `y` (both + inclusive). As an example, the pattern `lpeg.R('09')` matches any digit, + and `lpeg.R('az', 'AZ')` matches any ASCII letter. + + Example: >lua + local pattern = lpeg.R('az') ^ 1 * -1 + assert(pattern:match('hello') == 6) +< + + Parameters: ~ + • {...} (`string`) + + Return: ~ + (`vim.lpeg.Pattern`) + +vim.lpeg.S({string}) *vim.lpeg.S()* + Returns a pattern that matches any single character that appears in the + given string (the `S` stands for Set). As an example, the pattern + `lpeg.S('+-*/')` matches any arithmetic operator. Note that, if `s` is a + character (that is, a string of length 1), then `lpeg.P(s)` is equivalent + to `lpeg.S(s)` which is equivalent to `lpeg.R(s..s)`. Note also that both + `lpeg.S('')` and `lpeg.R()` are patterns that always fail. + + Parameters: ~ + • {string} (`string`) + + Return: ~ + (`vim.lpeg.Pattern`) + +vim.lpeg.setmaxstack({max}) *vim.lpeg.setmaxstack()* + Sets a limit for the size of the backtrack stack used by LPeg to track + calls and choices. The default limit is `400`. Most well-written patterns + need little backtrack levels and therefore you seldom need to change this + limit; before changing it you should try to rewrite your pattern to avoid + the need for extra space. Nevertheless, a few useful patterns may + overflow. Also, with recursive grammars, subjects with deep recursion may + also need larger limits. + + Parameters: ~ + • {max} (`integer`) + +vim.lpeg.type({value}) *vim.lpeg.type()* + Returns the string `"pattern"` if the given value is a pattern, otherwise + `nil`. + + Parameters: ~ + • {value} (`vim.lpeg.Pattern|string|integer|boolean|table|function`) + + Return: ~ + (`"pattern"?`) + +vim.lpeg.V({v}) *vim.lpeg.V()* + Creates a non-terminal (a variable) for a grammar. This operation creates + a non-terminal (a variable) for a grammar. The created non-terminal refers + to the rule indexed by `v` in the enclosing grammar. + + Example: >lua + local b = lpeg.P({'(' * ((1 - lpeg.S '()') + lpeg.V(1)) ^ 0 * ')'}) + assert(b:match('((string))') == 11) + assert(b:match('(') == nil) +< + + Parameters: ~ + • {v} (`string|integer`) + + Return: ~ + (`vim.lpeg.Pattern`) + +vim.lpeg.version() *vim.lpeg.version()* + Returns a string with the running version of LPeg. + + Return: ~ + (`string`) + + +============================================================================== +VIM.RE *vim.re* + +The `vim.re` module provides a conventional regex-like syntax for pattern +usage within LPeg |vim.lpeg|. + +See https://www.inf.puc-rio.br/~roberto/lpeg/re.html for the original +documentation including regex syntax and more concrete examples. + + +vim.re.compile({string}, {defs}) *vim.re.compile()* + Compiles the given {string} and returns an equivalent LPeg pattern. The + given string may define either an expression or a grammar. The optional + {defs} table provides extra Lua values to be used by the pattern. + + Parameters: ~ + • {string} (`string`) + • {defs} (`table?`) + + Return: ~ + (`vim.lpeg.Pattern`) + +vim.re.find({subject}, {pattern}, {init}) *vim.re.find()* + Searches the given {pattern} in the given {subject}. If it finds a match, + returns the index where this occurrence starts and the index where it + ends. Otherwise, returns nil. + + An optional numeric argument {init} makes the search starts at that + position in the subject string. As usual in Lua libraries, a negative + value counts from the end. + + Parameters: ~ + • {subject} (`string`) + • {pattern} (`vim.lpeg.Pattern|string`) + • {init} (`integer?`) Return (multiple): ~ - fun(_, dir: string): string? Iterator - nil - (string|nil) + (`integer?`) the index where the occurrence starts, nil if no match + (`integer?`) the index where the occurrence ends, nil if no match + +vim.re.gsub({subject}, {pattern}, {replacement}) *vim.re.gsub()* + Does a global substitution, replacing all occurrences of {pattern} in the + given {subject} by {replacement}. + + Parameters: ~ + • {subject} (`string`) + • {pattern} (`vim.lpeg.Pattern|string`) + • {replacement} (`string`) + + Return: ~ + (`string`) + +vim.re.match({subject}, {pattern}, {init}) *vim.re.match()* + Matches the given {pattern} against the given {subject}, returning all + captures. + + Parameters: ~ + • {subject} (`string`) + • {pattern} (`vim.lpeg.Pattern|string`) + • {init} (`integer?`) + + Return: ~ + (`integer|vim.lpeg.Capture?`) + + See also: ~ + • vim.lpeg.match() + +vim.re.updatelocale() *vim.re.updatelocale()* + Updates the pre-defined character classes to the current locale. + + +============================================================================== +VIM.REGEX *vim.regex* + +Vim regexes can be used directly from Lua. Currently they only allow matching +within a single line. + + + *regex:match_line()* +regex:match_line({bufnr}, {line_idx}, {start}, {end_}) + Match line {line_idx} (zero-based) in buffer {bufnr}. If {start} and {end} + are supplied, match only this byte index range. Otherwise see + |regex:match_str()|. If {start} is used, then the returned byte indices + will be relative {start}. + + Parameters: ~ + • {bufnr} (`integer`) + • {line_idx} (`integer`) + • {start} (`integer?`) + • {end_} (`integer?`) + +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.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|. + + Parameters: ~ + • {re} (`string`) + + Return: ~ + (`vim.regex`) ============================================================================== @@ -2999,10 +3538,10 @@ vim.secure.read({path}) *vim.secure.read()* $XDG_STATE_HOME/nvim/trust. Parameters: ~ - • {path} (string) Path to a file to read. + • {path} (`string`) Path to a file to read. Return: ~ - (string|nil) The contents of the given file if it exists and is + (`string?`) The contents of the given file if it exists and is trusted, or nil otherwise. See also: ~ @@ -3014,47 +3553,43 @@ vim.secure.trust({opts}) *vim.secure.trust()* The trust database is located at |$XDG_STATE_HOME|/nvim/trust. Parameters: ~ - • {opts} (table) - • action (string): "allow" to add a file to the trust database - and trust it, "deny" to add a file to the trust database and - deny it, "remove" to remove file from the trust database - • path (string|nil): Path to a file to update. Mutually + • {opts} (`table?`) A table with the following fields: + • {action} (`'allow'|'deny'|'remove'`) - `'allow'` to add a + file to the trust database and trust it, + • `'deny'` to add a file to the trust database and deny it, + • `'remove'` to remove file from the trust database + • {path}? (`string`) Path to a file to update. Mutually exclusive with {bufnr}. Cannot be used when {action} is "allow". - • bufnr (number|nil): Buffer number to update. Mutually + • {bufnr}? (`integer`) Buffer number to update. Mutually exclusive with {path}. Return (multiple): ~ - (boolean) success true if operation was successful - (string) msg full path if operation was successful, else error message + (`boolean`) success true if operation was successful + (`string`) msg full path if operation was successful, else error + message ============================================================================== Lua module: vim.version *vim.version* - -The `vim.version` module provides functions for comparing versions and -ranges conforming to the - -https://semver.org - -spec. Plugins, and plugin managers, can use this to check available tools -and dependencies on the current system. +The `vim.version` module provides functions for comparing versions and ranges +conforming to the https://semver.org spec. Plugins, and plugin managers, can +use this to check available tools and dependencies on the current system. Example: >lua local v = vim.version.parse(vim.fn.system({'tmux', '-V'}), {strict=false}) if vim.version.gt(v, {3, 2, 0}) then -- ... end - < *vim.version()* returns the version of the current Nvim process. -VERSION RANGE SPEC *version-range* +VERSION RANGE SPEC *version-range* -A version "range spec" defines a semantic version range which can be -tested against a version, using |vim.version.range()|. +A version "range spec" defines a semantic version range which can be tested +against a version, using |vim.version.range()|. Supported range specs are shown in the following table. Note: suffixed versions (1.2.3-rc1) are not matched. > @@ -3085,9 +3620,9 @@ versions (1.2.3-rc1) are not matched. > Partial left: missing pieces treated as 0 (1.2 => 1.2.0). 1.2 - 2.3.0 is 1.2.0 - 2.3.0 - < + vim.version.cmp({v1}, {v2}) *vim.version.cmp()* Parses and compares two version objects (the result of |vim.version.parse()|, or specified literally as a `{major, minor, patch}` @@ -3109,50 +3644,71 @@ vim.version.cmp({v1}, {v2}) *vim.version.cmp()* otherwise-equivalent versions. Parameters: ~ - • {v1} Version|number[] Version object. - • {v2} Version|number[] Version to compare with `v1` . + • {v1} (`vim.Version|number[]|string`) Version object. + • {v2} (`vim.Version|number[]|string`) Version to compare with `v1`. Return: ~ - (integer) -1 if `v1 < v2`, 0 if `v1 == v2`, 1 if `v1 > v2`. + (`integer`) -1 if `v1 < v2`, 0 if `v1 == v2`, 1 if `v1 > v2`. vim.version.eq({v1}, {v2}) *vim.version.eq()* - Returns `true` if the given versions are equal. See |vim.version.cmp()| for usage. + Returns `true` if the given versions are equal. See |vim.version.cmp()| + for usage. Parameters: ~ - • {v1} Version|number[] - • {v2} Version|number[] + • {v1} (`vim.Version|number[]|string`) + • {v2} (`vim.Version|number[]|string`) Return: ~ - (boolean) + (`boolean`) + +vim.version.ge({v1}, {v2}) *vim.version.ge()* + Returns `true` if `v1 >= v2`. See |vim.version.cmp()| for usage. + + Parameters: ~ + • {v1} (`vim.Version|number[]|string`) + • {v2} (`vim.Version|number[]|string`) + + Return: ~ + (`boolean`) vim.version.gt({v1}, {v2}) *vim.version.gt()* - Returns `true` if `v1 > v2` . See |vim.version.cmp()| for usage. + Returns `true` if `v1 > v2`. See |vim.version.cmp()| for usage. Parameters: ~ - • {v1} Version|number[] - • {v2} Version|number[] + • {v1} (`vim.Version|number[]|string`) + • {v2} (`vim.Version|number[]|string`) Return: ~ - (boolean) + (`boolean`) vim.version.last({versions}) *vim.version.last()* TODO: generalize this, move to func.lua Parameters: ~ - • {versions} Version [] + • {versions} (`vim.Version[]`) + + Return: ~ + (`vim.Version?`) + +vim.version.le({v1}, {v2}) *vim.version.le()* + Returns `true` if `v1 <= v2`. See |vim.version.cmp()| for usage. + + Parameters: ~ + • {v1} (`vim.Version|number[]|string`) + • {v2} (`vim.Version|number[]|string`) Return: ~ - Version ?|nil + (`boolean`) vim.version.lt({v1}, {v2}) *vim.version.lt()* - Returns `true` if `v1 < v2` . See |vim.version.cmp()| for usage. + Returns `true` if `v1 < v2`. See |vim.version.cmp()| for usage. Parameters: ~ - • {v1} Version|number[] - • {v2} Version|number[] + • {v1} (`vim.Version|number[]|string`) + • {v2} (`vim.Version|number[]|string`) Return: ~ - (boolean) + (`boolean`) vim.version.parse({version}, {opts}) *vim.version.parse()* Parses a semantic version string and returns a version object which can be @@ -3162,18 +3718,19 @@ vim.version.parse({version}, {opts}) *vim.version.parse()* < Parameters: ~ - • {version} (string) Version string to parse. - • {opts} (table|nil) Optional keyword arguments: + • {version} (`string`) Version string to parse. + • {opts} (`table?`) Optional keyword arguments: • strict (boolean): Default false. If `true`, no coercion is attempted on input not conforming to semver v2.0.0. If `false`, `parse()` attempts to coerce input such as "1.0", "0-x", "tmux 3.2a" into valid versions. Return: ~ - (table|nil) parsed_version Version object or `nil` if input is invalid. + (`vim.Version?`) parsed_version Version object or `nil` if input is + invalid. See also: ~ - • # https://semver.org/spec/v2.0.0.html + • https://semver.org/spec/v2.0.0.html vim.version.range({spec}) *vim.version.range()* Parses a semver |version-range| "spec" and returns a range object: > @@ -3194,44 +3751,46 @@ vim.version.range({spec}) *vim.version.range()* print(r:has(vim.version())) -- check against current Nvim version < - Or use cmp(), eq(), lt(), and gt() to compare `.to` and `.from` directly: >lua - local r = vim.version.range('1.0.0 - 2.0.0') - print(vim.version.gt({1,0,3}, r.from) and vim.version.lt({1,0,3}, r.to)) + Or use cmp(), le(), lt(), ge(), gt(), and/or eq() to compare a version + against `.to` and `.from` directly: >lua + local r = vim.version.range('1.0.0 - 2.0.0') -- >=1.0, <2.0 + print(vim.version.ge({1,0,3}, r.from) and vim.version.lt({1,0,3}, r.to)) < Parameters: ~ - • {spec} (string) Version range "spec" + • {spec} (`string`) Version range "spec" + + Return: ~ + (`table?`) A table with the following fields: + • {from} (`vim.Version`) + • {to}? (`vim.Version`) + • {has} (`fun(self: vim.VersionRangeversion: string|vim.Version)`) See also: ~ - • # https://github.com/npm/node-semver#ranges + • https://github.com/npm/node-semver#ranges ============================================================================== Lua module: vim.iter *vim.iter* - *vim.iter()* is an interface for |iterable|s: it wraps a table or function argument into an *Iter* object with methods (such as |Iter:filter()| and -|Iter:map()|) that transform the underlying source data. These methods can -be chained to create iterator "pipelines": the output of each pipeline -stage is input to the next stage. The first stage depends on the type -passed to `vim.iter()`: - +|Iter:map()|) that transform the underlying source data. These methods can be +chained to create iterator "pipelines": the output of each pipeline stage is +input to the next stage. The first stage depends on the type passed to +`vim.iter()`: • List tables (arrays, |lua-list|) yield only the value of each element. • Use |Iter:enumerate()| to also pass the index to the next stage. • Or initialize with ipairs(): `vim.iter(ipairs(…))`. - -• Non-list tables (|lua-dict|) yield both the key and value of each - element. -• Function |iterator|s yield all values returned by the underlying - function. +• Non-list tables (|lua-dict|) yield both the key and value of each element. +• Function |iterator|s yield all values returned by the underlying function. • Tables with a |__call()| metamethod are treated as function iterators. -The iterator pipeline terminates when the underlying |iterable| is -exhausted (for function iterators this means it returned nil). +The iterator pipeline terminates when the underlying |iterable| is exhausted +(for function iterators this means it returned nil). -Note: `vim.iter()` scans table input to decide if it is a list or a dict; -to avoid this cost you can wrap the table with an iterator e.g. +Note: `vim.iter()` scans table input to decide if it is a list or a dict; to +avoid this cost you can wrap the table with an iterator e.g. `vim.iter(ipairs({…}))`, but that precludes the use of |list-iterator| operations such as |Iter:rev()|). @@ -3272,26 +3831,26 @@ Examples: >lua rb:push("b") vim.iter(rb):totable() -- { "a", "b" } - < In addition to the |vim.iter()| function, the |vim.iter| module provides convenience functions like |vim.iter.filter()| and |vim.iter.totable()|. -filter({f}, {src}, {...}) *vim.iter.filter()* + +filter({f}, {src}) *vim.iter.filter()* Filters a table or other |iterable|. >lua -- Equivalent to: vim.iter(src):filter(f):totable() < Parameters: ~ - • {f} function(...):bool Filter function. Accepts the current + • {f} (`fun(...):boolean`) 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 + • {src} (`table|function`) Table or iterator function to filter Return: ~ - (table) + (`table`) See also: ~ • |Iter:filter()| @@ -3300,7 +3859,7 @@ Iter:all({pred}) *Iter:all()* Returns true if all items in the iterator match the given predicate. Parameters: ~ - • {pred} function(...):bool Predicate function. Takes all values + • {pred} (`fun(...):boolean`) Predicate function. Takes all values returned from the previous stage in the pipeline as arguments and returns true if the predicate matches. @@ -3309,7 +3868,7 @@ Iter:any({pred}) *Iter:any()* predicate. Parameters: ~ - • {pred} function(...):bool Predicate function. Takes all values + • {pred} (`fun(...):boolean`) Predicate function. Takes all values returned from the previous stage in the pipeline as arguments and returns true if the predicate matches. @@ -3321,7 +3880,7 @@ Iter:each({f}) *Iter:each()* |Iter:map()|. Parameters: ~ - • {f} function(...) Function to execute for each item in the pipeline. + • {f} (`fun(...)`) Function to execute for each item in the pipeline. Takes all of the values returned by the previous stage in the pipeline as arguments. @@ -3340,15 +3899,15 @@ Iter:enumerate() *Iter:enumerate()* Example: >lua local it = vim.iter(vim.gsplit('abc', '')):enumerate() it:next() - -- 1 'a' + -- 1 'a' it:next() - -- 2 'b' + -- 2 'b' it:next() - -- 3 'c' + -- 3 'c' < Return: ~ - Iter + (`Iter`) Iter:filter({f}) *Iter:filter()* Filters an iterator pipeline. @@ -3358,12 +3917,12 @@ Iter:filter({f}) *Iter:filter()* < Parameters: ~ - • {f} function(...):bool Takes all values returned from the previous + • {f} (`fun(...):boolean`) Takes all values returned from the previous stage in the pipeline and returns false or nil if the current iterator element should be removed. Return: ~ - Iter + (`Iter`) Iter:find({f}) *Iter:find()* Find the first value in the iterator that satisfies the given predicate. @@ -3385,8 +3944,33 @@ Iter:find({f}) *Iter:find()* -- 12 < + Parameters: ~ + • {f} (`any`) + + Return: ~ + (`any`) + +Iter:flatten({depth}) *Iter:flatten()* + Flattens a |list-iterator|, un-nesting nested values up to the given + {depth}. Errors if it attempts to flatten a dict-like value. + + Examples: >lua + vim.iter({ 1, { 2 }, { { 3 } } }):flatten():totable() + -- { 1, 2, { 3 } } + + vim.iter({1, { { a = 2 } }, { 3 } }):flatten():totable() + -- { 1, { a = 2 }, 3 } + + vim.iter({ 1, { { a = 2 } }, { 3 } }):flatten(math.huge):totable() + -- error: attempt to flatten a dict-like table +< + + Parameters: ~ + • {depth} (`number?`) Depth to which |list-iterator| should be + flattened (defaults to 1) + Return: ~ - any + (`Iter`) Iter:fold({init}, {f}) *Iter:fold()* Folds ("reduces") an iterator into a single value. @@ -3404,11 +3988,24 @@ Iter:fold({init}, {f}) *Iter:fold()* < Parameters: ~ - • {init} any Initial value of the accumulator. - • {f} function(acc:any, ...):A Accumulation function. + • {init} (`any`) Initial value of the accumulator. + • {f} (`fun(acc:A, ...):A`) Accumulation function. Return: ~ - any + (`any`) + +Iter:join({delim}) *Iter:join()* + Collect the iterator into a delimited string. + + Each element in the iterator is joined into a string separated by {delim}. + + Consumes the iterator. + + Parameters: ~ + • {delim} (`string`) Delimiter + + Return: ~ + (`string`) Iter:last() *Iter:last()* Drains the iterator and returns the last item. @@ -3424,7 +4021,7 @@ Iter:last() *Iter:last()* < Return: ~ - any + (`any`) Iter:map({f}) *Iter:map()* Maps the items of an iterator pipeline to the values returned by `f`. @@ -3442,13 +4039,13 @@ Iter:map({f}) *Iter:map()* < Parameters: ~ - • {f} function(...):any Mapping function. Takes all values returned - from the previous stage in the pipeline as arguments and returns - one or more new values, which are used in the next pipeline - stage. Nil return values are filtered from the output. + • {f} (`fun(...):any`) Mapping function. Takes all values returned from + the previous stage in the pipeline as arguments and returns one + or more new values, which are used in the next pipeline stage. + Nil return values are filtered from the output. Return: ~ - Iter + (`Iter`) Iter:next() *Iter:next()* Gets the next value from the iterator. @@ -3464,7 +4061,7 @@ Iter:next() *Iter:next()* < Return: ~ - any + (`any`) Iter:nextback() *Iter:nextback()* "Pops" a value from a |list-iterator| (gets the last value and decrements @@ -3479,7 +4076,7 @@ Iter:nextback() *Iter:nextback()* < Return: ~ - any + (`any`) Iter:nth({n}) *Iter:nth()* Gets the nth value of an iterator (and advances to it). @@ -3493,10 +4090,10 @@ Iter:nth({n}) *Iter:nth()* < Parameters: ~ - • {n} (number) The index of the value to return. + • {n} (`number`) The index of the value to return. Return: ~ - any + (`any`) Iter:nthback({n}) *Iter:nthback()* Gets the nth value from the end of a |list-iterator| (and advances to it). @@ -3510,10 +4107,10 @@ Iter:nthback({n}) *Iter:nthback()* < Parameters: ~ - • {n} (number) The index of the value to return. + • {n} (`number`) The index of the value to return. Return: ~ - any + (`any`) Iter:peek() *Iter:peek()* Gets the next value in a |list-iterator| without consuming it. @@ -3529,7 +4126,7 @@ Iter:peek() *Iter:peek()* < Return: ~ - any + (`any`) Iter:peekback() *Iter:peekback()* Gets the last value of a |list-iterator| without consuming it. @@ -3547,7 +4144,7 @@ Iter:peekback() *Iter:peekback()* < Return: ~ - any + (`any`) Iter:rev() *Iter:rev()* Reverses a |list-iterator| pipeline. @@ -3559,7 +4156,7 @@ Iter:rev() *Iter:rev()* < Return: ~ - Iter + (`Iter`) Iter:rfind({f}) *Iter:rfind()* Gets the first value in a |list-iterator| that satisfies a predicate, @@ -3571,13 +4168,16 @@ Iter:rfind({f}) *Iter:rfind()* Examples: >lua local it = vim.iter({ 1, 2, 3, 2, 1 }):enumerate() it:rfind(1) - -- 5 1 + -- 5 1 it:rfind(1) - -- 1 1 + -- 1 1 < + Parameters: ~ + • {f} (`any`) + Return: ~ - any + (`any`) See also: ~ • Iter.find @@ -3592,10 +4192,10 @@ Iter:skip({n}) *Iter:skip()* < Parameters: ~ - • {n} (number) Number of values to skip. + • {n} (`number`) Number of values to skip. Return: ~ - Iter + (`Iter`) Iter:skipback({n}) *Iter:skipback()* Skips `n` values backwards from the end of a |list-iterator| pipeline. @@ -3609,10 +4209,10 @@ Iter:skipback({n}) *Iter:skipback()* < Parameters: ~ - • {n} (number) Number of values to skip. + • {n} (`number`) Number of values to skip. Return: ~ - Iter + (`Iter`) Iter:slice({first}, {last}) *Iter:slice()* Sets the start and end of a |list-iterator| pipeline. @@ -3620,11 +4220,30 @@ Iter:slice({first}, {last}) *Iter:slice()* Equivalent to `:skip(first - 1):skipback(len - last + 1)`. Parameters: ~ - • {first} (number) - • {last} (number) + • {first} (`number`) + • {last} (`number`) Return: ~ - Iter + (`Iter`) + +Iter:take({n}) *Iter:take()* + Transforms an iterator to yield only the first n values. + + Example: >lua + local it = vim.iter({ 1, 2, 3, 4 }):take(2) + it:next() + -- 1 + it:next() + -- 2 + it:next() + -- nil +< + + Parameters: ~ + • {n} (`integer`) + + Return: ~ + (`Iter`) Iter:totable() *Iter:totable()* Collect the iterator into a table. @@ -3650,37 +4269,37 @@ Iter:totable() *Iter:totable()* |Iter:fold()|. Return: ~ - (table) + (`table`) -map({f}, {src}, {...}) *vim.iter.map()* +map({f}, {src}) *vim.iter.map()* Maps a table or other |iterable|. >lua -- Equivalent to: vim.iter(src):map(f):totable() < Parameters: ~ - • {f} function(...):?any Map function. Accepts the current iterator + • {f} (`fun(...): 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 + • {src} (`table|function`) Table or iterator function to filter Return: ~ - (table) + (`table`) See also: ~ • |Iter:map()| -totable({f}, {...}) *vim.iter.totable()* +totable({f}) *vim.iter.totable()* Collects an |iterable| into a table. >lua -- Equivalent to: vim.iter(f):totable() < Parameters: ~ - • {f} (function) Iterator function + • {f} (`function`) Iterator function Return: ~ - (table) + (`table`) ============================================================================== @@ -3690,18 +4309,20 @@ vim.snippet.active() *vim.snippet.active()* Returns `true` if there's an active snippet in the current buffer. Return: ~ - (boolean) + (`boolean`) vim.snippet.exit() *vim.snippet.exit()* Exits the current snippet. vim.snippet.expand({input}) *vim.snippet.expand()* - Expands the given snippet text. Refer to https://microsoft.github.io/language-server-protocol/specification/#snippet_syntax for the specification of valid input. + Expands the given snippet text. Refer to + https://microsoft.github.io/language-server-protocol/specification/#snippet_syntax + for the specification of valid input. Tabstops are highlighted with hl-SnippetTabstop. Parameters: ~ - • {input} (string) + • {input} (`string`) vim.snippet.jump({direction}) *vim.snippet.jump()* Jumps within the active snippet in the given direction. If the jump isn't @@ -3718,7 +4339,7 @@ vim.snippet.jump({direction}) *vim.snippet.jump()* < Parameters: ~ - • {direction} (vim.snippet.Direction) Navigation direction. -1 for + • {direction} (`vim.snippet.Direction`) Navigation direction. -1 for previous, 1 for next. vim.snippet.jumpable({direction}) *vim.snippet.jumpable()* @@ -3735,11 +4356,11 @@ vim.snippet.jumpable({direction}) *vim.snippet.jumpable()* < Parameters: ~ - • {direction} (vim.snippet.Direction) Navigation direction. -1 for + • {direction} (`vim.snippet.Direction`) Navigation direction. -1 for previous, 1 for next. Return: ~ - (boolean) + (`boolean`) ============================================================================== @@ -3749,18 +4370,50 @@ vim.text.hexdecode({enc}) *vim.text.hexdecode()* Hex decode a string. Parameters: ~ - • {enc} (string) String to decode + • {enc} (`string`) String to decode Return: ~ - (string) Decoded string + (`string`) Decoded string vim.text.hexencode({str}) *vim.text.hexencode()* Hex encode a string. Parameters: ~ - • {str} (string) String to encode + • {str} (`string`) String to encode Return: ~ - (string) Hex encoded string + (`string`) Hex encoded string + + +============================================================================== +Lua module: tohtml *vim.tohtml* + + +:TOhtml {file} *:TOhtml* +Converts the buffer shown in the current window to HTML, opens the generated +HTML in a new split window, and saves its contents to {file}. If {file} is not +given, a temporary file (created by |tempname()|) is used. + + +tohtml.tohtml({winid}, {opt}) *tohtml.tohtml.tohtml()* + Converts the buffer shown in the window {winid} to HTML and returns the + output as a list of string. + + Parameters: ~ + • {winid} (`integer?`) Window to convert (defaults to current window) + • {opt} (`table?`) Optional parameters. + • {title}? (`string|false`, default: buffer name) Title tag + to set in the generated HTML code. + • {number_lines}? (`boolean`, default: `false`) Show line + numbers. + • {font}? (`string[]|string`, default: `guifont`) Fonts to + use. + • {width}? (`integer`, default: 'textwidth' if non-zero or + window width otherwise) Width used for items which are + either right aligned or repeat a character infinitely. + + Return: ~ + (`string[]`) + vim:tw=78:ts=8:sw=4:sts=4:et:ft=help:norl: |