diff options
author | Josh Rahm <rahm@google.com> | 2022-08-19 12:26:08 -0600 |
---|---|---|
committer | Josh Rahm <rahm@google.com> | 2022-08-19 13:06:41 -0600 |
commit | a7237662f96933efe29eed8212464571e3778cd0 (patch) | |
tree | 27930202726b4251437c8cfa53069f65b4db90dc /runtime/doc | |
parent | 02292344929069ea63c0bb872cc22d552d86b67f (diff) | |
parent | b2f979b30beac67906b2dd717fcb6a34f46f5e54 (diff) | |
download | rneovim-tmp.tar.gz rneovim-tmp.tar.bz2 rneovim-tmp.zip |
Merge branch 'master' of https://github.com/neovim/neovim into rahmtmp
Diffstat (limited to 'runtime/doc')
-rw-r--r-- | runtime/doc/api.txt | 4682 | ||||
-rw-r--r-- | runtime/doc/autocmd.txt | 4 | ||||
-rw-r--r-- | runtime/doc/builtin.txt | 97 | ||||
-rw-r--r-- | runtime/doc/cmdline.txt | 18 | ||||
-rw-r--r-- | runtime/doc/diagnostic.txt | 930 | ||||
-rw-r--r-- | runtime/doc/editing.txt | 11 | ||||
-rw-r--r-- | runtime/doc/help.txt | 3 | ||||
-rw-r--r-- | runtime/doc/index.txt | 1 | ||||
-rw-r--r-- | runtime/doc/lsp.txt | 2558 | ||||
-rw-r--r-- | runtime/doc/lua.txt | 2162 | ||||
-rw-r--r-- | runtime/doc/luaref.txt | 4966 | ||||
-rw-r--r-- | runtime/doc/luvref.txt | 3898 | ||||
-rw-r--r-- | runtime/doc/map.txt | 11 | ||||
-rw-r--r-- | runtime/doc/motion.txt | 3 | ||||
-rw-r--r-- | runtime/doc/options.txt | 40 | ||||
-rw-r--r-- | runtime/doc/syntax.txt | 2 | ||||
-rw-r--r-- | runtime/doc/treesitter.txt | 794 | ||||
-rw-r--r-- | runtime/doc/usr_41.txt | 11 | ||||
-rw-r--r-- | runtime/doc/vim_diff.txt | 4 | ||||
-rw-r--r-- | runtime/doc/windows.txt | 3 |
20 files changed, 14303 insertions, 5895 deletions
diff --git a/runtime/doc/api.txt b/runtime/doc/api.txt index be42b7c14e..a388592981 100644 --- a/runtime/doc/api.txt +++ b/runtime/doc/api.txt @@ -1,10 +1,10 @@ -*api.txt* Nvim +*api.txt* Nvim - NVIM REFERENCE MANUAL by Thiago de Arruda + NVIM REFERENCE MANUAL by Thiago de Arruda -Nvim API *API* *api* +Nvim API *API* *api* Nvim exposes a powerful API that can be used by plugins and external processes via |RPC|, |Lua| and VimL (|eval-api|). @@ -14,9 +14,9 @@ Applications can also embed libnvim to work with the C API directly. Type |gO| to see the table of contents. ============================================================================== -API Usage *api-rpc* *RPC* *rpc* +API Usage *api-rpc* *RPC* *rpc* - *msgpack-rpc* + *msgpack-rpc* RPC is the typical way to control Nvim programmatically. Nvim implements the MessagePack-RPC protocol: https://github.com/msgpack-rpc/msgpack-rpc/blob/master/spec.md @@ -32,7 +32,7 @@ other Nvim instances. API clients can: The RPC API is like a more powerful version of Vim's "clientserver" feature. -CONNECTING *rpc-connecting* +CONNECTING *rpc-connecting* See |channel-intro| for various ways to open a channel. Channel-opening functions take an `rpc` key in the options dictionary. RPC channels can also @@ -85,21 +85,21 @@ and |rpcnotify()|: call jobstop(nvim) ============================================================================== -API Definitions *api-definitions* +API Definitions *api-definitions* - *api-types* + *api-types* The Nvim C API defines custom types for all function parameters. Some are just typedefs around C99 standard types, others are Nvim-defined data structures. Basic types ~ - API Type C type + API Type C type ------------------------------------------------------------------------ Nil - Boolean bool - Integer (signed 64-bit integer) int64_t - Float (IEEE 754 double precision) double - String {char* data, size_t size} struct + Boolean bool + Integer (signed 64-bit integer) int64_t + Float (IEEE 754 double precision) double + String {char* data, size_t size} struct Array Dictionary (msgpack: map) Object @@ -116,14 +116,14 @@ Special types (msgpack EXT) ~ in the |api-metadata| `types` key are stable: they will not change and are thus forward-compatible. - EXT Type C type Data + EXT Type C type Data ------------------------------------------------------------------------ - Buffer enum value kObjectTypeBuffer |bufnr()| - Window enum value kObjectTypeWindow |window-ID| - Tabpage enum value kObjectTypeTabpage internal handle + Buffer enum value kObjectTypeBuffer |bufnr()| + Window enum value kObjectTypeWindow |window-ID| + Tabpage enum value kObjectTypeTabpage internal handle - *api-indexing* + *api-indexing* Most of the API uses 0-based indices, and ranges are end-exclusive. For the end of a range, -1 denotes the last line/column. @@ -144,7 +144,7 @@ indices, end-inclusive): |nvim_buf_get_extmarks()| |nvim_buf_set_extmark()| - *api-fast* + *api-fast* Most API functions are "deferred": they are queued on the main loop and processed sequentially with normal input. So if the editor is waiting for user input in a "modal" fashion (e.g. the |hit-enter-prompt|), the request @@ -153,7 +153,7 @@ will block. Non-deferred (fast) functions such as |nvim_get_mode()| and queue). Lua code can use |vim.in_fast_event()| to detect a fast context. ============================================================================== -API metadata *api-metadata* +API metadata *api-metadata* The Nvim C API is automatically exposed to RPC by the build system, which parses headers in src/nvim/api/* and generates dispatch-functions mapping RPC @@ -162,19 +162,19 @@ and return values. Nvim exposes its API metadata as a Dictionary with these items: -version Nvim version, API level/compatibility -version.api_level API version integer *api-level* -version.api_compatible API is backwards-compatible with this level -version.api_prerelease Declares the API as unstable/unreleased > - (version.api_prerelease && fn.since == version.api_level) -functions API function signatures, containing |api-types| info +version Nvim version, API level/compatibility +version.api_level API version integer *api-level* +version.api_compatible API is backwards-compatible with this level +version.api_prerelease Declares the API as unstable/unreleased > + (version.api_prerelease && fn.since == version.api_level) +functions API function signatures, containing |api-types| info describing the return value and parameters. -ui_events |UI| event signatures -ui_options Supported |ui-option|s -{fn}.since API level where function {fn} was introduced -{fn}.deprecated_since API level where function {fn} was deprecated -types Custom handle types defined by Nvim -error_types Possible error types returned by API functions +ui_events |UI| event signatures +ui_options Supported |ui-option|s +{fn}.since API level where function {fn} was introduced +{fn}.deprecated_since API level where function {fn} was deprecated +types Custom handle types defined by Nvim +error_types Possible error types returned by API functions About the `functions` map: @@ -188,7 +188,7 @@ About the `functions` map: - Global functions have the "method=false" flag and are prefixed with just `nvim_`, e.g. `nvim_list_bufs`. - *api-mapping* + *api-mapping* External programs (clients) can use the metadata to discover the API, using any of these approaches: @@ -231,7 +231,7 @@ As Nvim evolves the API may change in compliance with this CONTRACT: - Deprecated functions will not be removed until Nvim version 2.0 ============================================================================== -Global events *api-global-events* +Global events *api-global-events* When a client invokes an API request as an async notification, it is not possible for Nvim to send an error response. Instead, in case of error, the @@ -244,7 +244,7 @@ nvim_error_event[{type}, {message}] a string with the error message. ============================================================================== -Buffer update events *api-buffer-updates* +Buffer update events *api-buffer-updates* API clients can "attach" to Nvim buffers to subscribe to buffer update events. This is similar to |TextChanged| but more powerful and granular. @@ -254,89 +254,90 @@ Call |nvim_buf_attach()| to receive these events on the channel: *nvim_buf_lines_event* nvim_buf_lines_event[{buf}, {changedtick}, {firstline}, {lastline}, {linedata}, {more}] - When the buffer text between {firstline} and {lastline} (end-exclusive, - zero-indexed) were changed to the new text in the {linedata} list. The - granularity is a line, i.e. if a single character is changed in the editor, - the entire line is sent. + When the buffer text between {firstline} and {lastline} (end-exclusive, + zero-indexed) were changed to the new text in the {linedata} list. The + granularity is a line, i.e. if a single character is changed in the + editor, the entire line is sent. - When {changedtick} is |v:null| this means the screen lines (display) changed - but not the buffer contents. {linedata} contains the changed screen lines. - This happens when 'inccommand' shows a buffer preview. + When {changedtick} is |v:null| this means the screen lines (display) + changed but not the buffer contents. {linedata} contains the changed + screen lines. This happens when 'inccommand' shows a buffer preview. - Properties:~ - {buf} API buffer handle (buffer number) + Properties:~ + {buf} API buffer handle (buffer number) - {changedtick} value of |b:changedtick| for the buffer. If you send an API - command back to nvim you can check the value of |b:changedtick| as part of - your request to ensure that no other changes have been made. + {changedtick} value of |b:changedtick| for the buffer. If you send an + API command back to nvim you can check the value of |b:changedtick| as + part of your request to ensure that no other changes have been made. - {firstline} integer line number of the first line that was replaced. - Zero-indexed: if line 1 was replaced then {firstline} will be 0, not 1. - {firstline} is always less than or equal to the number of lines that were - in the buffer before the lines were replaced. + {firstline} integer line number of the first line that was replaced. + Zero-indexed: if line 1 was replaced then {firstline} will be 0, not + 1. {firstline} is always less than or equal to the number of lines + that were in the buffer before the lines were replaced. - {lastline} integer line number of the first line that was not replaced - (i.e. the range {firstline}, {lastline} is end-exclusive). - Zero-indexed: if line numbers 2 to 5 were replaced, this will be 5 instead - of 6. {lastline} is always be less than or equal to the number of lines - that were in the buffer before the lines were replaced. {lastline} will be - -1 if the event is part of the initial update after attaching. + {lastline} integer line number of the first line that was not replaced + (i.e. the range {firstline}, {lastline} is end-exclusive). + Zero-indexed: if line numbers 2 to 5 were replaced, this will be 5 + instead of 6. {lastline} is always be less than or equal to the number + of lines that were in the buffer before the lines were replaced. + {lastline} will be -1 if the event is part of the initial update after + attaching. - {linedata} list of strings containing the contents of the new buffer - lines. Newline characters are omitted; empty lines are sent as empty - strings. + {linedata} list of strings containing the contents of the new buffer + lines. Newline characters are omitted; empty lines are sent as empty + strings. - {more} boolean, true for a "multipart" change notification: the current - change was chunked into multiple |nvim_buf_lines_event| notifications - (e.g. because it was too big). + {more} boolean, true for a "multipart" change notification: the + current change was chunked into multiple |nvim_buf_lines_event| + notifications (e.g. because it was too big). nvim_buf_changedtick_event[{buf}, {changedtick}] *nvim_buf_changedtick_event* - When |b:changedtick| was incremented but no text was changed. Relevant for - undo/redo. + When |b:changedtick| was incremented but no text was changed. Relevant for + undo/redo. - Properties:~ - {buf} API buffer handle (buffer number) - {changedtick} new value of |b:changedtick| for the buffer + Properties:~ + {buf} API buffer handle (buffer number) + {changedtick} new value of |b:changedtick| for the buffer nvim_buf_detach_event[{buf}] *nvim_buf_detach_event* - When buffer is detached (i.e. updates are disabled). Triggered explicitly by - |nvim_buf_detach()| or implicitly in these cases: - - Buffer was |abandon|ed and 'hidden' is not set. - - Buffer was reloaded, e.g. with |:edit| or an external change triggered - |:checktime| or 'autoread'. - - Generally: whenever the buffer contents are unloaded from memory. + When buffer is detached (i.e. updates are disabled). Triggered explicitly by + |nvim_buf_detach()| or implicitly in these cases: + - Buffer was |abandon|ed and 'hidden' is not set. + - Buffer was reloaded, e.g. with |:edit| or an external change triggered + |:checktime| or 'autoread'. + - Generally: whenever the buffer contents are unloaded from memory. - Properties:~ - {buf} API buffer handle (buffer number) + Properties:~ + {buf} API buffer handle (buffer number) EXAMPLE ~ Calling |nvim_buf_attach()| with send_buffer=true on an empty buffer, emits: > - nvim_buf_lines_event[{buf}, {changedtick}, 0, -1, [""], v:false] + nvim_buf_lines_event[{buf}, {changedtick}, 0, -1, [""], v:false] User adds two lines to the buffer, emits: > - nvim_buf_lines_event[{buf}, {changedtick}, 0, 0, ["line1", "line2"], v:false] + nvim_buf_lines_event[{buf}, {changedtick}, 0, 0, ["line1", "line2"], v:false] User moves to a line containing the text "Hello world" and inserts "!", emits: > - nvim_buf_lines_event[{buf}, {changedtick}, {linenr}, {linenr} + 1, - ["Hello world!"], v:false] + nvim_buf_lines_event[{buf}, {changedtick}, {linenr}, {linenr} + 1, + ["Hello world!"], v:false] User moves to line 3 and deletes 20 lines using "20dd", emits: > - nvim_buf_lines_event[{buf}, {changedtick}, 2, 22, [], v:false] + nvim_buf_lines_event[{buf}, {changedtick}, 2, 22, [], v:false] User selects lines 3-5 using |linewise-visual| mode and then types "p" to paste a block of 6 lines, emits: > - nvim_buf_lines_event[{buf}, {changedtick}, 2, 5, - ['pasted line 1', 'pasted line 2', 'pasted line 3', 'pasted line 4', - 'pasted line 5', 'pasted line 6'], - v:false - ] + nvim_buf_lines_event[{buf}, {changedtick}, 2, 5, + ['pasted line 1', 'pasted line 2', 'pasted line 3', 'pasted line 4', + 'pasted line 5', 'pasted line 6'], + v:false + ] User reloads the buffer with ":edit", emits: > - nvim_buf_detach_event[{buf}] + nvim_buf_detach_event[{buf}] < LUA ~ @@ -369,7 +370,7 @@ callbacks attached with the same |nvim_buf_attach()| call. ============================================================================== -Buffer highlighting *api-highlights* +Buffer highlighting *api-highlights* Nvim allows plugins to add position-based highlights to buffers. This is similar to |matchaddpos()| but with some key differences. The added highlights @@ -413,7 +414,7 @@ Example using the API from Vimscript: > ============================================================================== -Floating windows *api-floatwin* +Floating windows *api-floatwin* Floating windows ("floats") are displayed on top of normal windows. This is useful to implement simple widgets, such as tooltips displayed next to the @@ -457,7 +458,7 @@ Example: create a float with scratch buffer: > > ============================================================================== -Extended marks *api-extended-marks* *extmarks* +Extended marks *api-extended-marks* *extmarks* Extended marks (extmarks) represent buffer annotations that track text changes in the buffer. They can represent cursors, folds, misspelled words, anything @@ -537,1025 +538,961 @@ created for extmark changes. Global Functions *api-global* nvim__get_runtime({pat}, {all}, {*opts}) *nvim__get_runtime()* - Find files in runtime directories + Find files in runtime directories - Attributes: ~ - |api-fast| + Attributes: ~ + |api-fast| - Parameters: ~ - {pat} pattern of files to search for - {all} whether to return all matches or only the first - {opts} is_lua: only search lua subdirs + Parameters: ~ + {pat} pattern of files to search for + {all} whether to return all matches or only the first + {opts} is_lua: only search lua subdirs - Return: ~ - list of absolute paths to the found files + Return: ~ + list of absolute paths to the found files nvim__id({obj}) *nvim__id()* - Returns object given as argument. + Returns object given as argument. - This API function is used for testing. One should not rely on - its presence in plugins. + This API function is used for testing. One should not rely on its presence + in plugins. - Parameters: ~ - {obj} Object to return. + Parameters: ~ + {obj} Object to return. - Return: ~ - its argument. + Return: ~ + its argument. nvim__id_array({arr}) *nvim__id_array()* - Returns array given as argument. + Returns array given as argument. - This API function is used for testing. One should not rely on - its presence in plugins. + This API function is used for testing. One should not rely on its presence + in plugins. - Parameters: ~ - {arr} Array to return. + Parameters: ~ + {arr} Array to return. - Return: ~ - its argument. + Return: ~ + its argument. nvim__id_dictionary({dct}) *nvim__id_dictionary()* - Returns dictionary given as argument. + Returns dictionary given as argument. - This API function is used for testing. One should not rely on - its presence in plugins. + This API function is used for testing. One should not rely on its presence + in plugins. - Parameters: ~ - {dct} Dictionary to return. + Parameters: ~ + {dct} Dictionary to return. - Return: ~ - its argument. + Return: ~ + its argument. nvim__id_float({flt}) *nvim__id_float()* - Returns floating-point value given as argument. + Returns floating-point value given as argument. - This API function is used for testing. One should not rely on - its presence in plugins. + This API function is used for testing. One should not rely on its presence + in plugins. - Parameters: ~ - {flt} Value to return. + Parameters: ~ + {flt} Value to return. - Return: ~ - its argument. + Return: ~ + its argument. nvim__inspect_cell({grid}, {row}, {col}) *nvim__inspect_cell()* - NB: if your UI doesn't use hlstate, this will not return - hlstate first time. - -nvim__set_hl_ns({ns_id}) *nvim__set_hl_ns()* - Set active namespace for highlights. - - NB: this function can be called from async contexts, but the - semantics are not yet well-defined. To start with - |nvim_set_decoration_provider| on_win and on_line callbacks - are explicitly allowed to change the namespace during a redraw - cycle. - - Attributes: ~ - |api-fast| - - Parameters: ~ - {ns_id} the namespace to activate + NB: if your UI doesn't use hlstate, this will not return hlstate first + time. nvim__stats() *nvim__stats()* - Gets internal stats. + Gets internal stats. - Return: ~ - Map of various internal stats. + Return: ~ + Map of various internal stats. nvim_call_atomic({calls}) *nvim_call_atomic()* - Calls many API methods atomically. - - This has two main usages: - 1. To perform several requests from an async context - atomically, i.e. without interleaving redraws, RPC requests - from other clients, or user interactions (however API - methods may trigger autocommands or event processing which - have such side effects, e.g. |:sleep| may wake timers). - 2. To minimize RPC overhead (roundtrips) of a sequence of many - requests. - - Attributes: ~ - |RPC| only - - Parameters: ~ - {calls} an array of calls, where each call is described - by an array with two elements: the request name, - and an array of arguments. - - Return: ~ - Array of two elements. The first is an array of return - values. The second is NIL if all calls succeeded. If a - call resulted in an error, it is a three-element array - with the zero-based index of the call which resulted in an - error, the error type and the error message. If an error - occurred, the values from all preceding calls will still - be returned. + Calls many API methods atomically. + + This has two main usages: + 1. To perform several requests from an async context atomically, i.e. + without interleaving redraws, RPC requests from other clients, or user + interactions (however API methods may trigger autocommands or event + processing which have such side effects, e.g. |:sleep| may wake + timers). + 2. To minimize RPC overhead (roundtrips) of a sequence of many requests. + + Attributes: ~ + |RPC| only + + Parameters: ~ + {calls} an array of calls, where each call is described by an array + with two elements: the request name, and an array of + arguments. + + Return: ~ + Array of two elements. The first is an array of return values. The + second is NIL if all calls succeeded. If a call resulted in an error, + it is a three-element array with the zero-based index of the call + which resulted in an error, the error type and the error message. If + an error occurred, the values from all preceding calls will still be + returned. nvim_chan_send({chan}, {data}) *nvim_chan_send()* - Send data to channel `id`. For a job, it writes it to the - stdin of the process. For the stdio channel |channel-stdio|, - it writes to Nvim's stdout. For an internal terminal instance - (|nvim_open_term()|) it writes directly to terminal output. - See |channel-bytes| for more information. + Send data to channel `id`. For a job, it writes it to the stdin of the + process. For the stdio channel |channel-stdio|, it writes to Nvim's + stdout. For an internal terminal instance (|nvim_open_term()|) it writes + directly to terminal output. See |channel-bytes| for more information. - This function writes raw data, not RPC messages. If the - channel was created with `rpc=true` then the channel expects - RPC messages, use |vim.rpcnotify()| and |vim.rpcrequest()| - instead. + This function writes raw data, not RPC messages. If the channel was + created with `rpc=true` then the channel expects RPC messages, use + |vim.rpcnotify()| and |vim.rpcrequest()| instead. - Attributes: ~ - |RPC| only - |vim.api| only + Attributes: ~ + |RPC| only + |vim.api| only - Parameters: ~ - {chan} id of the channel - {data} data to write. 8-bit clean: can contain NUL bytes. + Parameters: ~ + {chan} id of the channel + {data} data to write. 8-bit clean: can contain NUL bytes. nvim_create_buf({listed}, {scratch}) *nvim_create_buf()* - Creates a new, empty, unnamed buffer. + Creates a new, empty, unnamed buffer. - Parameters: ~ - {listed} Sets 'buflisted' - {scratch} Creates a "throwaway" |scratch-buffer| for - temporary work (always 'nomodified'). Also sets - 'nomodeline' on the buffer. + Parameters: ~ + {listed} Sets 'buflisted' + {scratch} Creates a "throwaway" |scratch-buffer| for temporary work + (always 'nomodified'). Also sets 'nomodeline' on the + buffer. - Return: ~ - Buffer handle, or 0 on error + Return: ~ + Buffer handle, or 0 on error - See also: ~ - buf_open_scratch + See also: ~ + buf_open_scratch nvim_del_current_line() *nvim_del_current_line()* - Deletes the current line. + Deletes the current line. - Attributes: ~ - not allowed when |textlock| is active + Attributes: ~ + not allowed when |textlock| is active nvim_del_keymap({mode}, {lhs}) *nvim_del_keymap()* - Unmaps a global |mapping| for the given mode. + Unmaps a global |mapping| for the given mode. - To unmap a buffer-local mapping, use |nvim_buf_del_keymap()|. + To unmap a buffer-local mapping, use |nvim_buf_del_keymap()|. - See also: ~ - |nvim_set_keymap()| + See also: ~ + |nvim_set_keymap()| nvim_del_mark({name}) *nvim_del_mark()* - Deletes an uppercase/file named mark. See |mark-motions|. + Deletes an uppercase/file named mark. See |mark-motions|. - Note: - fails with error if a lowercase or buffer local named mark - is used. + Note: + fails with error if a lowercase or buffer local named mark is used. - Parameters: ~ - {name} Mark name + Parameters: ~ + {name} Mark name - Return: ~ - true if the mark was deleted, else false. + Return: ~ + true if the mark was deleted, else false. - See also: ~ - |nvim_buf_del_mark()| - |nvim_get_mark()| + See also: ~ + |nvim_buf_del_mark()| + |nvim_get_mark()| nvim_del_var({name}) *nvim_del_var()* - Removes a global (g:) variable. + Removes a global (g:) variable. - Parameters: ~ - {name} Variable name + Parameters: ~ + {name} Variable name nvim_echo({chunks}, {history}, {opts}) *nvim_echo()* - Echo a message. + Echo a message. - Parameters: ~ - {chunks} A list of [text, hl_group] arrays, each - representing a text chunk with specified - highlight. `hl_group` element can be omitted - for no highlight. - {history} if true, add to |message-history|. - {opts} Optional parameters. Reserved for future use. + Parameters: ~ + {chunks} A list of [text, hl_group] arrays, each representing a text + chunk with specified highlight. `hl_group` element can be + omitted for no highlight. + {history} if true, add to |message-history|. + {opts} Optional parameters. Reserved for future use. nvim_err_write({str}) *nvim_err_write()* - Writes a message to the Vim error buffer. Does not append - "\n", the message is buffered (won't display) until a linefeed - is written. + Writes a message to the Vim error buffer. Does not append "\n", the + message is buffered (won't display) until a linefeed is written. - Parameters: ~ - {str} Message + Parameters: ~ + {str} Message nvim_err_writeln({str}) *nvim_err_writeln()* - Writes a message to the Vim error buffer. Appends "\n", so the - buffer is flushed (and displayed). + Writes a message to the Vim error buffer. Appends "\n", so the buffer is + flushed (and displayed). - Parameters: ~ - {str} Message + Parameters: ~ + {str} Message - See also: ~ - nvim_err_write() + See also: ~ + nvim_err_write() nvim_eval_statusline({str}, {*opts}) *nvim_eval_statusline()* - Evaluates statusline string. - - Attributes: ~ - |api-fast| - - Parameters: ~ - {str} Statusline string (see 'statusline'). - {opts} Optional parameters. - • winid: (number) |window-ID| of the window to use - as context for statusline. - • maxwidth: (number) Maximum width of statusline. - • fillchar: (string) Character to fill blank - spaces in the statusline (see 'fillchars'). - Treated as single-width even if it isn't. - • highlights: (boolean) Return highlight - information. - • use_winbar: (boolean) Evaluate winbar instead of - statusline. - • use_tabline: (boolean) Evaluate tabline instead - of statusline. When |TRUE|, {winid} is ignored. - Mutually exclusive with {use_winbar}. - - Return: ~ - Dictionary containing statusline information, with these - keys: - • str: (string) Characters that will be displayed on the - statusline. - • width: (number) Display width of the statusline. - • highlights: Array containing highlight information of - the statusline. Only included when the "highlights" key - in {opts} is |TRUE|. Each element of the array is a - |Dictionary| with these keys: - • start: (number) Byte index (0-based) of first - character that uses the highlight. - • group: (string) Name of highlight group. + Evaluates statusline string. + + Attributes: ~ + |api-fast| + + Parameters: ~ + {str} Statusline string (see 'statusline'). + {opts} Optional parameters. + • winid: (number) |window-ID| of the window to use as context + for statusline. + • maxwidth: (number) Maximum width of statusline. + • fillchar: (string) Character to fill blank spaces in the + statusline (see 'fillchars'). Treated as single-width even + if it isn't. + • highlights: (boolean) Return highlight information. + • use_winbar: (boolean) Evaluate winbar instead of statusline. + • use_tabline: (boolean) Evaluate tabline instead of + statusline. When |TRUE|, {winid} is ignored. Mutually + exclusive with {use_winbar}. + + Return: ~ + Dictionary containing statusline information, with these keys: + • str: (string) Characters that will be displayed on the statusline. + • width: (number) Display width of the statusline. + • highlights: Array containing highlight information of the + statusline. Only included when the "highlights" key in {opts} is + |TRUE|. Each element of the array is a |Dictionary| with these keys: + • start: (number) Byte index (0-based) of first character that uses + the highlight. + • group: (string) Name of highlight group. nvim_exec_lua({code}, {args}) *nvim_exec_lua()* - Execute Lua code. Parameters (if any) are available as `...` - inside the chunk. The chunk can return a value. + Execute Lua code. Parameters (if any) are available as `...` inside the + chunk. The chunk can return a value. - Only statements are executed. To evaluate an expression, - prefix it with `return`: return my_function(...) + Only statements are executed. To evaluate an expression, prefix it with + `return`: return my_function(...) - Attributes: ~ - |RPC| only + Attributes: ~ + |RPC| only - Parameters: ~ - {code} Lua code to execute - {args} Arguments to the code + Parameters: ~ + {code} Lua code to execute + {args} Arguments to the code - Return: ~ - Return value of Lua code if present or NIL. + Return: ~ + Return value of Lua code if present or NIL. nvim_feedkeys({keys}, {mode}, {escape_ks}) *nvim_feedkeys()* - Sends input-keys to Nvim, subject to various quirks controlled - by `mode` flags. This is a blocking call, unlike - |nvim_input()|. + Sends input-keys to Nvim, subject to various quirks controlled by `mode` + flags. This is a blocking call, unlike |nvim_input()|. - On execution error: does not fail, but updates v:errmsg. + On execution error: does not fail, but updates v:errmsg. - To input sequences like <C-o> use |nvim_replace_termcodes()| - (typically with escape_ks=false) to replace |keycodes|, then - pass the result to nvim_feedkeys(). + To input sequences like <C-o> use |nvim_replace_termcodes()| (typically + with escape_ks=false) to replace |keycodes|, then pass the result to + nvim_feedkeys(). - Example: > - :let key = nvim_replace_termcodes("<C-o>", v:true, v:false, v:true) - :call nvim_feedkeys(key, 'n', v:false) + Example: > + :let key = nvim_replace_termcodes("<C-o>", v:true, v:false, v:true) + :call nvim_feedkeys(key, 'n', v:false) < - Parameters: ~ - {keys} to be typed - {mode} behavior flags, see |feedkeys()| - {escape_ks} If true, escape K_SPECIAL bytes in `keys` - This should be false if you already used - |nvim_replace_termcodes()|, and true - otherwise. + Parameters: ~ + {keys} to be typed + {mode} behavior flags, see |feedkeys()| + {escape_ks} If true, escape K_SPECIAL bytes in `keys` This should be + false if you already used |nvim_replace_termcodes()|, and + true otherwise. - See also: ~ - feedkeys() - vim_strsave_escape_ks + See also: ~ + feedkeys() + vim_strsave_escape_ks nvim_get_api_info() *nvim_get_api_info()* - Returns a 2-tuple (Array), where item 0 is the current channel - id and item 1 is the |api-metadata| map (Dictionary). + Returns a 2-tuple (Array), where item 0 is the current channel id and item + 1 is the |api-metadata| map (Dictionary). - Return: ~ - 2-tuple [{channel-id}, {api-metadata}] + Return: ~ + 2-tuple [{channel-id}, {api-metadata}] - Attributes: ~ - |api-fast| - |RPC| only + Attributes: ~ + |api-fast| + |RPC| only nvim_get_chan_info({chan}) *nvim_get_chan_info()* - Gets information about a channel. - - Return: ~ - Dictionary describing a channel, with these keys: - • "id" Channel id. - • "argv" (optional) Job arguments list. - • "stream" Stream underlying the channel. - • "stdio" stdin and stdout of this Nvim instance - • "stderr" stderr of this Nvim instance - • "socket" TCP/IP socket or named pipe - • "job" Job with communication over its stdio. - - • "mode" How data received on the channel is interpreted. - • "bytes" Send and receive raw bytes. - • "terminal" |terminal| instance interprets ASCII - sequences. - • "rpc" |RPC| communication on the channel is active. - - • "pty" (optional) Name of pseudoterminal. On a POSIX - system this is a device path like "/dev/pts/1". If the - name is unknown, the key will still be present if a pty - is used (e.g. for conpty on Windows). - • "buffer" (optional) Buffer with connected |terminal| - instance. - • "client" (optional) Info about the peer (client on the - other end of the RPC channel), if provided by it via - |nvim_set_client_info()|. + Gets information about a channel. + + Return: ~ + Dictionary describing a channel, with these keys: + • "id" Channel id. + • "argv" (optional) Job arguments list. + • "stream" Stream underlying the channel. + • "stdio" stdin and stdout of this Nvim instance + • "stderr" stderr of this Nvim instance + • "socket" TCP/IP socket or named pipe + • "job" Job with communication over its stdio. + + • "mode" How data received on the channel is interpreted. + • "bytes" Send and receive raw bytes. + • "terminal" |terminal| instance interprets ASCII sequences. + • "rpc" |RPC| communication on the channel is active. + + • "pty" (optional) Name of pseudoterminal. On a POSIX system this is a + device path like "/dev/pts/1". If the name is unknown, the key will + still be present if a pty is used (e.g. for conpty on Windows). + • "buffer" (optional) Buffer with connected |terminal| instance. + • "client" (optional) Info about the peer (client on the other end of + the RPC channel), if provided by it via |nvim_set_client_info()|. nvim_get_color_by_name({name}) *nvim_get_color_by_name()* - Returns the 24-bit RGB value of a |nvim_get_color_map()| color - name or "#rrggbb" hexadecimal string. + Returns the 24-bit RGB value of a |nvim_get_color_map()| color name or + "#rrggbb" hexadecimal string. - Example: > - :echo nvim_get_color_by_name("Pink") - :echo nvim_get_color_by_name("#cbcbcb") + Example: > + :echo nvim_get_color_by_name("Pink") + :echo nvim_get_color_by_name("#cbcbcb") < - Parameters: ~ - {name} Color name or "#rrggbb" string + Parameters: ~ + {name} Color name or "#rrggbb" string - Return: ~ - 24-bit RGB value, or -1 for invalid argument. + Return: ~ + 24-bit RGB value, or -1 for invalid argument. nvim_get_color_map() *nvim_get_color_map()* - Returns a map of color names and RGB values. + Returns a map of color names and RGB values. - Keys are color names (e.g. "Aqua") and values are 24-bit RGB - color values (e.g. 65535). + Keys are color names (e.g. "Aqua") and values are 24-bit RGB color values + (e.g. 65535). - Return: ~ - Map of color names and RGB values. + Return: ~ + Map of color names and RGB values. nvim_get_context({*opts}) *nvim_get_context()* - Gets a map of the current editor state. + Gets a map of the current editor state. - Parameters: ~ - {opts} Optional parameters. - • types: List of |context-types| ("regs", "jumps", - "bufs", "gvars", …) to gather, or empty for - "all". + Parameters: ~ + {opts} Optional parameters. + • types: List of |context-types| ("regs", "jumps", "bufs", + "gvars", …) to gather, or empty for "all". - Return: ~ - map of global |context|. + Return: ~ + map of global |context|. nvim_get_current_buf() *nvim_get_current_buf()* - Gets the current buffer. + Gets the current buffer. - Return: ~ - Buffer handle + Return: ~ + Buffer handle nvim_get_current_line() *nvim_get_current_line()* - Gets the current line. + Gets the current line. - Return: ~ - Current line string + Return: ~ + Current line string nvim_get_current_tabpage() *nvim_get_current_tabpage()* - Gets the current tabpage. + Gets the current tabpage. - Return: ~ - Tabpage handle + Return: ~ + Tabpage handle nvim_get_current_win() *nvim_get_current_win()* - Gets the current window. + Gets the current window. - Return: ~ - Window handle + Return: ~ + Window handle nvim_get_hl_by_id({hl_id}, {rgb}) *nvim_get_hl_by_id()* - Gets a highlight definition by id. |hlID()| + Gets a highlight definition by id. |hlID()| - Parameters: ~ - {hl_id} Highlight id as returned by |hlID()| - {rgb} Export RGB colors + Parameters: ~ + {hl_id} Highlight id as returned by |hlID()| + {rgb} Export RGB colors - Return: ~ - Highlight definition map + Return: ~ + Highlight definition map - See also: ~ - nvim_get_hl_by_name + See also: ~ + nvim_get_hl_by_name nvim_get_hl_by_name({name}, {rgb}) *nvim_get_hl_by_name()* - Gets a highlight definition by name. + Gets a highlight definition by name. - Parameters: ~ - {name} Highlight group name - {rgb} Export RGB colors + Parameters: ~ + {name} Highlight group name + {rgb} Export RGB colors - Return: ~ - Highlight definition map + Return: ~ + Highlight definition map - See also: ~ - nvim_get_hl_by_id + See also: ~ + nvim_get_hl_by_id nvim_get_hl_id_by_name({name}) *nvim_get_hl_id_by_name()* - Gets a highlight group by name + Gets a highlight group by name - similar to |hlID()|, but allocates a new ID if not present. + similar to |hlID()|, but allocates a new ID if not present. nvim_get_keymap({mode}) *nvim_get_keymap()* - Gets a list of global (non-buffer-local) |mapping| - definitions. + Gets a list of global (non-buffer-local) |mapping| definitions. - Parameters: ~ - {mode} Mode short-name ("n", "i", "v", ...) + Parameters: ~ + {mode} Mode short-name ("n", "i", "v", ...) - Return: ~ - Array of |maparg()|-like dictionaries describing mappings. - The "buffer" key is always zero. + Return: ~ + Array of |maparg()|-like dictionaries describing mappings. The + "buffer" key is always zero. nvim_get_mark({name}, {opts}) *nvim_get_mark()* - Return a tuple (row, col, buffer, buffername) representing the - position of the uppercase/file named mark. See |mark-motions|. + Return a tuple (row, col, buffer, buffername) representing the position of + the uppercase/file named mark. See |mark-motions|. - Marks are (1,0)-indexed. |api-indexing| + Marks are (1,0)-indexed. |api-indexing| - Note: - fails with error if a lowercase or buffer local named mark - is used. + Note: + fails with error if a lowercase or buffer local named mark is used. - Parameters: ~ - {name} Mark name - {opts} Optional parameters. Reserved for future use. + Parameters: ~ + {name} Mark name + {opts} Optional parameters. Reserved for future use. - Return: ~ - 4-tuple (row, col, buffer, buffername), (0, 0, 0, '') if - the mark is not set. + Return: ~ + 4-tuple (row, col, buffer, buffername), (0, 0, 0, '') if the mark is + not set. - See also: ~ - |nvim_buf_set_mark()| - |nvim_del_mark()| + See also: ~ + |nvim_buf_set_mark()| + |nvim_del_mark()| nvim_get_mode() *nvim_get_mode()* - Gets the current mode. |mode()| "blocking" is true if Nvim is - waiting for input. + Gets the current mode. |mode()| "blocking" is true if Nvim is waiting for + input. - Return: ~ - Dictionary { "mode": String, "blocking": Boolean } + Return: ~ + Dictionary { "mode": String, "blocking": Boolean } - Attributes: ~ - |api-fast| + Attributes: ~ + |api-fast| nvim_get_proc({pid}) *nvim_get_proc()* - Gets info describing process `pid`. + Gets info describing process `pid`. - Return: ~ - Map of process properties, or NIL if process not found. + Return: ~ + Map of process properties, or NIL if process not found. nvim_get_proc_children({pid}) *nvim_get_proc_children()* - Gets the immediate children of process `pid`. + Gets the immediate children of process `pid`. - Return: ~ - Array of child process ids, empty if process not found. + Return: ~ + Array of child process ids, empty if process not found. nvim_get_runtime_file({name}, {all}) *nvim_get_runtime_file()* - Find files in runtime directories + Find files in runtime directories - 'name' can contain wildcards. For example - nvim_get_runtime_file("colors/*.vim", true) will return all - color scheme files. Always use forward slashes (/) in the - search pattern for subdirectories regardless of platform. + 'name' can contain wildcards. For example + nvim_get_runtime_file("colors/*.vim", true) will return all color scheme + files. Always use forward slashes (/) in the search pattern for + subdirectories regardless of platform. - It is not an error to not find any files. An empty array is - returned then. + It is not an error to not find any files. An empty array is returned then. - Attributes: ~ - |api-fast| + Attributes: ~ + |api-fast| - Parameters: ~ - {name} pattern of files to search for - {all} whether to return all matches or only the first + Parameters: ~ + {name} pattern of files to search for + {all} whether to return all matches or only the first - Return: ~ - list of absolute paths to the found files + Return: ~ + list of absolute paths to the found files nvim_get_var({name}) *nvim_get_var()* - Gets a global (g:) variable. + Gets a global (g:) variable. - Parameters: ~ - {name} Variable name + Parameters: ~ + {name} Variable name - Return: ~ - Variable value + Return: ~ + Variable value nvim_get_vvar({name}) *nvim_get_vvar()* - Gets a v: variable. + Gets a v: variable. - Parameters: ~ - {name} Variable name + Parameters: ~ + {name} Variable name - Return: ~ - Variable value + Return: ~ + Variable value nvim_input({keys}) *nvim_input()* - Queues raw user-input. Unlike |nvim_feedkeys()|, this uses a - low-level input buffer and the call is non-blocking (input is - processed asynchronously by the eventloop). + Queues raw user-input. Unlike |nvim_feedkeys()|, this uses a low-level + input buffer and the call is non-blocking (input is processed + asynchronously by the eventloop). - On execution error: does not fail, but updates v:errmsg. + On execution error: does not fail, but updates v:errmsg. - Note: - |keycodes| like <CR> are translated, so "<" is special. To - input a literal "<", send <LT>. + Note: + |keycodes| like <CR> are translated, so "<" is special. To input a + literal "<", send <LT>. - Note: - For mouse events use |nvim_input_mouse()|. The pseudokey - form "<LeftMouse><col,row>" is deprecated since - |api-level| 6. + Note: + For mouse events use |nvim_input_mouse()|. The pseudokey form + "<LeftMouse><col,row>" is deprecated since |api-level| 6. - Attributes: ~ - |api-fast| + Attributes: ~ + |api-fast| - Parameters: ~ - {keys} to be typed + Parameters: ~ + {keys} to be typed - Return: ~ - Number of bytes actually written (can be fewer than - requested if the buffer becomes full). + Return: ~ + Number of bytes actually written (can be fewer than requested if the + buffer becomes full). *nvim_input_mouse()* nvim_input_mouse({button}, {action}, {modifier}, {grid}, {row}, {col}) - Send mouse event from GUI. - - Non-blocking: does not wait on any result, but queues the - event to be processed soon by the event loop. - - Note: - Currently this doesn't support "scripting" multiple mouse - events by calling it multiple times in a loop: the - intermediate mouse positions will be ignored. It should be - used to implement real-time mouse input in a GUI. The - deprecated pseudokey form ("<LeftMouse><col,row>") of - |nvim_input()| has the same limitation. - - Attributes: ~ - |api-fast| - - Parameters: ~ - {button} Mouse button: one of "left", "right", - "middle", "wheel". - {action} For ordinary buttons, one of "press", "drag", - "release". For the wheel, one of "up", "down", - "left", "right". - {modifier} String of modifiers each represented by a - single char. The same specifiers are used as - for a key press, except that the "-" separator - is optional, so "C-A-", "c-a" and "CA" can all - be used to specify Ctrl+Alt+click. - {grid} Grid number if the client uses |ui-multigrid|, - else 0. - {row} Mouse row-position (zero-based, like redraw - events) - {col} Mouse column-position (zero-based, like redraw - events) + Send mouse event from GUI. + + Non-blocking: does not wait on any result, but queues the event to be + processed soon by the event loop. + + Note: + Currently this doesn't support "scripting" multiple mouse events by + calling it multiple times in a loop: the intermediate mouse positions + will be ignored. It should be used to implement real-time mouse input + in a GUI. The deprecated pseudokey form ("<LeftMouse><col,row>") of + |nvim_input()| has the same limitation. + + Attributes: ~ + |api-fast| + + Parameters: ~ + {button} Mouse button: one of "left", "right", "middle", "wheel". + {action} For ordinary buttons, one of "press", "drag", "release". + For the wheel, one of "up", "down", "left", "right". + {modifier} String of modifiers each represented by a single char. The + same specifiers are used as for a key press, except that + the "-" separator is optional, so "C-A-", "c-a" and "CA" + can all be used to specify Ctrl+Alt+click. + {grid} Grid number if the client uses |ui-multigrid|, else 0. + {row} Mouse row-position (zero-based, like redraw events) + {col} Mouse column-position (zero-based, like redraw events) nvim_list_bufs() *nvim_list_bufs()* - Gets the current list of buffer handles + Gets the current list of buffer handles - Includes unlisted (unloaded/deleted) buffers, like `:ls!`. Use - |nvim_buf_is_loaded()| to check if a buffer is loaded. + Includes unlisted (unloaded/deleted) buffers, like `:ls!`. Use + |nvim_buf_is_loaded()| to check if a buffer is loaded. - Return: ~ - List of buffer handles + Return: ~ + List of buffer handles nvim_list_chans() *nvim_list_chans()* - Get information about all open channels. + Get information about all open channels. - Return: ~ - Array of Dictionaries, each describing a channel with the - format specified at |nvim_get_chan_info()|. + Return: ~ + Array of Dictionaries, each describing a channel with the format + specified at |nvim_get_chan_info()|. nvim_list_runtime_paths() *nvim_list_runtime_paths()* - Gets the paths contained in 'runtimepath'. + Gets the paths contained in 'runtimepath'. - Return: ~ - List of paths + Return: ~ + List of paths nvim_list_tabpages() *nvim_list_tabpages()* - Gets the current list of tabpage handles. + Gets the current list of tabpage handles. - Return: ~ - List of tabpage handles + Return: ~ + List of tabpage handles nvim_list_uis() *nvim_list_uis()* - Gets a list of dictionaries representing attached UIs. + Gets a list of dictionaries representing attached UIs. - Return: ~ - Array of UI dictionaries, each with these keys: - • "height" Requested height of the UI - • "width" Requested width of the UI - • "rgb" true if the UI uses RGB colors (false implies - |cterm-colors|) - • "ext_..." Requested UI extensions, see |ui-option| - • "chan" Channel id of remote UI (not present for TUI) + Return: ~ + Array of UI dictionaries, each with these keys: + • "height" Requested height of the UI + • "width" Requested width of the UI + • "rgb" true if the UI uses RGB colors (false implies |cterm-colors|) + • "ext_..." Requested UI extensions, see |ui-option| + • "chan" Channel id of remote UI (not present for TUI) nvim_list_wins() *nvim_list_wins()* - Gets the current list of window handles. + Gets the current list of window handles. - Return: ~ - List of window handles + Return: ~ + List of window handles nvim_load_context({dict}) *nvim_load_context()* - Sets the current editor state from the given |context| map. + Sets the current editor state from the given |context| map. - Parameters: ~ - {dict} |Context| map. + Parameters: ~ + {dict} |Context| map. nvim_notify({msg}, {log_level}, {opts}) *nvim_notify()* - Notify the user with a message + Notify the user with a message - Relays the call to vim.notify . By default forwards your - message in the echo area but can be overridden to trigger - desktop notifications. + Relays the call to vim.notify . By default forwards your message in the + echo area but can be overridden to trigger desktop notifications. - Parameters: ~ - {msg} Message to display to the user - {log_level} The log level - {opts} Reserved for future use. + Parameters: ~ + {msg} Message to display to the user + {log_level} The log level + {opts} Reserved for future use. nvim_open_term({buffer}, {opts}) *nvim_open_term()* - Open a terminal instance in a buffer - - By default (and currently the only option) the terminal will - not be connected to an external process. Instead, input send - on the channel will be echoed directly by the terminal. This - is useful to display ANSI terminal sequences returned as part - of a rpc message, or similar. - - Note: to directly initiate the terminal using the right size, - display the buffer in a configured window before calling this. - For instance, for a floating display, first create an empty - buffer using |nvim_create_buf()|, then display it using - |nvim_open_win()|, and then call this function. Then - |nvim_chan_send()| can be called immediately to process - sequences in a virtual terminal having the intended size. - - Parameters: ~ - {buffer} the buffer to use (expected to be empty) - {opts} Optional parameters. - • on_input: lua callback for input sent, i e - keypresses in terminal mode. Note: keypresses - are sent raw as they would be to the pty - master end. For instance, a carriage return is - sent as a "\r", not as a "\n". |textlock| - applies. It is possible to call - |nvim_chan_send| directly in the callback - however. ["input", term, bufnr, data] - - Return: ~ - Channel id, or 0 on error + Open a terminal instance in a buffer + + By default (and currently the only option) the terminal will not be + connected to an external process. Instead, input send on the channel will + be echoed directly by the terminal. This is useful to display ANSI + terminal sequences returned as part of a rpc message, or similar. + + Note: to directly initiate the terminal using the right size, display the + buffer in a configured window before calling this. For instance, for a + floating display, first create an empty buffer using |nvim_create_buf()|, + then display it using |nvim_open_win()|, and then call this function. Then + |nvim_chan_send()| can be called immediately to process sequences in a + virtual terminal having the intended size. + + Parameters: ~ + {buffer} the buffer to use (expected to be empty) + {opts} Optional parameters. + • on_input: lua callback for input sent, i e keypresses in + terminal mode. Note: keypresses are sent raw as they would + be to the pty master end. For instance, a carriage return + is sent as a "\r", not as a "\n". |textlock| applies. It + is possible to call |nvim_chan_send| directly in the + callback however. ["input", term, bufnr, data] + + Return: ~ + Channel id, or 0 on error nvim_out_write({str}) *nvim_out_write()* - Writes a message to the Vim output buffer. Does not append - "\n", the message is buffered (won't display) until a linefeed - is written. + Writes a message to the Vim output buffer. Does not append "\n", the + message is buffered (won't display) until a linefeed is written. - Parameters: ~ - {str} Message + Parameters: ~ + {str} Message nvim_paste({data}, {crlf}, {phase}) *nvim_paste()* - Pastes at cursor, in any mode. + Pastes at cursor, in any mode. - Invokes the `vim.paste` handler, which handles each mode - appropriately. Sets redo/undo. Faster than |nvim_input()|. - Lines break at LF ("\n"). + Invokes the `vim.paste` handler, which handles each mode appropriately. + Sets redo/undo. Faster than |nvim_input()|. Lines break at LF ("\n"). - Errors ('nomodifiable', `vim.paste()` failure, …) are - reflected in `err` but do not affect the return value (which - is strictly decided by `vim.paste()`). On error, subsequent - calls are ignored ("drained") until the next paste is - initiated (phase 1 or -1). + Errors ('nomodifiable', `vim.paste()` failure, …) are reflected in `err` + but do not affect the return value (which is strictly decided by + `vim.paste()`). On error, subsequent calls are ignored ("drained") until + the next paste is initiated (phase 1 or -1). - Attributes: ~ - not allowed when |textlock| is active + Attributes: ~ + not allowed when |textlock| is active - Parameters: ~ - {data} Multiline input. May be binary (containing NUL - bytes). - {crlf} Also break lines at CR and CRLF. - {phase} -1: paste in a single call (i.e. without - streaming). To "stream" a paste, call `nvim_paste` sequentially with these `phase` values: - • 1: starts the paste (exactly once) - • 2: continues the paste (zero or more times) - • 3: ends the paste (exactly once) + Parameters: ~ + {data} Multiline input. May be binary (containing NUL bytes). + {crlf} Also break lines at CR and CRLF. + {phase} -1: paste in a single call (i.e. without streaming). To + "stream" a paste, call `nvim_paste` sequentially with these `phase` values: + • 1: starts the paste (exactly once) + • 2: continues the paste (zero or more times) + • 3: ends the paste (exactly once) - Return: ~ + Return: ~ - • true: Client may continue pasting. - • false: Client must cancel the paste. + • true: Client may continue pasting. + • false: Client must cancel the paste. nvim_put({lines}, {type}, {after}, {follow}) *nvim_put()* - Puts text at cursor, in any mode. - - Compare |:put| and |p| which are always linewise. - - Attributes: ~ - not allowed when |textlock| is active - - Parameters: ~ - {lines} |readfile()|-style list of lines. - |channel-lines| - {type} Edit behavior: any |getregtype()| result, or: - • "b" |blockwise-visual| mode (may include - width, e.g. "b3") - • "c" |charwise| mode - • "l" |linewise| mode - • "" guess by contents, see |setreg()| - {after} If true insert after cursor (like |p|), or - before (like |P|). - {follow} If true place cursor at end of inserted text. + Puts text at cursor, in any mode. + + Compare |:put| and |p| which are always linewise. + + Attributes: ~ + not allowed when |textlock| is active + + Parameters: ~ + {lines} |readfile()|-style list of lines. |channel-lines| + {type} Edit behavior: any |getregtype()| result, or: + • "b" |blockwise-visual| mode (may include width, e.g. "b3") + • "c" |charwise| mode + • "l" |linewise| mode + • "" guess by contents, see |setreg()| + {after} If true insert after cursor (like |p|), or before (like + |P|). + {follow} If true place cursor at end of inserted text. *nvim_replace_termcodes()* nvim_replace_termcodes({str}, {from_part}, {do_lt}, {special}) - Replaces terminal codes and |keycodes| (<CR>, <Esc>, ...) in a - string with the internal representation. + Replaces terminal codes and |keycodes| (<CR>, <Esc>, ...) in a string with + the internal representation. - Parameters: ~ - {str} String to be converted. - {from_part} Legacy Vim parameter. Usually true. - {do_lt} Also translate <lt>. Ignored if `special` is - false. - {special} Replace |keycodes|, e.g. <CR> becomes a "\r" - char. + Parameters: ~ + {str} String to be converted. + {from_part} Legacy Vim parameter. Usually true. + {do_lt} Also translate <lt>. Ignored if `special` is false. + {special} Replace |keycodes|, e.g. <CR> becomes a "\r" char. - See also: ~ - replace_termcodes - cpoptions + See also: ~ + replace_termcodes + cpoptions *nvim_select_popupmenu_item()* nvim_select_popupmenu_item({item}, {insert}, {finish}, {opts}) - Selects an item in the completion popupmenu. - - If |ins-completion| is not active this API call is silently - ignored. Useful for an external UI using |ui-popupmenu| to - control the popupmenu with the mouse. Can also be used in a - mapping; use <cmd> |:map-cmd| to ensure the mapping doesn't - end completion mode. - - Parameters: ~ - {item} Index (zero-based) of the item to select. Value - of -1 selects nothing and restores the original - text. - {insert} Whether the selection should be inserted in the - buffer. - {finish} Finish the completion and dismiss the popupmenu. - Implies `insert`. - {opts} Optional parameters. Reserved for future use. + Selects an item in the completion popupmenu. + + If |ins-completion| is not active this API call is silently ignored. + Useful for an external UI using |ui-popupmenu| to control the popupmenu + with the mouse. Can also be used in a mapping; use <cmd> |:map-cmd| to + ensure the mapping doesn't end completion mode. + + Parameters: ~ + {item} Index (zero-based) of the item to select. Value of -1 + selects nothing and restores the original text. + {insert} Whether the selection should be inserted in the buffer. + {finish} Finish the completion and dismiss the popupmenu. Implies + `insert`. + {opts} Optional parameters. Reserved for future use. *nvim_set_client_info()* nvim_set_client_info({name}, {version}, {type}, {methods}, {attributes}) - Self-identifies the client. - - The client/plugin/application should call this after - connecting, to provide hints about its identity and purpose, - for debugging and orchestration. - - Can be called more than once; the caller should merge old info - if appropriate. Example: library first identifies the channel, - then a plugin using that library later identifies itself. - - Note: - "Something is better than nothing". You don't need to - include all the fields. - - Attributes: ~ - |RPC| only - - Parameters: ~ - {name} Short name for the connected client - {version} Dictionary describing the version, with - these (optional) keys: - • "major" major version (defaults to 0 if - not set, for no release yet) - • "minor" minor version - • "patch" patch number - • "prerelease" string describing a - prerelease, like "dev" or "beta1" - • "commit" hash or similar identifier of - commit - {type} Must be one of the following values. Client - libraries should default to "remote" unless - overridden by the user. - • "remote" remote client connected to Nvim. - • "ui" gui frontend - • "embedder" application using Nvim as a - component (for example, IDE/editor - implementing a vim mode). - • "host" plugin host, typically started by - nvim - • "plugin" single plugin, started by nvim - {methods} Builtin methods in the client. For a host, - this does not include plugin methods which - will be discovered later. The key should be - the method name, the values are dicts with - these (optional) keys (more keys may be - added in future versions of Nvim, thus - unknown keys are ignored. Clients must only - use keys defined in this or later versions - of Nvim): - • "async" if true, send as a notification. - If false or unspecified, use a blocking - request - • "nargs" Number of arguments. Could be a - single integer or an array of two - integers, minimum and maximum inclusive. - {attributes} Arbitrary string:string map of informal - client properties. Suggested keys: - • "website": Client homepage URL (e.g. - GitHub repository) - • "license": License description ("Apache - 2", "GPLv3", "MIT", …) - • "logo": URI or path to image, preferably - small logo or icon. .png or .svg format is - preferred. + Self-identifies the client. + + The client/plugin/application should call this after connecting, to + provide hints about its identity and purpose, for debugging and + orchestration. + + Can be called more than once; the caller should merge old info if + appropriate. Example: library first identifies the channel, then a plugin + using that library later identifies itself. + + Note: + "Something is better than nothing". You don't need to include all the + fields. + + Attributes: ~ + |RPC| only + + Parameters: ~ + {name} Short name for the connected client + {version} Dictionary describing the version, with these (optional) + keys: + • "major" major version (defaults to 0 if not set, for + no release yet) + • "minor" minor version + • "patch" patch number + • "prerelease" string describing a prerelease, like + "dev" or "beta1" + • "commit" hash or similar identifier of commit + {type} Must be one of the following values. Client libraries + should default to "remote" unless overridden by the + user. + • "remote" remote client connected to Nvim. + • "ui" gui frontend + • "embedder" application using Nvim as a component (for + example, IDE/editor implementing a vim mode). + • "host" plugin host, typically started by nvim + • "plugin" single plugin, started by nvim + {methods} Builtin methods in the client. For a host, this does not + include plugin methods which will be discovered later. + The key should be the method name, the values are dicts + with these (optional) keys (more keys may be added in + future versions of Nvim, thus unknown keys are ignored. + Clients must only use keys defined in this or later + versions of Nvim): + • "async" if true, send as a notification. If false or + unspecified, use a blocking request + • "nargs" Number of arguments. Could be a single integer + or an array of two integers, minimum and maximum + inclusive. + {attributes} Arbitrary string:string map of informal client + properties. Suggested keys: + • "website": Client homepage URL (e.g. GitHub + repository) + • "license": License description ("Apache 2", "GPLv3", + "MIT", …) + • "logo": URI or path to image, preferably small logo or + icon. .png or .svg format is preferred. nvim_set_current_buf({buffer}) *nvim_set_current_buf()* - Sets the current buffer. + Sets the current buffer. - Attributes: ~ - not allowed when |textlock| is active + Attributes: ~ + not allowed when |textlock| is active - Parameters: ~ - {buffer} Buffer handle + Parameters: ~ + {buffer} Buffer handle nvim_set_current_dir({dir}) *nvim_set_current_dir()* - Changes the global working directory. + Changes the global working directory. - Parameters: ~ - {dir} Directory path + Parameters: ~ + {dir} Directory path nvim_set_current_line({line}) *nvim_set_current_line()* - Sets the current line. + Sets the current line. - Attributes: ~ - not allowed when |textlock| is active + Attributes: ~ + not allowed when |textlock| is active - Parameters: ~ - {line} Line contents + Parameters: ~ + {line} Line contents nvim_set_current_tabpage({tabpage}) *nvim_set_current_tabpage()* - Sets the current tabpage. + Sets the current tabpage. - Attributes: ~ - not allowed when |textlock| is active + Attributes: ~ + not allowed when |textlock| is active - Parameters: ~ - {tabpage} Tabpage handle + Parameters: ~ + {tabpage} Tabpage handle nvim_set_current_win({window}) *nvim_set_current_win()* - Sets the current window. + Sets the current window. - Attributes: ~ - not allowed when |textlock| is active + Attributes: ~ + not allowed when |textlock| is active - Parameters: ~ - {window} Window handle + Parameters: ~ + {window} Window handle nvim_set_hl({ns_id}, {name}, {*val}) *nvim_set_hl()* - Sets a highlight group. - - Note: - Unlike the `:highlight` command which can update a - highlight group, this function completely replaces the - definition. For example: `nvim_set_hl(0, 'Visual', {})` - will clear the highlight group 'Visual'. - - Note: - The fg and bg keys also accept the string values `"fg"` or - `"bg"` which act as aliases to the corresponding - foreground and background values of the Normal group. If - the Normal group has not been defined, using these values - results in an error. - - Parameters: ~ - {ns_id} Namespace id for this highlight - |nvim_create_namespace()|. Use 0 to set a - highlight group globally |:highlight|. - {name} Highlight group name, e.g. "ErrorMsg" - {val} Highlight definition map, accepts the following - keys: - • fg (or foreground): color name or "#RRGGBB", - see note. - • bg (or background): color name or "#RRGGBB", - see note. - • sp (or special): color name or "#RRGGBB" - • blend: integer between 0 and 100 - • bold: boolean - • standout: boolean - • underline: boolean - • undercurl: boolean - • underdouble: boolean - • underdotted: boolean - • underdashed: boolean - • strikethrough: boolean - • italic: boolean - • reverse: boolean - • nocombine: boolean - • link: name of another highlight group to link - to, see |:hi-link|. - • default: Don't override existing definition - |:hi-default| - • ctermfg: Sets foreground of cterm color - |highlight-ctermfg| - • ctermbg: Sets background of cterm color - |highlight-ctermbg| - • cterm: cterm attribute map, like - |highlight-args|. If not set, cterm attributes - will match those from the attribute map - documented above. + Sets a highlight group. + + Note: + Unlike the `:highlight` command which can update a highlight group, + this function completely replaces the definition. For example: + `nvim_set_hl(0, 'Visual', {})` will clear the highlight group + 'Visual'. + + Note: + The fg and bg keys also accept the string values `"fg"` or `"bg"` + which act as aliases to the corresponding foreground and background + values of the Normal group. If the Normal group has not been defined, + using these values results in an error. + + Parameters: ~ + {ns_id} Namespace id for this highlight |nvim_create_namespace()|. + Use 0 to set a highlight group globally |:highlight|. + {name} Highlight group name, e.g. "ErrorMsg" + {val} Highlight definition map, accepts the following keys: + • fg (or foreground): color name or "#RRGGBB", see note. + • bg (or background): color name or "#RRGGBB", see note. + • sp (or special): color name or "#RRGGBB" + • blend: integer between 0 and 100 + • bold: boolean + • standout: boolean + • underline: boolean + • undercurl: boolean + • underdouble: boolean + • underdotted: boolean + • underdashed: boolean + • strikethrough: boolean + • italic: boolean + • reverse: boolean + • nocombine: boolean + • link: name of another highlight group to link to, see + |:hi-link|. + • default: Don't override existing definition |:hi-default| + • ctermfg: Sets foreground of cterm color |highlight-ctermfg| + • ctermbg: Sets background of cterm color |highlight-ctermbg| + • cterm: cterm attribute map, like |highlight-args|. If not + set, cterm attributes will match those from the attribute + map documented above. + +nvim_set_hl_ns({ns_id}) *nvim_set_hl_ns()* + Set active namespace for highlights. This can be set for a single window, + see |nvim_win_set_hl_ns|. + + Parameters: ~ + {ns_id} the namespace to use + +nvim_set_hl_ns_fast({ns_id}) *nvim_set_hl_ns_fast()* + Set active namespace for highlights while redrawing. + + This function meant to be called while redrawing, primarily from + |nvim_set_decoration_provider| on_win and on_line callbacks, which are + allowed to change the namespace during a redraw cycle. + + Attributes: ~ + |api-fast| + + Parameters: ~ + {ns_id} the namespace to activate nvim_set_keymap({mode}, {lhs}, {rhs}, {*opts}) *nvim_set_keymap()* - Sets a global |mapping| for the given mode. + Sets a global |mapping| for the given mode. - To set a buffer-local mapping, use |nvim_buf_set_keymap()|. + To set a buffer-local mapping, use |nvim_buf_set_keymap()|. - Unlike |:map|, leading/trailing whitespace is accepted as part - of the {lhs} or {rhs}. Empty {rhs} is |<Nop>|. |keycodes| are - replaced as usual. + Unlike |:map|, leading/trailing whitespace is accepted as part of the + {lhs} or {rhs}. Empty {rhs} is |<Nop>|. |keycodes| are replaced as usual. - Example: > - call nvim_set_keymap('n', ' <NL>', '', {'nowait': v:true}) + Example: > + call nvim_set_keymap('n', ' <NL>', '', {'nowait': v:true}) < - is equivalent to: > - nmap <nowait> <Space><NL> <Nop> + is equivalent to: > + nmap <nowait> <Space><NL> <Nop> < - Parameters: ~ - {mode} Mode short-name (map command prefix: "n", "i", - "v", "x", …) or "!" for |:map!|, or empty string - for |:map|. - {lhs} Left-hand-side |{lhs}| of the mapping. - {rhs} Right-hand-side |{rhs}| of the mapping. - {opts} Optional parameters map: keys are - |:map-arguments|, values are booleans (default - false). Accepts all |:map-arguments| as keys - excluding |<buffer>| but including |noremap| and - "desc". Unknown key is an error. "desc" can be - used to give a description to the mapping. When - called from Lua, also accepts a "callback" key - that takes a Lua function to call when the mapping - is executed. When "expr" is true, - "replace_keycodes" (boolean) can be used to - replace keycodes in the resulting string (see - |nvim_replace_termcodes()|), and a Lua callback - returning `nil` is equivalent to returning an - empty string. + Parameters: ~ + {mode} Mode short-name (map command prefix: "n", "i", "v", "x", …) or + "!" for |:map!|, or empty string for |:map|. + {lhs} Left-hand-side |{lhs}| of the mapping. + {rhs} Right-hand-side |{rhs}| of the mapping. + {opts} Optional parameters map: keys are |:map-arguments|, values are + booleans (default false). Accepts all |:map-arguments| as keys + excluding |<buffer>| but including |noremap| and "desc". + Unknown key is an error. "desc" can be used to give a + description to the mapping. When called from Lua, also accepts + a "callback" key that takes a Lua function to call when the + mapping is executed. When "expr" is true, "replace_keycodes" + (boolean) can be used to replace keycodes in the resulting + string (see |nvim_replace_termcodes()|), and a Lua callback + returning `nil` is equivalent to returning an empty string. nvim_set_var({name}, {value}) *nvim_set_var()* - Sets a global (g:) variable. + Sets a global (g:) variable. - Parameters: ~ - {name} Variable name - {value} Variable value + Parameters: ~ + {name} Variable name + {value} Variable value nvim_set_vvar({name}, {value}) *nvim_set_vvar()* - Sets a v: variable, if it is not readonly. + Sets a v: variable, if it is not readonly. - Parameters: ~ - {name} Variable name - {value} Variable value + Parameters: ~ + {name} Variable name + {value} Variable value nvim_strwidth({text}) *nvim_strwidth()* - Calculates the number of display cells occupied by `text`. - Control characters including <Tab> count as one cell. + Calculates the number of display cells occupied by `text`. Control + characters including <Tab> count as one cell. - Parameters: ~ - {text} Some text + Parameters: ~ + {text} Some text - Return: ~ - Number of cells + Return: ~ + Number of cells nvim_subscribe({event}) *nvim_subscribe()* - Subscribes to event broadcasts. + Subscribes to event broadcasts. - Attributes: ~ - |RPC| only + Attributes: ~ + |RPC| only - Parameters: ~ - {event} Event type string + Parameters: ~ + {event} Event type string nvim_unsubscribe({event}) *nvim_unsubscribe()* - Unsubscribes to event broadcasts. + Unsubscribes to event broadcasts. - Attributes: ~ - |RPC| only + Attributes: ~ + |RPC| only - Parameters: ~ - {event} Event type string + Parameters: ~ + {event} Event type string ============================================================================== @@ -1563,178 +1500,157 @@ Vimscript Functions *api-vimscript* *nvim_call_dict_function()* nvim_call_dict_function({dict}, {fn}, {args}) - Calls a VimL |Dictionary-function| with the given arguments. + Calls a VimL |Dictionary-function| with the given arguments. - On execution error: fails with VimL error, updates v:errmsg. + On execution error: fails with VimL error, updates v:errmsg. - Parameters: ~ - {dict} Dictionary, or String evaluating to a VimL |self| - dict - {fn} Name of the function defined on the VimL dict - {args} Function arguments packed in an Array + Parameters: ~ + {dict} Dictionary, or String evaluating to a VimL |self| dict + {fn} Name of the function defined on the VimL dict + {args} Function arguments packed in an Array - Return: ~ - Result of the function call + Return: ~ + Result of the function call nvim_call_function({fn}, {args}) *nvim_call_function()* - Calls a VimL function with the given arguments. + Calls a VimL function with the given arguments. - On execution error: fails with VimL error, updates v:errmsg. + On execution error: fails with VimL error, updates v:errmsg. - Parameters: ~ - {fn} Function to call - {args} Function arguments packed in an Array + Parameters: ~ + {fn} Function to call + {args} Function arguments packed in an Array - Return: ~ - Result of the function call + Return: ~ + Result of the function call nvim_command({command}) *nvim_command()* - Executes an Ex command. + Executes an Ex command. - On execution error: fails with VimL error, updates v:errmsg. + On execution error: fails with VimL error, updates v:errmsg. - Prefer using |nvim_cmd()| or |nvim_exec()| over this. To - evaluate multiple lines of Vim script or an Ex command - directly, use |nvim_exec()|. To construct an Ex command using - a structured format and then execute it, use |nvim_cmd()|. To - modify an Ex command before evaluating it, use - |nvim_parse_cmd()| in conjunction with |nvim_cmd()|. + Prefer using |nvim_cmd()| or |nvim_exec()| over this. To evaluate multiple + lines of Vim script or an Ex command directly, use |nvim_exec()|. To + construct an Ex command using a structured format and then execute it, use + |nvim_cmd()|. To modify an Ex command before evaluating it, use + |nvim_parse_cmd()| in conjunction with |nvim_cmd()|. - Parameters: ~ - {command} Ex command string + Parameters: ~ + {command} Ex command string nvim_eval({expr}) *nvim_eval()* - Evaluates a VimL |expression|. Dictionaries and Lists are - recursively expanded. + Evaluates a VimL |expression|. Dictionaries and Lists are recursively + expanded. - On execution error: fails with VimL error, updates v:errmsg. + On execution error: fails with VimL error, updates v:errmsg. - Parameters: ~ - {expr} VimL expression string + Parameters: ~ + {expr} VimL expression string - Return: ~ - Evaluation result or expanded object + Return: ~ + Evaluation result or expanded object nvim_exec({src}, {output}) *nvim_exec()* - Executes Vimscript (multiline block of Ex commands), like - anonymous |:source|. + Executes Vimscript (multiline block of Ex commands), like anonymous + |:source|. - Unlike |nvim_command()| this function supports heredocs, - script-scope (s:), etc. + Unlike |nvim_command()| this function supports heredocs, script-scope + (s:), etc. - On execution error: fails with VimL error, updates v:errmsg. + On execution error: fails with VimL error, updates v:errmsg. - Parameters: ~ - {src} Vimscript code - {output} Capture and return all (non-error, non-shell - |:!|) output + Parameters: ~ + {src} Vimscript code + {output} Capture and return all (non-error, non-shell |:!|) output - Return: ~ - Output (non-error, non-shell |:!|) if `output` is true, - else empty string. + Return: ~ + Output (non-error, non-shell |:!|) if `output` is true, else empty + string. - See also: ~ - |execute()| - |nvim_command()| - |nvim_cmd()| + See also: ~ + |execute()| + |nvim_command()| + |nvim_cmd()| *nvim_parse_expression()* nvim_parse_expression({expr}, {flags}, {highlight}) - Parse a VimL expression. - - Attributes: ~ - |api-fast| - - Parameters: ~ - {expr} Expression to parse. Always treated as a - single line. - {flags} Flags: - • "m" if multiple expressions in a row are - allowed (only the first one will be - parsed), - • "E" if EOC tokens are not allowed - (determines whether they will stop parsing - process or be recognized as an - operator/space, though also yielding an - error). - • "l" when needing to start parsing with - lvalues for ":let" or ":for". Common flag - sets: - • "m" to parse like for ":echo". - • "E" to parse like for "<C-r>=". - • empty string for ":call". - • "lm" to parse for ":let". - {highlight} If true, return value will also include - "highlight" key containing array of 4-tuples - (arrays) (Integer, Integer, Integer, String), - where first three numbers define the - highlighted region and represent line, - starting column and ending column (latter - exclusive: one should highlight region - [start_col, end_col)). - - Return: ~ - - • AST: top-level dictionary with these keys: - • "error": Dictionary with error, present only if parser - saw some error. Contains the following keys: - • "message": String, error message in printf format, - translated. Must contain exactly one "%.*s". - • "arg": String, error message argument. - - • "len": Amount of bytes successfully parsed. With flags - equal to "" that should be equal to the length of expr - string. (“Successfully parsed” here means - “participated in AST creation”, not “till the first - error”.) - • "ast": AST, either nil or a dictionary with these - keys: - • "type": node type, one of the value names from - ExprASTNodeType stringified without "kExprNode" - prefix. - • "start": a pair [line, column] describing where node - is "started" where "line" is always 0 (will not be 0 - if you will be using nvim_parse_viml() on e.g. - ":let", but that is not present yet). Both elements - are Integers. - • "len": “length” of the node. This and "start" are - there for debugging purposes primary (debugging - parser and providing debug information). - • "children": a list of nodes described in top/"ast". - There always is zero, one or two children, key will - not be present if node has no children. Maximum - number of children may be found in node_maxchildren - array. - - • Local values (present only for certain nodes): - • "scope": a single Integer, specifies scope for - "Option" and "PlainIdentifier" nodes. For "Option" it - is one of ExprOptScope values, for "PlainIdentifier" - it is one of ExprVarScope values. - • "ident": identifier (without scope, if any), present - for "Option", "PlainIdentifier", "PlainKey" and - "Environment" nodes. - • "name": Integer, register name (one character) or -1. - Only present for "Register" nodes. - • "cmp_type": String, comparison type, one of the value - names from ExprComparisonType, stringified without - "kExprCmp" prefix. Only present for "Comparison" - nodes. - • "ccs_strategy": String, case comparison strategy, one - of the value names from ExprCaseCompareStrategy, - stringified without "kCCStrategy" prefix. Only present - for "Comparison" nodes. - • "augmentation": String, augmentation type for - "Assignment" nodes. Is either an empty string, "Add", - "Subtract" or "Concat" for "=", "+=", "-=" or ".=" - respectively. - • "invert": Boolean, true if result of comparison needs - to be inverted. Only present for "Comparison" nodes. - • "ivalue": Integer, integer value for "Integer" nodes. - • "fvalue": Float, floating-point value for "Float" - nodes. - • "svalue": String, value for "SingleQuotedString" and - "DoubleQuotedString" nodes. + Parse a VimL expression. + + Attributes: ~ + |api-fast| + + Parameters: ~ + {expr} Expression to parse. Always treated as a single line. + {flags} Flags: + • "m" if multiple expressions in a row are allowed (only + the first one will be parsed), + • "E" if EOC tokens are not allowed (determines whether + they will stop parsing process or be recognized as an + operator/space, though also yielding an error). + • "l" when needing to start parsing with lvalues for + ":let" or ":for". Common flag sets: + • "m" to parse like for ":echo". + • "E" to parse like for "<C-r>=". + • empty string for ":call". + • "lm" to parse for ":let". + {highlight} If true, return value will also include "highlight" key + containing array of 4-tuples (arrays) (Integer, Integer, + Integer, String), where first three numbers define the + highlighted region and represent line, starting column + and ending column (latter exclusive: one should highlight + region [start_col, end_col)). + + Return: ~ + + • AST: top-level dictionary with these keys: + • "error": Dictionary with error, present only if parser saw some + error. Contains the following keys: + • "message": String, error message in printf format, translated. + Must contain exactly one "%.*s". + • "arg": String, error message argument. + + • "len": Amount of bytes successfully parsed. With flags equal to "" + that should be equal to the length of expr string. (“Successfully + parsed” here means “participated in AST creation”, not “till the + first error”.) + • "ast": AST, either nil or a dictionary with these keys: + • "type": node type, one of the value names from ExprASTNodeType + stringified without "kExprNode" prefix. + • "start": a pair [line, column] describing where node is + "started" where "line" is always 0 (will not be 0 if you will be + using nvim_parse_viml() on e.g. ":let", but that is not present + yet). Both elements are Integers. + • "len": “length” of the node. This and "start" are there for + debugging purposes primary (debugging parser and providing debug + information). + • "children": a list of nodes described in top/"ast". There always + is zero, one or two children, key will not be present if node + has no children. Maximum number of children may be found in + node_maxchildren array. + + • Local values (present only for certain nodes): + • "scope": a single Integer, specifies scope for "Option" and + "PlainIdentifier" nodes. For "Option" it is one of ExprOptScope + values, for "PlainIdentifier" it is one of ExprVarScope values. + • "ident": identifier (without scope, if any), present for "Option", + "PlainIdentifier", "PlainKey" and "Environment" nodes. + • "name": Integer, register name (one character) or -1. Only present + for "Register" nodes. + • "cmp_type": String, comparison type, one of the value names from + ExprComparisonType, stringified without "kExprCmp" prefix. Only + present for "Comparison" nodes. + • "ccs_strategy": String, case comparison strategy, one of the value + names from ExprCaseCompareStrategy, stringified without + "kCCStrategy" prefix. Only present for "Comparison" nodes. + • "augmentation": String, augmentation type for "Assignment" nodes. + Is either an empty string, "Add", "Subtract" or "Concat" for "=", + "+=", "-=" or ".=" respectively. + • "invert": Boolean, true if result of comparison needs to be + inverted. Only present for "Comparison" nodes. + • "ivalue": Integer, integer value for "Integer" nodes. + • "fvalue": Float, floating-point value for "Float" nodes. + • "svalue": String, value for "SingleQuotedString" and + "DoubleQuotedString" nodes. ============================================================================== @@ -1742,351 +1658,328 @@ Command Functions *api-command* *nvim_buf_create_user_command()* nvim_buf_create_user_command({buffer}, {name}, {command}, {*opts}) - Create a new user command |user-commands| in the given buffer. + Create a new user command |user-commands| in the given buffer. - Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer. + Parameters: ~ + {buffer} Buffer handle, or 0 for current buffer. - See also: ~ - nvim_create_user_command + See also: ~ + nvim_create_user_command *nvim_buf_del_user_command()* nvim_buf_del_user_command({buffer}, {name}) - Delete a buffer-local user-defined command. + Delete a buffer-local user-defined command. - Only commands created with |:command-buffer| or - |nvim_buf_create_user_command()| can be deleted with this - function. + Only commands created with |:command-buffer| or + |nvim_buf_create_user_command()| can be deleted with this function. - Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer. - {name} Name of the command to delete. + Parameters: ~ + {buffer} Buffer handle, or 0 for current buffer. + {name} Name of the command to delete. nvim_buf_get_commands({buffer}, {*opts}) *nvim_buf_get_commands()* - Gets a map of buffer-local |user-commands|. + Gets a map of buffer-local |user-commands|. - Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer - {opts} Optional parameters. Currently not used. + Parameters: ~ + {buffer} Buffer handle, or 0 for current buffer + {opts} Optional parameters. Currently not used. - Return: ~ - Map of maps describing commands. + Return: ~ + Map of maps describing commands. nvim_cmd({*cmd}, {*opts}) *nvim_cmd()* - Executes an Ex command. - - Unlike |nvim_command()| this command takes a structured - Dictionary instead of a String. This allows for easier - construction and manipulation of an Ex command. This also - allows for things such as having spaces inside a command - argument, expanding filenames in a command that otherwise - doesn't expand filenames, etc. - - On execution error: fails with VimL error, updates v:errmsg. - - Parameters: ~ - {cmd} Command to execute. Must be a Dictionary that can - contain the same values as the return value of - |nvim_parse_cmd()| except "addr", "nargs" and - "nextcmd" which are ignored if provided. All - values except for "cmd" are optional. - {opts} Optional parameters. - • output: (boolean, default false) Whether to - return command output. - - Return: ~ - Command output (non-error, non-shell |:!|) if `output` is - true, else empty string. - - See also: ~ - |nvim_exec()| - |nvim_command()| + Executes an Ex command. + + Unlike |nvim_command()| this command takes a structured Dictionary instead + of a String. This allows for easier construction and manipulation of an Ex + command. This also allows for things such as having spaces inside a + command argument, expanding filenames in a command that otherwise doesn't + expand filenames, etc. + + On execution error: fails with VimL error, updates v:errmsg. + + Parameters: ~ + {cmd} Command to execute. Must be a Dictionary that can contain the + same values as the return value of |nvim_parse_cmd()| except + "addr", "nargs" and "nextcmd" which are ignored if provided. + All values except for "cmd" are optional. + {opts} Optional parameters. + • output: (boolean, default false) Whether to return command + output. + + Return: ~ + Command output (non-error, non-shell |:!|) if `output` is true, else + empty string. + + See also: ~ + |nvim_exec()| + |nvim_command()| *nvim_create_user_command()* nvim_create_user_command({name}, {command}, {*opts}) - Create a new user command |user-commands| + Create a new user command |user-commands| - {name} is the name of the new command. The name must begin - with an uppercase letter. + {name} is the name of the new command. The name must begin with an + uppercase letter. - {command} is the replacement text or Lua function to execute. + {command} is the replacement text or Lua function to execute. - Example: > - :call nvim_create_user_command('SayHello', 'echo "Hello world!"', {}) - :SayHello - Hello world! + Example: > + :call nvim_create_user_command('SayHello', 'echo "Hello world!"', {}) + :SayHello + Hello world! < - Parameters: ~ - {name} Name of the new user command. Must begin with - an uppercase letter. - {command} Replacement command to execute when this user - command is executed. When called from Lua, the - command can also be a Lua function. The - function is called with a single table argument - that contains the following keys: - • args: (string) The args passed to the - command, if any |<args>| - • fargs: (table) The args split by unescaped - whitespace (when more than one argument is - allowed), if any |<f-args>| - • bang: (boolean) "true" if the command was - executed with a ! modifier |<bang>| - • line1: (number) The starting line of the - command range |<line1>| - • line2: (number) The final line of the command - range |<line2>| - • range: (number) The number of items in the - command range: 0, 1, or 2 |<range>| - • count: (number) Any count supplied |<count>| - • reg: (string) The optional register, if - specified |<reg>| - • mods: (string) Command modifiers, if any - |<mods>| - • smods: (table) Command modifiers in a - structured format. Has the same structure as - the "mods" key of |nvim_parse_cmd()|. - {opts} Optional command attributes. See - |command-attributes| for more details. To use - boolean attributes (such as |:command-bang| or - |:command-bar|) set the value to "true". In - addition to the string options listed in - |:command-complete|, the "complete" key also - accepts a Lua function which works like the - "customlist" completion mode - |:command-completion-customlist|. Additional - parameters: - • desc: (string) Used for listing the command - when a Lua function is used for {command}. - • force: (boolean, default true) Override any - previous definition. - • preview: (function) Preview callback for - 'inccommand' |:command-preview| + Parameters: ~ + {name} Name of the new user command. Must begin with an uppercase + letter. + {command} Replacement command to execute when this user command is + executed. When called from Lua, the command can also be a + Lua function. The function is called with a single table + argument that contains the following keys: + • args: (string) The args passed to the command, if any + |<args>| + • fargs: (table) The args split by unescaped whitespace + (when more than one argument is allowed), if any + |<f-args>| + • bang: (boolean) "true" if the command was executed with a + ! modifier |<bang>| + • line1: (number) The starting line of the command range + |<line1>| + • line2: (number) The final line of the command range + |<line2>| + • range: (number) The number of items in the command range: + 0, 1, or 2 |<range>| + • count: (number) Any count supplied |<count>| + • reg: (string) The optional register, if specified |<reg>| + • mods: (string) Command modifiers, if any |<mods>| + • smods: (table) Command modifiers in a structured format. + Has the same structure as the "mods" key of + |nvim_parse_cmd()|. + {opts} Optional command attributes. See |command-attributes| for + more details. To use boolean attributes (such as + |:command-bang| or |:command-bar|) set the value to "true". + In addition to the string options listed in + |:command-complete|, the "complete" key also accepts a Lua + function which works like the "customlist" completion mode + |:command-completion-customlist|. Additional parameters: + • desc: (string) Used for listing the command when a Lua + function is used for {command}. + • force: (boolean, default true) Override any previous + definition. + • preview: (function) Preview callback for 'inccommand' + |:command-preview| nvim_del_user_command({name}) *nvim_del_user_command()* - Delete a user-defined command. + Delete a user-defined command. - Parameters: ~ - {name} Name of the command to delete. + Parameters: ~ + {name} Name of the command to delete. nvim_get_commands({*opts}) *nvim_get_commands()* - Gets a map of global (non-buffer-local) Ex commands. + Gets a map of global (non-buffer-local) Ex commands. - Currently only |user-commands| are supported, not builtin Ex - commands. + Currently only |user-commands| are supported, not builtin Ex commands. - Parameters: ~ - {opts} Optional parameters. Currently only supports - {"builtin":false} + Parameters: ~ + {opts} Optional parameters. Currently only supports {"builtin":false} - Return: ~ - Map of maps describing commands. + Return: ~ + Map of maps describing commands. nvim_parse_cmd({str}, {opts}) *nvim_parse_cmd()* - Parse command line. - - Doesn't check the validity of command arguments. - - Attributes: ~ - |api-fast| - - Parameters: ~ - {str} Command line string to parse. Cannot contain "\n". - {opts} Optional parameters. Reserved for future use. - - Return: ~ - Dictionary containing command information, with these - keys: - • cmd: (string) Command name. - • range: (array) Command <range>. Can have 0-2 elements - depending on how many items the range contains. Has no - elements if command doesn't accept a range or if no - range was specified, one element if only a single range - item was specified and two elements if both range items - were specified. - • count: (number) Any |<count>| that was supplied to the - command. -1 if command cannot take a count. - • reg: (number) The optional command |<register>|, if - specified. Empty string if not specified or if command - cannot take a register. - • bang: (boolean) Whether command contains a |<bang>| (!) - modifier. - • args: (array) Command arguments. - • addr: (string) Value of |:command-addr|. Uses short - name. - • nargs: (string) Value of |:command-nargs|. - • nextcmd: (string) Next command if there are multiple - commands separated by a |:bar|. Empty if there isn't a - next command. - • magic: (dictionary) Which characters have special - meaning in the command arguments. - • file: (boolean) The command expands filenames. Which - means characters such as "%", "#" and wildcards are - expanded. - • bar: (boolean) The "|" character is treated as a - command separator and the double quote character (") - is treated as the start of a comment. - - • mods: (dictionary) |:command-modifiers|. - • filter: (dictionary) |:filter|. - • pattern: (string) Filter pattern. Empty string if - there is no filter. - • force: (boolean) Whether filter is inverted or not. - - • silent: (boolean) |:silent|. - • emsg_silent: (boolean) |:silent!|. - • unsilent: (boolean) |:unsilent|. - • sandbox: (boolean) |:sandbox|. - • noautocmd: (boolean) |:noautocmd|. - • browse: (boolean) |:browse|. - • confirm: (boolean) |:confirm|. - • hide: (boolean) |:hide|. - • keepalt: (boolean) |:keepalt|. - • keepjumps: (boolean) |:keepjumps|. - • keepmarks: (boolean) |:keepmarks|. - • keeppatterns: (boolean) |:keeppatterns|. - • lockmarks: (boolean) |:lockmarks|. - • noswapfile: (boolean) |:noswapfile|. - • tab: (integer) |:tab|. - • verbose: (integer) |:verbose|. -1 when omitted. - • vertical: (boolean) |:vertical|. - • split: (string) Split modifier string, is an empty - string when there's no split modifier. If there is a - split modifier it can be one of: - • "aboveleft": |:aboveleft|. - • "belowright": |:belowright|. - • "topleft": |:topleft|. - • "botright": |:botright|. + Parse command line. + + Doesn't check the validity of command arguments. + + Attributes: ~ + |api-fast| + + Parameters: ~ + {str} Command line string to parse. Cannot contain "\n". + {opts} Optional parameters. Reserved for future use. + + Return: ~ + Dictionary containing command information, with these keys: + • cmd: (string) Command name. + • range: (array) Command <range>. Can have 0-2 elements depending on + how many items the range contains. Has no elements if command + doesn't accept a range or if no range was specified, one element if + only a single range item was specified and two elements if both + range items were specified. + • count: (number) Any |<count>| that was supplied to the command. -1 + if command cannot take a count. + • reg: (number) The optional command |<register>|, if specified. Empty + string if not specified or if command cannot take a register. + • bang: (boolean) Whether command contains a |<bang>| (!) modifier. + • args: (array) Command arguments. + • addr: (string) Value of |:command-addr|. Uses short name. + • nargs: (string) Value of |:command-nargs|. + • nextcmd: (string) Next command if there are multiple commands + separated by a |:bar|. Empty if there isn't a next command. + • magic: (dictionary) Which characters have special meaning in the + command arguments. + • file: (boolean) The command expands filenames. Which means + characters such as "%", "#" and wildcards are expanded. + • bar: (boolean) The "|" character is treated as a command separator + and the double quote character (") is treated as the start of a + comment. + + • mods: (dictionary) |:command-modifiers|. + • filter: (dictionary) |:filter|. + • pattern: (string) Filter pattern. Empty string if there is no + filter. + • force: (boolean) Whether filter is inverted or not. + + • silent: (boolean) |:silent|. + • emsg_silent: (boolean) |:silent!|. + • unsilent: (boolean) |:unsilent|. + • sandbox: (boolean) |:sandbox|. + • noautocmd: (boolean) |:noautocmd|. + • browse: (boolean) |:browse|. + • confirm: (boolean) |:confirm|. + • hide: (boolean) |:hide|. + • keepalt: (boolean) |:keepalt|. + • keepjumps: (boolean) |:keepjumps|. + • keepmarks: (boolean) |:keepmarks|. + • keeppatterns: (boolean) |:keeppatterns|. + • lockmarks: (boolean) |:lockmarks|. + • noswapfile: (boolean) |:noswapfile|. + • tab: (integer) |:tab|. + • verbose: (integer) |:verbose|. -1 when omitted. + • vertical: (boolean) |:vertical|. + • split: (string) Split modifier string, is an empty string when + there's no split modifier. If there is a split modifier it can be + one of: + • "aboveleft": |:aboveleft|. + • "belowright": |:belowright|. + • "topleft": |:topleft|. + • "botright": |:botright|. ============================================================================== Options Functions *api-options* nvim_buf_get_option({buffer}, {name}) *nvim_buf_get_option()* - Gets a buffer option value + Gets a buffer option value - Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer - {name} Option name + Parameters: ~ + {buffer} Buffer handle, or 0 for current buffer + {name} Option name - Return: ~ - Option value + Return: ~ + Option value nvim_buf_set_option({buffer}, {name}, {value}) *nvim_buf_set_option()* - Sets a buffer option value. Passing `nil` as value deletes the - option (only works if there's a global fallback) + Sets a buffer option value. Passing `nil` as value deletes the option + (only works if there's a global fallback) - Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer - {name} Option name - {value} Option value + Parameters: ~ + {buffer} Buffer handle, or 0 for current buffer + {name} Option name + {value} Option value nvim_get_all_options_info() *nvim_get_all_options_info()* - Gets the option information for all options. + Gets the option information for all options. - The dictionary has the full option names as keys and option - metadata dictionaries as detailed at |nvim_get_option_info|. + The dictionary has the full option names as keys and option metadata + dictionaries as detailed at |nvim_get_option_info|. - Return: ~ - dictionary of all options + Return: ~ + dictionary of all options nvim_get_option({name}) *nvim_get_option()* - Gets the global value of an option. + Gets the global value of an option. - Parameters: ~ - {name} Option name + Parameters: ~ + {name} Option name - Return: ~ - Option value (global) + Return: ~ + Option value (global) nvim_get_option_info({name}) *nvim_get_option_info()* - Gets the option information for one option - - Resulting dictionary has keys: - • name: Name of the option (like 'filetype') - • shortname: Shortened name of the option (like 'ft') - • type: type of option ("string", "number" or "boolean") - • default: The default value for the option - • was_set: Whether the option was set. - • last_set_sid: Last set script id (if any) - • last_set_linenr: line number where option was set - • last_set_chan: Channel where option was set (0 for local) - • scope: one of "global", "win", or "buf" - • global_local: whether win or buf option has a global value - • commalist: List of comma separated values - • flaglist: List of single char flags - - Parameters: ~ - {name} Option name - - Return: ~ - Option Information + Gets the option information for one option + + Resulting dictionary has keys: + • name: Name of the option (like 'filetype') + • shortname: Shortened name of the option (like 'ft') + • type: type of option ("string", "number" or "boolean") + • default: The default value for the option + • was_set: Whether the option was set. + • last_set_sid: Last set script id (if any) + • last_set_linenr: line number where option was set + • last_set_chan: Channel where option was set (0 for local) + • scope: one of "global", "win", or "buf" + • global_local: whether win or buf option has a global value + • commalist: List of comma separated values + • flaglist: List of single char flags + + Parameters: ~ + {name} Option name + + Return: ~ + Option Information nvim_get_option_value({name}, {*opts}) *nvim_get_option_value()* - Gets the value of an option. The behavior of this function - matches that of |:set|: the local value of an option is - returned if it exists; otherwise, the global value is - returned. Local values always correspond to the current buffer - or window, unless "buf" or "win" is set in {opts}. - - Parameters: ~ - {name} Option name - {opts} Optional parameters - • scope: One of "global" or "local". Analogous to - |:setglobal| and |:setlocal|, respectively. - • win: |window-ID|. Used for getting window local - options. - • buf: Buffer number. Used for getting buffer - local options. Implies {scope} is "local". - - Return: ~ - Option value + Gets the value of an option. The behavior of this function matches that of + |:set|: the local value of an option is returned if it exists; otherwise, + the global value is returned. Local values always correspond to the + current buffer or window, unless "buf" or "win" is set in {opts}. + + Parameters: ~ + {name} Option name + {opts} Optional parameters + • scope: One of "global" or "local". Analogous to |:setglobal| + and |:setlocal|, respectively. + • win: |window-ID|. Used for getting window local options. + • buf: Buffer number. Used for getting buffer local options. + Implies {scope} is "local". + + Return: ~ + Option value nvim_set_option({name}, {value}) *nvim_set_option()* - Sets the global value of an option. + Sets the global value of an option. - Parameters: ~ - {name} Option name - {value} New option value + Parameters: ~ + {name} Option name + {value} New option value *nvim_set_option_value()* nvim_set_option_value({name}, {value}, {*opts}) - Sets the value of an option. The behavior of this function - matches that of |:set|: for global-local options, both the - global and local value are set unless otherwise specified with - {scope}. - - Note the options {win} and {buf} cannot be used together. - - Parameters: ~ - {name} Option name - {value} New option value - {opts} Optional parameters - • scope: One of 'global' or 'local'. Analogous to - |:setglobal| and |:setlocal|, respectively. - • win: |window-ID|. Used for setting window local - option. - • buf: Buffer number. Used for setting buffer - local option. + Sets the value of an option. The behavior of this function matches that of + |:set|: for global-local options, both the global and local value are set + unless otherwise specified with {scope}. + + Note the options {win} and {buf} cannot be used together. + + Parameters: ~ + {name} Option name + {value} New option value + {opts} Optional parameters + • scope: One of 'global' or 'local'. Analogous to + |:setglobal| and |:setlocal|, respectively. + • win: |window-ID|. Used for setting window local option. + • buf: Buffer number. Used for setting buffer local option. nvim_win_get_option({window}, {name}) *nvim_win_get_option()* - Gets a window option value + Gets a window option value - Parameters: ~ - {window} Window handle, or 0 for current window - {name} Option name + Parameters: ~ + {window} Window handle, or 0 for current window + {name} Option name - Return: ~ - Option value + Return: ~ + Option value nvim_win_set_option({window}, {name}, {value}) *nvim_win_set_option()* - Sets a window option value. Passing `nil` as value deletes the - option (only works if there's a global fallback) + Sets a window option value. Passing `nil` as value deletes the option + (only works if there's a global fallback) - Parameters: ~ - {window} Window handle, or 0 for current window - {name} Option name - {value} Option value + Parameters: ~ + {window} Window handle, or 0 for current window + {name} Option name + {value} Option value ============================================================================== @@ -2097,451 +1990,427 @@ For more information on buffers, see |buffers|. Unloaded Buffers:~ -Buffers may be unloaded by the |:bunload| command or the -buffer's |'bufhidden'| option. When a buffer is unloaded its -file contents are freed from memory and vim cannot operate on -the buffer lines until it is reloaded (usually by opening the -buffer again in a new window). API methods such as -|nvim_buf_get_lines()| and |nvim_buf_line_count()| will be +Buffers may be unloaded by the |:bunload| command or the buffer's +|'bufhidden'| option. When a buffer is unloaded its file contents are +freed from memory and vim cannot operate on the buffer lines until it is +reloaded (usually by opening the buffer again in a new window). API +methods such as |nvim_buf_get_lines()| and |nvim_buf_line_count()| will be affected. -You can use |nvim_buf_is_loaded()| or |nvim_buf_line_count()| -to check whether a buffer is loaded. +You can use |nvim_buf_is_loaded()| or |nvim_buf_line_count()| to check +whether a buffer is loaded. nvim_buf_attach({buffer}, {send_buffer}, {opts}) *nvim_buf_attach()* - Activates buffer-update events on a channel, or as Lua - callbacks. - - Example (Lua): capture buffer updates in a global `events` variable (use "print(vim.inspect(events))" to see its - contents): > - events = {} - vim.api.nvim_buf_attach(0, false, { - on_lines=function(...) table.insert(events, {...}) end}) + Activates buffer-update events on a channel, or as Lua callbacks. + + Example (Lua): capture buffer updates in a global `events` variable (use "print(vim.inspect(events))" to see its contents): > + events = {} + vim.api.nvim_buf_attach(0, false, { + on_lines=function(...) table.insert(events, {...}) end}) < - Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer - {send_buffer} True if the initial notification should - contain the whole buffer: first - notification will be - `nvim_buf_lines_event`. Else the first - notification will be - `nvim_buf_changedtick_event`. Not for Lua - callbacks. - {opts} Optional parameters. - • on_lines: Lua callback invoked on change. - Return `true` to detach. Args: - • the string "lines" - • buffer handle - • b:changedtick - • first line that changed (zero-indexed) - • last line that was changed - • last line in the updated range - • byte count of previous contents - • deleted_codepoints (if `utf_sizes` is - true) - • deleted_codeunits (if `utf_sizes` is - true) - - • on_bytes: lua callback invoked on change. - This callback receives more granular - information about the change compared to - on_lines. Return `true` to detach. Args: - • the string "bytes" - • buffer handle - • b:changedtick - • start row of the changed text - (zero-indexed) - • start column of the changed text - • byte offset of the changed text (from - the start of the buffer) - • old end row of the changed text - • old end column of the changed text - • old end byte length of the changed text - • new end row of the changed text - • new end column of the changed text - • new end byte length of the changed text - - • on_changedtick: Lua callback invoked on - changedtick increment without text - change. Args: - • the string "changedtick" - • buffer handle - • b:changedtick - - • on_detach: Lua callback invoked on - detach. Args: - • the string "detach" - • buffer handle - - • on_reload: Lua callback invoked on - reload. The entire buffer content should - be considered changed. Args: - • the string "reload" - • buffer handle - - • utf_sizes: include UTF-32 and UTF-16 size - of the replaced region, as args to - `on_lines`. - • preview: also attach to command preview - (i.e. 'inccommand') events. - - Return: ~ - False if attach failed (invalid parameter, or buffer isn't - loaded); otherwise True. TODO: LUA_API_NO_EVAL - - See also: ~ - |nvim_buf_detach()| - |api-buffer-updates-lua| + Parameters: ~ + {buffer} Buffer handle, or 0 for current buffer + {send_buffer} True if the initial notification should contain the + whole buffer: first notification will be + `nvim_buf_lines_event`. Else the first notification + will be `nvim_buf_changedtick_event`. Not for Lua + callbacks. + {opts} Optional parameters. + • on_lines: Lua callback invoked on change. Return `true` to detach. Args: + • the string "lines" + • buffer handle + • b:changedtick + • first line that changed (zero-indexed) + • last line that was changed + • last line in the updated range + • byte count of previous contents + • deleted_codepoints (if `utf_sizes` is true) + • deleted_codeunits (if `utf_sizes` is true) + + • on_bytes: lua callback invoked on change. This + callback receives more granular information about the + change compared to on_lines. Return `true` to detach. Args: + • the string "bytes" + • buffer handle + • b:changedtick + • start row of the changed text (zero-indexed) + • start column of the changed text + • byte offset of the changed text (from the start of + the buffer) + • old end row of the changed text + • old end column of the changed text + • old end byte length of the changed text + • new end row of the changed text + • new end column of the changed text + • new end byte length of the changed text + + • on_changedtick: Lua callback invoked on changedtick + increment without text change. Args: + • the string "changedtick" + • buffer handle + • b:changedtick + + • on_detach: Lua callback invoked on detach. Args: + • the string "detach" + • buffer handle + + • on_reload: Lua callback invoked on reload. The entire + buffer content should be considered changed. Args: + • the string "reload" + • buffer handle + + • utf_sizes: include UTF-32 and UTF-16 size of the + replaced region, as args to `on_lines`. + • preview: also attach to command preview (i.e. + 'inccommand') events. + + Return: ~ + False if attach failed (invalid parameter, or buffer isn't loaded); + otherwise True. TODO: LUA_API_NO_EVAL + + See also: ~ + |nvim_buf_detach()| + |api-buffer-updates-lua| nvim_buf_call({buffer}, {fun}) *nvim_buf_call()* - call a function with buffer as temporary current buffer + call a function with buffer as temporary current buffer - This temporarily switches current buffer to "buffer". If the - current window already shows "buffer", the window is not - switched If a window inside the current tabpage (including a - float) already shows the buffer One of these windows will be - set as current window temporarily. Otherwise a temporary - scratch window (called the "autocmd window" for historical - reasons) will be used. + This temporarily switches current buffer to "buffer". If the current + window already shows "buffer", the window is not switched If a window + inside the current tabpage (including a float) already shows the buffer + One of these windows will be set as current window temporarily. Otherwise + a temporary scratch window (called the "autocmd window" for historical + reasons) will be used. - This is useful e.g. to call vimL functions that only work with - the current buffer/window currently, like |termopen()|. + This is useful e.g. to call vimL functions that only work with the current + buffer/window currently, like |termopen()|. - Attributes: ~ - |vim.api| only + Attributes: ~ + |vim.api| only - Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer - {fun} Function to call inside the buffer (currently - lua callable only) + Parameters: ~ + {buffer} Buffer handle, or 0 for current buffer + {fun} Function to call inside the buffer (currently lua callable + only) - Return: ~ - Return value of function. NB: will deepcopy lua values - currently, use upvalues to send lua references in and out. + Return: ~ + Return value of function. NB: will deepcopy lua values currently, use + upvalues to send lua references in and out. nvim_buf_del_keymap({buffer}, {mode}, {lhs}) *nvim_buf_del_keymap()* - Unmaps a buffer-local |mapping| for the given mode. + Unmaps a buffer-local |mapping| for the given mode. - Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer + Parameters: ~ + {buffer} Buffer handle, or 0 for current buffer - See also: ~ - |nvim_del_keymap()| + See also: ~ + |nvim_del_keymap()| nvim_buf_del_mark({buffer}, {name}) *nvim_buf_del_mark()* - Deletes a named mark in the buffer. See |mark-motions|. + Deletes a named mark in the buffer. See |mark-motions|. - Note: - only deletes marks set in the buffer, if the mark is not - set in the buffer it will return false. + Note: + only deletes marks set in the buffer, if the mark is not set in the + buffer it will return false. - Parameters: ~ - {buffer} Buffer to set the mark on - {name} Mark name + Parameters: ~ + {buffer} Buffer to set the mark on + {name} Mark name - Return: ~ - true if the mark was deleted, else false. + Return: ~ + true if the mark was deleted, else false. - See also: ~ - |nvim_buf_set_mark()| - |nvim_del_mark()| + See also: ~ + |nvim_buf_set_mark()| + |nvim_del_mark()| nvim_buf_del_var({buffer}, {name}) *nvim_buf_del_var()* - Removes a buffer-scoped (b:) variable + Removes a buffer-scoped (b:) variable - Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer - {name} Variable name + Parameters: ~ + {buffer} Buffer handle, or 0 for current buffer + {name} Variable name nvim_buf_delete({buffer}, {opts}) *nvim_buf_delete()* - Deletes the buffer. See |:bwipeout| + Deletes the buffer. See |:bwipeout| - Attributes: ~ - not allowed when |textlock| is active + Attributes: ~ + not allowed when |textlock| is active - Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer - {opts} Optional parameters. Keys: - • force: Force deletion and ignore unsaved - changes. - • unload: Unloaded only, do not delete. See - |:bunload| + Parameters: ~ + {buffer} Buffer handle, or 0 for current buffer + {opts} Optional parameters. Keys: + • force: Force deletion and ignore unsaved changes. + • unload: Unloaded only, do not delete. See |:bunload| nvim_buf_detach({buffer}) *nvim_buf_detach()* - Deactivates buffer-update events on the channel. + Deactivates buffer-update events on the channel. - Attributes: ~ - |RPC| only + Attributes: ~ + |RPC| only - Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer + Parameters: ~ + {buffer} Buffer handle, or 0 for current buffer - Return: ~ - False if detach failed (because the buffer isn't loaded); - otherwise True. + Return: ~ + False if detach failed (because the buffer isn't loaded); otherwise + True. - See also: ~ - |nvim_buf_attach()| - |api-lua-detach| for detaching Lua callbacks + See also: ~ + |nvim_buf_attach()| + |api-lua-detach| for detaching Lua callbacks nvim_buf_get_changedtick({buffer}) *nvim_buf_get_changedtick()* - Gets a changed tick of a buffer + Gets a changed tick of a buffer - Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer + Parameters: ~ + {buffer} Buffer handle, or 0 for current buffer - Return: ~ - `b:changedtick` value. + Return: ~ + `b:changedtick` value. nvim_buf_get_keymap({buffer}, {mode}) *nvim_buf_get_keymap()* - Gets a list of buffer-local |mapping| definitions. + Gets a list of buffer-local |mapping| definitions. - Parameters: ~ - {mode} Mode short-name ("n", "i", "v", ...) - {buffer} Buffer handle, or 0 for current buffer + Parameters: ~ + {mode} Mode short-name ("n", "i", "v", ...) + {buffer} Buffer handle, or 0 for current buffer - Return: ~ - Array of |maparg()|-like dictionaries describing mappings. - The "buffer" key holds the associated buffer handle. + Return: ~ + Array of |maparg()|-like dictionaries describing mappings. The + "buffer" key holds the associated buffer handle. *nvim_buf_get_lines()* nvim_buf_get_lines({buffer}, {start}, {end}, {strict_indexing}) - Gets a line-range from the buffer. + Gets a line-range from the buffer. - Indexing is zero-based, end-exclusive. Negative indices are - interpreted as length+1+index: -1 refers to the index past the - end. So to get the last element use start=-2 and end=-1. + Indexing is zero-based, end-exclusive. Negative indices are interpreted as + length+1+index: -1 refers to the index past the end. So to get the last + element use start=-2 and end=-1. - Out-of-bounds indices are clamped to the nearest valid value, - unless `strict_indexing` is set. + Out-of-bounds indices are clamped to the nearest valid value, unless + `strict_indexing` is set. - Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer - {start} First line index - {end} Last line index, exclusive - {strict_indexing} Whether out-of-bounds should be an - error. + Parameters: ~ + {buffer} Buffer handle, or 0 for current buffer + {start} First line index + {end} Last line index, exclusive + {strict_indexing} Whether out-of-bounds should be an error. - Return: ~ - Array of lines, or empty array for unloaded buffer. + Return: ~ + Array of lines, or empty array for unloaded buffer. nvim_buf_get_mark({buffer}, {name}) *nvim_buf_get_mark()* - Returns a tuple (row,col) representing the position of the - named mark. See |mark-motions|. + Returns a tuple (row,col) representing the position of the named mark. See + |mark-motions|. - Marks are (1,0)-indexed. |api-indexing| + Marks are (1,0)-indexed. |api-indexing| - Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer - {name} Mark name + Parameters: ~ + {buffer} Buffer handle, or 0 for current buffer + {name} Mark name - Return: ~ - (row, col) tuple, (0, 0) if the mark is not set, or is an - uppercase/file mark set in another buffer. + Return: ~ + (row, col) tuple, (0, 0) if the mark is not set, or is an + uppercase/file mark set in another buffer. - See also: ~ - |nvim_buf_set_mark()| - |nvim_buf_del_mark()| + See also: ~ + |nvim_buf_set_mark()| + |nvim_buf_del_mark()| nvim_buf_get_name({buffer}) *nvim_buf_get_name()* - Gets the full file name for the buffer + Gets the full file name for the buffer - Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer + Parameters: ~ + {buffer} Buffer handle, or 0 for current buffer - Return: ~ - Buffer name + Return: ~ + Buffer name nvim_buf_get_offset({buffer}, {index}) *nvim_buf_get_offset()* - Returns the byte offset of a line (0-indexed). |api-indexing| + Returns the byte offset of a line (0-indexed). |api-indexing| - Line 1 (index=0) has offset 0. UTF-8 bytes are counted. EOL is - one byte. 'fileformat' and 'fileencoding' are ignored. The - line index just after the last line gives the total byte-count - of the buffer. A final EOL byte is counted if it would be - written, see 'eol'. + Line 1 (index=0) has offset 0. UTF-8 bytes are counted. EOL is one byte. + 'fileformat' and 'fileencoding' are ignored. The line index just after the + last line gives the total byte-count of the buffer. A final EOL byte is + counted if it would be written, see 'eol'. - Unlike |line2byte()|, throws error for out-of-bounds indexing. - Returns -1 for unloaded buffer. + Unlike |line2byte()|, throws error for out-of-bounds indexing. Returns -1 + for unloaded buffer. - Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer - {index} Line index + Parameters: ~ + {buffer} Buffer handle, or 0 for current buffer + {index} Line index - Return: ~ - Integer byte offset, or -1 for unloaded buffer. + Return: ~ + Integer byte offset, or -1 for unloaded buffer. *nvim_buf_get_text()* nvim_buf_get_text({buffer}, {start_row}, {start_col}, {end_row}, {end_col}, {opts}) - Gets a range from the buffer. + Gets a range from the buffer. - This differs from |nvim_buf_get_lines()| in that it allows - retrieving only portions of a line. + This differs from |nvim_buf_get_lines()| in that it allows retrieving only + portions of a line. - Indexing is zero-based. Row indices are end-inclusive, and - column indices are end-exclusive. + Indexing is zero-based. Row indices are end-inclusive, and column indices + are end-exclusive. - Prefer |nvim_buf_get_lines()| when retrieving entire lines. + Prefer |nvim_buf_get_lines()| when retrieving entire lines. - Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer - {start_row} First line index - {start_col} Starting column (byte offset) on first line - {end_row} Last line index, inclusive - {end_col} Ending column (byte offset) on last line, - exclusive - {opts} Optional parameters. Currently unused. + Parameters: ~ + {buffer} Buffer handle, or 0 for current buffer + {start_row} First line index + {start_col} Starting column (byte offset) on first line + {end_row} Last line index, inclusive + {end_col} Ending column (byte offset) on last line, exclusive + {opts} Optional parameters. Currently unused. - Return: ~ - Array of lines, or empty array for unloaded buffer. + Return: ~ + Array of lines, or empty array for unloaded buffer. nvim_buf_get_var({buffer}, {name}) *nvim_buf_get_var()* - Gets a buffer-scoped (b:) variable. + Gets a buffer-scoped (b:) variable. - Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer - {name} Variable name + Parameters: ~ + {buffer} Buffer handle, or 0 for current buffer + {name} Variable name - Return: ~ - Variable value + Return: ~ + Variable value nvim_buf_is_loaded({buffer}) *nvim_buf_is_loaded()* - Checks if a buffer is valid and loaded. See |api-buffer| for - more info about unloaded buffers. + Checks if a buffer is valid and loaded. See |api-buffer| for more info + about unloaded buffers. - Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer + Parameters: ~ + {buffer} Buffer handle, or 0 for current buffer - Return: ~ - true if the buffer is valid and loaded, false otherwise. + Return: ~ + true if the buffer is valid and loaded, false otherwise. nvim_buf_is_valid({buffer}) *nvim_buf_is_valid()* - Checks if a buffer is valid. + Checks if a buffer is valid. - Note: - Even if a buffer is valid it may have been unloaded. See - |api-buffer| for more info about unloaded buffers. + Note: + Even if a buffer is valid it may have been unloaded. See |api-buffer| + for more info about unloaded buffers. - Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer + Parameters: ~ + {buffer} Buffer handle, or 0 for current buffer - Return: ~ - true if the buffer is valid, false otherwise. + Return: ~ + true if the buffer is valid, false otherwise. nvim_buf_line_count({buffer}) *nvim_buf_line_count()* - Returns the number of lines in the given buffer. + Returns the number of lines in the given buffer. - Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer + Parameters: ~ + {buffer} Buffer handle, or 0 for current buffer - Return: ~ - Line count, or 0 for unloaded buffer. |api-buffer| + Return: ~ + Line count, or 0 for unloaded buffer. |api-buffer| *nvim_buf_set_keymap()* nvim_buf_set_keymap({buffer}, {mode}, {lhs}, {rhs}, {*opts}) - Sets a buffer-local |mapping| for the given mode. + Sets a buffer-local |mapping| for the given mode. - Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer + Parameters: ~ + {buffer} Buffer handle, or 0 for current buffer - See also: ~ - |nvim_set_keymap()| + See also: ~ + |nvim_set_keymap()| *nvim_buf_set_lines()* nvim_buf_set_lines({buffer}, {start}, {end}, {strict_indexing}, {replacement}) - Sets (replaces) a line-range in the buffer. + Sets (replaces) a line-range in the buffer. - Indexing is zero-based, end-exclusive. Negative indices are - interpreted as length+1+index: -1 refers to the index past the - end. So to change or delete the last element use start=-2 and - end=-1. + Indexing is zero-based, end-exclusive. Negative indices are interpreted as + length+1+index: -1 refers to the index past the end. So to change or + delete the last element use start=-2 and end=-1. - To insert lines at a given index, set `start` and `end` to the - same index. To delete a range of lines, set `replacement` to - an empty array. + To insert lines at a given index, set `start` and `end` to the same index. + To delete a range of lines, set `replacement` to an empty array. - Out-of-bounds indices are clamped to the nearest valid value, - unless `strict_indexing` is set. + Out-of-bounds indices are clamped to the nearest valid value, unless + `strict_indexing` is set. - Attributes: ~ - not allowed when |textlock| is active + Attributes: ~ + not allowed when |textlock| is active - Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer - {start} First line index - {end} Last line index, exclusive - {strict_indexing} Whether out-of-bounds should be an - error. - {replacement} Array of lines to use as replacement + Parameters: ~ + {buffer} Buffer handle, or 0 for current buffer + {start} First line index + {end} Last line index, exclusive + {strict_indexing} Whether out-of-bounds should be an error. + {replacement} Array of lines to use as replacement *nvim_buf_set_mark()* nvim_buf_set_mark({buffer}, {name}, {line}, {col}, {opts}) - Sets a named mark in the given buffer, all marks are allowed - file/uppercase, visual, last change, etc. See |mark-motions|. + Sets a named mark in the given buffer, all marks are allowed + file/uppercase, visual, last change, etc. See |mark-motions|. - Marks are (1,0)-indexed. |api-indexing| + Marks are (1,0)-indexed. |api-indexing| - Note: - Passing 0 as line deletes the mark + Note: + Passing 0 as line deletes the mark - Parameters: ~ - {buffer} Buffer to set the mark on - {name} Mark name - {line} Line number - {col} Column/row number - {opts} Optional parameters. Reserved for future use. + Parameters: ~ + {buffer} Buffer to set the mark on + {name} Mark name + {line} Line number + {col} Column/row number + {opts} Optional parameters. Reserved for future use. - Return: ~ - true if the mark was set, else false. + Return: ~ + true if the mark was set, else false. - See also: ~ - |nvim_buf_del_mark()| - |nvim_buf_get_mark()| + See also: ~ + |nvim_buf_del_mark()| + |nvim_buf_get_mark()| nvim_buf_set_name({buffer}, {name}) *nvim_buf_set_name()* - Sets the full file name for a buffer + Sets the full file name for a buffer - Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer - {name} Buffer name + Parameters: ~ + {buffer} Buffer handle, or 0 for current buffer + {name} Buffer name *nvim_buf_set_text()* nvim_buf_set_text({buffer}, {start_row}, {start_col}, {end_row}, {end_col}, {replacement}) - Sets (replaces) a range in the buffer + Sets (replaces) a range in the buffer - This is recommended over |nvim_buf_set_lines()| when only - modifying parts of a line, as extmarks will be preserved on - non-modified parts of the touched lines. + This is recommended over |nvim_buf_set_lines()| when only modifying parts + of a line, as extmarks will be preserved on non-modified parts of the + touched lines. - Indexing is zero-based. Row indices are end-inclusive, and - column indices are end-exclusive. + Indexing is zero-based. Row indices are end-inclusive, and column indices + are end-exclusive. - To insert text at a given `(row, column)` location, use - `start_row = end_row = row` and `start_col = end_col = col`. - To delete the text in a range, use `replacement = {}`. + To insert text at a given `(row, column)` location, use `start_row = + end_row = row` and `start_col = end_col = col`. To delete the text in a + range, use `replacement = {}`. - Prefer |nvim_buf_set_lines()| if you are only adding or - deleting entire lines. + Prefer |nvim_buf_set_lines()| if you are only adding or deleting entire + lines. - Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer - {start_row} First line index - {start_col} Starting column (byte offset) on first line - {end_row} Last line index, inclusive - {end_col} Ending column (byte offset) on last line, - exclusive - {replacement} Array of lines to use as replacement + Parameters: ~ + {buffer} Buffer handle, or 0 for current buffer + {start_row} First line index + {start_col} Starting column (byte offset) on first line + {end_row} Last line index, inclusive + {end_col} Ending column (byte offset) on last line, exclusive + {replacement} Array of lines to use as replacement nvim_buf_set_var({buffer}, {name}, {value}) *nvim_buf_set_var()* - Sets a buffer-scoped (b:) variable + Sets a buffer-scoped (b:) variable - Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer - {name} Variable name - {value} Variable value + Parameters: ~ + {buffer} Buffer handle, or 0 for current buffer + {name} Variable name + {value} Variable value ============================================================================== @@ -2550,107 +2419,96 @@ Extmark Functions *api-extmark* *nvim_buf_add_highlight()* nvim_buf_add_highlight({buffer}, {ns_id}, {hl_group}, {line}, {col_start}, {col_end}) - Adds a highlight to buffer. - - Useful for plugins that dynamically generate highlights to a - buffer (like a semantic highlighter or linter). The function - adds a single highlight to a buffer. Unlike |matchaddpos()| - highlights follow changes to line numbering (as lines are - inserted/removed above the highlighted line), like signs and - marks do. - - Namespaces are used for batch deletion/updating of a set of - highlights. To create a namespace, use - |nvim_create_namespace()| which returns a namespace id. Pass - it in to this function as `ns_id` to add highlights to the - namespace. All highlights in the same namespace can then be - cleared with single call to |nvim_buf_clear_namespace()|. If - the highlight never will be deleted by an API call, pass - `ns_id = -1`. - - As a shorthand, `ns_id = 0` can be used to create a new - namespace for the highlight, the allocated id is then - returned. If `hl_group` is the empty string no highlight is - added, but a new `ns_id` is still returned. This is supported - for backwards compatibility, new code should use - |nvim_create_namespace()| to create a new empty namespace. - - Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer - {ns_id} namespace to use or -1 for ungrouped - highlight - {hl_group} Name of the highlight group to use - {line} Line to highlight (zero-indexed) - {col_start} Start of (byte-indexed) column range to - highlight - {col_end} End of (byte-indexed) column range to - highlight, or -1 to highlight to end of line - - Return: ~ - The ns_id that was used + Adds a highlight to buffer. + + Useful for plugins that dynamically generate highlights to a buffer (like + a semantic highlighter or linter). The function adds a single highlight to + a buffer. Unlike |matchaddpos()| highlights follow changes to line + numbering (as lines are inserted/removed above the highlighted line), like + signs and marks do. + + Namespaces are used for batch deletion/updating of a set of highlights. To + create a namespace, use |nvim_create_namespace()| which returns a + namespace id. Pass it in to this function as `ns_id` to add highlights to + the namespace. All highlights in the same namespace can then be cleared + with single call to |nvim_buf_clear_namespace()|. If the highlight never + will be deleted by an API call, pass `ns_id = -1`. + + As a shorthand, `ns_id = 0` can be used to create a new namespace for the + highlight, the allocated id is then returned. If `hl_group` is the empty + string no highlight is added, but a new `ns_id` is still returned. This is + supported for backwards compatibility, new code should use + |nvim_create_namespace()| to create a new empty namespace. + + Parameters: ~ + {buffer} Buffer handle, or 0 for current buffer + {ns_id} namespace to use or -1 for ungrouped highlight + {hl_group} Name of the highlight group to use + {line} Line to highlight (zero-indexed) + {col_start} Start of (byte-indexed) column range to highlight + {col_end} End of (byte-indexed) column range to highlight, or -1 to + highlight to end of line + + Return: ~ + The ns_id that was used *nvim_buf_clear_namespace()* nvim_buf_clear_namespace({buffer}, {ns_id}, {line_start}, {line_end}) - Clears namespaced objects (highlights, extmarks, virtual text) - from a region. + Clears namespaced objects (highlights, extmarks, virtual text) from a + region. - Lines are 0-indexed. |api-indexing| To clear the namespace in - the entire buffer, specify line_start=0 and line_end=-1. + Lines are 0-indexed. |api-indexing| To clear the namespace in the entire + buffer, specify line_start=0 and line_end=-1. - Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer - {ns_id} Namespace to clear, or -1 to clear all - namespaces. - {line_start} Start of range of lines to clear - {line_end} End of range of lines to clear (exclusive) - or -1 to clear to end of buffer. + Parameters: ~ + {buffer} Buffer handle, or 0 for current buffer + {ns_id} Namespace to clear, or -1 to clear all namespaces. + {line_start} Start of range of lines to clear + {line_end} End of range of lines to clear (exclusive) or -1 to + clear to end of buffer. nvim_buf_del_extmark({buffer}, {ns_id}, {id}) *nvim_buf_del_extmark()* - Removes an extmark. + Removes an extmark. - Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer - {ns_id} Namespace id from |nvim_create_namespace()| - {id} Extmark id + Parameters: ~ + {buffer} Buffer handle, or 0 for current buffer + {ns_id} Namespace id from |nvim_create_namespace()| + {id} Extmark id - Return: ~ - true if the extmark was found, else false + Return: ~ + true if the extmark was found, else false *nvim_buf_get_extmark_by_id()* nvim_buf_get_extmark_by_id({buffer}, {ns_id}, {id}, {opts}) - Gets the position (0-indexed) of an extmark. + Gets the position (0-indexed) of an extmark. - Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer - {ns_id} Namespace id from |nvim_create_namespace()| - {id} Extmark id - {opts} Optional parameters. Keys: - • details: Whether to include the details dict + Parameters: ~ + {buffer} Buffer handle, or 0 for current buffer + {ns_id} Namespace id from |nvim_create_namespace()| + {id} Extmark id + {opts} Optional parameters. Keys: + • details: Whether to include the details dict - Return: ~ - 0-indexed (row, col) tuple or empty list () if extmark id - was absent + Return: ~ + 0-indexed (row, col) tuple or empty list () if extmark id was absent *nvim_buf_get_extmarks()* nvim_buf_get_extmarks({buffer}, {ns_id}, {start}, {end}, {opts}) - Gets extmarks in "traversal order" from a |charwise| region - defined by buffer positions (inclusive, 0-indexed - |api-indexing|). - - Region can be given as (row,col) tuples, or valid extmark ids - (whose positions define the bounds). 0 and -1 are understood - as (0,0) and (-1,-1) respectively, thus the following are - equivalent: + Gets extmarks in "traversal order" from a |charwise| region defined by + buffer positions (inclusive, 0-indexed |api-indexing|). + + Region can be given as (row,col) tuples, or valid extmark ids (whose + positions define the bounds). 0 and -1 are understood as (0,0) and (-1,-1) + respectively, thus the following are equivalent: > nvim_buf_get_extmarks(0, my_ns, 0, -1, {}) nvim_buf_get_extmarks(0, my_ns, [0,0], [-1,-1], {}) < - If `end` is less than `start`, traversal works backwards. - (Useful with `limit`, to get the first marks prior to a given - position.) + If `end` is less than `start`, traversal works backwards. (Useful with + `limit`, to get the first marks prior to a given position.) - Example: + Example: > local a = vim.api local pos = a.nvim_win_get_cursor(0) @@ -2666,759 +2524,694 @@ nvim_buf_get_extmarks({buffer}, {ns_id}, {start}, {end}, {opts}) print(vim.inspect(ms)) < - Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer - {ns_id} Namespace id from |nvim_create_namespace()| - {start} Start of range: a 0-indexed (row, col) or valid - extmark id (whose position defines the bound). - |api-indexing| - {end} End of range (inclusive): a 0-indexed (row, col) - or valid extmark id (whose position defines the - bound). |api-indexing| - {opts} Optional parameters. Keys: - • limit: Maximum number of marks to return - • details Whether to include the details dict - - Return: ~ - List of [extmark_id, row, col] tuples in "traversal - order". + Parameters: ~ + {buffer} Buffer handle, or 0 for current buffer + {ns_id} Namespace id from |nvim_create_namespace()| + {start} Start of range: a 0-indexed (row, col) or valid extmark id + (whose position defines the bound). |api-indexing| + {end} End of range (inclusive): a 0-indexed (row, col) or valid + extmark id (whose position defines the bound). + |api-indexing| + {opts} Optional parameters. Keys: + • limit: Maximum number of marks to return + • details Whether to include the details dict + + Return: ~ + List of [extmark_id, row, col] tuples in "traversal order". *nvim_buf_set_extmark()* nvim_buf_set_extmark({buffer}, {ns_id}, {line}, {col}, {*opts}) - Creates or updates an extmark. - - By default a new extmark is created when no id is passed in, - but it is also possible to create a new mark by passing in a - previously unused id or move an existing mark by passing in - its id. The caller must then keep track of existing and unused - ids itself. (Useful over RPC, to avoid waiting for the return - value.) - - Using the optional arguments, it is possible to use this to - highlight a range of text, and also to associate virtual text - to the mark. - - Parameters: ~ - {buffer} Buffer handle, or 0 for current buffer - {ns_id} Namespace id from |nvim_create_namespace()| - {line} Line where to place the mark, 0-based. - |api-indexing| - {col} Column where to place the mark, 0-based. - |api-indexing| - {opts} Optional parameters. - • id : id of the extmark to edit. - • end_row : ending line of the mark, 0-based - inclusive. - • end_col : ending col of the mark, 0-based - exclusive. - • hl_group : name of the highlight group used to - highlight this mark. - • hl_eol : when true, for a multiline highlight - covering the EOL of a line, continue the - highlight for the rest of the screen line - (just like for diff and cursorline highlight). - • virt_text : virtual text to link to this mark. - A list of [text, highlight] tuples, each - representing a text chunk with specified - highlight. `highlight` element can either be a - a single highlight group, or an array of - multiple highlight groups that will be stacked - (highest priority last). A highlight group can - be supplied either as a string or as an - integer, the latter which can be obtained - using |nvim_get_hl_id_by_name|. - • virt_text_pos : position of virtual text. - Possible values: - • "eol": right after eol character (default) - • "overlay": display over the specified - column, without shifting the underlying - text. - • "right_align": display right aligned in the - window. - - • virt_text_win_col : position the virtual text - at a fixed window column (starting from the - first text column) - • virt_text_hide : hide the virtual text when - the background text is selected or hidden due - to horizontal scroll 'nowrap' - • hl_mode : control how highlights are combined - with the highlights of the text. Currently - only affects virt_text highlights, but might - affect `hl_group` in later versions. - • "replace": only show the virt_text color. - This is the default - • "combine": combine with background text - color - • "blend": blend with background text color. - - • virt_lines : virtual lines to add next to this - mark This should be an array over lines, where - each line in turn is an array over [text, - highlight] tuples. In general, buffer and - window options do not affect the display of - the text. In particular 'wrap' and 'linebreak' - options do not take effect, so the number of - extra screen lines will always match the size - of the array. However the 'tabstop' buffer - option is still used for hard tabs. By default - lines are placed below the buffer line - containing the mark. - • virt_lines_above: place virtual lines above - instead. - • virt_lines_leftcol: Place extmarks in the - leftmost column of the window, bypassing sign - and number columns. - • ephemeral : for use with - |nvim_set_decoration_provider| callbacks. The - mark will only be used for the current redraw - cycle, and not be permantently stored in the - buffer. - • right_gravity : boolean that indicates the - direction the extmark will be shifted in when - new text is inserted (true for right, false - for left). defaults to true. - • end_right_gravity : boolean that indicates the - direction the extmark end position (if it - exists) will be shifted in when new text is - inserted (true for right, false for left). - Defaults to false. - • priority: a priority value for the highlight - group. For example treesitter highlighting - uses a value of 100. - • strict: boolean that indicates extmark should - not be placed if the line or column value is - past the end of the buffer or end of the line - respectively. Defaults to true. - • sign_text: string of length 1-2 used to - display in the sign column. Note: ranges are - unsupported and decorations are only applied - to start_row - • sign_hl_group: name of the highlight group - used to highlight the sign column text. Note: - ranges are unsupported and decorations are - only applied to start_row - • number_hl_group: name of the highlight group - used to highlight the number column. Note: - ranges are unsupported and decorations are - only applied to start_row - • line_hl_group: name of the highlight group - used to highlight the whole line. Note: ranges - are unsupported and decorations are only - applied to start_row - • cursorline_hl_group: name of the highlight - group used to highlight the line when the - cursor is on the same line as the mark and - 'cursorline' is enabled. Note: ranges are - unsupported and decorations are only applied - to start_row - • conceal: string which should be either empty - or a single character. Enable concealing - similar to |:syn-conceal|. When a character is - supplied it is used as |:syn-cchar|. - "hl_group" is used as highlight for the cchar - if provided, otherwise it defaults to - |hl-Conceal|. - • ui_watched: boolean that indicates the mark - should be drawn by a UI. When set, the UI will - receive win_extmark events. Note: the mark is - positioned by virt_text attributes. Can be - used together with virt_text. - - Return: ~ - Id of the created/updated extmark + Creates or updates an extmark. + + By default a new extmark is created when no id is passed in, but it is + also possible to create a new mark by passing in a previously unused id or + move an existing mark by passing in its id. The caller must then keep + track of existing and unused ids itself. (Useful over RPC, to avoid + waiting for the return value.) + + Using the optional arguments, it is possible to use this to highlight a + range of text, and also to associate virtual text to the mark. + + Parameters: ~ + {buffer} Buffer handle, or 0 for current buffer + {ns_id} Namespace id from |nvim_create_namespace()| + {line} Line where to place the mark, 0-based. |api-indexing| + {col} Column where to place the mark, 0-based. |api-indexing| + {opts} Optional parameters. + • id : id of the extmark to edit. + • end_row : ending line of the mark, 0-based inclusive. + • end_col : ending col of the mark, 0-based exclusive. + • hl_group : name of the highlight group used to highlight + this mark. + • hl_eol : when true, for a multiline highlight covering the + EOL of a line, continue the highlight for the rest of the + screen line (just like for diff and cursorline highlight). + • virt_text : virtual text to link to this mark. A list of + [text, highlight] tuples, each representing a text chunk + with specified highlight. `highlight` element can either + be a a single highlight group, or an array of multiple + highlight groups that will be stacked (highest priority + last). A highlight group can be supplied either as a + string or as an integer, the latter which can be obtained + using |nvim_get_hl_id_by_name|. + • virt_text_pos : position of virtual text. Possible values: + • "eol": right after eol character (default) + • "overlay": display over the specified column, without + shifting the underlying text. + • "right_align": display right aligned in the window. + + • virt_text_win_col : position the virtual text at a fixed + window column (starting from the first text column) + • virt_text_hide : hide the virtual text when the background + text is selected or hidden due to horizontal scroll + 'nowrap' + • hl_mode : control how highlights are combined with the + highlights of the text. Currently only affects virt_text + highlights, but might affect `hl_group` in later versions. + • "replace": only show the virt_text color. This is the + default + • "combine": combine with background text color + • "blend": blend with background text color. + + • virt_lines : virtual lines to add next to this mark This + should be an array over lines, where each line in turn is + an array over [text, highlight] tuples. In general, buffer + and window options do not affect the display of the text. + In particular 'wrap' and 'linebreak' options do not take + effect, so the number of extra screen lines will always + match the size of the array. However the 'tabstop' buffer + option is still used for hard tabs. By default lines are + placed below the buffer line containing the mark. + • virt_lines_above: place virtual lines above instead. + • virt_lines_leftcol: Place extmarks in the leftmost column + of the window, bypassing sign and number columns. + • ephemeral : for use with |nvim_set_decoration_provider| + callbacks. The mark will only be used for the current + redraw cycle, and not be permantently stored in the + buffer. + • right_gravity : boolean that indicates the direction the + extmark will be shifted in when new text is inserted (true + for right, false for left). defaults to true. + • end_right_gravity : boolean that indicates the direction + the extmark end position (if it exists) will be shifted in + when new text is inserted (true for right, false for + left). Defaults to false. + • priority: a priority value for the highlight group or sign + attribute. For example treesitter highlighting uses a + value of 100. + • strict: boolean that indicates extmark should not be + placed if the line or column value is past the end of the + buffer or end of the line respectively. Defaults to true. + • sign_text: string of length 1-2 used to display in the + sign column. Note: ranges are unsupported and decorations + are only applied to start_row + • sign_hl_group: name of the highlight group used to + highlight the sign column text. Note: ranges are + unsupported and decorations are only applied to start_row + • number_hl_group: name of the highlight group used to + highlight the number column. Note: ranges are unsupported + and decorations are only applied to start_row + • line_hl_group: name of the highlight group used to + highlight the whole line. Note: ranges are unsupported and + decorations are only applied to start_row + • cursorline_hl_group: name of the highlight group used to + highlight the line when the cursor is on the same line as + the mark and 'cursorline' is enabled. Note: ranges are + unsupported and decorations are only applied to start_row + • conceal: string which should be either empty or a single + character. Enable concealing similar to |:syn-conceal|. + When a character is supplied it is used as |:syn-cchar|. + "hl_group" is used as highlight for the cchar if provided, + otherwise it defaults to |hl-Conceal|. + • ui_watched: boolean that indicates the mark should be + drawn by a UI. When set, the UI will receive win_extmark + events. Note: the mark is positioned by virt_text + attributes. Can be used together with virt_text. + + Return: ~ + Id of the created/updated extmark nvim_create_namespace({name}) *nvim_create_namespace()* - Creates a new *namespace* or gets an existing one. + Creates a new *namespace* or gets an existing one. - Namespaces are used for buffer highlights and virtual text, - see |nvim_buf_add_highlight()| and |nvim_buf_set_extmark()|. + Namespaces are used for buffer highlights and virtual text, see + |nvim_buf_add_highlight()| and |nvim_buf_set_extmark()|. - Namespaces can be named or anonymous. If `name` matches an - existing namespace, the associated id is returned. If `name` - is an empty string a new, anonymous namespace is created. + Namespaces can be named or anonymous. If `name` matches an existing + namespace, the associated id is returned. If `name` is an empty string a + new, anonymous namespace is created. - Parameters: ~ - {name} Namespace name or empty string + Parameters: ~ + {name} Namespace name or empty string - Return: ~ - Namespace id + Return: ~ + Namespace id nvim_get_namespaces() *nvim_get_namespaces()* - Gets existing, non-anonymous namespaces. + Gets existing, non-anonymous namespaces. - Return: ~ - dict that maps from names to namespace ids. + Return: ~ + dict that maps from names to namespace ids. *nvim_set_decoration_provider()* nvim_set_decoration_provider({ns_id}, {opts}) - Set or change decoration provider for a namespace - - This is a very general purpose interface for having lua - callbacks being triggered during the redraw code. - - The expected usage is to set extmarks for the currently - redrawn buffer. |nvim_buf_set_extmark| can be called to add - marks on a per-window or per-lines basis. Use the `ephemeral` - key to only use the mark for the current screen redraw (the - callback will be called again for the next redraw ). - - Note: this function should not be called often. Rather, the - callbacks themselves can be used to throttle unneeded - callbacks. the `on_start` callback can return `false` to - disable the provider until the next redraw. Similarly, return - `false` in `on_win` will skip the `on_lines` calls for that - window (but any extmarks set in `on_win` will still be used). - A plugin managing multiple sources of decoration should - ideally only set one provider, and merge the sources - internally. You can use multiple `ns_id` for the extmarks - set/modified inside the callback anyway. - - Note: doing anything other than setting extmarks is considered - experimental. Doing things like changing options are not - expliticly forbidden, but is likely to have unexpected - consequences (such as 100% CPU consumption). doing - `vim.rpcnotify` should be OK, but `vim.rpcrequest` is quite - dubious for the moment. - - Attributes: ~ - |vim.api| only - - Parameters: ~ - {ns_id} Namespace id from |nvim_create_namespace()| - {opts} Callbacks invoked during redraw: - • on_start: called first on each screen redraw - ["start", tick] - • on_buf: called for each buffer being redrawn - (before window callbacks) ["buf", bufnr, tick] - • on_win: called when starting to redraw a - specific window. ["win", winid, bufnr, topline, - botline_guess] - • on_line: called for each buffer line being - redrawn. (The interaction with fold lines is - subject to change) ["win", winid, bufnr, row] - • on_end: called at the end of a redraw cycle - ["end", tick] + Set or change decoration provider for a namespace + + This is a very general purpose interface for having lua callbacks being + triggered during the redraw code. + + The expected usage is to set extmarks for the currently redrawn buffer. + |nvim_buf_set_extmark| can be called to add marks on a per-window or + per-lines basis. Use the `ephemeral` key to only use the mark for the + current screen redraw (the callback will be called again for the next + redraw ). + + Note: this function should not be called often. Rather, the callbacks + themselves can be used to throttle unneeded callbacks. the `on_start` + callback can return `false` to disable the provider until the next redraw. + Similarly, return `false` in `on_win` will skip the `on_lines` calls for + that window (but any extmarks set in `on_win` will still be used). A + plugin managing multiple sources of decoration should ideally only set one + provider, and merge the sources internally. You can use multiple `ns_id` + for the extmarks set/modified inside the callback anyway. + + Note: doing anything other than setting extmarks is considered + experimental. Doing things like changing options are not expliticly + forbidden, but is likely to have unexpected consequences (such as 100% CPU + consumption). doing `vim.rpcnotify` should be OK, but `vim.rpcrequest` is + quite dubious for the moment. + + Attributes: ~ + |vim.api| only + + Parameters: ~ + {ns_id} Namespace id from |nvim_create_namespace()| + {opts} Callbacks invoked during redraw: + • on_start: called first on each screen redraw ["start", + tick] + • on_buf: called for each buffer being redrawn (before window + callbacks) ["buf", bufnr, tick] + • on_win: called when starting to redraw a specific window. + ["win", winid, bufnr, topline, botline_guess] + • on_line: called for each buffer line being redrawn. (The + interaction with fold lines is subject to change) ["win", + winid, bufnr, row] + • on_end: called at the end of a redraw cycle ["end", tick] ============================================================================== Window Functions *api-window* nvim_win_call({window}, {fun}) *nvim_win_call()* - Calls a function with window as temporary current window. + Calls a function with window as temporary current window. - Attributes: ~ - |vim.api| only + Attributes: ~ + |vim.api| only - Parameters: ~ - {window} Window handle, or 0 for current window - {fun} Function to call inside the window (currently - lua callable only) + Parameters: ~ + {window} Window handle, or 0 for current window + {fun} Function to call inside the window (currently lua callable + only) - Return: ~ - Return value of function. NB: will deepcopy lua values - currently, use upvalues to send lua references in and out. + Return: ~ + Return value of function. NB: will deepcopy lua values currently, use + upvalues to send lua references in and out. - See also: ~ - |win_execute()| - |nvim_buf_call()| + See also: ~ + |win_execute()| + |nvim_buf_call()| nvim_win_close({window}, {force}) *nvim_win_close()* - Closes the window (like |:close| with a |window-ID|). + Closes the window (like |:close| with a |window-ID|). - Attributes: ~ - not allowed when |textlock| is active + Attributes: ~ + not allowed when |textlock| is active - Parameters: ~ - {window} Window handle, or 0 for current window - {force} Behave like `:close!` The last window of a - buffer with unwritten changes can be closed. The - buffer will become hidden, even if 'hidden' is - not set. + Parameters: ~ + {window} Window handle, or 0 for current window + {force} Behave like `:close!` The last window of a buffer with + unwritten changes can be closed. The buffer will become + hidden, even if 'hidden' is not set. nvim_win_del_var({window}, {name}) *nvim_win_del_var()* - Removes a window-scoped (w:) variable + Removes a window-scoped (w:) variable - Parameters: ~ - {window} Window handle, or 0 for current window - {name} Variable name + Parameters: ~ + {window} Window handle, or 0 for current window + {name} Variable name nvim_win_get_buf({window}) *nvim_win_get_buf()* - Gets the current buffer in a window + Gets the current buffer in a window - Parameters: ~ - {window} Window handle, or 0 for current window + Parameters: ~ + {window} Window handle, or 0 for current window - Return: ~ - Buffer handle + Return: ~ + Buffer handle nvim_win_get_cursor({window}) *nvim_win_get_cursor()* - Gets the (1,0)-indexed cursor position in the window. - |api-indexing| + Gets the (1,0)-indexed cursor position in the window. |api-indexing| - Parameters: ~ - {window} Window handle, or 0 for current window + Parameters: ~ + {window} Window handle, or 0 for current window - Return: ~ - (row, col) tuple + Return: ~ + (row, col) tuple nvim_win_get_height({window}) *nvim_win_get_height()* - Gets the window height + Gets the window height - Parameters: ~ - {window} Window handle, or 0 for current window + Parameters: ~ + {window} Window handle, or 0 for current window - Return: ~ - Height as a count of rows + Return: ~ + Height as a count of rows nvim_win_get_number({window}) *nvim_win_get_number()* - Gets the window number + Gets the window number - Parameters: ~ - {window} Window handle, or 0 for current window + Parameters: ~ + {window} Window handle, or 0 for current window - Return: ~ - Window number + Return: ~ + Window number nvim_win_get_position({window}) *nvim_win_get_position()* - Gets the window position in display cells. First position is - zero. + Gets the window position in display cells. First position is zero. - Parameters: ~ - {window} Window handle, or 0 for current window + Parameters: ~ + {window} Window handle, or 0 for current window - Return: ~ - (row, col) tuple with the window position + Return: ~ + (row, col) tuple with the window position nvim_win_get_tabpage({window}) *nvim_win_get_tabpage()* - Gets the window tabpage + Gets the window tabpage - Parameters: ~ - {window} Window handle, or 0 for current window + Parameters: ~ + {window} Window handle, or 0 for current window - Return: ~ - Tabpage that contains the window + Return: ~ + Tabpage that contains the window nvim_win_get_var({window}, {name}) *nvim_win_get_var()* - Gets a window-scoped (w:) variable + Gets a window-scoped (w:) variable - Parameters: ~ - {window} Window handle, or 0 for current window - {name} Variable name + Parameters: ~ + {window} Window handle, or 0 for current window + {name} Variable name - Return: ~ - Variable value + Return: ~ + Variable value nvim_win_get_width({window}) *nvim_win_get_width()* - Gets the window width + Gets the window width - Parameters: ~ - {window} Window handle, or 0 for current window + Parameters: ~ + {window} Window handle, or 0 for current window - Return: ~ - Width as a count of columns + Return: ~ + Width as a count of columns nvim_win_hide({window}) *nvim_win_hide()* - Closes the window and hide the buffer it contains (like - |:hide| with a |window-ID|). + Closes the window and hide the buffer it contains (like |:hide| with a + |window-ID|). - Like |:hide| the buffer becomes hidden unless another window - is editing it, or 'bufhidden' is `unload`, `delete` or `wipe` - as opposed to |:close| or |nvim_win_close|, which will close - the buffer. + Like |:hide| the buffer becomes hidden unless another window is editing + it, or 'bufhidden' is `unload`, `delete` or `wipe` as opposed to |:close| + or |nvim_win_close|, which will close the buffer. - Attributes: ~ - not allowed when |textlock| is active + Attributes: ~ + not allowed when |textlock| is active - Parameters: ~ - {window} Window handle, or 0 for current window + Parameters: ~ + {window} Window handle, or 0 for current window nvim_win_is_valid({window}) *nvim_win_is_valid()* - Checks if a window is valid + Checks if a window is valid - Parameters: ~ - {window} Window handle, or 0 for current window + Parameters: ~ + {window} Window handle, or 0 for current window - Return: ~ - true if the window is valid, false otherwise + Return: ~ + true if the window is valid, false otherwise nvim_win_set_buf({window}, {buffer}) *nvim_win_set_buf()* - Sets the current buffer in a window, without side effects + Sets the current buffer in a window, without side effects - Attributes: ~ - not allowed when |textlock| is active + Attributes: ~ + not allowed when |textlock| is active - Parameters: ~ - {window} Window handle, or 0 for current window - {buffer} Buffer handle + Parameters: ~ + {window} Window handle, or 0 for current window + {buffer} Buffer handle nvim_win_set_cursor({window}, {pos}) *nvim_win_set_cursor()* - Sets the (1,0)-indexed cursor position in the window. - |api-indexing| This scrolls the window even if it is not the - current one. + Sets the (1,0)-indexed cursor position in the window. |api-indexing| This + scrolls the window even if it is not the current one. - Parameters: ~ - {window} Window handle, or 0 for current window - {pos} (row, col) tuple representing the new position + Parameters: ~ + {window} Window handle, or 0 for current window + {pos} (row, col) tuple representing the new position nvim_win_set_height({window}, {height}) *nvim_win_set_height()* - Sets the window height. + Sets the window height. + + Parameters: ~ + {window} Window handle, or 0 for current window + {height} Height as a count of rows - Parameters: ~ - {window} Window handle, or 0 for current window - {height} Height as a count of rows +nvim_win_set_hl_ns({window}, {ns_id}) *nvim_win_set_hl_ns()* + Set highlight namespace for a window. This will use highlights defined in + this namespace, but fall back to global highlights (ns=0) when missing. + + This takes predecence over the 'winhighlight' option. + + Parameters: ~ + {ns_id} the namespace to use nvim_win_set_var({window}, {name}, {value}) *nvim_win_set_var()* - Sets a window-scoped (w:) variable + Sets a window-scoped (w:) variable - Parameters: ~ - {window} Window handle, or 0 for current window - {name} Variable name - {value} Variable value + Parameters: ~ + {window} Window handle, or 0 for current window + {name} Variable name + {value} Variable value nvim_win_set_width({window}, {width}) *nvim_win_set_width()* - Sets the window width. This will only succeed if the screen is - split vertically. + Sets the window width. This will only succeed if the screen is split + vertically. - Parameters: ~ - {window} Window handle, or 0 for current window - {width} Width as a count of columns + Parameters: ~ + {window} Window handle, or 0 for current window + {width} Width as a count of columns ============================================================================== Win_Config Functions *api-win_config* nvim_open_win({buffer}, {enter}, {*config}) *nvim_open_win()* - Open a new window. - - Currently this is used to open floating and external windows. - Floats are windows that are drawn above the split layout, at - some anchor position in some other window. Floats can be drawn - internally or by external GUI with the |ui-multigrid| - extension. External windows are only supported with multigrid - GUIs, and are displayed as separate top-level windows. - - For a general overview of floats, see |api-floatwin|. - - Exactly one of `external` and `relative` must be specified. - The `width` and `height` of the new window must be specified. - - With relative=editor (row=0,col=0) refers to the top-left - corner of the screen-grid and (row=Lines-1,col=Columns-1) - refers to the bottom-right corner. Fractional values are - allowed, but the builtin implementation (used by non-multigrid - UIs) will always round down to nearest integer. - - Out-of-bounds values, and configurations that make the float - not fit inside the main editor, are allowed. The builtin - implementation truncates values so floats are fully within the - main screen grid. External GUIs could let floats hover outside - of the main window like a tooltip, but this should not be used - to specify arbitrary WM screen positions. - - Example (Lua): window-relative float > - vim.api.nvim_open_win(0, false, - {relative='win', row=3, col=3, width=12, height=3}) + Open a new window. + + Currently this is used to open floating and external windows. Floats are + windows that are drawn above the split layout, at some anchor position in + some other window. Floats can be drawn internally or by external GUI with + the |ui-multigrid| extension. External windows are only supported with + multigrid GUIs, and are displayed as separate top-level windows. + + For a general overview of floats, see |api-floatwin|. + + Exactly one of `external` and `relative` must be specified. The `width` + and `height` of the new window must be specified. + + With relative=editor (row=0,col=0) refers to the top-left corner of the + screen-grid and (row=Lines-1,col=Columns-1) refers to the bottom-right + corner. Fractional values are allowed, but the builtin implementation + (used by non-multigrid UIs) will always round down to nearest integer. + + Out-of-bounds values, and configurations that make the float not fit + inside the main editor, are allowed. The builtin implementation truncates + values so floats are fully within the main screen grid. External GUIs + could let floats hover outside of the main window like a tooltip, but this + should not be used to specify arbitrary WM screen positions. + + Example (Lua): window-relative float > + vim.api.nvim_open_win(0, false, + {relative='win', row=3, col=3, width=12, height=3}) < - Example (Lua): buffer-relative float (travels as buffer is - scrolled) > - vim.api.nvim_open_win(0, false, - {relative='win', width=12, height=3, bufpos={100,10}}) + Example (Lua): buffer-relative float (travels as buffer is scrolled) > + vim.api.nvim_open_win(0, false, + {relative='win', width=12, height=3, bufpos={100,10}}) < - Attributes: ~ - not allowed when |textlock| is active - - Parameters: ~ - {buffer} Buffer to display, or 0 for current buffer - {enter} Enter the window (make it the current window) - {config} Map defining the window configuration. Keys: - • relative: Sets the window layout to - "floating", placed at (row,col) coordinates - relative to: - • "editor" The global editor grid - • "win" Window given by the `win` field, or - current window. - • "cursor" Cursor position in current window. - - • win: |window-ID| for relative="win". - • anchor: Decides which corner of the float to - place at (row,col): - • "NW" northwest (default) - • "NE" northeast - • "SW" southwest - • "SE" southeast - - • width: Window width (in character cells). - Minimum of 1. - • height: Window height (in character cells). - Minimum of 1. - • bufpos: Places float relative to buffer text - (only when relative="win"). Takes a tuple of - zero-indexed [line, column]. `row` and `col` if given are applied relative to this - position, else they default to: - • `row=1` and `col=0` if `anchor` is "NW" or - "NE" - • `row=0` and `col=0` if `anchor` is "SW" or - "SE" (thus like a tooltip near the buffer - text). - - • row: Row position in units of "screen cell - height", may be fractional. - • col: Column position in units of "screen cell - width", may be fractional. - • focusable: Enable focus by user actions - (wincmds, mouse events). Defaults to true. - Non-focusable windows can be entered by - |nvim_set_current_win()|. - • external: GUI should display the window as an - external top-level window. Currently accepts - no other positioning configuration together - with this. - • zindex: Stacking order. floats with higher `zindex` go on top on floats with lower indices. Must - be larger than zero. The following screen - elements have hard-coded z-indices: - • 100: insert completion popupmenu - • 200: message scrollback - • 250: cmdline completion popupmenu (when - wildoptions+=pum) The default value for - floats are 50. In general, values below 100 - are recommended, unless there is a good - reason to overshadow builtin elements. - - • style: Configure the appearance of the window. - Currently only takes one non-empty value: - • "minimal" Nvim will display the window with - many UI options disabled. This is useful - when displaying a temporary float where the - text should not be edited. Disables - 'number', 'relativenumber', 'cursorline', - 'cursorcolumn', 'foldcolumn', 'spell' and - 'list' options. 'signcolumn' is changed to - `auto` and 'colorcolumn' is cleared. The - end-of-buffer region is hidden by setting - `eob` flag of 'fillchars' to a space char, - and clearing the |EndOfBuffer| region in - 'winhighlight'. - - • border: Style of (optional) window border. - This can either be a string or an array. The - string values are - • "none": No border (default). - • "single": A single line box. - • "double": A double line box. - • "rounded": Like "single", but with rounded - corners ("╭" etc.). - • "solid": Adds padding by a single whitespace - cell. - • "shadow": A drop shadow effect by blending - with the background. - • If it is an array, it should have a length - of eight or any divisor of eight. The array - will specifify the eight chars building up - the border in a clockwise fashion starting - with the top-left corner. As an example, the - double box style could be specified as [ - "╔", "═" ,"╗", "║", "╝", "═", "╚", "║" ]. If - the number of chars are less than eight, - they will be repeated. Thus an ASCII border - could be specified as [ "/", "-", "\\", "|" - ], or all chars the same as [ "x" ]. An - empty string can be used to turn off a - specific border, for instance, [ "", "", "", - ">", "", "", "", "<" ] will only make - vertical borders but not horizontal ones. By - default, `FloatBorder` highlight is used, - which links to `WinSeparator` when not - defined. It could also be specified by - character: [ {"+", "MyCorner"}, {"x", - "MyBorder"} ]. - - • noautocmd: If true then no buffer-related - autocommand events such as |BufEnter|, - |BufLeave| or |BufWinEnter| may fire from - calling this function. - - Return: ~ - Window handle, or 0 on error + Attributes: ~ + not allowed when |textlock| is active + + Parameters: ~ + {buffer} Buffer to display, or 0 for current buffer + {enter} Enter the window (make it the current window) + {config} Map defining the window configuration. Keys: + • relative: Sets the window layout to "floating", placed at + (row,col) coordinates relative to: + • "editor" The global editor grid + • "win" Window given by the `win` field, or current + window. + • "cursor" Cursor position in current window. + + • win: |window-ID| for relative="win". + • anchor: Decides which corner of the float to place at + (row,col): + • "NW" northwest (default) + • "NE" northeast + • "SW" southwest + • "SE" southeast + + • width: Window width (in character cells). Minimum of 1. + • height: Window height (in character cells). Minimum of 1. + • bufpos: Places float relative to buffer text (only when + relative="win"). Takes a tuple of zero-indexed [line, + column]. `row` and `col` if given are applied relative to this position, else they + default to: + • `row=1` and `col=0` if `anchor` is "NW" or "NE" + • `row=0` and `col=0` if `anchor` is "SW" or "SE" (thus + like a tooltip near the buffer text). + + • row: Row position in units of "screen cell height", may be + fractional. + • col: Column position in units of "screen cell width", may + be fractional. + • focusable: Enable focus by user actions (wincmds, mouse + events). Defaults to true. Non-focusable windows can be + entered by |nvim_set_current_win()|. + • external: GUI should display the window as an external + top-level window. Currently accepts no other positioning + configuration together with this. + • zindex: Stacking order. floats with higher `zindex` go on top on floats with lower indices. Must be larger + than zero. The following screen elements have hard-coded + z-indices: + • 100: insert completion popupmenu + • 200: message scrollback + • 250: cmdline completion popupmenu (when + wildoptions+=pum) The default value for floats are 50. + In general, values below 100 are recommended, unless + there is a good reason to overshadow builtin elements. + + • style: Configure the appearance of the window. Currently + only takes one non-empty value: + • "minimal" Nvim will display the window with many UI + options disabled. This is useful when displaying a + temporary float where the text should not be edited. + Disables 'number', 'relativenumber', 'cursorline', + 'cursorcolumn', 'foldcolumn', 'spell' and 'list' + options. 'signcolumn' is changed to `auto` and + 'colorcolumn' is cleared. The end-of-buffer region is + hidden by setting `eob` flag of 'fillchars' to a space + char, and clearing the |EndOfBuffer| region in + 'winhighlight'. + + • border: Style of (optional) window border. This can either + be a string or an array. The string values are + • "none": No border (default). + • "single": A single line box. + • "double": A double line box. + • "rounded": Like "single", but with rounded corners ("╭" + etc.). + • "solid": Adds padding by a single whitespace cell. + • "shadow": A drop shadow effect by blending with the + background. + • If it is an array, it should have a length of eight or + any divisor of eight. The array will specifify the eight + chars building up the border in a clockwise fashion + starting with the top-left corner. As an example, the + double box style could be specified as [ "╔", "═" ,"╗", + "║", "╝", "═", "╚", "║" ]. If the number of chars are + less than eight, they will be repeated. Thus an ASCII + border could be specified as [ "/", "-", "\\", "|" ], or + all chars the same as [ "x" ]. An empty string can be + used to turn off a specific border, for instance, [ "", + "", "", ">", "", "", "", "<" ] will only make vertical + borders but not horizontal ones. By default, + `FloatBorder` highlight is used, which links to + `WinSeparator` when not defined. It could also be + specified by character: [ {"+", "MyCorner"}, {"x", + "MyBorder"} ]. + + • noautocmd: If true then no buffer-related autocommand + events such as |BufEnter|, |BufLeave| or |BufWinEnter| may + fire from calling this function. + + Return: ~ + Window handle, or 0 on error nvim_win_get_config({window}) *nvim_win_get_config()* - Gets window configuration. + Gets window configuration. - The returned value may be given to |nvim_open_win()|. + The returned value may be given to |nvim_open_win()|. - `relative` is empty for normal windows. + `relative` is empty for normal windows. - Parameters: ~ - {window} Window handle, or 0 for current window + Parameters: ~ + {window} Window handle, or 0 for current window - Return: ~ - Map defining the window configuration, see - |nvim_open_win()| + Return: ~ + Map defining the window configuration, see |nvim_open_win()| nvim_win_set_config({window}, {*config}) *nvim_win_set_config()* - Configures window layout. Currently only for floating and - external windows (including changing a split window to those - layouts). + Configures window layout. Currently only for floating and external windows + (including changing a split window to those layouts). - When reconfiguring a floating window, absent option keys will - not be changed. `row`/`col` and `relative` must be - reconfigured together. + When reconfiguring a floating window, absent option keys will not be + changed. `row`/`col` and `relative` must be reconfigured together. - Parameters: ~ - {window} Window handle, or 0 for current window - {config} Map defining the window configuration, see - |nvim_open_win()| + Parameters: ~ + {window} Window handle, or 0 for current window + {config} Map defining the window configuration, see |nvim_open_win()| - See also: ~ - |nvim_open_win()| + See also: ~ + |nvim_open_win()| ============================================================================== Tabpage Functions *api-tabpage* nvim_tabpage_del_var({tabpage}, {name}) *nvim_tabpage_del_var()* - Removes a tab-scoped (t:) variable + Removes a tab-scoped (t:) variable - Parameters: ~ - {tabpage} Tabpage handle, or 0 for current tabpage - {name} Variable name + Parameters: ~ + {tabpage} Tabpage handle, or 0 for current tabpage + {name} Variable name nvim_tabpage_get_number({tabpage}) *nvim_tabpage_get_number()* - Gets the tabpage number + Gets the tabpage number - Parameters: ~ - {tabpage} Tabpage handle, or 0 for current tabpage + Parameters: ~ + {tabpage} Tabpage handle, or 0 for current tabpage - Return: ~ - Tabpage number + Return: ~ + Tabpage number nvim_tabpage_get_var({tabpage}, {name}) *nvim_tabpage_get_var()* - Gets a tab-scoped (t:) variable + Gets a tab-scoped (t:) variable - Parameters: ~ - {tabpage} Tabpage handle, or 0 for current tabpage - {name} Variable name + Parameters: ~ + {tabpage} Tabpage handle, or 0 for current tabpage + {name} Variable name - Return: ~ - Variable value + Return: ~ + Variable value nvim_tabpage_get_win({tabpage}) *nvim_tabpage_get_win()* - Gets the current window in a tabpage + Gets the current window in a tabpage - Parameters: ~ - {tabpage} Tabpage handle, or 0 for current tabpage + Parameters: ~ + {tabpage} Tabpage handle, or 0 for current tabpage - Return: ~ - Window handle + Return: ~ + Window handle nvim_tabpage_is_valid({tabpage}) *nvim_tabpage_is_valid()* - Checks if a tabpage is valid + Checks if a tabpage is valid - Parameters: ~ - {tabpage} Tabpage handle, or 0 for current tabpage + Parameters: ~ + {tabpage} Tabpage handle, or 0 for current tabpage - Return: ~ - true if the tabpage is valid, false otherwise + Return: ~ + true if the tabpage is valid, false otherwise nvim_tabpage_list_wins({tabpage}) *nvim_tabpage_list_wins()* - Gets the windows in a tabpage + Gets the windows in a tabpage - Parameters: ~ - {tabpage} Tabpage handle, or 0 for current tabpage + Parameters: ~ + {tabpage} Tabpage handle, or 0 for current tabpage - Return: ~ - List of windows in `tabpage` + Return: ~ + List of windows in `tabpage` *nvim_tabpage_set_var()* nvim_tabpage_set_var({tabpage}, {name}, {value}) - Sets a tab-scoped (t:) variable + Sets a tab-scoped (t:) variable - Parameters: ~ - {tabpage} Tabpage handle, or 0 for current tabpage - {name} Variable name - {value} Variable value + Parameters: ~ + {tabpage} Tabpage handle, or 0 for current tabpage + {name} Variable name + {value} Variable value ============================================================================== Autocmd Functions *api-autocmd* nvim_clear_autocmds({*opts}) *nvim_clear_autocmds()* - Clear all autocommands that match the corresponding {opts}. To - delete a particular autocmd, see |nvim_del_autocmd|. + Clear all autocommands that match the corresponding {opts}. To delete a + particular autocmd, see |nvim_del_autocmd|. - Parameters: ~ - {opts} Parameters - • event: (string|table) Examples: - • event: "pat1" - • event: { "pat1" } - • event: { "pat1", "pat2", "pat3" } + Parameters: ~ + {opts} Parameters + • event: (string|table) Examples: + • event: "pat1" + • event: { "pat1" } + • event: { "pat1", "pat2", "pat3" } - • pattern: (string|table) - • pattern or patterns to match exactly. - • For example, if you have `*.py` as that - pattern for the autocmd, you must pass - `*.py` exactly to clear it. `test.py` will - not match the pattern. + • pattern: (string|table) + • pattern or patterns to match exactly. + • For example, if you have `*.py` as that pattern for the + autocmd, you must pass `*.py` exactly to clear it. + `test.py` will not match the pattern. - • defaults to clearing all patterns. - • NOTE: Cannot be used with {buffer} + • defaults to clearing all patterns. + • NOTE: Cannot be used with {buffer} - • buffer: (bufnr) - • clear only |autocmd-buflocal| autocommands. - • NOTE: Cannot be used with {pattern} + • buffer: (bufnr) + • clear only |autocmd-buflocal| autocommands. + • NOTE: Cannot be used with {pattern} - • group: (string|int) The augroup name or id. - • NOTE: If not passed, will only delete autocmds not in any group. + • group: (string|int) The augroup name or id. + • NOTE: If not passed, will only delete autocmds not in any group. nvim_create_augroup({name}, {*opts}) *nvim_create_augroup()* - Create or get an autocommand group |autocmd-groups|. + Create or get an autocommand group |autocmd-groups|. - To get an existing group id, do: > - local id = vim.api.nvim_create_augroup("MyGroup", { - clear = false - }) + To get an existing group id, do: > + local id = vim.api.nvim_create_augroup("MyGroup", { + clear = false + }) < - Parameters: ~ - {name} String: The name of the group - {opts} Dictionary Parameters - • clear (bool) optional: defaults to true. Clear - existing commands if the group already exists - |autocmd-groups|. + Parameters: ~ + {name} String: The name of the group + {opts} Dictionary Parameters + • clear (bool) optional: defaults to true. Clear existing + commands if the group already exists |autocmd-groups|. - Return: ~ - Integer id of the created group. + Return: ~ + Integer id of the created group. - See also: ~ - |autocmd-groups| + See also: ~ + |autocmd-groups| nvim_create_autocmd({event}, {*opts}) *nvim_create_autocmd()* - Create an |autocommand| + Create an |autocommand| - The API allows for two (mutually exclusive) types of actions - to be executed when the autocommand triggers: a callback - function (Lua or Vimscript), or a command (like regular - autocommands). + The API allows for two (mutually exclusive) types of actions to be + executed when the autocommand triggers: a callback function (Lua or + Vimscript), or a command (like regular autocommands). - Example using callback: > - -- Lua function - local myluafun = function() print("This buffer enters") end + Example using callback: > + -- Lua function + local myluafun = function() print("This buffer enters") end - -- Vimscript function name (as a string) - local myvimfun = "g:MyVimFunction" + -- Vimscript function name (as a string) + local myvimfun = "g:MyVimFunction" - vim.api.nvim_create_autocmd({"BufEnter", "BufWinEnter"}, { - pattern = {"*.c", "*.h"}, - callback = myluafun, -- Or myvimfun - }) + vim.api.nvim_create_autocmd({"BufEnter", "BufWinEnter"}, { + pattern = {"*.c", "*.h"}, + callback = myluafun, -- Or myvimfun + }) < - Lua functions receive a table with information about the - autocmd event as an argument. To use a function which itself - accepts another (optional) parameter, wrap the function in a - lambda: + Lua functions receive a table with information about the autocmd event as + an argument. To use a function which itself accepts another (optional) + parameter, wrap the function in a lambda: > -- Lua function with an optional parameter. -- The autocmd callback would pass a table as argument but this @@ -3431,282 +3224,263 @@ nvim_create_autocmd({event}, {*opts}) *nvim_create_autocmd()* }) < - Example using command: > - vim.api.nvim_create_autocmd({"BufEnter", "BufWinEnter"}, { - pattern = {"*.c", "*.h"}, - command = "echo 'Entering a C or C++ file'", - }) + Example using command: > + vim.api.nvim_create_autocmd({"BufEnter", "BufWinEnter"}, { + pattern = {"*.c", "*.h"}, + command = "echo 'Entering a C or C++ file'", + }) < - Example values for pattern: > - pattern = "*.py" - pattern = { "*.py", "*.pyi" } + Example values for pattern: > + pattern = "*.py" + pattern = { "*.py", "*.pyi" } < - Example values for event: > - "BufWritePre" - {"CursorHold", "BufWritePre", "BufWritePost"} + Example values for event: > + "BufWritePre" + {"CursorHold", "BufWritePre", "BufWritePost"} < - Parameters: ~ - {event} (string|array) The event or events to register - this autocommand - {opts} Dictionary of autocommand options: - • group (string|integer) optional: the - autocommand group name or id to match against. - • pattern (string|array) optional: pattern or - patterns to match against |autocmd-pattern|. - • buffer (integer) optional: buffer number for - buffer local autocommands |autocmd-buflocal|. - Cannot be used with {pattern}. - • desc (string) optional: description of the - autocommand. - • callback (function|string) optional: if a - string, the name of a Vimscript function to - call when this autocommand is triggered. - Otherwise, a Lua function which is called when - this autocommand is triggered. Cannot be used - with {command}. Lua callbacks can return true - to delete the autocommand; in addition, they - accept a single table argument with the - following keys: - • id: (number) the autocommand id - • event: (string) the name of the event that - triggered the autocommand |autocmd-events| - • group: (number|nil) the autocommand group id, - if it exists - • match: (string) the expanded value of - |<amatch>| - • buf: (number) the expanded value of |<abuf>| - • file: (string) the expanded value of - |<afile>| - • data: (any) arbitrary data passed to - |nvim_exec_autocmds()| - - • command (string) optional: Vim command to - execute on event. Cannot be used with - {callback} - • once (boolean) optional: defaults to false. Run - the autocommand only once |autocmd-once|. - • nested (boolean) optional: defaults to false. - Run nested autocommands |autocmd-nested|. - - Return: ~ - Integer id of the created autocommand. - - See also: ~ - |autocommand| - |nvim_del_autocmd()| + Parameters: ~ + {event} (string|array) The event or events to register this + autocommand + {opts} Dictionary of autocommand options: + • group (string|integer) optional: the autocommand group name + or id to match against. + • pattern (string|array) optional: pattern or patterns to + match against |autocmd-pattern|. + • buffer (integer) optional: buffer number for buffer local + autocommands |autocmd-buflocal|. Cannot be used with + {pattern}. + • desc (string) optional: description of the autocommand. + • callback (function|string) optional: if a string, the name + of a Vimscript function to call when this autocommand is + triggered. Otherwise, a Lua function which is called when + this autocommand is triggered. Cannot be used with + {command}. Lua callbacks can return true to delete the + autocommand; in addition, they accept a single table + argument with the following keys: + • id: (number) the autocommand id + • event: (string) the name of the event that triggered the + autocommand |autocmd-events| + • group: (number|nil) the autocommand group id, if it + exists + • match: (string) the expanded value of |<amatch>| + • buf: (number) the expanded value of |<abuf>| + • file: (string) the expanded value of |<afile>| + • data: (any) arbitrary data passed to + |nvim_exec_autocmds()| + + • command (string) optional: Vim command to execute on event. + Cannot be used with {callback} + • once (boolean) optional: defaults to false. Run the + autocommand only once |autocmd-once|. + • nested (boolean) optional: defaults to false. Run nested + autocommands |autocmd-nested|. + + Return: ~ + Integer id of the created autocommand. + + See also: ~ + |autocommand| + |nvim_del_autocmd()| nvim_del_augroup_by_id({id}) *nvim_del_augroup_by_id()* - Delete an autocommand group by id. + Delete an autocommand group by id. - To get a group id one can use |nvim_get_autocmds()|. + To get a group id one can use |nvim_get_autocmds()|. - NOTE: behavior differs from |augroup-delete|. When deleting a - group, autocommands contained in this group will also be - deleted and cleared. This group will no longer exist. + NOTE: behavior differs from |augroup-delete|. When deleting a group, + autocommands contained in this group will also be deleted and cleared. + This group will no longer exist. - Parameters: ~ - {id} Integer The id of the group. + Parameters: ~ + {id} Integer The id of the group. - See also: ~ - |nvim_del_augroup_by_name()| - |nvim_create_augroup()| + See also: ~ + |nvim_del_augroup_by_name()| + |nvim_create_augroup()| nvim_del_augroup_by_name({name}) *nvim_del_augroup_by_name()* - Delete an autocommand group by name. + Delete an autocommand group by name. - NOTE: behavior differs from |augroup-delete|. When deleting a - group, autocommands contained in this group will also be - deleted and cleared. This group will no longer exist. + NOTE: behavior differs from |augroup-delete|. When deleting a group, + autocommands contained in this group will also be deleted and cleared. + This group will no longer exist. - Parameters: ~ - {name} String The name of the group. + Parameters: ~ + {name} String The name of the group. - See also: ~ - |autocommand-groups| + See also: ~ + |autocommand-groups| nvim_del_autocmd({id}) *nvim_del_autocmd()* - Delete an autocommand by id. + Delete an autocommand by id. - NOTE: Only autocommands created via the API have an id. + NOTE: Only autocommands created via the API have an id. - Parameters: ~ - {id} Integer The id returned by nvim_create_autocmd + Parameters: ~ + {id} Integer The id returned by nvim_create_autocmd - See also: ~ - |nvim_create_autocmd()| + See also: ~ + |nvim_create_autocmd()| nvim_exec_autocmds({event}, {*opts}) *nvim_exec_autocmds()* - Execute all autocommands for {event} that match the - corresponding {opts} |autocmd-execute|. - - Parameters: ~ - {event} (String|Array) The event or events to execute - {opts} Dictionary of autocommand options: - • group (string|integer) optional: the - autocommand group name or id to match against. - |autocmd-groups|. - • pattern (string|array) optional: defaults to - "*" |autocmd-pattern|. Cannot be used with - {buffer}. - • buffer (integer) optional: buffer number - |autocmd-buflocal|. Cannot be used with - {pattern}. - • modeline (bool) optional: defaults to true. - Process the modeline after the autocommands - |<nomodeline>|. - • data (any): arbitrary data to send to the - autocommand callback. See - |nvim_create_autocmd()| for details. - - See also: ~ - |:doautocmd| + Execute all autocommands for {event} that match the corresponding {opts} + |autocmd-execute|. + + Parameters: ~ + {event} (String|Array) The event or events to execute + {opts} Dictionary of autocommand options: + • group (string|integer) optional: the autocommand group name + or id to match against. |autocmd-groups|. + • pattern (string|array) optional: defaults to "*" + |autocmd-pattern|. Cannot be used with {buffer}. + • buffer (integer) optional: buffer number + |autocmd-buflocal|. Cannot be used with {pattern}. + • modeline (bool) optional: defaults to true. Process the + modeline after the autocommands |<nomodeline>|. + • data (any): arbitrary data to send to the autocommand + callback. See |nvim_create_autocmd()| for details. + + See also: ~ + |:doautocmd| nvim_get_autocmds({*opts}) *nvim_get_autocmds()* - Get all autocommands that match the corresponding {opts}. - - These examples will get autocommands matching ALL the given - criteria: > - -- Matches all criteria - autocommands = vim.api.nvim_get_autocmds({ - group = "MyGroup", - event = {"BufEnter", "BufWinEnter"}, - pattern = {"*.c", "*.h"} - }) - - -- All commands from one group - autocommands = vim.api.nvim_get_autocmds({ - group = "MyGroup", - }) + Get all autocommands that match the corresponding {opts}. + + These examples will get autocommands matching ALL the given criteria: > + -- Matches all criteria + autocommands = vim.api.nvim_get_autocmds({ + group = "MyGroup", + event = {"BufEnter", "BufWinEnter"}, + pattern = {"*.c", "*.h"} + }) + + -- All commands from one group + autocommands = vim.api.nvim_get_autocmds({ + group = "MyGroup", + }) < - NOTE: When multiple patterns or events are provided, it will - find all the autocommands that match any combination of them. - - Parameters: ~ - {opts} Dictionary with at least one of the following: - • group (string|integer): the autocommand group - name or id to match against. - • event (string|array): event or events to match - against |autocmd-events|. - • pattern (string|array): pattern or patterns to - match against |autocmd-pattern|. - - Return: ~ - Array of autocommands matching the criteria, with each - item containing the following fields: - • id (number): the autocommand id (only when defined with - the API). - • group (integer): the autocommand group id. - • group_name (string): the autocommand group name. - • desc (string): the autocommand description. - • event (string): the autocommand event. - • command (string): the autocommand command. Note: this - will be empty if a callback is set. - • callback (function|string|nil): Lua function or name of - a Vim script function which is executed when this - autocommand is triggered. - • once (boolean): whether the autocommand is only run - once. - • pattern (string): the autocommand pattern. If the - autocommand is buffer local |autocmd-buffer-local|: - • buflocal (boolean): true if the autocommand is buffer - local. - • buffer (number): the buffer number. + NOTE: When multiple patterns or events are provided, it will find all the + autocommands that match any combination of them. + + Parameters: ~ + {opts} Dictionary with at least one of the following: + • group (string|integer): the autocommand group name or id to + match against. + • event (string|array): event or events to match against + |autocmd-events|. + • pattern (string|array): pattern or patterns to match against + |autocmd-pattern|. + + Return: ~ + Array of autocommands matching the criteria, with each item containing + the following fields: + • id (number): the autocommand id (only when defined with the API). + • group (integer): the autocommand group id. + • group_name (string): the autocommand group name. + • desc (string): the autocommand description. + • event (string): the autocommand event. + • command (string): the autocommand command. Note: this will be empty + if a callback is set. + • callback (function|string|nil): Lua function or name of a Vim script + function which is executed when this autocommand is triggered. + • once (boolean): whether the autocommand is only run once. + • pattern (string): the autocommand pattern. If the autocommand is + buffer local |autocmd-buffer-local|: + • buflocal (boolean): true if the autocommand is buffer local. + • buffer (number): the buffer number. ============================================================================== UI Functions *api-ui* nvim_ui_attach({width}, {height}, {options}) *nvim_ui_attach()* - Activates UI events on the channel. + Activates UI events on the channel. - Entry point of all UI clients. Allows |--embed| to continue - startup. Implies that the client is ready to show the UI. Adds - the client to the list of UIs. |nvim_list_uis()| + Entry point of all UI clients. Allows |--embed| to continue startup. + Implies that the client is ready to show the UI. Adds the client to the + list of UIs. |nvim_list_uis()| - Note: - If multiple UI clients are attached, the global screen - dimensions degrade to the smallest client. E.g. if client - A requests 80x40 but client B requests 200x100, the global - screen has size 80x40. + Note: + If multiple UI clients are attached, the global screen dimensions + degrade to the smallest client. E.g. if client A requests 80x40 but + client B requests 200x100, the global screen has size 80x40. - Attributes: ~ - |RPC| only + Attributes: ~ + |RPC| only - Parameters: ~ - {width} Requested screen columns - {height} Requested screen rows - {options} |ui-option| map + Parameters: ~ + {width} Requested screen columns + {height} Requested screen rows + {options} |ui-option| map nvim_ui_detach() *nvim_ui_detach()* - Deactivates UI events on the channel. + Deactivates UI events on the channel. - Removes the client from the list of UIs. |nvim_list_uis()| + Removes the client from the list of UIs. |nvim_list_uis()| - Attributes: ~ - |RPC| only + Attributes: ~ + |RPC| only *nvim_ui_pum_set_bounds()* nvim_ui_pum_set_bounds({width}, {height}, {row}, {col}) - Tells Nvim the geometry of the popumenu, to align floating - windows with an external popup menu. - - Note that this method is not to be confused with - |nvim_ui_pum_set_height()|, which sets the number of visible - items in the popup menu, while this function sets the bounding - box of the popup menu, including visual elements such as - borders and sliders. Floats need not use the same font size, - nor be anchored to exact grid corners, so one can set - floating-point numbers to the popup menu geometry. - - Attributes: ~ - |RPC| only - - Parameters: ~ - {width} Popupmenu width. - {height} Popupmenu height. - {row} Popupmenu row. - {col} Popupmenu height. + Tells Nvim the geometry of the popumenu, to align floating windows with an + external popup menu. + + Note that this method is not to be confused with + |nvim_ui_pum_set_height()|, which sets the number of visible items in the + popup menu, while this function sets the bounding box of the popup menu, + including visual elements such as borders and sliders. Floats need not use + the same font size, nor be anchored to exact grid corners, so one can set + floating-point numbers to the popup menu geometry. + + Attributes: ~ + |RPC| only + + Parameters: ~ + {width} Popupmenu width. + {height} Popupmenu height. + {row} Popupmenu row. + {col} Popupmenu height. nvim_ui_pum_set_height({height}) *nvim_ui_pum_set_height()* - Tells Nvim the number of elements displaying in the popumenu, - to decide <PageUp> and <PageDown> movement. + Tells Nvim the number of elements displaying in the popumenu, to decide + <PageUp> and <PageDown> movement. - Attributes: ~ - |RPC| only + Attributes: ~ + |RPC| only - Parameters: ~ - {height} Popupmenu height, must be greater than zero. + Parameters: ~ + {height} Popupmenu height, must be greater than zero. nvim_ui_set_option({name}, {value}) *nvim_ui_set_option()* - TODO: Documentation + TODO: Documentation - Attributes: ~ - |RPC| only + Attributes: ~ + |RPC| only nvim_ui_try_resize({width}, {height}) *nvim_ui_try_resize()* - TODO: Documentation + TODO: Documentation - Attributes: ~ - |RPC| only + Attributes: ~ + |RPC| only *nvim_ui_try_resize_grid()* nvim_ui_try_resize_grid({grid}, {width}, {height}) - Tell Nvim to resize a grid. Triggers a grid_resize event with - the requested grid size or the maximum size if it exceeds size - limits. + Tell Nvim to resize a grid. Triggers a grid_resize event with the + requested grid size or the maximum size if it exceeds size limits. - On invalid grid handle, fails with error. + On invalid grid handle, fails with error. - Attributes: ~ - |RPC| only + Attributes: ~ + |RPC| only - Parameters: ~ - {grid} The handle of the grid to be changed. - {width} The new requested width. - {height} The new requested height. + Parameters: ~ + {grid} The handle of the grid to be changed. + {width} The new requested width. + {height} The new requested height. - vim:tw=78:ts=8:ft=help:norl: + vim:tw=78:ts=8:sw=4:sts=4:et:ft=help:norl: diff --git a/runtime/doc/autocmd.txt b/runtime/doc/autocmd.txt index 59e5c078a3..63226fe701 100644 --- a/runtime/doc/autocmd.txt +++ b/runtime/doc/autocmd.txt @@ -441,8 +441,8 @@ CompleteChanged *CompleteChanged* Non-recursive (event cannot trigger itself). Cannot change the text. |textlock| - The size and position of the popup are also - available by calling |pum_getpos()|. + The size and position of the popup are also + available by calling |pum_getpos()|. *CompleteDonePre* CompleteDonePre After Insert mode completion is done. Either diff --git a/runtime/doc/builtin.txt b/runtime/doc/builtin.txt index c56ab70774..0fc8a30c20 100644 --- a/runtime/doc/builtin.txt +++ b/runtime/doc/builtin.txt @@ -77,6 +77,7 @@ changenr() Number current change number chanclose({id} [, {stream}]) Number Closes a channel or one of its streams chansend({id}, {data}) Number Writes {data} to channel char2nr({expr} [, {utf8}]) Number ASCII/UTF-8 value of first char in {expr} +charclass({string}) Number character class of {string} charcol({expr}) Number column number of cursor or mark charidx({string}, {idx} [, {countcc}]) Number char index of byte {idx} in {string} @@ -119,7 +120,7 @@ dictwatcherdel({dict}, {pattern}, {callback}) did_filetype() Number |TRUE| if FileType autocommand event used diff_filler({lnum}) Number diff filler lines about {lnum} diff_hlID({lnum}, {col}) Number diff highlighting at {lnum}/{col} -digraph_get({chars}) String get the digraph of {chars} +digraph_get({chars}) String get the |digraph| of {chars} digraph_getlist([{listall}]) List get all |digraph|s digraph_set({chars}, {digraph}) Boolean register |digraph| digraph_setlist({digraphlist}) Boolean register multiple |digraph|s @@ -239,8 +240,8 @@ haslocaldir([{winnr} [, {tabnr}]]) the tab executed |:tcd| hasmapto({what} [, {mode} [, {abbr}]]) Number |TRUE| if mapping to {what} exists -histadd({history}, {item}) String add an item to a history -histdel({history} [, {item}]) String remove an item from a history +histadd({history}, {item}) Number add an item to a history +histdel({history} [, {item}]) Number remove an item from a history histget({history} [, {index}]) String get the item {index} from a history histnr({history}) Number highest index of a history hlID({name}) Number syntax ID of highlight group {name} @@ -396,6 +397,7 @@ setbufline({expr}, {lnum}, {text}) Number set line {lnum} to {text} in buffer {expr} setbufvar({buf}, {varname}, {val}) set {varname} in buffer {buf} to {val} +setcellwidths({list}) none set character cell width overrides setcharpos({expr}, {list}) Number set the {expr} position to {list} setcharsearch({dict}) Dict set character search from {dict} setcmdpos({pos}) Number set cursor position in command-line @@ -586,7 +588,7 @@ acos({expr}) *acos()* {expr} must evaluate to a |Float| or a |Number| in the range [-1, 1]. Returns NaN if {expr} is outside the range [-1, 1]. Returns - 0.0 if {expr} is not a |Float| or a |Number|. + 0.0 if {expr} is not a |Float| or a |Number|. Examples: > :echo acos(0) < 1.570796 > @@ -1063,7 +1065,19 @@ char2nr({string} [, {utf8}]) *char2nr()* Can also be used as a |method|: > GetChar()->char2nr() -< + +charclass({string}) *charclass()* + Return the character class of the first character in {string}. + The character class is one of: + 0 blank + 1 punctuation + 2 word character + 3 emoji + other specific Unicode class + The class is used in patterns and word motions. + Returns 0 if {string} is not a |String|. + + *charcol()* charcol({expr}) Same as |col()| but returns the character index of the column position given with {expr} instead of the byte position. @@ -1135,8 +1149,8 @@ cindent({lnum}) *cindent()* GetLnum()->cindent() clearmatches([{win}]) *clearmatches()* - Clears all matches previously defined for the current window - by |matchadd()| and the |:match| commands. + Clears all matches previously defined for the current window + by |matchadd()| and the |:match| commands. If {win} is specified, use the window with this number or window ID instead of the current window. @@ -1988,6 +2002,7 @@ expand({string} [, {nosuf} [, {list}]]) *expand()* <afile> autocmd file name <abuf> autocmd buffer number (as a String!) <amatch> autocmd matched name + <cexpr> C expression under the cursor <sfile> sourced script file or function name <slnum> sourced script line number or function line number @@ -1995,6 +2010,7 @@ expand({string} [, {nosuf} [, {list}]]) *expand()* a function <SID> "<SNR>123_" where "123" is the current script ID |<SID>| + <stack> call stack <cword> word under the cursor <cWORD> WORD under the cursor <client> the {clientid} of the last received @@ -2980,10 +2996,10 @@ getcurpos([{winid}]) current value of the buffer if it is not the current window. If {winid} is invalid a list with zeroes is returned. - This can be used to save and restore the cursor position: > - let save_cursor = getcurpos() - MoveTheCursorAround - call setpos('.', save_cursor) + This can be used to save and restore the cursor position: > + let save_cursor = getcurpos() + MoveTheCursorAround + call setpos('.', save_cursor) < Note that this only works within the window. See |winrestview()| for restoring more state. @@ -3118,7 +3134,7 @@ getjumplist([{winnr} [, {tabnr}]]) *getjumplist()* {winnr} can also be a |window-ID|. With {winnr} and {tabnr} use the window in the specified tab page. If {winnr} or {tabnr} is invalid, an empty list is - returned. + returned. The returned list contains two entries: a list with the jump locations and the last used jump position number in the list. @@ -3505,7 +3521,7 @@ gettabwinvar({tabnr}, {winnr}, {varname} [, {def}]) *gettabwinvar()* Get the value of window-local variable {varname} in window {winnr} in tab page {tabnr}. The {varname} argument is a string. When {varname} is empty a - dictionary with all window-local variables is returned. + dictionary with all window-local variables is returned. When {varname} is equal to "&" get the values of all window-local options in a |Dictionary|. Otherwise, when {varname} starts with "&" get the value of a @@ -4727,9 +4743,9 @@ maparg({name} [, {mode} [, {abbr} [, {dict}]]]) *maparg()* listing. When there is no mapping for {name}, an empty String is - returned if {dict} is FALSE, otherwise returns an empty Dict. - When the mapping for {name} is empty, then "<Nop>" is - returned. + returned if {dict} is FALSE, otherwise returns an empty Dict. + When the mapping for {name} is empty, then "<Nop>" is + returned. The {name} can have special key names, like in the ":map" command. @@ -5903,7 +5919,7 @@ pum_getpos() *pum_getpos()* size total nr of items scrollbar |TRUE| if scrollbar is visible - The values are the same as in |v:event| during |CompleteChanged|. + The values are the same as in |v:event| during |CompleteChanged|. pumvisible() *pumvisible()* Returns non-zero when the popup menu is visible, zero @@ -6653,7 +6669,7 @@ searchpair({start}, {middle}, {end} [, {flags} [, {skip} When {skip} is omitted or empty, every match is accepted. When evaluating {skip} causes an error the search is aborted and -1 returned. - {skip} can be a string, a lambda, a funcref or a partial. + {skip} can be a string, a lambda, a funcref or a partial. Anything else makes the function fail. For {stopline} and {timeout} see |search()|. @@ -6817,6 +6833,33 @@ setbufvar({buf}, {varname}, {val}) *setbufvar()* third argument: > GetValue()->setbufvar(buf, varname) + +setcellwidths({list}) *setcellwidths()* + Specify overrides for cell widths of character ranges. This + tells Vim how wide characters are, counted in screen cells. + This overrides 'ambiwidth'. Example: > + setcellwidths([[0xad, 0xad, 1], + \ [0x2194, 0x2199, 2]]) + +< *E1109* *E1110* *E1111* *E1112* *E1113* *E1114* + The {list} argument is a list of lists with each three + numbers. These three numbers are [low, high, width]. "low" + and "high" can be the same, in which case this refers to one + character. Otherwise it is the range of characters from "low" + to "high" (inclusive). "width" is either 1 or 2, indicating + the character width in screen cells. + An error is given if the argument is invalid, also when a + range overlaps with another. + Only characters with value 0x100 and higher can be used. + + If the new value causes 'fillchars' or 'listchars' to become + invalid it is rejected and an error is given. + + To clear the overrides pass an empty list: > + setcellwidths([]); +< You can use the script $VIMRUNTIME/tools/emoji_list.vim to see + the effect for known emoji characters. + setcharpos({expr}, {list}) *setcharpos()* Same as |setpos()| but uses the specified column number as the character index instead of the byte index in the line. @@ -7665,15 +7708,15 @@ stdpath({what}) *stdpath()* *E6100* str2float({string} [, {quoted}]) *str2float()* - Convert String {string} to a Float. This mostly works the - same as when using a floating point number in an expression, - see |floating-point-format|. But it's a bit more permissive. - E.g., "1e40" is accepted, while in an expression you need to - write "1.0e40". The hexadecimal form "0x123" is also - accepted, but not others, like binary or octal. - When {quoted} is present and non-zero then embedded single - quotes before the dot are ignored, thus "1'000.0" is a - thousand. + Convert String {string} to a Float. This mostly works the + same as when using a floating point number in an expression, + see |floating-point-format|. But it's a bit more permissive. + E.g., "1e40" is accepted, while in an expression you need to + write "1.0e40". The hexadecimal form "0x123" is also + accepted, but not others, like binary or octal. + When {quoted} is present and non-zero then embedded single + quotes before the dot are ignored, thus "1'000.0" is a + thousand. Text after the number is silently ignored. The decimal point is always '.', no matter what the locale is set to. A comma ends the number: "12,345.67" is converted to diff --git a/runtime/doc/cmdline.txt b/runtime/doc/cmdline.txt index 5d82f5985b..29eff75bfa 100644 --- a/runtime/doc/cmdline.txt +++ b/runtime/doc/cmdline.txt @@ -875,16 +875,22 @@ Note: these are typed literally, they are not special keys! match with (for FileType, Syntax and SpellFileMissing events). When the match is with a file name, it is expanded to the - full path. + full path. *:<sfile>* *<sfile>* <sfile> When executing a `:source` command, is replaced with the file name of the sourced file. *E498* - When executing a function, is replaced with: - "function {function-name}[{lnum}]" - function call nesting is indicated like this: - "function {function-name1}[{lnum}]..{function-name2}[{lnum}]" + When executing a function, is replaced with the call stack, + as with <stack> (this is for backwards compatibility, using + <stack> is preferred). Note that filename-modifiers are useless when <sfile> is - used inside a function. + not used inside a script. + *:<stack>* *<stack>* + <stack> is replaced with the call stack, using + "function {function-name}[{lnum}]" for a function line + and "script {file-name}[{lnum}]" for a script line, and + ".." in between items. E.g.: + "function {function-name1}[{lnum}]..{function-name2}[{lnum}]" + If there is no call stack you get error *E489* . *:<slnum>* *<slnum>* <slnum> When executing a `:source` command, is replaced with the line number. *E842* diff --git a/runtime/doc/diagnostic.txt b/runtime/doc/diagnostic.txt index 7fb10f2a66..e1b52746be 100644 --- a/runtime/doc/diagnostic.txt +++ b/runtime/doc/diagnostic.txt @@ -38,60 +38,60 @@ optionally supplied). A good rule of thumb is that if a method is meant to modify the diagnostics for a buffer (e.g. |vim.diagnostic.set()|) then it requires a namespace. - *diagnostic-structure* + *diagnostic-structure* A diagnostic is a Lua table with the following keys. Required keys are indicated with (*): - bufnr: Buffer number - lnum(*): The starting line of the diagnostic - end_lnum: The final line of the diagnostic - col(*): The starting column of the diagnostic - end_col: The final column of the diagnostic - severity: The severity of the diagnostic |vim.diagnostic.severity| - message(*): The diagnostic text - source: The source of the diagnostic - code: The diagnostic code - user_data: Arbitrary data plugins or users can add + bufnr: Buffer number + lnum(*): The starting line of the diagnostic + end_lnum: The final line of the diagnostic + col(*): The starting column of the diagnostic + end_col: The final column of the diagnostic + severity: The severity of the diagnostic |vim.diagnostic.severity| + message(*): The diagnostic text + source: The source of the diagnostic + code: The diagnostic code + user_data: Arbitrary data plugins or users can add Diagnostics use the same indexing as the rest of the Nvim API (i.e. 0-based rows and columns). |api-indexing| - *vim.diagnostic.severity* *diagnostic-severity* + *vim.diagnostic.severity* *diagnostic-severity* The "severity" key in a diagnostic is one of the values defined in `vim.diagnostic.severity`: - vim.diagnostic.severity.ERROR - vim.diagnostic.severity.WARN - vim.diagnostic.severity.INFO - vim.diagnostic.severity.HINT + vim.diagnostic.severity.ERROR + vim.diagnostic.severity.WARN + vim.diagnostic.severity.INFO + vim.diagnostic.severity.HINT Functions that take a severity as an optional parameter (e.g. |vim.diagnostic.get()|) accept one of two forms: 1. A single |vim.diagnostic.severity| value: > - vim.diagnostic.get(0, { severity = vim.diagnostic.severity.WARN }) + vim.diagnostic.get(0, { severity = vim.diagnostic.severity.WARN }) 2. A table with a "min" or "max" key (or both): > - vim.diagnostic.get(0, { severity = { min = vim.diagnostic.severity.WARN } }) + vim.diagnostic.get(0, { severity = { min = vim.diagnostic.severity.WARN } }) The latter form allows users to specify a range of severities. ============================================================================== -HANDLERS *diagnostic-handlers* +HANDLERS *diagnostic-handlers* Diagnostics are shown to the user with |vim.diagnostic.show()|. The display of diagnostics is managed through handlers. A handler is a table with a "show" and (optionally) a "hide" function. The "show" function has the signature > - function(namespace, bufnr, diagnostics, opts) + function(namespace, bufnr, diagnostics, opts) < and is responsible for displaying or otherwise handling the given diagnostics. The "hide" function takes care of "cleaning up" any actions taken by the "show" function and has the signature > - function(namespace, bufnr) + function(namespace, bufnr) < Handlers can be configured with |vim.diagnostic.config()| and added by creating a new key in `vim.diagnostic.handlers` (see @@ -105,31 +105,31 @@ function for a config option, the function has already been evaluated). Nvim provides these handlers by default: "virtual_text", "signs", and "underline". - *diagnostic-handlers-example* + *diagnostic-handlers-example* The example below creates a new handler that notifies the user of diagnostics with |vim.notify()|: > - -- It's good practice to namespace custom handlers to avoid collisions - vim.diagnostic.handlers["my/notify"] = { - show = function(namespace, bufnr, diagnostics, opts) - -- In our example, the opts table has a "log_level" option - local level = opts["my/notify"].log_level - - local name = vim.diagnostic.get_namespace(namespace).name - local msg = string.format("%d diagnostics in buffer %d from %s", - #diagnostics, - bufnr, - name) - vim.notify(msg, level) - end, - } - - -- Users can configure the handler - vim.diagnostic.config({ - ["my/notify"] = { - log_level = vim.log.levels.INFO - } - }) + -- It's good practice to namespace custom handlers to avoid collisions + vim.diagnostic.handlers["my/notify"] = { + show = function(namespace, bufnr, diagnostics, opts) + -- In our example, the opts table has a "log_level" option + local level = opts["my/notify"].log_level + + local name = vim.diagnostic.get_namespace(namespace).name + local msg = string.format("%d diagnostics in buffer %d from %s", + #diagnostics, + bufnr, + name) + vim.notify(msg, level) + end, + } + + -- Users can configure the handler + vim.diagnostic.config({ + ["my/notify"] = { + log_level = vim.log.levels.INFO + } + }) < In this example, there is nothing to do when diagnostics are hidden, so we omit the "hide" function. @@ -137,43 +137,43 @@ omit the "hide" function. Existing handlers can be overridden. For example, use the following to only show a sign for the highest severity diagnostic on a given line: > - -- Create a custom namespace. This will aggregate signs from all other - -- namespaces and only show the one with the highest severity on a - -- given line - local ns = vim.api.nvim_create_namespace("my_namespace") - - -- Get a reference to the original signs handler - local orig_signs_handler = vim.diagnostic.handlers.signs - - -- Override the built-in signs handler - vim.diagnostic.handlers.signs = { - show = function(_, bufnr, _, opts) - -- Get all diagnostics from the whole buffer rather than just the - -- diagnostics passed to the handler - local diagnostics = vim.diagnostic.get(bufnr) - - -- Find the "worst" diagnostic per line - local max_severity_per_line = {} - for _, d in pairs(diagnostics) do - local m = max_severity_per_line[d.lnum] - if not m or d.severity < m.severity then - max_severity_per_line[d.lnum] = d - end - end - - -- Pass the filtered diagnostics (with our custom namespace) to - -- the original handler - local filtered_diagnostics = vim.tbl_values(max_severity_per_line) - orig_signs_handler.show(ns, bufnr, filtered_diagnostics, opts) - end, - hide = function(_, bufnr) - orig_signs_handler.hide(ns, bufnr) - end, - } + -- Create a custom namespace. This will aggregate signs from all other + -- namespaces and only show the one with the highest severity on a + -- given line + local ns = vim.api.nvim_create_namespace("my_namespace") + + -- Get a reference to the original signs handler + local orig_signs_handler = vim.diagnostic.handlers.signs + + -- Override the built-in signs handler + vim.diagnostic.handlers.signs = { + show = function(_, bufnr, _, opts) + -- Get all diagnostics from the whole buffer rather than just the + -- diagnostics passed to the handler + local diagnostics = vim.diagnostic.get(bufnr) + + -- Find the "worst" diagnostic per line + local max_severity_per_line = {} + for _, d in pairs(diagnostics) do + local m = max_severity_per_line[d.lnum] + if not m or d.severity < m.severity then + max_severity_per_line[d.lnum] = d + end + end + + -- Pass the filtered diagnostics (with our custom namespace) to + -- the original handler + local filtered_diagnostics = vim.tbl_values(max_severity_per_line) + orig_signs_handler.show(ns, bufnr, filtered_diagnostics, opts) + end, + hide = function(_, bufnr) + orig_signs_handler.hide(ns, bufnr) + end, + } < ============================================================================== -HIGHLIGHTS *diagnostic-highlights* +HIGHLIGHTS *diagnostic-highlights* All highlights defined for diagnostics begin with `Diagnostic` followed by the type of highlight (e.g., `Sign`, `Underline`, etc.) and the severity (e.g. @@ -189,102 +189,102 @@ highlights), use the |:highlight| command: > highlight DiagnosticError guifg="BrightRed" < - *hl-DiagnosticError* + *hl-DiagnosticError* DiagnosticError - Used as the base highlight group. - Other Diagnostic highlights link to this by default (except Underline) + Used as the base highlight group. + Other Diagnostic highlights link to this by default (except Underline) - *hl-DiagnosticWarn* + *hl-DiagnosticWarn* DiagnosticWarn - Used as the base highlight group. - Other Diagnostic highlights link to this by default (except Underline) + Used as the base highlight group. + Other Diagnostic highlights link to this by default (except Underline) - *hl-DiagnosticInfo* + *hl-DiagnosticInfo* DiagnosticInfo - Used as the base highlight group. - Other Diagnostic highlights link to this by default (except Underline) + Used as the base highlight group. + Other Diagnostic highlights link to this by default (except Underline) - *hl-DiagnosticHint* + *hl-DiagnosticHint* DiagnosticHint - Used as the base highlight group. - Other Diagnostic highlights link to this by default (except Underline) + Used as the base highlight group. + Other Diagnostic highlights link to this by default (except Underline) - *hl-DiagnosticVirtualTextError* + *hl-DiagnosticVirtualTextError* DiagnosticVirtualTextError - Used for "Error" diagnostic virtual text. + Used for "Error" diagnostic virtual text. - *hl-DiagnosticVirtualTextWarn* + *hl-DiagnosticVirtualTextWarn* DiagnosticVirtualTextWarn - Used for "Warn" diagnostic virtual text. + Used for "Warn" diagnostic virtual text. - *hl-DiagnosticVirtualTextInfo* + *hl-DiagnosticVirtualTextInfo* DiagnosticVirtualTextInfo - Used for "Info" diagnostic virtual text. + Used for "Info" diagnostic virtual text. - *hl-DiagnosticVirtualTextHint* + *hl-DiagnosticVirtualTextHint* DiagnosticVirtualTextHint - Used for "Hint" diagnostic virtual text. + Used for "Hint" diagnostic virtual text. - *hl-DiagnosticUnderlineError* + *hl-DiagnosticUnderlineError* DiagnosticUnderlineError - Used to underline "Error" diagnostics. + Used to underline "Error" diagnostics. - *hl-DiagnosticUnderlineWarn* + *hl-DiagnosticUnderlineWarn* DiagnosticUnderlineWarn - Used to underline "Warn" diagnostics. + Used to underline "Warn" diagnostics. - *hl-DiagnosticUnderlineInfo* + *hl-DiagnosticUnderlineInfo* DiagnosticUnderlineInfo - Used to underline "Info" diagnostics. + Used to underline "Info" diagnostics. - *hl-DiagnosticUnderlineHint* + *hl-DiagnosticUnderlineHint* DiagnosticUnderlineHint - Used to underline "Hint" diagnostics. + Used to underline "Hint" diagnostics. - *hl-DiagnosticFloatingError* + *hl-DiagnosticFloatingError* DiagnosticFloatingError - Used to color "Error" diagnostic messages in diagnostics float. - See |vim.diagnostic.open_float()| + Used to color "Error" diagnostic messages in diagnostics float. + See |vim.diagnostic.open_float()| - *hl-DiagnosticFloatingWarn* + *hl-DiagnosticFloatingWarn* DiagnosticFloatingWarn - Used to color "Warn" diagnostic messages in diagnostics float. + Used to color "Warn" diagnostic messages in diagnostics float. - *hl-DiagnosticFloatingInfo* + *hl-DiagnosticFloatingInfo* DiagnosticFloatingInfo - Used to color "Info" diagnostic messages in diagnostics float. + Used to color "Info" diagnostic messages in diagnostics float. - *hl-DiagnosticFloatingHint* + *hl-DiagnosticFloatingHint* DiagnosticFloatingHint - Used to color "Hint" diagnostic messages in diagnostics float. + Used to color "Hint" diagnostic messages in diagnostics float. - *hl-DiagnosticSignError* + *hl-DiagnosticSignError* DiagnosticSignError - Used for "Error" signs in sign column. + Used for "Error" signs in sign column. - *hl-DiagnosticSignWarn* + *hl-DiagnosticSignWarn* DiagnosticSignWarn - Used for "Warn" signs in sign column. + Used for "Warn" signs in sign column. - *hl-DiagnosticSignInfo* + *hl-DiagnosticSignInfo* DiagnosticSignInfo - Used for "Info" signs in sign column. + Used for "Info" signs in sign column. - *hl-DiagnosticSignHint* + *hl-DiagnosticSignHint* DiagnosticSignHint - Used for "Hint" signs in sign column. + Used for "Hint" signs in sign column. ============================================================================== -SIGNS *diagnostic-signs* +SIGNS *diagnostic-signs* Signs are defined for each diagnostic severity. The default text for each sign is the first letter of the severity name (for example, "E" for ERROR). Signs can be customized using the following: > - sign define DiagnosticSignError text=E texthl=DiagnosticSignError linehl= numhl= - sign define DiagnosticSignWarn text=W texthl=DiagnosticSignWarn linehl= numhl= - sign define DiagnosticSignInfo text=I texthl=DiagnosticSignInfo linehl= numhl= - sign define DiagnosticSignHint text=H texthl=DiagnosticSignHint linehl= numhl= + sign define DiagnosticSignError text=E texthl=DiagnosticSignError linehl= numhl= + sign define DiagnosticSignWarn text=W texthl=DiagnosticSignWarn linehl= numhl= + sign define DiagnosticSignInfo text=I texthl=DiagnosticSignInfo linehl= numhl= + sign define DiagnosticSignHint text=H texthl=DiagnosticSignHint linehl= numhl= When the "severity_sort" option is set (see |vim.diagnostic.config()|) the priority of each sign depends on the severity of the associated diagnostic. @@ -292,459 +292,407 @@ Otherwise, all signs have the same priority (the value of the "priority" option in the "signs" table of |vim.diagnostic.config()| or 10 if unset). ============================================================================== -EVENTS *diagnostic-events* +EVENTS *diagnostic-events* - *DiagnosticChanged* -DiagnosticChanged After diagnostics have changed. + *DiagnosticChanged* +DiagnosticChanged After diagnostics have changed. Example: > - autocmd DiagnosticChanged * lua vim.diagnostic.setqflist({ open = false }) + autocmd DiagnosticChanged * lua vim.diagnostic.setqflist({ open = false }) < ============================================================================== Lua module: vim.diagnostic *diagnostic-api* config({opts}, {namespace}) *vim.diagnostic.config()* - Configure diagnostic options globally or for a specific - diagnostic namespace. + Configure diagnostic options globally or for a specific diagnostic + namespace. - Configuration can be specified globally, per-namespace, or - ephemerally (i.e. only for a single call to - |vim.diagnostic.set()| or |vim.diagnostic.show()|). Ephemeral - configuration has highest priority, followed by namespace - configuration, and finally global configuration. + Configuration can be specified globally, per-namespace, or ephemerally + (i.e. only for a single call to |vim.diagnostic.set()| or + |vim.diagnostic.show()|). Ephemeral configuration has highest priority, + followed by namespace configuration, and finally global configuration. - For example, if a user enables virtual text globally with > + For example, if a user enables virtual text globally with > - vim.diagnostic.config({ virtual_text = true }) + vim.diagnostic.config({ virtual_text = true }) < - and a diagnostic producer sets diagnostics with > + and a diagnostic producer sets diagnostics with > - vim.diagnostic.set(ns, 0, diagnostics, { virtual_text = false }) + vim.diagnostic.set(ns, 0, diagnostics, { virtual_text = false }) < - then virtual text will not be enabled for those diagnostics. - - Note: - Each of the configuration options below accepts one of the - following: - • `false`: Disable this feature - • `true`: Enable this feature, use default settings. - • `table`: Enable this feature with overrides. Use an - empty table to use default values. - • `function`: Function with signature (namespace, bufnr) - that returns any of the above. - - Parameters: ~ - {opts} (table|nil) When omitted or "nil", retrieve - the current configuration. Otherwise, a - configuration table with the following keys: - • underline: (default true) Use underline for - diagnostics. Options: - • severity: Only underline diagnostics - matching the given severity - |diagnostic-severity| - - • virtual_text: (default true) Use virtual - text for diagnostics. If multiple - diagnostics are set for a namespace, one - prefix per diagnostic + the last diagnostic - message are shown. Options: - • severity: Only show virtual text for - diagnostics matching the given severity - |diagnostic-severity| - • source: (boolean or string) Include the - diagnostic source in virtual text. Use - "if_many" to only show sources if there - is more than one diagnostic source in the - buffer. Otherwise, any truthy value means - to always show the diagnostic source. - • spacing: (number) Amount of empty spaces - inserted at the beginning of the virtual - text. - • prefix: (string) Prepend diagnostic - message with prefix. - • format: (function) A function that takes - a diagnostic as input and returns a - string. The return value is the text used - to display the diagnostic. Example: > - - function(diagnostic) - if diagnostic.severity == vim.diagnostic.severity.ERROR then - return string.format("E: %s", diagnostic.message) - end - return diagnostic.message - end + then virtual text will not be enabled for those diagnostics. + + Note: + Each of the configuration options below accepts one of the following: + • `false`: Disable this feature + • `true`: Enable this feature, use default settings. + • `table`: Enable this feature with overrides. Use an empty table to + use default values. + • `function`: Function with signature (namespace, bufnr) that returns + any of the above. + + Parameters: ~ + {opts} (table|nil) When omitted or "nil", retrieve the current + configuration. Otherwise, a configuration table with the + following keys: + • underline: (default true) Use underline for + diagnostics. Options: + • severity: Only underline diagnostics matching the + given severity |diagnostic-severity| + + • virtual_text: (default true) Use virtual text for + diagnostics. If multiple diagnostics are set for a + namespace, one prefix per diagnostic + the last + diagnostic message are shown. Options: + • severity: Only show virtual text for diagnostics + matching the given severity |diagnostic-severity| + • source: (boolean or string) Include the diagnostic + source in virtual text. Use "if_many" to only show + sources if there is more than one diagnostic source + in the buffer. Otherwise, any truthy value means to + always show the diagnostic source. + • spacing: (number) Amount of empty spaces inserted at + the beginning of the virtual text. + • prefix: (string) Prepend diagnostic message with + prefix. + • format: (function) A function that takes a diagnostic + as input and returns a string. The return value is + the text used to display the diagnostic. Example: > + + function(diagnostic) + if diagnostic.severity == vim.diagnostic.severity.ERROR then + return string.format("E: %s", diagnostic.message) + end + return diagnostic.message + end < - • signs: (default true) Use signs for - diagnostics. Options: - • severity: Only show signs for diagnostics - matching the given severity - |diagnostic-severity| - • priority: (number, default 10) Base - priority to use for signs. When - {severity_sort} is used, the priority of - a sign is adjusted based on its severity. - Otherwise, all signs use the same - priority. - - • float: Options for floating windows. See - |vim.diagnostic.open_float()|. - • update_in_insert: (default false) Update - diagnostics in Insert mode (if false, - diagnostics are updated on InsertLeave) - • severity_sort: (default false) Sort - diagnostics by severity. This affects the - order in which signs and virtual text are - displayed. When true, higher severities are - displayed before lower severities (e.g. - ERROR is displayed before WARN). Options: - • reverse: (boolean) Reverse sort order - {namespace} (number|nil) Update the options for the given - namespace. When omitted, update the global - diagnostic options. + • signs: (default true) Use signs for diagnostics. + Options: + • severity: Only show signs for diagnostics matching + the given severity |diagnostic-severity| + • priority: (number, default 10) Base priority to use + for signs. When {severity_sort} is used, the priority + of a sign is adjusted based on its severity. + Otherwise, all signs use the same priority. + + • float: Options for floating windows. See + |vim.diagnostic.open_float()|. + • update_in_insert: (default false) Update diagnostics in + Insert mode (if false, diagnostics are updated on + InsertLeave) + • severity_sort: (default false) Sort diagnostics by + severity. This affects the order in which signs and + virtual text are displayed. When true, higher + severities are displayed before lower severities (e.g. + ERROR is displayed before WARN). Options: + • reverse: (boolean) Reverse sort order + {namespace} (number|nil) Update the options for the given namespace. + When omitted, update the global diagnostic options. disable({bufnr}, {namespace}) *vim.diagnostic.disable()* - Disable diagnostics in the given buffer. + Disable diagnostics in the given buffer. - Parameters: ~ - {bufnr} (number|nil) Buffer number, or 0 for current - buffer. When omitted, disable diagnostics in - all buffers. - {namespace} (number|nil) Only disable diagnostics for the - given namespace. + Parameters: ~ + {bufnr} (number|nil) Buffer number, or 0 for current buffer. When + omitted, disable diagnostics in all buffers. + {namespace} (number|nil) Only disable diagnostics for the given + namespace. enable({bufnr}, {namespace}) *vim.diagnostic.enable()* - Enable diagnostics in the given buffer. + Enable diagnostics in the given buffer. - Parameters: ~ - {bufnr} (number|nil) Buffer number, or 0 for current - buffer. When omitted, enable diagnostics in - all buffers. - {namespace} (number|nil) Only enable diagnostics for the - given namespace. + Parameters: ~ + {bufnr} (number|nil) Buffer number, or 0 for current buffer. When + omitted, enable diagnostics in all buffers. + {namespace} (number|nil) Only enable diagnostics for the given + namespace. fromqflist({list}) *vim.diagnostic.fromqflist()* - Convert a list of quickfix items to a list of diagnostics. + Convert a list of quickfix items to a list of diagnostics. - Parameters: ~ - {list} (table) A list of quickfix items from - |getqflist()| or |getloclist()|. + Parameters: ~ + {list} (table) A list of quickfix items from |getqflist()| or + |getloclist()|. - Return: ~ - array of diagnostics |diagnostic-structure| + Return: ~ + array of diagnostics |diagnostic-structure| get({bufnr}, {opts}) *vim.diagnostic.get()* - Get current diagnostics. - - Parameters: ~ - {bufnr} (number|nil) Buffer number to get diagnostics - from. Use 0 for current buffer or nil for all - buffers. - {opts} (table|nil) A table with the following keys: - • namespace: (number) Limit diagnostics to the - given namespace. - • lnum: (number) Limit diagnostics to the given - line number. - • severity: See |diagnostic-severity|. - - Return: ~ - (table) A list of diagnostic items |diagnostic-structure|. + Get current diagnostics. + + Parameters: ~ + {bufnr} (number|nil) Buffer number to get diagnostics from. Use 0 for + current buffer or nil for all buffers. + {opts} (table|nil) A table with the following keys: + • namespace: (number) Limit diagnostics to the given + namespace. + • lnum: (number) Limit diagnostics to the given line number. + • severity: See |diagnostic-severity|. + + Return: ~ + (table) A list of diagnostic items |diagnostic-structure|. get_namespace({namespace}) *vim.diagnostic.get_namespace()* - Get namespace metadata. + Get namespace metadata. - Parameters: ~ - {namespace} (number) Diagnostic namespace + Parameters: ~ + {namespace} (number) Diagnostic namespace - Return: ~ - (table) Namespace metadata + Return: ~ + (table) Namespace metadata get_namespaces() *vim.diagnostic.get_namespaces()* - Get current diagnostic namespaces. + Get current diagnostic namespaces. - Return: ~ - (table) A list of active diagnostic namespaces - |vim.diagnostic|. + Return: ~ + (table) A list of active diagnostic namespaces |vim.diagnostic|. get_next({opts}) *vim.diagnostic.get_next()* - Get the next diagnostic closest to the cursor position. + Get the next diagnostic closest to the cursor position. - Parameters: ~ - {opts} (table) See |vim.diagnostic.goto_next()| + Parameters: ~ + {opts} (table) See |vim.diagnostic.goto_next()| - Return: ~ - (table) Next diagnostic + Return: ~ + (table) Next diagnostic get_next_pos({opts}) *vim.diagnostic.get_next_pos()* - Return the position of the next diagnostic in the current - buffer. + Return the position of the next diagnostic in the current buffer. - Parameters: ~ - {opts} (table) See |vim.diagnostic.goto_next()| + Parameters: ~ + {opts} (table) See |vim.diagnostic.goto_next()| - Return: ~ - (table) Next diagnostic position as a (row, col) tuple. + Return: ~ + (table) Next diagnostic position as a (row, col) tuple. get_prev({opts}) *vim.diagnostic.get_prev()* - Get the previous diagnostic closest to the cursor position. + Get the previous diagnostic closest to the cursor position. - Parameters: ~ - {opts} (table) See |vim.diagnostic.goto_next()| + Parameters: ~ + {opts} (table) See |vim.diagnostic.goto_next()| - Return: ~ - (table) Previous diagnostic + Return: ~ + (table) Previous diagnostic get_prev_pos({opts}) *vim.diagnostic.get_prev_pos()* - Return the position of the previous diagnostic in the current - buffer. + Return the position of the previous diagnostic in the current buffer. - Parameters: ~ - {opts} (table) See |vim.diagnostic.goto_next()| + Parameters: ~ + {opts} (table) See |vim.diagnostic.goto_next()| - Return: ~ - (table) Previous diagnostic position as a (row, col) - tuple. + Return: ~ + (table) Previous diagnostic position as a (row, col) tuple. goto_next({opts}) *vim.diagnostic.goto_next()* - Move to the next diagnostic. - - Parameters: ~ - {opts} (table|nil) Configuration table with the following - keys: - • namespace: (number) Only consider diagnostics - from the given namespace. - • cursor_position: (cursor position) Cursor - position as a (row, col) tuple. See - |nvim_win_get_cursor()|. Defaults to the current - cursor position. - • wrap: (boolean, default true) Whether to loop - around file or not. Similar to 'wrapscan'. - • severity: See |diagnostic-severity|. - • float: (boolean or table, default true) If - "true", call |vim.diagnostic.open_float()| after - moving. If a table, pass the table as the {opts} - parameter to |vim.diagnostic.open_float()|. - Unless overridden, the float will show - diagnostics at the new cursor position (as if - "cursor" were passed to the "scope" option). - • win_id: (number, default 0) Window ID + Move to the next diagnostic. + + Parameters: ~ + {opts} (table|nil) Configuration table with the following keys: + • namespace: (number) Only consider diagnostics from the given + namespace. + • cursor_position: (cursor position) Cursor position as a + (row, col) tuple. See |nvim_win_get_cursor()|. Defaults to + the current cursor position. + • wrap: (boolean, default true) Whether to loop around file or + not. Similar to 'wrapscan'. + • severity: See |diagnostic-severity|. + • float: (boolean or table, default true) If "true", call + |vim.diagnostic.open_float()| after moving. If a table, pass + the table as the {opts} parameter to + |vim.diagnostic.open_float()|. Unless overridden, the float + will show diagnostics at the new cursor position (as if + "cursor" were passed to the "scope" option). + • win_id: (number, default 0) Window ID goto_prev({opts}) *vim.diagnostic.goto_prev()* - Move to the previous diagnostic in the current buffer. + Move to the previous diagnostic in the current buffer. - Parameters: ~ - {opts} (table) See |vim.diagnostic.goto_next()| + Parameters: ~ + {opts} (table) See |vim.diagnostic.goto_next()| hide({namespace}, {bufnr}) *vim.diagnostic.hide()* - Hide currently displayed diagnostics. + Hide currently displayed diagnostics. - This only clears the decorations displayed in the buffer. - Diagnostics can be redisplayed with |vim.diagnostic.show()|. - To completely remove diagnostics, use - |vim.diagnostic.reset()|. + This only clears the decorations displayed in the buffer. Diagnostics can + be redisplayed with |vim.diagnostic.show()|. To completely remove + diagnostics, use |vim.diagnostic.reset()|. - To hide diagnostics and prevent them from re-displaying, use - |vim.diagnostic.disable()|. + To hide diagnostics and prevent them from re-displaying, use + |vim.diagnostic.disable()|. - Parameters: ~ - {namespace} (number|nil) Diagnostic namespace. When - omitted, hide diagnostics from all - namespaces. - {bufnr} (number|nil) Buffer number, or 0 for current - buffer. When omitted, hide diagnostics in all - buffers. + Parameters: ~ + {namespace} (number|nil) Diagnostic namespace. When omitted, hide + diagnostics from all namespaces. + {bufnr} (number|nil) Buffer number, or 0 for current buffer. When + omitted, hide diagnostics in all buffers. *vim.diagnostic.match()* match({str}, {pat}, {groups}, {severity_map}, {defaults}) - Parse a diagnostic from a string. + Parse a diagnostic from a string. - For example, consider a line of output from a linter: > + For example, consider a line of output from a linter: > - WARNING filename:27:3: Variable 'foo' does not exist + WARNING filename:27:3: Variable 'foo' does not exist < - This can be parsed into a diagnostic |diagnostic-structure| - with: > + This can be parsed into a diagnostic |diagnostic-structure| with: > - local s = "WARNING filename:27:3: Variable 'foo' does not exist" - local pattern = "^(%w+) %w+:(%d+):(%d+): (.+)$" - local groups = { "severity", "lnum", "col", "message" } - vim.diagnostic.match(s, pattern, groups, { WARNING = vim.diagnostic.WARN }) + local s = "WARNING filename:27:3: Variable 'foo' does not exist" + local pattern = "^(%w+) %w+:(%d+):(%d+): (.+)$" + local groups = { "severity", "lnum", "col", "message" } + vim.diagnostic.match(s, pattern, groups, { WARNING = vim.diagnostic.WARN }) < - Parameters: ~ - {str} (string) String to parse diagnostics from. - {pat} (string) Lua pattern with capture groups. - {groups} (table) List of fields in a - |diagnostic-structure| to associate with - captures from {pat}. - {severity_map} (table) A table mapping the severity field - from {groups} with an item from - |vim.diagnostic.severity|. - {defaults} (table|nil) Table of default values for - any fields not listed in {groups}. When - omitted, numeric values default to 0 and - "severity" defaults to ERROR. - - Return: ~ - diagnostic |diagnostic-structure| or `nil` if {pat} fails - to match {str}. + Parameters: ~ + {str} (string) String to parse diagnostics from. + {pat} (string) Lua pattern with capture groups. + {groups} (table) List of fields in a |diagnostic-structure| to + associate with captures from {pat}. + {severity_map} (table) A table mapping the severity field from + {groups} with an item from |vim.diagnostic.severity|. + {defaults} (table|nil) Table of default values for any fields not + listed in {groups}. When omitted, numeric values + default to 0 and "severity" defaults to ERROR. + + Return: ~ + diagnostic |diagnostic-structure| or `nil` if {pat} fails to match + {str}. open_float({opts}, {...}) *vim.diagnostic.open_float()* - Show diagnostics in a floating window. - - Parameters: ~ - {opts} (table|nil) Configuration table with the same keys - as |vim.lsp.util.open_floating_preview()| in - addition to the following: - • bufnr: (number) Buffer number to show - diagnostics from. Defaults to the current - buffer. - • namespace: (number) Limit diagnostics to the - given namespace - • scope: (string, default "line") Show diagnostics - from the whole buffer ("buffer"), the current - cursor line ("line"), or the current cursor - position ("cursor"). Shorthand versions are also - accepted ("c" for "cursor", "l" for "line", "b" - for "buffer"). - • pos: (number or table) If {scope} is "line" or - "cursor", use this position rather than the - cursor position. If a number, interpreted as a - line number; otherwise, a (row, col) tuple. - • severity_sort: (default false) Sort diagnostics - by severity. Overrides the setting from - |vim.diagnostic.config()|. - • severity: See |diagnostic-severity|. Overrides - the setting from |vim.diagnostic.config()|. - • header: (string or table) String to use as the - header for the floating window. If a table, it - is interpreted as a [text, hl_group] tuple. - Overrides the setting from - |vim.diagnostic.config()|. - • source: (boolean or string) Include the - diagnostic source in the message. Use "if_many" - to only show sources if there is more than one - source of diagnostics in the buffer. Otherwise, - any truthy value means to always show the - diagnostic source. Overrides the setting from - |vim.diagnostic.config()|. - • format: (function) A function that takes a - diagnostic as input and returns a string. The - return value is the text used to display the - diagnostic. Overrides the setting from - |vim.diagnostic.config()|. - • prefix: (function, string, or table) Prefix each - diagnostic in the floating window. If a - function, it must have the signature - (diagnostic, i, total) -> (string, string), - where {i} is the index of the diagnostic being - evaluated and {total} is the total number of - diagnostics displayed in the window. The - function should return a string which is - prepended to each diagnostic in the window as - well as an (optional) highlight group which will - be used to highlight the prefix. If {prefix} is - a table, it is interpreted as a [text, hl_group] - tuple as in |nvim_echo()|; otherwise, if - {prefix} is a string, it is prepended to each - diagnostic in the window with no highlight. - Overrides the setting from - |vim.diagnostic.config()|. - - Return: ~ - tuple ({float_bufnr}, {win_id}) + Show diagnostics in a floating window. + + Parameters: ~ + {opts} (table|nil) Configuration table with the same keys as + |vim.lsp.util.open_floating_preview()| in addition to the + following: + • bufnr: (number) Buffer number to show diagnostics from. + Defaults to the current buffer. + • namespace: (number) Limit diagnostics to the given namespace + • scope: (string, default "line") Show diagnostics from the + whole buffer ("buffer"), the current cursor line ("line"), + or the current cursor position ("cursor"). Shorthand + versions are also accepted ("c" for "cursor", "l" for + "line", "b" for "buffer"). + • pos: (number or table) If {scope} is "line" or "cursor", use + this position rather than the cursor position. If a number, + interpreted as a line number; otherwise, a (row, col) tuple. + • severity_sort: (default false) Sort diagnostics by severity. + Overrides the setting from |vim.diagnostic.config()|. + • severity: See |diagnostic-severity|. Overrides the setting + from |vim.diagnostic.config()|. + • header: (string or table) String to use as the header for + the floating window. If a table, it is interpreted as a + [text, hl_group] tuple. Overrides the setting from + |vim.diagnostic.config()|. + • source: (boolean or string) Include the diagnostic source in + the message. Use "if_many" to only show sources if there is + more than one source of diagnostics in the buffer. + Otherwise, any truthy value means to always show the + diagnostic source. Overrides the setting from + |vim.diagnostic.config()|. + • format: (function) A function that takes a diagnostic as + input and returns a string. The return value is the text + used to display the diagnostic. Overrides the setting from + |vim.diagnostic.config()|. + • prefix: (function, string, or table) Prefix each diagnostic + in the floating window. If a function, it must have the + signature (diagnostic, i, total) -> (string, string), where + {i} is the index of the diagnostic being evaluated and + {total} is the total number of diagnostics displayed in the + window. The function should return a string which is + prepended to each diagnostic in the window as well as an + (optional) highlight group which will be used to highlight + the prefix. If {prefix} is a table, it is interpreted as a + [text, hl_group] tuple as in |nvim_echo()|; otherwise, if + {prefix} is a string, it is prepended to each diagnostic in + the window with no highlight. Overrides the setting from + |vim.diagnostic.config()|. + + Return: ~ + tuple ({float_bufnr}, {win_id}) reset({namespace}, {bufnr}) *vim.diagnostic.reset()* - Remove all diagnostics from the given namespace. - - Unlike |vim.diagnostic.hide()|, this function removes all - saved diagnostics. They cannot be redisplayed using - |vim.diagnostic.show()|. To simply remove diagnostic - decorations in a way that they can be re-displayed, use - |vim.diagnostic.hide()|. - - Parameters: ~ - {namespace} (number|nil) Diagnostic namespace. When - omitted, remove diagnostics from all - namespaces. - {bufnr} (number|nil) Remove diagnostics for the given - buffer. When omitted, diagnostics are removed - for all buffers. + Remove all diagnostics from the given namespace. + + Unlike |vim.diagnostic.hide()|, this function removes all saved + diagnostics. They cannot be redisplayed using |vim.diagnostic.show()|. To + simply remove diagnostic decorations in a way that they can be + re-displayed, use |vim.diagnostic.hide()|. + + Parameters: ~ + {namespace} (number|nil) Diagnostic namespace. When omitted, remove + diagnostics from all namespaces. + {bufnr} (number|nil) Remove diagnostics for the given buffer. + When omitted, diagnostics are removed for all buffers. set({namespace}, {bufnr}, {diagnostics}, {opts}) *vim.diagnostic.set()* - Set diagnostics for the given namespace and buffer. + Set diagnostics for the given namespace and buffer. - Parameters: ~ - {namespace} (number) The diagnostic namespace - {bufnr} (number) Buffer number - {diagnostics} (table) A list of diagnostic items - |diagnostic-structure| - {opts} (table|nil) Display options to pass to - |vim.diagnostic.show()| + Parameters: ~ + {namespace} (number) The diagnostic namespace + {bufnr} (number) Buffer number + {diagnostics} (table) A list of diagnostic items + |diagnostic-structure| + {opts} (table|nil) Display options to pass to + |vim.diagnostic.show()| setloclist({opts}) *vim.diagnostic.setloclist()* - Add buffer diagnostics to the location list. - - Parameters: ~ - {opts} (table|nil) Configuration table with the following - keys: - • namespace: (number) Only add diagnostics from - the given namespace. - • winnr: (number, default 0) Window number to set - location list for. - • open: (boolean, default true) Open the location - list after setting. - • title: (string) Title of the location list. - Defaults to "Diagnostics". - • severity: See |diagnostic-severity|. + Add buffer diagnostics to the location list. + + Parameters: ~ + {opts} (table|nil) Configuration table with the following keys: + • namespace: (number) Only add diagnostics from the given + namespace. + • winnr: (number, default 0) Window number to set location + list for. + • open: (boolean, default true) Open the location list after + setting. + • title: (string) Title of the location list. Defaults to + "Diagnostics". + • severity: See |diagnostic-severity|. setqflist({opts}) *vim.diagnostic.setqflist()* - Add all diagnostics to the quickfix list. - - Parameters: ~ - {opts} (table|nil) Configuration table with the following - keys: - • namespace: (number) Only add diagnostics from - the given namespace. - • open: (boolean, default true) Open quickfix list - after setting. - • title: (string) Title of quickfix list. Defaults - to "Diagnostics". - • severity: See |diagnostic-severity|. + Add all diagnostics to the quickfix list. + + Parameters: ~ + {opts} (table|nil) Configuration table with the following keys: + • namespace: (number) Only add diagnostics from the given + namespace. + • open: (boolean, default true) Open quickfix list after + setting. + • title: (string) Title of quickfix list. Defaults to + "Diagnostics". + • severity: See |diagnostic-severity|. *vim.diagnostic.show()* show({namespace}, {bufnr}, {diagnostics}, {opts}) - Display diagnostics for the given namespace and buffer. - - Parameters: ~ - {namespace} (number|nil) Diagnostic namespace. When - omitted, show diagnostics from all - namespaces. - {bufnr} (number|nil) Buffer number, or 0 for - current buffer. When omitted, show - diagnostics in all buffers. - {diagnostics} (table|nil) The diagnostics to display. - When omitted, use the saved diagnostics for - the given namespace and buffer. This can be - used to display a list of diagnostics - without saving them or to display only a - subset of diagnostics. May not be used when - {namespace} or {bufnr} is nil. - {opts} (table|nil) Display options. See - |vim.diagnostic.config()|. + Display diagnostics for the given namespace and buffer. + + Parameters: ~ + {namespace} (number|nil) Diagnostic namespace. When omitted, show + diagnostics from all namespaces. + {bufnr} (number|nil) Buffer number, or 0 for current buffer. + When omitted, show diagnostics in all buffers. + {diagnostics} (table|nil) The diagnostics to display. When omitted, + use the saved diagnostics for the given namespace and + buffer. This can be used to display a list of + diagnostics without saving them or to display only a + subset of diagnostics. May not be used when {namespace} + or {bufnr} is nil. + {opts} (table|nil) Display options. See + |vim.diagnostic.config()|. toqflist({diagnostics}) *vim.diagnostic.toqflist()* - Convert a list of diagnostics to a list of quickfix items that - can be passed to |setqflist()| or |setloclist()|. + Convert a list of diagnostics to a list of quickfix items that can be + passed to |setqflist()| or |setloclist()|. - Parameters: ~ - {diagnostics} (table) List of diagnostics - |diagnostic-structure|. + Parameters: ~ + {diagnostics} (table) List of diagnostics |diagnostic-structure|. - Return: ~ - array of quickfix list items |setqflist-what| + Return: ~ + array of quickfix list items |setqflist-what| - vim:tw=78:ts=8:ft=help:norl: + vim:tw=78:ts=8:sw=4:sts=4:et:ft=help:norl: diff --git a/runtime/doc/editing.txt b/runtime/doc/editing.txt index c19d9f482b..dcb0bf8a2e 100644 --- a/runtime/doc/editing.txt +++ b/runtime/doc/editing.txt @@ -613,12 +613,19 @@ list of the current window. And after the last one: :+2argadd y a b c x y There is no check for duplicates, it is possible to - add a file to the argument list twice. - The currently edited file is not changed. + add a file to the argument list twice. You can use + |:argdedupe| to fix it afterwards: > + :argadd *.txt | argdedupe +< The currently edited file is not changed. Note: you can also use this method: > :args ## x < This will add the "x" item and sort the new list. +:argded[upe] *:argded* *:argdedupe* + Remove duplicate filenames from the argument list. + If your current file is a duplicate, your current file + will change to the original file index. + :argd[elete] {pattern} .. *:argd* *:argdelete* *E480* *E610* Delete files from the argument list that match the {pattern}s. {pattern} is used like a file pattern, diff --git a/runtime/doc/help.txt b/runtime/doc/help.txt index b97c9a2e3f..04e31e0680 100644 --- a/runtime/doc/help.txt +++ b/runtime/doc/help.txt @@ -25,6 +25,7 @@ Get specific help: It is possible to go directly to whatever you want help Option ' :help 'textwidth' Regular expression / :help /[ See |help-summary| for more contexts and an explanation. + See |notation| for an explanation of the help syntax. Search for help: Type ":help word", then hit CTRL-D to see matching help entries for "word". @@ -185,6 +186,8 @@ Other ~ |channel.txt| Nvim asynchronous IO |dev_style.txt| Nvim style guide |job_control.txt| Spawn and control multiple processes +|luaref.txt| Lua reference manual +|luvref.txt| Luv (|vim.loop|) reference manual *standard-plugin-list* Standard plugins ~ diff --git a/runtime/doc/index.txt b/runtime/doc/index.txt index 7d8a89887a..7f3ef20762 100644 --- a/runtime/doc/index.txt +++ b/runtime/doc/index.txt @@ -1143,6 +1143,7 @@ tag command action ~ be remapped |:args| :ar[gs] print the argument list |:argadd| :arga[dd] add items to the argument list +|:argdedupe| :argded[upe] remove duplicates from the argument list |:argdelete| :argd[elete] delete items from the argument list |:argedit| :arge[dit] add item to the argument list and edit it |:argdo| :argdo do a command on all items in the argument list diff --git a/runtime/doc/lsp.txt b/runtime/doc/lsp.txt index 11f96db8c9..7fc0daa0ca 100644 --- a/runtime/doc/lsp.txt +++ b/runtime/doc/lsp.txt @@ -10,7 +10,7 @@ Nvim supports the Language Server Protocol (LSP), which means it acts as a client to LSP servers and includes a Lua framework `vim.lsp` for building enhanced LSP tools. - https://microsoft.github.io/language-server-protocol/ + https://microsoft.github.io/language-server-protocol/ LSP facilitates features like go-to-definition, find-references, hover, completion, rename, format, refactor, etc., using semantic whole-project @@ -34,11 +34,11 @@ Follow these steps to get LSP features: 2. Configure the LSP client per language server. A minimal example: > - vim.lsp.start({ - name = 'my-server-name', - cmd = {'name-of-language-server-executable'}, - root_dir = vim.fs.dirname(vim.fs.find({'setup.py', 'pyproject.toml'}, { upward = true })[1]), - }) + vim.lsp.start({ + name = 'my-server-name', + cmd = {'name-of-language-server-executable'}, + root_dir = vim.fs.dirname(vim.fs.find({'setup.py', 'pyproject.toml'}, { upward = true })[1]), + }) < See |vim.lsp.start| for details. @@ -59,6 +59,9 @@ language server supports the functionality. - |tagfunc| is set to |vim.lsp.tagfunc|. This enables features like go-to-definition, |:tjump|, and keymaps like |CTRL-]|, |CTRL-W_]|, |CTRL-W_}| to utilize the language server. +- |formatexpr| is set to |vim.lsp.formatexpr| if both |formatprg| and + |formatexpr| are empty. This allows to format lines via |gq| if the language + server supports it. To use other LSP features like hover, rename, etc. you can setup some additional keymaps. It's recommended to setup them in a |LspAttach| autocmd to @@ -98,7 +101,7 @@ To learn what capabilities are available you can run the following command in a buffer with a started LSP client: > - :lua =vim.lsp.get_active_clients()[1].server_capabilities + :lua =vim.lsp.get_active_clients()[1].server_capabilities < Full list of features provided by default can be found in |lsp-buf|. @@ -160,7 +163,7 @@ LSP request/response handlers are implemented as Lua functions (see |lsp-handler|). The |vim.lsp.handlers| table defines default handlers used when creating a new client. Keys are LSP method names: > - :lua print(vim.inspect(vim.tbl_keys(vim.lsp.handlers))) + :lua print(vim.inspect(vim.tbl_keys(vim.lsp.handlers))) < *lsp-method* @@ -201,84 +204,83 @@ For |lsp-request|, each |lsp-handler| has this signature: > function(err, result, ctx, config) < - Parameters: ~ - {err} (table|nil) - When the language server is unable to complete a - request, a table with information about the error - is sent. Otherwise, it is `nil`. See |lsp-response|. - {result} (Result | Params | nil) - When the language server is able to successfully - complete a request, this contains the `result` key - of the response. See |lsp-response|. - {ctx} (table) - Context describes additional calling state - associated with the handler. It consists of the - following key, value pairs: - - {method} (string) - The |lsp-method| name. - {client_id} (number) - The ID of the |vim.lsp.client|. - {bufnr} (Buffer) - Buffer handle, or 0 for current. - - {params} (table|nil) - The parameters used in the original request - which resulted in this handler - call. - {config} (table) - Configuration for the handler. - - Each handler can define its own configuration - table that allows users to customize the behavior - of a particular handler. - - To configure a particular |lsp-handler|, see: - |lsp-handler-configuration| - - - Returns: ~ - The |lsp-handler| can respond by returning two values: `result, err` - Where `err` must be shaped like an RPC error: - `{ code, message, data? }` - - You can use |vim.lsp.rpc_response_error()| to create this object. + Parameters: ~ + {err} (table|nil) + When the language server is unable to complete a + request, a table with information about the error is + sent. Otherwise, it is `nil`. See |lsp-response|. + {result} (Result | Params | nil) + When the language server is able to successfully + complete a request, this contains the `result` key of + the response. See |lsp-response|. + {ctx} (table) + Context describes additional calling state associated + with the handler. It consists of the following key, + value pairs: + + {method} (string) + The |lsp-method| name. + {client_id} (number) + The ID of the |vim.lsp.client|. + {bufnr} (Buffer) + Buffer handle, or 0 for current. + {params} (table|nil) + The parameters used in the original + request which resulted in this handler + call. + {config} (table) + Configuration for the handler. + + Each handler can define its own configuration table + that allows users to customize the behavior of a + particular handler. + + To configure a particular |lsp-handler|, see: + |lsp-handler-configuration| + + + Returns: ~ + The |lsp-handler| can respond by returning two values: `result, err` + Where `err` must be shaped like an RPC error: + `{ code, message, data? }` + + You can use |vim.lsp.rpc_response_error()| to create this object. For |lsp-notification|, each |lsp-handler| has this signature: > function(err, result, ctx, config) < - Parameters: ~ - {err} (nil) - This is always `nil`. - See |lsp-notification| - {result} (Result) - This contains the `params` key of the notification. - See |lsp-notification| - {ctx} (table) - Context describes additional calling state - associated with the handler. It consists of the - following key, value pairs: - - {method} (string) - The |lsp-method| name. - {client_id} (number) - The ID of the |vim.lsp.client|. - {config} (table) - Configuration for the handler. - - Each handler can define its own configuration - table that allows users to customize the behavior - of a particular handler. - - For an example, see: - |vim.lsp.diagnostic.on_publish_diagnostics()| - - To configure a particular |lsp-handler|, see: - |lsp-handler-configuration| - - Returns: ~ - The |lsp-handler|'s return value will be ignored. + Parameters: ~ + {err} (nil) + This is always `nil`. + See |lsp-notification| + {result} (Result) + This contains the `params` key of the notification. + See |lsp-notification| + {ctx} (table) + Context describes additional calling state associated + with the handler. It consists of the following key, + value pairs: + + {method} (string) + The |lsp-method| name. + {client_id} (number) + The ID of the |vim.lsp.client|. + {config} (table) + Configuration for the handler. + + Each handler can define its own configuration table + that allows users to customize the behavior of a + particular handler. + + For an example, see: + |vim.lsp.diagnostic.on_publish_diagnostics()| + + To configure a particular |lsp-handler|, see: + |lsp-handler-configuration| + + Returns: ~ + The |lsp-handler|'s return value will be ignored. *lsp-handler-configuration* @@ -289,49 +291,50 @@ To configure the behavior of a builtin |lsp-handler|, the convenient method consider the following example, where a new |lsp-handler| is created using |vim.lsp.with()| that no longer generates signs for the diagnostics: > - vim.lsp.handlers["textDocument/publishDiagnostics"] = vim.lsp.with( - vim.lsp.diagnostic.on_publish_diagnostics, { - -- Disable signs - signs = false, - } - ) + vim.lsp.handlers["textDocument/publishDiagnostics"] = vim.lsp.with( + vim.lsp.diagnostic.on_publish_diagnostics, { + -- Disable signs + signs = false, + } + ) < To enable signs, use |vim.lsp.with()| again to create and assign a new |lsp-handler| to |vim.lsp.handlers| for the associated method: > - vim.lsp.handlers["textDocument/publishDiagnostics"] = vim.lsp.with( - vim.lsp.diagnostic.on_publish_diagnostics, { - -- Enable signs - signs = true, - } - ) + vim.lsp.handlers["textDocument/publishDiagnostics"] = vim.lsp.with( + vim.lsp.diagnostic.on_publish_diagnostics, { + -- Enable signs + signs = true, + } + ) < To configure a handler on a per-server basis, you can use the {handlers} key for |vim.lsp.start_client()| > - vim.lsp.start_client { - ..., -- Other configuration omitted. - handlers = { - ["textDocument/publishDiagnostics"] = vim.lsp.with( - vim.lsp.diagnostic.on_publish_diagnostics, { - -- Disable virtual_text - virtual_text = false, - } - }, - } + vim.lsp.start_client { + ..., -- Other configuration omitted. + handlers = { + ["textDocument/publishDiagnostics"] = vim.lsp.with( + vim.lsp.diagnostic.on_publish_diagnostics, { + -- Disable virtual_text + virtual_text = false, + } + ), + }, + } < or if using 'nvim-lspconfig', you can use the {handlers} key of `setup()`: > - require('lspconfig').rust_analyzer.setup { - handlers = { - ["textDocument/publishDiagnostics"] = vim.lsp.with( - vim.lsp.diagnostic.on_publish_diagnostics, { - -- Disable virtual_text - virtual_text = false - } - ), - } - } + require('lspconfig').rust_analyzer.setup { + handlers = { + ["textDocument/publishDiagnostics"] = vim.lsp.with( + vim.lsp.diagnostic.on_publish_diagnostics, { + -- Disable virtual_text + virtual_text = false + } + ), + } + } < Some handlers do not have an explicitly named handler function (such as |on_publish_diagnostics()|). To override these, first create a reference @@ -354,31 +357,31 @@ Handlers can be set by: To override the handler for the `"textDocument/definition"` method: > - vim.lsp.handlers["textDocument/definition"] = my_custom_default_definition + vim.lsp.handlers["textDocument/definition"] = my_custom_default_definition < - The {handlers} parameter for |vim.lsp.start_client|. This will set the |lsp-handler| as the default handler for this server. For example: > - vim.lsp.start_client { - ..., -- Other configuration omitted. - handlers = { + vim.lsp.start_client { + ..., -- Other configuration omitted. + handlers = { ["textDocument/definition"] = my_custom_server_definition - }, - } + }, + } - The {handler} parameter for |vim.lsp.buf_request()|. This will set the |lsp-handler| ONLY for the current request. For example: > - vim.lsp.buf_request( - 0, - "textDocument/definition", - definition_params, - my_request_custom_definition - ) + vim.lsp.buf_request( + 0, + "textDocument/definition", + definition_params, + my_request_custom_definition + ) < In summary, the |lsp-handler| will be chosen based on the current |lsp-method| in the following order: @@ -400,8 +403,8 @@ https://github.com/microsoft/language-server-protocol/raw/gh-pages/_specificatio For example `vim.lsp.protocol.ErrorCodes` allows reverse lookup by number or name: > - vim.lsp.protocol.TextDocumentSyncKind.Full == 1 - vim.lsp.protocol.TextDocumentSyncKind[1] == "Full" + vim.lsp.protocol.TextDocumentSyncKind.Full == 1 + vim.lsp.protocol.TextDocumentSyncKind[1] == "Full" < *lsp-response* @@ -412,7 +415,7 @@ For the format of the response message, see: For the format of the notification message, see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#notificationMessage - *on-list-handler* + *lsp-on-list-handler* `on_list` receives a table with: @@ -421,22 +424,22 @@ For the format of the notification message, see: - `context` table|nil. `ctx` from |lsp-handler| This table can be used with vim.fn.setqflist or vim.fn.setloclist. E.g.: +> + local function on_list(options) + vim.fn.setqflist({}, ' ', options) + vim.api.nvim_command('cfirst') + end - local function on_list(options) - vim.fn.setqflist({}, ' ', options) - vim.api.nvim_command('cfirst') - end - - vim.lsp.buf.definition{on_list=on_list} - vim.lsp.buf.references(nil, {on_list=on_list}) - + vim.lsp.buf.definition{on_list=on_list} + vim.lsp.buf.references(nil, {on_list=on_list}) +< If you prefer loclist do something like this: - - local function on_list(options) - vim.fn.setloclist(0, {}, ' ', options) - vim.api.nvim_command('lopen') - end - +> + local function on_list(options) + vim.fn.setloclist(0, {}, ' ', options) + vim.api.nvim_command('lopen') + end +< ================================================================================ LSP HIGHLIGHT *lsp-highlight* @@ -461,11 +464,11 @@ Highlight groups related to |lsp-codelens| functionality. *hl-LspCodeLens* LspCodeLens - Used to color the virtual text of the codelens. See - |nvim_buf_set_extmark()|. + Used to color the virtual text of the codelens. See + |nvim_buf_set_extmark()|. LspCodeLensSeparator *hl-LspCodeLensSeparator* - Used to color the separator between two or more code lens. + Used to color the separator between two or more code lens. *lsp-highlight-signature* @@ -473,8 +476,8 @@ Highlight groups related to |vim.lsp.handlers.signature_help()|. *hl-LspSignatureActiveParameter* LspSignatureActiveParameter - Used to highlight the active parameter in the signature help. See - |vim.lsp.handlers.signature_help()|. + Used to highlight the active parameter in the signature help. See + |vim.lsp.handlers.signature_help()|. ============================================================================== EVENTS *lsp-events* @@ -513,317 +516,268 @@ callback in the "data" table. Example: > In addition, the following |User| |autocommands| are provided: LspProgressUpdate *LspProgressUpdate* - Upon receipt of a progress notification from the server. See - |vim.lsp.util.get_progress_messages()|. + Upon receipt of a progress notification from the server. See + |vim.lsp.util.get_progress_messages()|. LspRequest *LspRequest* - After a change to the active set of pending LSP requests. See {requests} - in |vim.lsp.client|. + After a change to the active set of pending LSP requests. See {requests} + in |vim.lsp.client|. Example: > - autocmd User LspProgressUpdate redrawstatus - autocmd User LspRequest redrawstatus + autocmd User LspProgressUpdate redrawstatus + autocmd User LspRequest redrawstatus < ============================================================================== Lua module: vim.lsp *lsp-core* buf_attach_client({bufnr}, {client_id}) *vim.lsp.buf_attach_client()* - Implements the `textDocument/did…` notifications required to - track a buffer for any language server. + Implements the `textDocument/did…` notifications required to track a + buffer for any language server. - Without calling this, the server won't be notified of changes - to a buffer. + Without calling this, the server won't be notified of changes to a buffer. - Parameters: ~ - {bufnr} (number) Buffer handle, or 0 for current - {client_id} (number) Client id + Parameters: ~ + {bufnr} (number) Buffer handle, or 0 for current + {client_id} (number) Client id buf_detach_client({bufnr}, {client_id}) *vim.lsp.buf_detach_client()* - Detaches client from the specified buffer. Note: While the - server is notified that the text document (buffer) was closed, - it is still able to send notifications should it ignore this - notification. + Detaches client from the specified buffer. Note: While the server is + notified that the text document (buffer) was closed, it is still able to + send notifications should it ignore this notification. - Parameters: ~ - {bufnr} (number) Buffer handle, or 0 for current - {client_id} (number) Client id + Parameters: ~ + {bufnr} (number) Buffer handle, or 0 for current + {client_id} (number) Client id buf_is_attached({bufnr}, {client_id}) *vim.lsp.buf_is_attached()* - Checks if a buffer is attached for a particular client. + Checks if a buffer is attached for a particular client. - Parameters: ~ - {bufnr} (number) Buffer handle, or 0 for current - {client_id} (number) the client id + Parameters: ~ + {bufnr} (number) Buffer handle, or 0 for current + {client_id} (number) the client id buf_notify({bufnr}, {method}, {params}) *vim.lsp.buf_notify()* - Send a notification to a server - - Parameters: ~ - {bufnr} [number] (optional): The number of the buffer - {method} [string]: Name of the request method - {params} [string]: Arguments to send to the server - - Return: ~ - true if any client returns true; false otherwise + Send a notification to a server - *vim.lsp.buf_request()* -buf_request({bufnr}, {method}, {params}, {handler}) - Sends an async request for all active clients attached to the - buffer. + Parameters: ~ + {bufnr} [number] (optional): The number of the buffer + {method} [string]: Name of the request method + {params} [string]: Arguments to send to the server - Parameters: ~ - {bufnr} (number) Buffer handle, or 0 for current. - {method} (string) LSP method name - {params} (optional, table) Parameters to send to the - server - {handler} (optional, function) See |lsp-handler| If nil, - follows resolution strategy defined in - |lsp-handler-configuration| - - Return: ~ - 2-tuple: - • Map of client-id:request-id pairs for all successful - requests. - • Function which can be used to cancel all the requests. - You could instead iterate all clients and call their - `cancel_request()` methods. + Return: ~ + true if any client returns true; false otherwise *vim.lsp.buf_request_all()* buf_request_all({bufnr}, {method}, {params}, {callback}) - Sends an async request for all active clients attached to the - buffer. Executes the callback on the combined result. - Parameters are the same as |vim.lsp.buf_request()| but the - return result and callback are different. - - Parameters: ~ - {bufnr} (number) Buffer handle, or 0 for current. - {method} (string) LSP method name - {params} (optional, table) Parameters to send to the - server - {callback} (function) The callback to call when all - requests are finished. - - Return: ~ - (function) A function that will cancel all requests which - is the same as the one returned from `buf_request`. + Sends an async request for all active clients attached to the buffer. + Executes the callback on the combined result. Parameters are the same as + |vim.lsp.buf_request()| but the return result and callback are different. + + Parameters: ~ + {bufnr} (number) Buffer handle, or 0 for current. + {method} (string) LSP method name + {params} (optional, table) Parameters to send to the server + {callback} (function) The callback to call when all requests are + finished. + + Return: ~ + (function) A function that will cancel all requests which is the same + as the one returned from `buf_request`. *vim.lsp.buf_request_sync()* buf_request_sync({bufnr}, {method}, {params}, {timeout_ms}) - Sends a request to all server and waits for the response of - all of them. - - Calls |vim.lsp.buf_request_all()| but blocks Nvim while - awaiting the result. Parameters are the same as - |vim.lsp.buf_request()| but the return result is different. - Wait maximum of {timeout_ms} (default 1000) ms. - - Parameters: ~ - {bufnr} (number) Buffer handle, or 0 for current. - {method} (string) LSP method name - {params} (optional, table) Parameters to send to the - server - {timeout_ms} (optional, number, default=1000) Maximum - time in milliseconds to wait for a result. - - Return: ~ - Map of client_id:request_result. On timeout, cancel or - error, returns `(nil, err)` where `err` is a string - describing the failure reason. + Sends a request to all server and waits for the response of all of them. + + Calls |vim.lsp.buf_request_all()| but blocks Nvim while awaiting the + result. Parameters are the same as |vim.lsp.buf_request()| but the return + result is different. Wait maximum of {timeout_ms} (default 1000) ms. + + Parameters: ~ + {bufnr} (number) Buffer handle, or 0 for current. + {method} (string) LSP method name + {params} (optional, table) Parameters to send to the server + {timeout_ms} (optional, number, default=1000) Maximum time in + milliseconds to wait for a result. + + Return: ~ + Map of client_id:request_result. On timeout, cancel or error, returns + `(nil, err)` where `err` is a string describing the failure reason. client() *vim.lsp.client* - LSP client object. You can get an active client object via - |vim.lsp.get_client_by_id()| or - |vim.lsp.get_active_clients()|. - - • Methods: - • request(method, params, [handler], bufnr) Sends a request - to the server. This is a thin wrapper around - {client.rpc.request} with some additional checking. If - {handler} is not specified, If one is not found there, - then an error will occur. Returns: {status}, - {[client_id]}. {status} is a boolean indicating if the - notification was successful. If it is `false`, then it - will always be `false` (the client has shutdown). If - {status} is `true`, the function returns {request_id} as - the second result. You can use this with - `client.cancel_request(request_id)` to cancel the request. - • request_sync(method, params, timeout_ms, bufnr) Sends a - request to the server and synchronously waits for the - response. This is a wrapper around {client.request} - Returns: { err=err, result=result }, a dictionary, where - `err` and `result` come from the |lsp-handler|. On - timeout, cancel or error, returns `(nil, err)` where `err` - is a string describing the failure reason. If the request - was unsuccessful returns `nil`. - • notify(method, params) Sends a notification to an LSP - server. Returns: a boolean to indicate if the notification - was successful. If it is false, then it will always be - false (the client has shutdown). - • cancel_request(id) Cancels a request with a given request - id. Returns: same as `notify()`. - • stop([force]) Stops a client, optionally with force. By - default, it will just ask the server to shutdown without - force. If you request to stop a client which has - previously been requested to shutdown, it will - automatically escalate and force shutdown. - • is_stopped() Checks whether a client is stopped. Returns: - true if the client is fully stopped. - • on_attach(client, bufnr) Runs the on_attach function from - the client's config if it was defined. Useful for - buffer-local setup. - - • Members - • {id} (number): The id allocated to the client. - • {name} (string): If a name is specified on creation, that - will be used. Otherwise it is just the client id. This is - used for logs and messages. - • {rpc} (table): RPC client object, for low level - interaction with the client. See |vim.lsp.rpc.start()|. - • {offset_encoding} (string): The encoding used for - communicating with the server. You can modify this in the - `config`'s `on_init` method before text is sent to the - server. - • {handlers} (table): The handlers used by the client as - described in |lsp-handler|. - • {requests} (table): The current pending requests in flight - to the server. Entries are key-value pairs with the key - being the request ID while the value is a table with - `type`, `bufnr`, and `method` key-value pairs. `type` is - either "pending" for an active request, or "cancel" for a - cancel request. - • {config} (table): copy of the table that was passed by the - user to |vim.lsp.start_client()|. - • {server_capabilities} (table): Response from the server - sent on `initialize` describing the server's capabilities. + LSP client object. You can get an active client object via + |vim.lsp.get_client_by_id()| or |vim.lsp.get_active_clients()|. + + • Methods: + • request(method, params, [handler], bufnr) Sends a request to the + server. This is a thin wrapper around {client.rpc.request} with some + additional checking. If {handler} is not specified, If one is not + found there, then an error will occur. Returns: {status}, + {[client_id]}. {status} is a boolean indicating if the notification + was successful. If it is `false`, then it will always be `false` (the + client has shutdown). If {status} is `true`, the function returns + {request_id} as the second result. You can use this with + `client.cancel_request(request_id)` to cancel the request. + • request_sync(method, params, timeout_ms, bufnr) Sends a request to the + server and synchronously waits for the response. This is a wrapper + around {client.request} Returns: { err=err, result=result }, a + dictionary, where `err` and `result` come from the |lsp-handler|. On + timeout, cancel or error, returns `(nil, err)` where `err` is a string + describing the failure reason. If the request was unsuccessful returns + `nil`. + • notify(method, params) Sends a notification to an LSP server. Returns: + a boolean to indicate if the notification was successful. If it is + false, then it will always be false (the client has shutdown). + • cancel_request(id) Cancels a request with a given request id. Returns: + same as `notify()`. + • stop([force]) Stops a client, optionally with force. By default, it + will just ask the server to shutdown without force. If you request to + stop a client which has previously been requested to shutdown, it will + automatically escalate and force shutdown. + • is_stopped() Checks whether a client is stopped. Returns: true if the + client is fully stopped. + • on_attach(client, bufnr) Runs the on_attach function from the client's + config if it was defined. Useful for buffer-local setup. + + • Members + • {id} (number): The id allocated to the client. + • {name} (string): If a name is specified on creation, that will be + used. Otherwise it is just the client id. This is used for logs and + messages. + • {rpc} (table): RPC client object, for low level interaction with the + client. See |vim.lsp.rpc.start()|. + • {offset_encoding} (string): The encoding used for communicating with + the server. You can modify this in the `config`'s `on_init` method + before text is sent to the server. + • {handlers} (table): The handlers used by the client as described in + |lsp-handler|. + • {requests} (table): The current pending requests in flight to the + server. Entries are key-value pairs with the key being the request ID + while the value is a table with `type`, `bufnr`, and `method` + key-value pairs. `type` is either "pending" for an active request, or + "cancel" for a cancel request. + • {config} (table): copy of the table that was passed by the user to + |vim.lsp.start_client()|. + • {server_capabilities} (table): Response from the server sent on + `initialize` describing the server's capabilities. client_is_stopped({client_id}) *vim.lsp.client_is_stopped()* - Checks whether a client is stopped. + Checks whether a client is stopped. - Parameters: ~ - {client_id} (Number) + Parameters: ~ + {client_id} (Number) - Return: ~ - true if client is stopped, false otherwise. + Return: ~ + true if client is stopped, false otherwise. *vim.lsp.for_each_buffer_client()* for_each_buffer_client({bufnr}, {fn}) - Invokes a function for each LSP client attached to a buffer. - - Parameters: ~ - {bufnr} (number) Buffer number - {fn} (function) Function to run on each client - attached to buffer {bufnr}. The function takes - the client, client ID, and buffer number as - arguments. Example: > - - vim.lsp.for_each_buffer_client(0, function(client, client_id, bufnr) - print(vim.inspect(client)) - end) + Invokes a function for each LSP client attached to a buffer. + + Parameters: ~ + {bufnr} (number) Buffer number + {fn} (function) Function to run on each client attached to buffer + {bufnr}. The function takes the client, client ID, and buffer + number as arguments. Example: > + + vim.lsp.for_each_buffer_client(0, function(client, client_id, bufnr) + print(vim.inspect(client)) + end) < formatexpr({opts}) *vim.lsp.formatexpr()* - Provides an interface between the built-in client and a - `formatexpr` function. - - Currently only supports a single client. This can be set via - `setlocal formatexpr=v:lua.vim.lsp.formatexpr()` but will - typically or in `on_attach` via - `vim.api.nvim_buf_set_option(bufnr, 'formatexpr', - 'v:lua.vim.lsp.formatexpr(#{timeout_ms:250})')`. - - Parameters: ~ - {opts} (table) options for customizing the formatting - expression which takes the following optional - keys: - • timeout_ms (default 500ms). The timeout period - for the formatting request. + Provides an interface between the built-in client and a `formatexpr` + function. + + Currently only supports a single client. This can be set via `setlocal + formatexpr=v:lua.vim.lsp.formatexpr()` but will typically or in + `on_attach` via `vim.api.nvim_buf_set_option(bufnr, 'formatexpr', + 'v:lua.vim.lsp.formatexpr(#{timeout_ms:250})')`. + + Parameters: ~ + {opts} (table) options for customizing the formatting expression + which takes the following optional keys: + • timeout_ms (default 500ms). The timeout period for the + formatting request. get_active_clients({filter}) *vim.lsp.get_active_clients()* - Get active clients. - - Parameters: ~ - {filter} (table|nil) A table with key-value pairs used to - filter the returned clients. The available keys - are: - • id (number): Only return clients with the - given id - • bufnr (number): Only return clients attached - to this buffer - • name (string): Only return clients with the - given name - - Return: ~ - (table) List of |vim.lsp.client| objects + Get active clients. + + Parameters: ~ + {filter} (table|nil) A table with key-value pairs used to filter the + returned clients. The available keys are: + • id (number): Only return clients with the given id + • bufnr (number): Only return clients attached to this + buffer + • name (string): Only return clients with the given name + + Return: ~ + (table) List of |vim.lsp.client| objects *vim.lsp.get_buffers_by_client_id()* get_buffers_by_client_id({client_id}) - Returns list of buffers attached to client_id. + Returns list of buffers attached to client_id. - Parameters: ~ - {client_id} (number) client id + Parameters: ~ + {client_id} (number) client id - Return: ~ - list of buffer ids + Return: ~ + list of buffer ids get_client_by_id({client_id}) *vim.lsp.get_client_by_id()* - Gets a client by id, or nil if the id is invalid. The returned - client may not yet be fully initialized. + Gets a client by id, or nil if the id is invalid. The returned client may + not yet be fully initialized. - Parameters: ~ - {client_id} (number) client id + Parameters: ~ + {client_id} (number) client id - Return: ~ - |vim.lsp.client| object, or nil + Return: ~ + |vim.lsp.client| object, or nil get_log_path() *vim.lsp.get_log_path()* - Gets the path of the logfile used by the LSP client. + Gets the path of the logfile used by the LSP client. - Return: ~ - (String) Path to logfile. + Return: ~ + (String) Path to logfile. omnifunc({findstart}, {base}) *vim.lsp.omnifunc()* - Implements 'omnifunc' compatible LSP completion. + Implements 'omnifunc' compatible LSP completion. - Parameters: ~ - {findstart} 0 or 1, decides behavior - {base} If findstart=0, text to match against + Parameters: ~ + {findstart} 0 or 1, decides behavior + {base} If findstart=0, text to match against - Return: ~ - (number) Decided by {findstart}: - • findstart=0: column where the completion starts, or -2 - or -3 - • findstart=1: list of matches (actually just calls - |complete()|) + Return: ~ + (number) Decided by {findstart}: + • findstart=0: column where the completion starts, or -2 or -3 + • findstart=1: list of matches (actually just calls |complete()|) - See also: ~ - |complete-functions| - |complete-items| - |CompleteDone| + See also: ~ + |complete-functions| + |complete-items| + |CompleteDone| set_log_level({level}) *vim.lsp.set_log_level()* - Sets the global log level for LSP logging. + Sets the global log level for LSP logging. - Levels by name: "TRACE", "DEBUG", "INFO", "WARN", "ERROR", - "OFF" + Levels by name: "TRACE", "DEBUG", "INFO", "WARN", "ERROR", "OFF" - Level numbers begin with "TRACE" at 0 + Level numbers begin with "TRACE" at 0 - Use `lsp.log_levels` for reverse lookup. + Use `lsp.log_levels` for reverse lookup. - Parameters: ~ - {level} [number|string] the case insensitive level name - or number + Parameters: ~ + {level} [number|string] the case insensitive level name or number - See also: ~ - |vim.lsp.log_levels| + See also: ~ + |vim.lsp.log_levels| start({config}, {opts}) *vim.lsp.start()* - Create a new LSP client and start a language server or reuses - an already running client if one is found matching `name` and - `root_dir`. Attaches the current buffer to the client. + Create a new LSP client and start a language server or reuses an already + running client if one is found matching `name` and `root_dir`. Attaches + the current buffer to the client. - Example: + Example: > vim.lsp.start({ @@ -833,248 +787,208 @@ start({config}, {opts}) *vim.lsp.start()* }) < - See |lsp.start_client| for all available options. The most - important are: - - `name` is an arbitrary name for the LSP client. It should be - unique per language server. - - `cmd` the command as list - used to start the language server. The - command must be present in the `$PATH` environment variable or an absolute path to the executable. - Shell constructs like `~` are NOT expanded. - - `root_dir` path to the project root. By default this is used - to decide if an existing client should be re-used. The example - above uses |vim.fs.find| and |vim.fs.dirname| to detect the - root by traversing the file system upwards starting from the - current directory until either a `pyproject.toml` or - `setup.py` file is found. - - `workspace_folders` a list of { uri:string, name: string } - tables. The project root folders used by the language server. - If `nil` the property is derived from the `root_dir` for - convenience. - - Language servers use this information to discover metadata - like the dependencies of your project and they tend to index - the contents within the project folder. - - To ensure a language server is only started for languages it - can handle, make sure to call |vim.lsp.start| within a - |FileType| autocmd. Either use |:au|, |nvim_create_autocmd()| - or put the call in a `ftplugin/<filetype_name>.lua` (See - |ftplugin-name|) - - Parameters: ~ - {config} (table) Same configuration as documented in - |lsp.start_client()| - {opts} nil|table Optional keyword arguments: - • reuse_client (fun(client: client, config: - table): boolean) Predicate used to decide if a - client should be re-used. Used on all running - clients. The default implementation re-uses a - client if name and root_dir matches. - - Return: ~ - (number) client_id + See |lsp.start_client| for all available options. The most important are: + + `name` is an arbitrary name for the LSP client. It should be unique per + language server. + + `cmd` the command as list - used to start the language server. The command must + be present in the `$PATH` environment variable or an absolute path to the executable. Shell + constructs like `~` are NOT expanded. + + `root_dir` path to the project root. By default this is used to decide if + an existing client should be re-used. The example above uses |vim.fs.find| + and |vim.fs.dirname| to detect the root by traversing the file system + upwards starting from the current directory until either a + `pyproject.toml` or `setup.py` file is found. + + `workspace_folders` a list of { uri:string, name: string } tables. The + project root folders used by the language server. If `nil` the property is + derived from the `root_dir` for convenience. + + Language servers use this information to discover metadata like the + dependencies of your project and they tend to index the contents within + the project folder. + + To ensure a language server is only started for languages it can handle, + make sure to call |vim.lsp.start| within a |FileType| autocmd. Either use + |:au|, |nvim_create_autocmd()| or put the call in a + `ftplugin/<filetype_name>.lua` (See |ftplugin-name|) + + Parameters: ~ + {config} (table) Same configuration as documented in + |lsp.start_client()| + {opts} nil|table Optional keyword arguments: + • reuse_client (fun(client: client, config: table): boolean) + Predicate used to decide if a client should be re-used. + Used on all running clients. The default implementation + re-uses a client if name and root_dir matches. + + Return: ~ + (number) client_id start_client({config}) *vim.lsp.start_client()* - Starts and initializes a client with the given configuration. - - Parameter `cmd` is required. - - The following parameters describe fields in the {config} - table. - - Parameters: ~ - {cmd} (required, string or list treated - like |jobstart()|) Base command that - initiates the LSP client. - {cmd_cwd} (string, default=|getcwd()|) - Directory to launch the `cmd` - process. Not related to `root_dir`. - {cmd_env} (table) Environment flags to pass to - the LSP on spawn. Can be specified - using keys like a map or as a list - with `k=v` pairs or both. Non-string values are - coerced to string. Example: > - - { "PRODUCTION=true"; "TEST=123"; PORT = 8080; HOST = "0.0.0.0"; } + Starts and initializes a client with the given configuration. + + Parameter `cmd` is required. + + The following parameters describe fields in the {config} table. + + Parameters: ~ + {cmd} (required, string or list treated like + |jobstart()|) Base command that initiates the LSP + client. + {cmd_cwd} (string, default=|getcwd()|) Directory to launch + the `cmd` process. Not related to `root_dir`. + {cmd_env} (table) Environment flags to pass to the LSP on + spawn. Can be specified using keys like a map or + as a list with `k=v` pairs or both. Non-string values are coerced to + string. Example: > + + { "PRODUCTION=true"; "TEST=123"; PORT = 8080; HOST = "0.0.0.0"; } < - {detached} (boolean, default true) Daemonize the - server process so that it runs in a - separate process group from Nvim. - Nvim will shutdown the process on - exit, but if Nvim fails to exit - cleanly this could leave behind - orphaned server processes. - {workspace_folders} (table) List of workspace folders - passed to the language server. For - backwards compatibility rootUri and - rootPath will be derived from the - first workspace folder in this list. - See `workspaceFolders` in the LSP - spec. - {capabilities} Map overriding the default - capabilities defined by - |vim.lsp.protocol.make_client_capabilities()|, - passed to the language server on - initialization. Hint: use - make_client_capabilities() and modify - its result. - • Note: To send an empty dictionary - use - `{[vim.type_idx]=vim.types.dictionary}`, - else it will be encoded as an - array. - {handlers} Map of language server method names - to |lsp-handler| - {settings} Map with language server specific - settings. These are returned to the - language server if requested via - `workspace/configuration`. Keys are - case-sensitive. - {commands} (table) Table that maps string of - clientside commands to user-defined - functions. Commands passed to - start_client take precedence over the - global command registry. Each key - must be a unique command name, and - the value is a function which is - called if any LSP action (code - action, code lenses, ...) triggers - the command. - {init_options} Values to pass in the initialization - request as `initializationOptions`. - See `initialize` in the LSP spec. - {name} (string, default=client-id) Name in - log messages. - {get_language_id} function(bufnr, filetype) -> language - ID as string. Defaults to the - filetype. - {offset_encoding} (default="utf-16") One of "utf-8", - "utf-16", or "utf-32" which is the - encoding that the LSP server expects. - Client does not verify this is - correct. - {on_error} Callback with parameters (code, ...), - invoked when the client operation - throws an error. `code` is a number - describing the error. Other arguments - may be passed depending on the error - kind. See |vim.lsp.rpc.client_errors| - for possible errors. Use - `vim.lsp.rpc.client_errors[code]` to - get human-friendly name. - {before_init} Callback with parameters - (initialize_params, config) invoked - before the LSP "initialize" phase, - where `params` contains the - parameters being sent to the server - and `config` is the config that was - passed to |vim.lsp.start_client()|. - You can use this to modify parameters - before they are sent. - {on_init} Callback (client, initialize_result) - invoked after LSP "initialize", where - `result` is a table of `capabilities` - and anything else the server may - send. For example, clangd sends - `initialize_result.offsetEncoding` if - `capabilities.offsetEncoding` was - sent to it. You can only modify the - `client.offset_encoding` here before - any notifications are sent. Most - language servers expect to be sent - client specified settings after - initialization. Neovim does not make - this assumption. A - `workspace/didChangeConfiguration` - notification should be sent to the - server during on_init. - {on_exit} Callback (code, signal, client_id) - invoked on client exit. - • code: exit code of the process - • signal: number describing the - signal used to terminate (if any) - • client_id: client handle - {on_attach} Callback (client, bufnr) invoked when - client attaches to a buffer. - {trace} "off" | "messages" | "verbose" | nil - passed directly to the language - server in the initialize request. - Invalid/empty values will default to - "off" - {flags} A table with flags for the client. - The current (experimental) flags are: - • allow_incremental_sync (bool, - default true): Allow using - incremental sync for buffer edits - • debounce_text_changes (number, - default 150): Debounce didChange - notifications to the server by the - given number in milliseconds. No - debounce occurs if nil - • exit_timeout (number, default 500): - Milliseconds to wait for server to - exit cleanly after sending the - 'shutdown' request before sending - kill -15. If set to false, nvim - exits immediately after sending the - 'shutdown' request to the server. - {root_dir} (string) Directory where the LSP - server will base its - workspaceFolders, rootUri, and - rootPath on initialization. - - Return: ~ - Client id. |vim.lsp.get_client_by_id()| Note: client may - not be fully initialized. Use `on_init` to do any actions - once the client has been initialized. + {detached} (boolean, default true) Daemonize the server + process so that it runs in a separate process + group from Nvim. Nvim will shutdown the process + on exit, but if Nvim fails to exit cleanly this + could leave behind orphaned server processes. + {workspace_folders} (table) List of workspace folders passed to the + language server. For backwards compatibility + rootUri and rootPath will be derived from the + first workspace folder in this list. See + `workspaceFolders` in the LSP spec. + {capabilities} Map overriding the default capabilities defined + by |vim.lsp.protocol.make_client_capabilities()|, + passed to the language server on initialization. + Hint: use make_client_capabilities() and modify + its result. + • Note: To send an empty dictionary use + `{[vim.type_idx]=vim.types.dictionary}`, else + it will be encoded as an array. + {handlers} Map of language server method names to + |lsp-handler| + {settings} Map with language server specific settings. These + are returned to the language server if requested + via `workspace/configuration`. Keys are + case-sensitive. + {commands} (table) Table that maps string of clientside + commands to user-defined functions. Commands + passed to start_client take precedence over the + global command registry. Each key must be a + unique command name, and the value is a function + which is called if any LSP action (code action, + code lenses, ...) triggers the command. + {init_options} Values to pass in the initialization request as + `initializationOptions`. See `initialize` in the + LSP spec. + {name} (string, default=client-id) Name in log messages. + {get_language_id} function(bufnr, filetype) -> language ID as + string. Defaults to the filetype. + {offset_encoding} (default="utf-16") One of "utf-8", "utf-16", or + "utf-32" which is the encoding that the LSP + server expects. Client does not verify this is + correct. + {on_error} Callback with parameters (code, ...), invoked + when the client operation throws an error. `code` + is a number describing the error. Other arguments + may be passed depending on the error kind. See + |vim.lsp.rpc.client_errors| for possible errors. + Use `vim.lsp.rpc.client_errors[code]` to get + human-friendly name. + {before_init} Callback with parameters (initialize_params, + config) invoked before the LSP "initialize" + phase, where `params` contains the parameters + being sent to the server and `config` is the + config that was passed to + |vim.lsp.start_client()|. You can use this to + modify parameters before they are sent. + {on_init} Callback (client, initialize_result) invoked + after LSP "initialize", where `result` is a table + of `capabilities` and anything else the server + may send. For example, clangd sends + `initialize_result.offsetEncoding` if + `capabilities.offsetEncoding` was sent to it. You + can only modify the `client.offset_encoding` here + before any notifications are sent. Most language + servers expect to be sent client specified + settings after initialization. Neovim does not + make this assumption. A + `workspace/didChangeConfiguration` notification + should be sent to the server during on_init. + {on_exit} Callback (code, signal, client_id) invoked on + client exit. + • code: exit code of the process + • signal: number describing the signal used to + terminate (if any) + • client_id: client handle + {on_attach} Callback (client, bufnr) invoked when client + attaches to a buffer. + {trace} "off" | "messages" | "verbose" | nil passed + directly to the language server in the initialize + request. Invalid/empty values will default to + "off" + {flags} A table with flags for the client. The current + (experimental) flags are: + • allow_incremental_sync (bool, default true): + Allow using incremental sync for buffer edits + • debounce_text_changes (number, default 150): + Debounce didChange notifications to the server + by the given number in milliseconds. No + debounce occurs if nil + • exit_timeout (number|boolean, default false): + Milliseconds to wait for server to exit cleanly + after sending the 'shutdown' request before + sending kill -15. If set to false, nvim exits + immediately after sending the 'shutdown' + request to the server. + {root_dir} (string) Directory where the LSP server will base + its workspaceFolders, rootUri, and rootPath on + initialization. + + Return: ~ + Client id. |vim.lsp.get_client_by_id()| Note: client may not be fully + initialized. Use `on_init` to do any actions once the client has been + initialized. stop_client({client_id}, {force}) *vim.lsp.stop_client()* - Stops a client(s). + Stops a client(s). - You can also use the `stop()` function on a |vim.lsp.client| - object. To stop all clients: + You can also use the `stop()` function on a |vim.lsp.client| object. To + stop all clients: > vim.lsp.stop_client(vim.lsp.get_active_clients()) < - By default asks the server to shutdown, unless stop was - requested already for this client, then force-shutdown is - attempted. + By default asks the server to shutdown, unless stop was requested already + for this client, then force-shutdown is attempted. - Parameters: ~ - {client_id} client id or |vim.lsp.client| object, or list - thereof - {force} (boolean) (optional) shutdown forcefully + Parameters: ~ + {client_id} client id or |vim.lsp.client| object, or list thereof + {force} (boolean) (optional) shutdown forcefully tagfunc({...}) *vim.lsp.tagfunc()* - Provides an interface between the built-in client and - 'tagfunc'. + Provides an interface between the built-in client and 'tagfunc'. - When used with normal mode commands (e.g. |CTRL-]|) this will - invoke the "textDocument/definition" LSP method to find the - tag under the cursor. Otherwise, uses "workspace/symbol". If - no results are returned from any LSP servers, falls back to - using built-in tags. + When used with normal mode commands (e.g. |CTRL-]|) this will invoke the + "textDocument/definition" LSP method to find the tag under the cursor. + Otherwise, uses "workspace/symbol". If no results are returned from any + LSP servers, falls back to using built-in tags. - Parameters: ~ - {pattern} Pattern used to find a workspace symbol - {flags} See |tag-function| + Parameters: ~ + {pattern} Pattern used to find a workspace symbol + {flags} See |tag-function| - Return: ~ - A list of matching tags + Return: ~ + A list of matching tags with({handler}, {override_config}) *vim.lsp.with()* - Function to manage overriding defaults for LSP handlers. + Function to manage overriding defaults for LSP handlers. - Parameters: ~ - {handler} (function) See |lsp-handler| - {override_config} (table) Table containing the keys to - override behavior of the {handler} + Parameters: ~ + {handler} (function) See |lsp-handler| + {override_config} (table) Table containing the keys to override + behavior of the {handler} ============================================================================== @@ -1082,471 +996,432 @@ Lua module: vim.lsp.buf *lsp-buf* *vim.lsp.buf.add_workspace_folder()* add_workspace_folder({workspace_folder}) - Add the folder at path to the workspace folders. If {path} is - not provided, the user will be prompted for a path using - |input()|. + Add the folder at path to the workspace folders. If {path} is not + provided, the user will be prompted for a path using |input()|. clear_references() *vim.lsp.buf.clear_references()* - Removes document highlights from current buffer. + Removes document highlights from current buffer. code_action({options}) *vim.lsp.buf.code_action()* - Selects a code action available at the current cursor - position. - - Parameters: ~ - {options} (table|nil) Optional table which holds the - following optional fields: - • context: (table|nil) Corresponds to `CodeActionContext` of the LSP specification: - • diagnostics (table|nil): LSP`Diagnostic[]` . Inferred from the current position if not - provided. - • only (table|nil): List of LSP - `CodeActionKind`s used to filter the code - actions. Most language servers support - values like `refactor` or `quickfix`. - - • filter: (function|nil) Predicate taking an - `CodeAction` and returning a boolean. - • apply: (boolean|nil) When set to `true`, and - there is just one remaining action (after - filtering), the action is applied without - user query. - • range: (table|nil) Range for which code - actions should be requested. If in visual - mode this defaults to the active selection. - Table must contain `start` and `end` keys - with {row, col} tuples using mark-like - indexing. See |api-indexing| - - See also: ~ - https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_codeAction + Selects a code action available at the current cursor position. + + Parameters: ~ + {options} (table|nil) Optional table which holds the following + optional fields: + • context: (table|nil) Corresponds to `CodeActionContext` of the LSP specification: + • diagnostics (table|nil): LSP`Diagnostic[]` . Inferred from the current position if not provided. + • only (table|nil): List of LSP `CodeActionKind`s used to + filter the code actions. Most language servers support + values like `refactor` or `quickfix`. + + • filter: (function|nil) Predicate taking an `CodeAction` + and returning a boolean. + • apply: (boolean|nil) When set to `true`, and there is + just one remaining action (after filtering), the action + is applied without user query. + • range: (table|nil) Range for which code actions should be + requested. If in visual mode this defaults to the active + selection. Table must contain `start` and `end` keys with + {row, col} tuples using mark-like indexing. See + |api-indexing| + + See also: ~ + https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_codeAction completion({context}) *vim.lsp.buf.completion()* - Retrieves the completion items at the current cursor position. - Can only be called in Insert mode. + Retrieves the completion items at the current cursor position. Can only be + called in Insert mode. - Parameters: ~ - {context} (context support not yet implemented) - Additional information about the context in - which a completion was triggered (how it was - triggered, and by which trigger character, if - applicable) + Parameters: ~ + {context} (context support not yet implemented) Additional + information about the context in which a completion was + triggered (how it was triggered, and by which trigger + character, if applicable) - See also: ~ - |vim.lsp.protocol.constants.CompletionTriggerKind| + See also: ~ + |vim.lsp.protocol.constants.CompletionTriggerKind| declaration({options}) *vim.lsp.buf.declaration()* - Jumps to the declaration of the symbol under the cursor. - Note: - Many servers do not implement this method. Generally, see - |vim.lsp.buf.definition()| instead. - - Parameters: ~ - {options} (table|nil) additional options - • reuse_win: (boolean) Jump to existing window - if buffer is already open. - • on_list: (function) handler for list results. - See |on-list-handler| + Jumps to the declaration of the symbol under the cursor. + Note: + Many servers do not implement this method. Generally, see + |vim.lsp.buf.definition()| instead. + + Parameters: ~ + {options} (table|nil) additional options + • reuse_win: (boolean) Jump to existing window if buffer is + already open. + • on_list: (function) handler for list results. See + |lsp-on-list-handler| definition({options}) *vim.lsp.buf.definition()* - Jumps to the definition of the symbol under the cursor. + Jumps to the definition of the symbol under the cursor. - Parameters: ~ - {options} (table|nil) additional options - • reuse_win: (boolean) Jump to existing window - if buffer is already open. - • on_list: (function) handler for list results. - See |on-list-handler| + Parameters: ~ + {options} (table|nil) additional options + • reuse_win: (boolean) Jump to existing window if buffer is + already open. + • on_list: (function) handler for list results. See + |lsp-on-list-handler| document_highlight() *vim.lsp.buf.document_highlight()* - Send request to the server to resolve document highlights for - the current text document position. This request can be - triggered by a key mapping or by events such as `CursorHold`, - e.g.: + Send request to the server to resolve document highlights for the current + text document position. This request can be triggered by a key mapping or + by events such as `CursorHold`, e.g.: > autocmd CursorHold <buffer> lua vim.lsp.buf.document_highlight() autocmd CursorHoldI <buffer> lua vim.lsp.buf.document_highlight() autocmd CursorMoved <buffer> lua vim.lsp.buf.clear_references() < - Note: Usage of |vim.lsp.buf.document_highlight()| requires the - following highlight groups to be defined or you won't be able - to see the actual highlights. |LspReferenceText| - |LspReferenceRead| |LspReferenceWrite| + Note: Usage of |vim.lsp.buf.document_highlight()| requires the following + highlight groups to be defined or you won't be able to see the actual + highlights. |LspReferenceText| |LspReferenceRead| |LspReferenceWrite| document_symbol({options}) *vim.lsp.buf.document_symbol()* - Lists all symbols in the current buffer in the quickfix - window. + Lists all symbols in the current buffer in the quickfix window. - Parameters: ~ - {options} (table|nil) additional options - • on_list: (function) handler for list results. - See |on-list-handler| + Parameters: ~ + {options} (table|nil) additional options + • on_list: (function) handler for list results. See + |lsp-on-list-handler| execute_command({command_params}) *vim.lsp.buf.execute_command()* - Executes an LSP server command. + Executes an LSP server command. - Parameters: ~ - {command_params} (table) A valid `ExecuteCommandParams` - object + Parameters: ~ + {command_params} (table) A valid `ExecuteCommandParams` object - See also: ~ - https://microsoft.github.io/language-server-protocol/specifications/specification-current/#workspace_executeCommand + See also: ~ + https://microsoft.github.io/language-server-protocol/specifications/specification-current/#workspace_executeCommand format({options}) *vim.lsp.buf.format()* - Formats a buffer using the attached (and optionally filtered) - language server clients. - - Parameters: ~ - {options} table|nil Optional table which holds the - following optional fields: - • formatting_options (table|nil): Can be used - to specify FormattingOptions. Some - unspecified options will be automatically - derived from the current Neovim options. See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#formattingOptions - • timeout_ms (integer|nil, default 1000): Time - in milliseconds to block for formatting - requests. No effect if async=true - • bufnr (number|nil): Restrict formatting to - the clients attached to the given buffer, - defaults to the current buffer (0). - • filter (function|nil): Predicate used to - filter clients. Receives a client as argument - and must return a boolean. Clients matching - the predicate are included. Example: • > - - -- Never request typescript-language-server for formatting - vim.lsp.buf.format { - filter = function(client) return client.name ~= "tsserver" end - } + Formats a buffer using the attached (and optionally filtered) language + server clients. + + Parameters: ~ + {options} table|nil Optional table which holds the following optional + fields: + • formatting_options (table|nil): Can be used to specify + FormattingOptions. Some unspecified options will be + automatically derived from the current Neovim options. + See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#formattingOptions + • timeout_ms (integer|nil, default 1000): Time in + milliseconds to block for formatting requests. No effect + if async=true + • bufnr (number|nil): Restrict formatting to the clients + attached to the given buffer, defaults to the current + buffer (0). + • filter (function|nil): Predicate used to filter clients. + Receives a client as argument and must return a boolean. + Clients matching the predicate are included. Example: • > + + -- Never request typescript-language-server for formatting + vim.lsp.buf.format { + filter = function(client) return client.name ~= "tsserver" end + } < - • async boolean|nil If true the method won't - block. Defaults to false. Editing the buffer - while formatting asynchronous can lead to - unexpected changes. - • id (number|nil): Restrict formatting to the - client with ID (client.id) matching this - field. - • name (string|nil): Restrict formatting to the - client with name (client.name) matching this - field. + • async boolean|nil If true the method won't block. + Defaults to false. Editing the buffer while formatting + asynchronous can lead to unexpected changes. + • id (number|nil): Restrict formatting to the client with + ID (client.id) matching this field. + • name (string|nil): Restrict formatting to the client with + name (client.name) matching this field. formatting({options}) *vim.lsp.buf.formatting()* - Formats the current buffer. + Formats the current buffer. - Parameters: ~ - {options} (table|nil) Can be used to specify - FormattingOptions. Some unspecified options - will be automatically derived from the current - Neovim options. + Parameters: ~ + {options} (table|nil) Can be used to specify FormattingOptions. Some + unspecified options will be automatically derived from the + current Neovim options. - See also: ~ - https://microsoft.github.io/language-server-protocol/specification#textDocument_formatting + See also: ~ + https://microsoft.github.io/language-server-protocol/specification#textDocument_formatting *vim.lsp.buf.formatting_seq_sync()* formatting_seq_sync({options}, {timeout_ms}, {order}) - Formats the current buffer by sequentially requesting - formatting from attached clients. + Formats the current buffer by sequentially requesting formatting from + attached clients. - Useful when multiple clients with formatting capability are - attached. + Useful when multiple clients with formatting capability are attached. - Since it's synchronous, can be used for running on save, to - make sure buffer is formatted prior to being saved. - {timeout_ms} is passed on to the |vim.lsp.client| `request_sync` method. Example: > + Since it's synchronous, can be used for running on save, to make sure + buffer is formatted prior to being saved. {timeout_ms} is passed on to the + |vim.lsp.client| `request_sync` method. Example: > - vim.api.nvim_command[[autocmd BufWritePre <buffer> lua vim.lsp.buf.formatting_seq_sync()]] + vim.api.nvim_command[[autocmd BufWritePre <buffer> lua vim.lsp.buf.formatting_seq_sync()]] < - Parameters: ~ - {options} (table|nil) `FormattingOptions` entries - {timeout_ms} (number|nil) Request timeout - {order} (table|nil) List of client names. Formatting - is requested from clients in the following - order: first all clients that are not in the - `order` list, then the remaining clients in - the order as they occur in the `order` list. + Parameters: ~ + {options} (table|nil) `FormattingOptions` entries + {timeout_ms} (number|nil) Request timeout + {order} (table|nil) List of client names. Formatting is + requested from clients in the following order: first all + clients that are not in the `order` list, then the + remaining clients in the order as they occur in the + `order` list. *vim.lsp.buf.formatting_sync()* formatting_sync({options}, {timeout_ms}) - Performs |vim.lsp.buf.formatting()| synchronously. + Performs |vim.lsp.buf.formatting()| synchronously. - Useful for running on save, to make sure buffer is formatted - prior to being saved. {timeout_ms} is passed on to - |vim.lsp.buf_request_sync()|. Example: + Useful for running on save, to make sure buffer is formatted prior to + being saved. {timeout_ms} is passed on to |vim.lsp.buf_request_sync()|. + Example: > autocmd BufWritePre <buffer> lua vim.lsp.buf.formatting_sync() < - Parameters: ~ - {options} (table|nil) with valid `FormattingOptions` - entries - {timeout_ms} (number) Request timeout + Parameters: ~ + {options} (table|nil) with valid `FormattingOptions` entries + {timeout_ms} (number) Request timeout - See also: ~ - |vim.lsp.buf.formatting_seq_sync| + See also: ~ + |vim.lsp.buf.formatting_seq_sync| hover() *vim.lsp.buf.hover()* - Displays hover information about the symbol under the cursor - in a floating window. Calling the function twice will jump - into the floating window. + Displays hover information about the symbol under the cursor in a floating + window. Calling the function twice will jump into the floating window. implementation({options}) *vim.lsp.buf.implementation()* - Lists all the implementations for the symbol under the cursor - in the quickfix window. + Lists all the implementations for the symbol under the cursor in the + quickfix window. - Parameters: ~ - {options} (table|nil) additional options - • on_list: (function) handler for list results. - See |on-list-handler| + Parameters: ~ + {options} (table|nil) additional options + • on_list: (function) handler for list results. See + |lsp-on-list-handler| incoming_calls() *vim.lsp.buf.incoming_calls()* - Lists all the call sites of the symbol under the cursor in the - |quickfix| window. If the symbol can resolve to multiple - items, the user can pick one in the |inputlist|. + Lists all the call sites of the symbol under the cursor in the |quickfix| + window. If the symbol can resolve to multiple items, the user can pick one + in the |inputlist|. list_workspace_folders() *vim.lsp.buf.list_workspace_folders()* - List workspace folders. + List workspace folders. outgoing_calls() *vim.lsp.buf.outgoing_calls()* - Lists all the items that are called by the symbol under the - cursor in the |quickfix| window. If the symbol can resolve to - multiple items, the user can pick one in the |inputlist|. + Lists all the items that are called by the symbol under the cursor in the + |quickfix| window. If the symbol can resolve to multiple items, the user + can pick one in the |inputlist|. *vim.lsp.buf.range_code_action()* range_code_action({context}, {start_pos}, {end_pos}) - Performs |vim.lsp.buf.code_action()| for a given range. - - Parameters: ~ - {context} (table|nil) `CodeActionContext` of the LSP specification: - • diagnostics: (table|nil) LSP`Diagnostic[]` . Inferred from the current position if not - provided. - • only: (table|nil) List of LSP - `CodeActionKind`s used to filter the code - actions. Most language servers support - values like `refactor` or `quickfix`. - {start_pos} ({number, number}, optional) mark-indexed - position. Defaults to the start of the last - visual selection. - {end_pos} ({number, number}, optional) mark-indexed - position. Defaults to the end of the last - visual selection. + Performs |vim.lsp.buf.code_action()| for a given range. + + Parameters: ~ + {context} (table|nil) `CodeActionContext` of the LSP specification: + • diagnostics: (table|nil) LSP`Diagnostic[]` . Inferred from the current position if not provided. + • only: (table|nil) List of LSP `CodeActionKind`s used to + filter the code actions. Most language servers support + values like `refactor` or `quickfix`. + {start_pos} ({number, number}, optional) mark-indexed position. + Defaults to the start of the last visual selection. + {end_pos} ({number, number}, optional) mark-indexed position. + Defaults to the end of the last visual selection. *vim.lsp.buf.range_formatting()* range_formatting({options}, {start_pos}, {end_pos}) - Formats a given range. + Formats a given range. - Parameters: ~ - {options} Table with valid `FormattingOptions` entries. - {start_pos} ({number, number}, optional) mark-indexed - position. Defaults to the start of the last - visual selection. - {end_pos} ({number, number}, optional) mark-indexed - position. Defaults to the end of the last - visual selection. + Parameters: ~ + {options} Table with valid `FormattingOptions` entries. + {start_pos} ({number, number}, optional) mark-indexed position. + Defaults to the start of the last visual selection. + {end_pos} ({number, number}, optional) mark-indexed position. + Defaults to the end of the last visual selection. references({context}, {options}) *vim.lsp.buf.references()* - Lists all the references to the symbol under the cursor in the - quickfix window. + Lists all the references to the symbol under the cursor in the quickfix + window. - Parameters: ~ - {context} (table) Context for the request - {options} (table|nil) additional options - • on_list: (function) handler for list results. - See |on-list-handler| + Parameters: ~ + {context} (table) Context for the request + {options} (table|nil) additional options + • on_list: (function) handler for list results. See + |lsp-on-list-handler| - See also: ~ - https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_references + See also: ~ + https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_references *vim.lsp.buf.remove_workspace_folder()* remove_workspace_folder({workspace_folder}) - Remove the folder at path from the workspace folders. If - {path} is not provided, the user will be prompted for a path - using |input()|. + Remove the folder at path from the workspace folders. If {path} is not + provided, the user will be prompted for a path using |input()|. rename({new_name}, {options}) *vim.lsp.buf.rename()* - Renames all references to the symbol under the cursor. - - Parameters: ~ - {new_name} (string|nil) If not provided, the user will be - prompted for a new name using - |vim.ui.input()|. - {options} (table|nil) additional options - • filter (function|nil): Predicate used to - filter clients. Receives a client as - argument and must return a boolean. Clients - matching the predicate are included. - • name (string|nil): Restrict clients used for - rename to ones where client.name matches - this field. + Renames all references to the symbol under the cursor. + + Parameters: ~ + {new_name} (string|nil) If not provided, the user will be prompted + for a new name using |vim.ui.input()|. + {options} (table|nil) additional options + • filter (function|nil): Predicate used to filter clients. + Receives a client as argument and must return a boolean. + Clients matching the predicate are included. + • name (string|nil): Restrict clients used for rename to + ones where client.name matches this field. server_ready() *vim.lsp.buf.server_ready()* - Checks whether the language servers attached to the current - buffer are ready. + Checks whether the language servers attached to the current buffer are + ready. - Return: ~ - `true` if server responds. + Return: ~ + `true` if server responds. signature_help() *vim.lsp.buf.signature_help()* - Displays signature information about the symbol under the - cursor in a floating window. + Displays signature information about the symbol under the cursor in a + floating window. type_definition({options}) *vim.lsp.buf.type_definition()* - Jumps to the definition of the type of the symbol under the - cursor. + Jumps to the definition of the type of the symbol under the cursor. - Parameters: ~ - {options} (table|nil) additional options - • reuse_win: (boolean) Jump to existing window - if buffer is already open. - • on_list: (function) handler for list results. - See |on-list-handler| + Parameters: ~ + {options} (table|nil) additional options + • reuse_win: (boolean) Jump to existing window if buffer is + already open. + • on_list: (function) handler for list results. See + |lsp-on-list-handler| workspace_symbol({query}, {options}) *vim.lsp.buf.workspace_symbol()* - Lists all symbols in the current workspace in the quickfix - window. + Lists all symbols in the current workspace in the quickfix window. - The list is filtered against {query}; if the argument is - omitted from the call, the user is prompted to enter a string - on the command line. An empty string means no filtering is - done. + The list is filtered against {query}; if the argument is omitted from the + call, the user is prompted to enter a string on the command line. An empty + string means no filtering is done. - Parameters: ~ - {query} (string, optional) - {options} (table|nil) additional options - • on_list: (function) handler for list results. - See |on-list-handler| + Parameters: ~ + {query} (string, optional) + {options} (table|nil) additional options + • on_list: (function) handler for list results. See + |lsp-on-list-handler| ============================================================================== Lua module: vim.lsp.diagnostic *lsp-diagnostic* get_namespace({client_id}) *vim.lsp.diagnostic.get_namespace()* - Get the diagnostic namespace associated with an LSP client - |vim.diagnostic|. + Get the diagnostic namespace associated with an LSP client + |vim.diagnostic|. - Parameters: ~ - {client_id} (number) The id of the LSP client + Parameters: ~ + {client_id} (number) The id of the LSP client *vim.lsp.diagnostic.on_publish_diagnostics()* on_publish_diagnostics({_}, {result}, {ctx}, {config}) - |lsp-handler| for the method "textDocument/publishDiagnostics" - - See |vim.diagnostic.config()| for configuration options. - Handler-specific configuration can be set using - |vim.lsp.with()|: > - - vim.lsp.handlers["textDocument/publishDiagnostics"] = vim.lsp.with( - vim.lsp.diagnostic.on_publish_diagnostics, { - -- Enable underline, use default values - underline = true, - -- Enable virtual text, override spacing to 4 - virtual_text = { - spacing = 4, - }, - -- Use a function to dynamically turn signs off - -- and on, using buffer local variables - signs = function(namespace, bufnr) - return vim.b[bufnr].show_signs == true - end, - -- Disable a feature - update_in_insert = false, - } - ) + |lsp-handler| for the method "textDocument/publishDiagnostics" + + See |vim.diagnostic.config()| for configuration options. Handler-specific + configuration can be set using |vim.lsp.with()|: > + + vim.lsp.handlers["textDocument/publishDiagnostics"] = vim.lsp.with( + vim.lsp.diagnostic.on_publish_diagnostics, { + -- Enable underline, use default values + underline = true, + -- Enable virtual text, override spacing to 4 + virtual_text = { + spacing = 4, + }, + -- Use a function to dynamically turn signs off + -- and on, using buffer local variables + signs = function(namespace, bufnr) + return vim.b[bufnr].show_signs == true + end, + -- Disable a feature + update_in_insert = false, + } + ) < - Parameters: ~ - {config} (table) Configuration table (see - |vim.diagnostic.config()|). + Parameters: ~ + {config} (table) Configuration table (see |vim.diagnostic.config()|). ============================================================================== Lua module: vim.lsp.codelens *lsp-codelens* display({lenses}, {bufnr}, {client_id}) *vim.lsp.codelens.display()* - Display the lenses using virtual text + Display the lenses using virtual text - Parameters: ~ - {lenses} (table) of lenses to display (`CodeLens[] | - null`) - {bufnr} (number) - {client_id} (number) + Parameters: ~ + {lenses} (table) of lenses to display (`CodeLens[] | null`) + {bufnr} (number) + {client_id} (number) get({bufnr}) *vim.lsp.codelens.get()* - Return all lenses for the given buffer + Return all lenses for the given buffer - Parameters: ~ - {bufnr} (number) Buffer number. 0 can be used for the - current buffer. + Parameters: ~ + {bufnr} (number) Buffer number. 0 can be used for the current buffer. - Return: ~ - (table) (`CodeLens[]`) + Return: ~ + (table) (`CodeLens[]`) *vim.lsp.codelens.on_codelens()* on_codelens({err}, {result}, {ctx}, {_}) - |lsp-handler| for the method `textDocument/codeLens` + |lsp-handler| for the method `textDocument/codeLens` refresh() *vim.lsp.codelens.refresh()* - Refresh the codelens for the current buffer + Refresh the codelens for the current buffer - It is recommended to trigger this using an autocmd or via - keymap. + It is recommended to trigger this using an autocmd or via keymap. > autocmd BufEnter,CursorHold,InsertLeave <buffer> lua vim.lsp.codelens.refresh() < run() *vim.lsp.codelens.run()* - Run the code lens in the current line + Run the code lens in the current line save({lenses}, {bufnr}, {client_id}) *vim.lsp.codelens.save()* - Store lenses for a specific buffer and client + Store lenses for a specific buffer and client - Parameters: ~ - {lenses} (table) of lenses to store (`CodeLens[] | - null`) - {bufnr} (number) - {client_id} (number) + Parameters: ~ + {lenses} (table) of lenses to store (`CodeLens[] | null`) + {bufnr} (number) + {client_id} (number) ============================================================================== Lua module: vim.lsp.handlers *lsp-handlers* hover({_}, {result}, {ctx}, {config}) *vim.lsp.handlers.hover()* - |lsp-handler| for the method "textDocument/hover" > - - vim.lsp.handlers["textDocument/hover"] = vim.lsp.with( - vim.lsp.handlers.hover, { - -- Use a sharp border with `FloatBorder` highlights - border = "single" - } - ) + |lsp-handler| for the method "textDocument/hover" > + + vim.lsp.handlers["textDocument/hover"] = vim.lsp.with( + vim.lsp.handlers.hover, { + -- Use a sharp border with `FloatBorder` highlights + border = "single" + } + ) < - Parameters: ~ - {config} (table) Configuration table. - • border: (default=nil) - • Add borders to the floating window - • See |nvim_open_win()| + Parameters: ~ + {config} (table) Configuration table. + • border: (default=nil) + • Add borders to the floating window + • See |nvim_open_win()| *vim.lsp.handlers.signature_help()* signature_help({_}, {result}, {ctx}, {config}) - |lsp-handler| for the method "textDocument/signatureHelp". The - active parameter is highlighted with - |hl-LspSignatureActiveParameter|. > - - vim.lsp.handlers["textDocument/signatureHelp"] = vim.lsp.with( - vim.lsp.handlers.signature_help, { - -- Use a sharp border with `FloatBorder` highlights - border = "single" - } - ) + |lsp-handler| for the method "textDocument/signatureHelp". The active + parameter is highlighted with |hl-LspSignatureActiveParameter|. > + + vim.lsp.handlers["textDocument/signatureHelp"] = vim.lsp.with( + vim.lsp.handlers.signature_help, { + -- Use a sharp border with `FloatBorder` highlights + border = "single" + } + ) < - Parameters: ~ - {config} (table) Configuration table. - • border: (default=nil) - • Add borders to the floating window - • See |vim.api.nvim_open_win()| + Parameters: ~ + {config} (table) Configuration table. + • border: (default=nil) + • Add borders to the floating window + • See |vim.api.nvim_open_win()| ============================================================================== @@ -1554,591 +1429,544 @@ Lua module: vim.lsp.util *lsp-util* *vim.lsp.util.apply_text_document_edit()* apply_text_document_edit({text_document_edit}, {index}, {offset_encoding}) - Applies a `TextDocumentEdit`, which is a list of changes to a - single document. + Applies a `TextDocumentEdit`, which is a list of changes to a single + document. - Parameters: ~ - {text_document_edit} table: a `TextDocumentEdit` object - {index} number: Optional index of the edit, - if from a list of edits (or nil, if - not from a list) + Parameters: ~ + {text_document_edit} table: a `TextDocumentEdit` object + {index} number: Optional index of the edit, if from a + list of edits (or nil, if not from a list) - See also: ~ - https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocumentEdit + See also: ~ + https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocumentEdit *vim.lsp.util.apply_text_edits()* apply_text_edits({text_edits}, {bufnr}, {offset_encoding}) - Applies a list of text edits to a buffer. + Applies a list of text edits to a buffer. - Parameters: ~ - {text_edits} (table) list of `TextEdit` objects - {bufnr} (number) Buffer id - {offset_encoding} (string) utf-8|utf-16|utf-32 + Parameters: ~ + {text_edits} (table) list of `TextEdit` objects + {bufnr} (number) Buffer id + {offset_encoding} (string) utf-8|utf-16|utf-32 - See also: ~ - https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textEdit + See also: ~ + https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textEdit *vim.lsp.util.apply_workspace_edit()* apply_workspace_edit({workspace_edit}, {offset_encoding}) - Applies a `WorkspaceEdit`. + Applies a `WorkspaceEdit`. - Parameters: ~ - {workspace_edit} (table) `WorkspaceEdit` - {offset_encoding} (string) utf-8|utf-16|utf-32 (required) + Parameters: ~ + {workspace_edit} (table) `WorkspaceEdit` + {offset_encoding} (string) utf-8|utf-16|utf-32 (required) buf_clear_references({bufnr}) *vim.lsp.util.buf_clear_references()* - Removes document highlights from a buffer. + Removes document highlights from a buffer. - Parameters: ~ - {bufnr} (number) Buffer id + Parameters: ~ + {bufnr} (number) Buffer id *vim.lsp.util.buf_highlight_references()* buf_highlight_references({bufnr}, {references}, {offset_encoding}) - Shows a list of document highlights for a certain buffer. + Shows a list of document highlights for a certain buffer. - Parameters: ~ - {bufnr} (number) Buffer id - {references} (table) List of `DocumentHighlight` - objects to highlight - {offset_encoding} (string) One of "utf-8", "utf-16", - "utf-32". + Parameters: ~ + {bufnr} (number) Buffer id + {references} (table) List of `DocumentHighlight` objects to + highlight + {offset_encoding} (string) One of "utf-8", "utf-16", "utf-32". - See also: ~ - https://microsoft.github.io/language-server-protocol/specifications/specification-3-17/#documentHighlight + See also: ~ + https://microsoft.github.io/language-server-protocol/specifications/specification-3-17/#documentHighlight *vim.lsp.util.character_offset()* character_offset({buf}, {row}, {col}, {offset_encoding}) - Returns the UTF-32 and UTF-16 offsets for a position in a - certain buffer. + Returns the UTF-32 and UTF-16 offsets for a position in a certain buffer. - Parameters: ~ - {buf} (number) buffer number (0 for current) - {row} 0-indexed line - {col} 0-indexed byte offset in line - {offset_encoding} (string) utf-8|utf-16|utf-32|nil - defaults to `offset_encoding` of first - client of `buf` + Parameters: ~ + {buf} (number) buffer number (0 for current) + {row} 0-indexed line + {col} 0-indexed byte offset in line + {offset_encoding} (string) utf-8|utf-16|utf-32|nil defaults to + `offset_encoding` of first client of `buf` - Return: ~ - (number, number) `offset_encoding` index of the character - in line {row} column {col} in buffer {buf} + Return: ~ + (number, number) `offset_encoding` index of the character in line + {row} column {col} in buffer {buf} *vim.lsp.util.convert_input_to_markdown_lines()* convert_input_to_markdown_lines({input}, {contents}) - Converts any of `MarkedString` | `MarkedString[]` | - `MarkupContent` into a list of lines containing valid - markdown. Useful to populate the hover window for - `textDocument/hover`, for parsing the result of - `textDocument/signatureHelp`, and potentially others. + Converts any of `MarkedString` | `MarkedString[]` | `MarkupContent` into a + list of lines containing valid markdown. Useful to populate the hover + window for `textDocument/hover`, for parsing the result of + `textDocument/signatureHelp`, and potentially others. - Parameters: ~ - {input} (`MarkedString` | `MarkedString[]` | - `MarkupContent`) - {contents} (table, optional, default `{}`) List of - strings to extend with converted lines + Parameters: ~ + {input} (`MarkedString` | `MarkedString[]` | `MarkupContent`) + {contents} (table, optional, default `{}`) List of strings to extend + with converted lines - Return: ~ - {contents}, extended with lines of converted markdown. + Return: ~ + {contents}, extended with lines of converted markdown. - See also: ~ - https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_hover + See also: ~ + https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_hover *vim.lsp.util.convert_signature_help_to_markdown_lines()* convert_signature_help_to_markdown_lines({signature_help}, {ft}, {triggers}) - Converts `textDocument/SignatureHelp` response to markdown - lines. + Converts `textDocument/SignatureHelp` response to markdown lines. - Parameters: ~ - {signature_help} Response of `textDocument/SignatureHelp` - {ft} optional filetype that will be use as - the `lang` for the label markdown code - block - {triggers} optional list of trigger characters from - the lsp server. used to better determine - parameter offsets + Parameters: ~ + {signature_help} Response of `textDocument/SignatureHelp` + {ft} optional filetype that will be use as the `lang` for + the label markdown code block + {triggers} optional list of trigger characters from the lsp + server. used to better determine parameter offsets - Return: ~ - list of lines of converted markdown. + Return: ~ + list of lines of converted markdown. - See also: ~ - https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_signatureHelp + See also: ~ + https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_signatureHelp *vim.lsp.util.extract_completion_items()* extract_completion_items({result}) - Can be used to extract the completion items from a `textDocument/completion` request, which may return one of `CompletionItem[]` , `CompletionList` or null. + Can be used to extract the completion items from a `textDocument/completion` request, which may return one of `CompletionItem[]` , `CompletionList` or null. - Parameters: ~ - {result} (table) The result of a - `textDocument/completion` request + Parameters: ~ + {result} (table) The result of a `textDocument/completion` request - Return: ~ - (table) List of completion items + Return: ~ + (table) List of completion items - See also: ~ - https://microsoft.github.io/language-server-protocol/specification#textDocument_completion + See also: ~ + https://microsoft.github.io/language-server-protocol/specification#textDocument_completion get_effective_tabstop({bufnr}) *vim.lsp.util.get_effective_tabstop()* - Returns indentation size. + Returns indentation size. - Parameters: ~ - {bufnr} (number|nil): Buffer handle, defaults to current + Parameters: ~ + {bufnr} (number|nil): Buffer handle, defaults to current - Return: ~ - (number) indentation size + Return: ~ + (number) indentation size - See also: ~ - |shiftwidth| + See also: ~ + |shiftwidth| *vim.lsp.util.jump_to_location()* jump_to_location({location}, {offset_encoding}, {reuse_win}) - Jumps to a location. + Jumps to a location. - Parameters: ~ - {location} (table) (`Location`|`LocationLink`) - {offset_encoding} (string) utf-8|utf-16|utf-32 (required) - {reuse_win} (boolean) Jump to existing window if - buffer is already opened. + Parameters: ~ + {location} (table) (`Location`|`LocationLink`) + {offset_encoding} (string) utf-8|utf-16|utf-32 (required) + {reuse_win} (boolean) Jump to existing window if buffer is + already opened. - Return: ~ - `true` if the jump succeeded + Return: ~ + `true` if the jump succeeded *vim.lsp.util.locations_to_items()* locations_to_items({locations}, {offset_encoding}) - Returns the items with the byte position calculated correctly - and in sorted order, for display in quickfix and location - lists. + Returns the items with the byte position calculated correctly and in + sorted order, for display in quickfix and location lists. - The result can be passed to the {list} argument of - |setqflist()| or |setloclist()|. + The result can be passed to the {list} argument of |setqflist()| or + |setloclist()|. - Parameters: ~ - {locations} (table) list of `Location`s or - `LocationLink`s - {offset_encoding} (string) offset_encoding for locations - utf-8|utf-16|utf-32 + Parameters: ~ + {locations} (table) list of `Location`s or `LocationLink`s + {offset_encoding} (string) offset_encoding for locations + utf-8|utf-16|utf-32 - Return: ~ - (table) list of items + Return: ~ + (table) list of items lookup_section({settings}, {section}) *vim.lsp.util.lookup_section()* - Helper function to return nested values in language server - settings + Helper function to return nested values in language server settings - Parameters: ~ - {settings} a table of language server settings - {section} a string indicating the field of the settings - table + Parameters: ~ + {settings} a table of language server settings + {section} a string indicating the field of the settings table - Return: ~ - (table or string) The value of settings accessed via - section + Return: ~ + (table or string) The value of settings accessed via section *vim.lsp.util.make_floating_popup_options()* make_floating_popup_options({width}, {height}, {opts}) - Creates a table with sensible default options for a floating - window. The table can be passed to |nvim_open_win()|. - - Parameters: ~ - {width} (number) window width (in character cells) - {height} (number) window height (in character cells) - {opts} (table, optional) - • offset_x (number) offset to add to `col` - • offset_y (number) offset to add to `row` - • border (string or table) override `border` - • focusable (string or table) override - `focusable` - • zindex (string or table) override `zindex`, - defaults to 50 - - Return: ~ - (table) Options + Creates a table with sensible default options for a floating window. The + table can be passed to |nvim_open_win()|. + + Parameters: ~ + {width} (number) window width (in character cells) + {height} (number) window height (in character cells) + {opts} (table, optional) + • offset_x (number) offset to add to `col` + • offset_y (number) offset to add to `row` + • border (string or table) override `border` + • focusable (string or table) override `focusable` + • zindex (string or table) override `zindex`, defaults to 50 + + Return: ~ + (table) Options *vim.lsp.util.make_formatting_params()* make_formatting_params({options}) - Creates a `DocumentFormattingParams` object for the current - buffer and cursor position. + Creates a `DocumentFormattingParams` object for the current buffer and + cursor position. - Parameters: ~ - {options} (table|nil) with valid `FormattingOptions` - entries + Parameters: ~ + {options} (table|nil) with valid `FormattingOptions` entries - Return: ~ - `DocumentFormattingParams` object + Return: ~ + `DocumentFormattingParams` object - See also: ~ - https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_formatting + See also: ~ + https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_formatting *vim.lsp.util.make_given_range_params()* make_given_range_params({start_pos}, {end_pos}, {bufnr}, {offset_encoding}) - Using the given range in the current buffer, creates an object - that is similar to |vim.lsp.util.make_range_params()|. - - Parameters: ~ - {start_pos} number[]|nil {row, col} mark-indexed - position. Defaults to the start of the - last visual selection. - {end_pos} number[]|nil {row, col} mark-indexed - position. Defaults to the end of the - last visual selection. - {bufnr} (number|nil) buffer handle or 0 for - current, defaults to current - {offset_encoding} "utf-8"|"utf-16"|"utf-32"|nil defaults - to `offset_encoding` of first client of - `bufnr` - - Return: ~ - { textDocument = { uri = `current_file_uri` }, range = { - start = `start_position`, end = `end_position` } } + Using the given range in the current buffer, creates an object that is + similar to |vim.lsp.util.make_range_params()|. + + Parameters: ~ + {start_pos} number[]|nil {row, col} mark-indexed position. + Defaults to the start of the last visual selection. + {end_pos} number[]|nil {row, col} mark-indexed position. + Defaults to the end of the last visual selection. + {bufnr} (number|nil) buffer handle or 0 for current, + defaults to current + {offset_encoding} "utf-8"|"utf-16"|"utf-32"|nil defaults to + `offset_encoding` of first client of `bufnr` + + Return: ~ + { textDocument = { uri = `current_file_uri` }, range = { start = + `start_position`, end = `end_position` } } *vim.lsp.util.make_position_params()* make_position_params({window}, {offset_encoding}) - Creates a `TextDocumentPositionParams` object for the current - buffer and cursor position. + Creates a `TextDocumentPositionParams` object for the current buffer and + cursor position. - Parameters: ~ - {window} number|nil: window handle or 0 for - current, defaults to current - {offset_encoding} (string) utf-8|utf-16|utf-32|nil - defaults to `offset_encoding` of first - client of buffer of `window` + Parameters: ~ + {window} number|nil: window handle or 0 for current, + defaults to current + {offset_encoding} (string) utf-8|utf-16|utf-32|nil defaults to + `offset_encoding` of first client of buffer of + `window` - Return: ~ - `TextDocumentPositionParams` object + Return: ~ + `TextDocumentPositionParams` object - See also: ~ - https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocumentPositionParams + See also: ~ + https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocumentPositionParams *vim.lsp.util.make_range_params()* make_range_params({window}, {offset_encoding}) - Using the current position in the current buffer, creates an - object that can be used as a building block for several LSP - requests, such as `textDocument/codeAction`, - `textDocument/colorPresentation`, - `textDocument/rangeFormatting`. - - Parameters: ~ - {window} number|nil: window handle or 0 for - current, defaults to current - {offset_encoding} "utf-8"|"utf-16"|"utf-32"|nil defaults - to `offset_encoding` of first client of - buffer of `window` - - Return: ~ - { textDocument = { uri = `current_file_uri` }, range = { - start = `current_position`, end = `current_position` } } + Using the current position in the current buffer, creates an object that + can be used as a building block for several LSP requests, such as + `textDocument/codeAction`, `textDocument/colorPresentation`, + `textDocument/rangeFormatting`. + + Parameters: ~ + {window} number|nil: window handle or 0 for current, + defaults to current + {offset_encoding} "utf-8"|"utf-16"|"utf-32"|nil defaults to + `offset_encoding` of first client of buffer of + `window` + + Return: ~ + { textDocument = { uri = `current_file_uri` }, range = { start = + `current_position`, end = `current_position` } } *vim.lsp.util.make_text_document_params()* make_text_document_params({bufnr}) - Creates a `TextDocumentIdentifier` object for the current - buffer. + Creates a `TextDocumentIdentifier` object for the current buffer. - Parameters: ~ - {bufnr} number|nil: Buffer handle, defaults to current + Parameters: ~ + {bufnr} number|nil: Buffer handle, defaults to current - Return: ~ - `TextDocumentIdentifier` + Return: ~ + `TextDocumentIdentifier` - See also: ~ - https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocumentIdentifier + See also: ~ + https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocumentIdentifier *vim.lsp.util.make_workspace_params()* make_workspace_params({added}, {removed}) - Create the workspace params + Create the workspace params - Parameters: ~ - {added} - {removed} + Parameters: ~ + {added} + {removed} *vim.lsp.util.open_floating_preview()* open_floating_preview({contents}, {syntax}, {opts}) - Shows contents in a floating window. - - Parameters: ~ - {contents} (table) of lines to show in window - {syntax} (string) of syntax to set for opened buffer - {opts} (table) with optional fields (additional keys - are passed on to |vim.api.nvim_open_win()|) - • height: (number) height of floating window - • width: (number) width of floating window - • wrap: (boolean, default true) wrap long - lines - • wrap_at: (number) character to wrap at for - computing height when wrap is enabled - • max_width: (number) maximal width of - floating window - • max_height: (number) maximal height of - floating window - • pad_top: (number) number of lines to pad - contents at top - • pad_bottom: (number) number of lines to pad - contents at bottom - • focus_id: (string) if a popup with this id - is opened, then focus it - • close_events: (table) list of events that - closes the floating window - • focusable: (boolean, default true) Make - float focusable - • focus: (boolean, default true) If `true`, - and if {focusable} is also `true`, focus an - existing floating window with the same - {focus_id} - - Return: ~ - bufnr,winnr buffer and window number of the newly created - floating preview window + Shows contents in a floating window. + + Parameters: ~ + {contents} (table) of lines to show in window + {syntax} (string) of syntax to set for opened buffer + {opts} (table) with optional fields (additional keys are passed + on to |vim.api.nvim_open_win()|) + • height: (number) height of floating window + • width: (number) width of floating window + • wrap: (boolean, default true) wrap long lines + • wrap_at: (number) character to wrap at for computing + height when wrap is enabled + • max_width: (number) maximal width of floating window + • max_height: (number) maximal height of floating window + • pad_top: (number) number of lines to pad contents at top + • pad_bottom: (number) number of lines to pad contents at + bottom + • focus_id: (string) if a popup with this id is opened, + then focus it + • close_events: (table) list of events that closes the + floating window + • focusable: (boolean, default true) Make float focusable + • focus: (boolean, default true) If `true`, and if + {focusable} is also `true`, focus an existing floating + window with the same {focus_id} + + Return: ~ + bufnr,winnr buffer and window number of the newly created floating + preview window parse_snippet({input}) *vim.lsp.util.parse_snippet()* - Parses snippets in a completion entry. + Parses snippets in a completion entry. - Parameters: ~ - {input} (string) unparsed snippet + Parameters: ~ + {input} (string) unparsed snippet - Return: ~ - (string) parsed snippet + Return: ~ + (string) parsed snippet preview_location({location}, {opts}) *vim.lsp.util.preview_location()* - Previews a location in a floating window + Previews a location in a floating window - behavior depends on type of location: - • for Location, range is shown (e.g., function definition) - • for LocationLink, targetRange is shown (e.g., body of - function definition) + behavior depends on type of location: + • for Location, range is shown (e.g., function definition) + • for LocationLink, targetRange is shown (e.g., body of function + definition) - Parameters: ~ - {location} a single `Location` or `LocationLink` + Parameters: ~ + {location} a single `Location` or `LocationLink` - Return: ~ - (bufnr,winnr) buffer and window number of floating window - or nil + Return: ~ + (bufnr,winnr) buffer and window number of floating window or nil rename({old_fname}, {new_fname}, {opts}) *vim.lsp.util.rename()* - Rename old_fname to new_fname + Rename old_fname to new_fname - Parameters: ~ - {opts} (table) + Parameters: ~ + {opts} (table) set_lines({lines}, {A}, {B}, {new_lines}) *vim.lsp.util.set_lines()* - Replaces text in a range with new text. + Replaces text in a range with new text. - CAUTION: Changes in-place! + CAUTION: Changes in-place! - Parameters: ~ - {lines} (table) Original list of strings - {A} (table) Start position; a 2-tuple of {line, - col} numbers - {B} (table) End position; a 2-tuple of {line, - col} numbers - {new_lines} A list of strings to replace the original + Parameters: ~ + {lines} (table) Original list of strings + {A} (table) Start position; a 2-tuple of {line, col} numbers + {B} (table) End position; a 2-tuple of {line, col} numbers + {new_lines} A list of strings to replace the original - Return: ~ - (table) The modified {lines} object + Return: ~ + (table) The modified {lines} object *vim.lsp.util.stylize_markdown()* stylize_markdown({bufnr}, {contents}, {opts}) - Converts markdown into syntax highlighted regions by stripping - the code blocks and converting them into highlighted code. - This will by default insert a blank line separator after those - code block regions to improve readability. - - This method configures the given buffer and returns the lines - to set. - - If you want to open a popup with fancy markdown, use - `open_floating_preview` instead - - Parameters: ~ - {contents} (table) of lines to show in window - {opts} dictionary with optional fields - • height of floating window - • width of floating window - • wrap_at character to wrap at for computing - height - • max_width maximal width of floating window - • max_height maximal height of floating window - • pad_top number of lines to pad contents at - top - • pad_bottom number of lines to pad contents - at bottom - • separator insert separator after code block - - Return: ~ - width,height size of float + Converts markdown into syntax highlighted regions by stripping the code + blocks and converting them into highlighted code. This will by default + insert a blank line separator after those code block regions to improve + readability. + + This method configures the given buffer and returns the lines to set. + + If you want to open a popup with fancy markdown, use + `open_floating_preview` instead + + Parameters: ~ + {contents} (table) of lines to show in window + {opts} dictionary with optional fields + • height of floating window + • width of floating window + • wrap_at character to wrap at for computing height + • max_width maximal width of floating window + • max_height maximal height of floating window + • pad_top number of lines to pad contents at top + • pad_bottom number of lines to pad contents at bottom + • separator insert separator after code block + + Return: ~ + width,height size of float symbols_to_items({symbols}, {bufnr}) *vim.lsp.util.symbols_to_items()* - Converts symbols to quickfix list items. + Converts symbols to quickfix list items. - Parameters: ~ - {symbols} DocumentSymbol[] or SymbolInformation[] + Parameters: ~ + {symbols} DocumentSymbol[] or SymbolInformation[] *vim.lsp.util.text_document_completion_list_to_complete_items()* text_document_completion_list_to_complete_items({result}, {prefix}) - Turns the result of a `textDocument/completion` request into - vim-compatible |complete-items|. + Turns the result of a `textDocument/completion` request into + vim-compatible |complete-items|. - Parameters: ~ - {result} The result of a `textDocument/completion` call, - e.g. from |vim.lsp.buf.completion()|, which may - be one of `CompletionItem[]`, `CompletionList` - or `null` - {prefix} (string) the prefix to filter the completion - items + Parameters: ~ + {result} The result of a `textDocument/completion` call, e.g. from + |vim.lsp.buf.completion()|, which may be one of + `CompletionItem[]`, `CompletionList` or `null` + {prefix} (string) the prefix to filter the completion items - Return: ~ - { matches = complete-items table, incomplete = bool } + Return: ~ + { matches = complete-items table, incomplete = bool } - See also: ~ - |complete-items| + See also: ~ + |complete-items| trim_empty_lines({lines}) *vim.lsp.util.trim_empty_lines()* - Removes empty lines from the beginning and end. + Removes empty lines from the beginning and end. - Parameters: ~ - {lines} (table) list of lines to trim + Parameters: ~ + {lines} (table) list of lines to trim - Return: ~ - (table) trimmed list of lines + Return: ~ + (table) trimmed list of lines *vim.lsp.util.try_trim_markdown_code_blocks()* try_trim_markdown_code_blocks({lines}) - Accepts markdown lines and tries to reduce them to a filetype - if they comprise just a single code block. + Accepts markdown lines and tries to reduce them to a filetype if they + comprise just a single code block. - CAUTION: Modifies the input in-place! + CAUTION: Modifies the input in-place! - Parameters: ~ - {lines} (table) list of lines + Parameters: ~ + {lines} (table) list of lines - Return: ~ - (string) filetype or 'markdown' if it was unchanged. + Return: ~ + (string) filetype or 'markdown' if it was unchanged. ============================================================================== Lua module: vim.lsp.log *lsp-log* get_filename() *vim.lsp.log.get_filename()* - Returns the log filename. + Returns the log filename. - Return: ~ - (string) log filename + Return: ~ + (string) log filename get_level() *vim.lsp.log.get_level()* - Gets the current log level. + Gets the current log level. - Return: ~ - (string) current log level + Return: ~ + (string) current log level set_format_func({handle}) *vim.lsp.log.set_format_func()* - Sets formatting function used to format logs + Sets formatting function used to format logs - Parameters: ~ - {handle} (function) function to apply to logging - arguments, pass vim.inspect for multi-line - formatting + Parameters: ~ + {handle} (function) function to apply to logging arguments, pass + vim.inspect for multi-line formatting set_level({level}) *vim.lsp.log.set_level()* - Sets the current log level. + Sets the current log level. - Parameters: ~ - {level} (string or number) One of `vim.lsp.log.levels` + Parameters: ~ + {level} (string or number) One of `vim.lsp.log.levels` should_log({level}) *vim.lsp.log.should_log()* - Checks whether the level is sufficient for logging. + Checks whether the level is sufficient for logging. - Parameters: ~ - {level} (number) log level + Parameters: ~ + {level} (number) log level - Return: ~ - (bool) true if would log, false if not + Return: ~ + (bool) true if would log, false if not ============================================================================== Lua module: vim.lsp.rpc *lsp-rpc* format_rpc_error({err}) *vim.lsp.rpc.format_rpc_error()* - Constructs an error message from an LSP error object. + Constructs an error message from an LSP error object. - Parameters: ~ - {err} (table) The error object + Parameters: ~ + {err} (table) The error object - Return: ~ - (string) The formatted error message + Return: ~ + (string) The formatted error message notify({method}, {params}) *vim.lsp.rpc.notify()* - Sends a notification to the LSP server. + Sends a notification to the LSP server. - Parameters: ~ - {method} (string) The invoked LSP method - {params} (table): Parameters for the invoked LSP method + Parameters: ~ + {method} (string) The invoked LSP method + {params} (table): Parameters for the invoked LSP method - Return: ~ - (bool) `true` if notification could be sent, `false` if - not + Return: ~ + (bool) `true` if notification could be sent, `false` if not *vim.lsp.rpc.request()* request({method}, {params}, {callback}, {notify_reply_callback}) - Sends a request to the LSP server and runs {callback} upon - response. - - Parameters: ~ - {method} (string) The invoked LSP method - {params} (table) Parameters for the - invoked LSP method - {callback} (function) Callback to invoke - {notify_reply_callback} (function|nil) Callback to invoke - as soon as a request is no longer - pending - - Return: ~ - (bool, number) `(true, message_id)` if request could be - sent, `false` if not + Sends a request to the LSP server and runs {callback} upon response. + + Parameters: ~ + {method} (string) The invoked LSP method + {params} (table) Parameters for the invoked LSP method + {callback} (function) Callback to invoke + {notify_reply_callback} (function|nil) Callback to invoke as soon as + a request is no longer pending + + Return: ~ + (bool, number) `(true, message_id)` if request could be sent, `false` + if not *vim.lsp.rpc.rpc_response_error()* rpc_response_error({code}, {message}, {data}) - Creates an RPC response object/table. + Creates an RPC response object/table. - Parameters: ~ - {code} RPC error code defined in - `vim.lsp.protocol.ErrorCodes` - {message} (optional) arbitrary message to send to server - {data} (optional) arbitrary data to send to server + Parameters: ~ + {code} (number) RPC error code defined in + `vim.lsp.protocol.ErrorCodes` + {message} (string|nil) arbitrary message to send to server + {data} any|nil arbitrary data to send to server *vim.lsp.rpc.start()* start({cmd}, {cmd_args}, {dispatchers}, {extra_spawn_params}) - Starts an LSP server process and create an LSP RPC client - object to interact with it. Communication with the server is - currently limited to stdio. - - Parameters: ~ - {cmd} (string) Command to start the LSP - server. - {cmd_args} (table) List of additional string - arguments to pass to {cmd}. - {dispatchers} (table, optional) Dispatchers for - LSP message types. Valid dispatcher - names are: - • `"notification"` - • `"server_request"` - • `"on_error"` - • `"on_exit"` - {extra_spawn_params} (table, optional) Additional context - for the LSP server process. May - contain: - • {cwd} (string) Working directory - for the LSP server process - • {env} (table) Additional - environment variables for LSP - server process - - Return: ~ - Client RPC object. - Methods: - • `notify()` |vim.lsp.rpc.notify()| - • `request()` |vim.lsp.rpc.request()| - - Members: - • {pid} (number) The LSP server's PID. - • {handle} A handle for low-level interaction with the LSP - server process |vim.loop|. + Starts an LSP server process and create an LSP RPC client object to + interact with it. Communication with the server is currently limited to + stdio. + + Parameters: ~ + {cmd} (string) Command to start the LSP server. + {cmd_args} (table) List of additional string arguments to + pass to {cmd}. + {dispatchers} (table|nil) Dispatchers for LSP message types. + Valid dispatcher names are: + • `"notification"` + • `"server_request"` + • `"on_error"` + • `"on_exit"` + {extra_spawn_params} (table|nil) Additional context for the LSP + server process. May contain: + • {cwd} (string) Working directory for the LSP + server process + • {env} (table) Additional environment variables + for LSP server process + + Return: ~ + Client RPC object. + Methods: + • `notify()` |vim.lsp.rpc.notify()| + • `request()` |vim.lsp.rpc.request()| + + Members: + • {pid} (number) The LSP server's PID. + • {handle} A handle for low-level interaction with the LSP server + process |vim.loop|. ============================================================================== @@ -2146,23 +1974,20 @@ Lua module: vim.lsp.sync *lsp-sync* *vim.lsp.sync.compute_diff()* compute_diff({___MissingCloseParenHere___}) - Returns the range table for the difference between prev and - curr lines + Returns the range table for the difference between prev and curr lines - Parameters: ~ - {prev_lines} (table) list of lines - {curr_lines} (table) list of lines - {firstline} (number) line to begin search for first - difference - {lastline} (number) line to begin search in - old_lines for last difference - {new_lastline} (number) line to begin search in - new_lines for last difference - {offset_encoding} (string) encoding requested by language - server + Parameters: ~ + {prev_lines} (table) list of lines + {curr_lines} (table) list of lines + {firstline} (number) line to begin search for first difference + {lastline} (number) line to begin search in old_lines for last + difference + {new_lastline} (number) line to begin search in new_lines for last + difference + {offset_encoding} (string) encoding requested by language server - Return: ~ - (table) TextDocumentContentChangeEvent see https://microsoft.github.io/language-server-protocol/specifications/specification-3-17/#textDocumentContentChangeEvent + Return: ~ + (table) TextDocumentContentChangeEvent see https://microsoft.github.io/language-server-protocol/specifications/specification-3-17/#textDocumentContentChangeEvent ============================================================================== @@ -2170,19 +1995,18 @@ Lua module: vim.lsp.protocol *lsp-protocol* *vim.lsp.protocol.make_client_capabilities()* make_client_capabilities() - Gets a new ClientCapabilities object describing the LSP client - capabilities. + Gets a new ClientCapabilities object describing the LSP client + capabilities. *vim.lsp.protocol.resolve_capabilities()* resolve_capabilities({server_capabilities}) - Creates a normalized object describing LSP server - capabilities. + Creates a normalized object describing LSP server capabilities. - Parameters: ~ - {server_capabilities} (table) Table of capabilities - supported by the server + Parameters: ~ + {server_capabilities} (table) Table of capabilities supported by the + server - Return: ~ - (table) Normalized table of capabilities + Return: ~ + (table) Normalized table of capabilities - vim:tw=78:ts=8:ft=help:norl: + vim:tw=78:ts=8:sw=4:sts=4:et:ft=help:norl: diff --git a/runtime/doc/lua.txt b/runtime/doc/lua.txt index 4062a35735..42f3a5e432 100644 --- a/runtime/doc/lua.txt +++ b/runtime/doc/lua.txt @@ -37,7 +37,7 @@ separator when searching. For a module `foo.bar`, each directory is searched for `lua/foo/bar.lua`, then `lua/foo/bar/init.lua`. If no files are found, the directories are searched again for a shared library with a name matching `lua/foo/bar.?`, where `?` is a list of suffixes (such as `so` or `dll`) derived from -the initial value of `package.cpath`. If still no files are found, Nvim falls +the initial value of |package.cpath|. If still no files are found, Nvim falls back to Lua's default search mechanism. The first script found is run and `require()` returns the value returned by the script if any, else `true`. @@ -46,7 +46,7 @@ with subsequent calls returning the cached value without searching for, or executing any script. For further details on `require()`, see the Lua documentation at https://www.lua.org/manual/5.1/manual.html#pdf-require. -For example, if 'runtimepath' is `foo,bar` and `package.cpath` was +For example, if 'runtimepath' is `foo,bar` and |package.cpath| was `./?.so;./?.dll` at startup, `require('mod')` searches these paths in order and loads the first module found: @@ -59,27 +59,27 @@ and loads the first module found: bar/lua/mod.so bar/lua/mod.dll -Nvim automatically adjusts `package.path` and `package.cpath` according to the +Nvim automatically adjusts |package.path| and |package.cpath| according to the effective 'runtimepath' value. Adjustment happens whenever 'runtimepath' is -changed. `package.path` is adjusted by simply appending `/lua/?.lua` and +changed. |package.path| is adjusted by simply appending `/lua/?.lua` and `/lua/?/init.lua` to each directory from 'runtimepath' (`/` is actually the first character of `package.config`). -Similarly to `package.path`, modified directories from 'runtimepath' are also -added to `package.cpath`. In this case, instead of appending `/lua/?.lua` and +Similarly to |package.path|, modified directories from 'runtimepath' are also +added to |package.cpath|. In this case, instead of appending `/lua/?.lua` and `/lua/?/init.lua` to each runtimepath, all unique `?`-containing suffixes of -the existing `package.cpath` are used. Example: +the existing |package.cpath| are used. Example: 1. Given that - 'runtimepath' contains `/foo/bar,/xxx;yyy/baz,/abc`; - initial (defined at compile-time or derived from - `$LUA_CPATH`/`$LUA_INIT`) `package.cpath` contains + `$LUA_CPATH`/`$LUA_INIT`) |package.cpath| contains `./?.so;/def/ghi/a?d/j/g.elf;/def/?.so`. 2. It finds `?`-containing suffixes `/?.so`, `/a?d/j/g.elf` and `/?.so`, in order: parts of the path starting from the first path component containing question mark and preceding path separator. 3. The suffix of `/def/?.so`, namely `/?.so` is not unique, as it’s the same - as the suffix of the first path from `package.path` (i.e. `./?.so`). Which + as the suffix of the first path from |package.path| (i.e. `./?.so`). Which leaves `/?.so` and `/a?d/j/g.elf`, in this order. 4. 'runtimepath' has three paths: `/foo/bar`, `/xxx;yyy/baz` and `/abc`. The second one contains a semicolon which is a paths separator so it is out, @@ -93,7 +93,7 @@ the existing `package.cpath` are used. Example: - `/abc/lua/?.so` - `/abc/lua/a?d/j/g.elf` -6. New paths are prepended to the original `package.cpath`. +6. New paths are prepended to the original |package.cpath|. The result will look like this: @@ -108,16 +108,16 @@ Note: remembered and removed at the next update, while all paths derived from the new 'runtimepath' are prepended as described above. This allows removing paths when path is removed from 'runtimepath', adding paths when they are - added and reordering `package.path`/`package.cpath` content if 'runtimepath' + added and reordering |package.path|/|package.cpath| content if 'runtimepath' was reordered. - Although adjustments happen automatically, Nvim does not track current - values of `package.path` or `package.cpath`. If you happen to delete some + values of |package.path| or |package.cpath|. If you happen to delete some paths from there you can set 'runtimepath' to trigger an update: > let &runtimepath = &runtimepath - Skipping paths from 'runtimepath' which contain semicolons applies both to - `package.path` and `package.cpath`. Given that there are some badly written + |package.path| and |package.cpath|. Given that there are some badly written plugins using shell, which will not work with paths containing semicolons, it is better to not have them in 'runtimepath' at all. @@ -182,7 +182,7 @@ Lua Patterns *lua-patterns* For performance reasons, Lua does not support regular expressions natively. Instead, the Lua `string` standard library allows manipulations using a -restricted set of "patterns", see https://www.lua.org/manual/5.1/manual.html#5.4.1 +restricted set of "patterns", see |luaref-patterns|. Examples (`string.match` extracts the first match): > @@ -292,68 +292,64 @@ arguments separated by " " (space) instead of "\t" (tab). *:lua* :lua {chunk} - Executes Lua chunk {chunk}. - If {chunk} starts with "=" the rest of the chunk is - evaluated as an expression and printed. `:lua =expr` - is equivalent to `:lua print(vim.inspect(expr))` - Examples: > - :lua vim.api.nvim_command('echo "Hello, Nvim!"') -< To see the Lua version: > - :lua print(_VERSION) -< To see the LuaJIT version: > - :lua =jit.version + Executes Lua chunk {chunk}. If {chunk} starts with "=" the rest of the + chunk is evaluated as an expression and printed. `:lua =expr` is + equivalent to `:lua print(vim.inspect(expr))` + + Examples: > + :lua vim.api.nvim_command('echo "Hello, Nvim!"') +< To see the Lua version: > + :lua print(_VERSION) +< To see the LuaJIT version: > + :lua =jit.version < *:lua-heredoc* :lua << [endmarker] {script} {endmarker} - Executes Lua script {script} from within Vimscript. - {endmarker} must NOT be preceded by whitespace. You - can omit [endmarker] after the "<<" and use a dot "." - after {script} (similar to |:append|, |:insert|). - - Example: - > - function! CurrentLineInfo() - lua << EOF - local linenr = vim.api.nvim_win_get_cursor(0)[1] - local curline = vim.api.nvim_buf_get_lines( - 0, linenr - 1, linenr, false)[1] - print(string.format("Current line [%d] has %d bytes", - linenr, #curline)) - EOF - endfunction + Executes Lua script {script} from within Vimscript. {endmarker} must NOT + be preceded by whitespace. You can omit [endmarker] after the "<<" and use + a dot "." after {script} (similar to |:append|, |:insert|). + + Example: > + function! CurrentLineInfo() + lua << EOF + local linenr = vim.api.nvim_win_get_cursor(0)[1] + local curline = vim.api.nvim_buf_get_lines( + 0, linenr - 1, linenr, false)[1] + print(string.format("Current line [%d] has %d bytes", + linenr, #curline)) + EOF + endfunction < - Note that the `local` variables will disappear when - the block finishes. But not globals. + Note that the `local` variables will disappear when the block finishes. + But not globals. *:luado* -:[range]luado {body} Executes Lua chunk "function(line, linenr) {body} end" - for each buffer line in [range], where `line` is the - current line text (without <EOL>), and `linenr` is the - current line number. If the function returns a string - that becomes the text of the corresponding buffer - line. Default [range] is the whole file: "1,$". - - Examples: - > - :luado return string.format("%s\t%d", line:reverse(), #line) - - :lua require"lpeg" - :lua -- balanced parenthesis grammar: - :lua bp = lpeg.P{ "(" * ((1 - lpeg.S"()") + lpeg.V(1))^0 * ")" } - :luado if bp:match(line) then return "-->\t" .. line end +:[range]luado {body} + Executes Lua chunk "function(line, linenr) {body} end" for each buffer + line in [range], where `line` is the current line text (without <EOL>), + and `linenr` is the current line number. If the function returns a string + that becomes the text of the corresponding buffer line. Default [range] is + the whole file: "1,$". + + Examples: > + :luado return string.format("%s\t%d", line:reverse(), #line) + + :lua require"lpeg" + :lua -- balanced parenthesis grammar: + :lua bp = lpeg.P{ "(" * ((1 - lpeg.S"()") + lpeg.V(1))^0 * ")" } + :luado if bp:match(line) then return "-->\t" .. line end < *:luafile* :luafile {file} - Execute Lua script in {file}. - The whole argument is used as the filename (like - |:edit|), spaces do not need to be escaped. - Alternatively you can |:source| Lua files. - - Examples: > - :luafile script.lua - :luafile % + Execute Lua script in {file}. + The whole argument is used as the filename (like |:edit|), spaces do not + need to be escaped. Alternatively you can |:source| Lua files. + + Examples: > + :luafile script.lua + :luafile % < ============================================================================== @@ -516,8 +512,8 @@ management. Try this command to see available functions: > :lua print(vim.inspect(vim.loop)) < -Reference: https://github.com/luvit/luv/blob/master/docs.md -Examples: https://github.com/luvit/luv/tree/master/examples +Internally, `vim.loop` wraps the "luv" Lua bindings for the LibUV library; +see |luv-intro| for a full reference manual. *E5560* *lua-loop-callbacks* It is an error to directly invoke `vim.api` functions (except |api-fast|) in @@ -634,53 +630,53 @@ VIM.HIGHLIGHT *lua-highlight* Nvim includes a function for highlighting a selection on yank (see for example https://github.com/machakann/vim-highlightedyank). To enable it, add > - au TextYankPost * silent! lua vim.highlight.on_yank() + au TextYankPost * silent! lua vim.highlight.on_yank() < to your `init.vim`. You can customize the highlight group and the duration of the highlight via > - au TextYankPost * silent! lua vim.highlight.on_yank {higroup="IncSearch", timeout=150} + au TextYankPost * silent! lua vim.highlight.on_yank {higroup="IncSearch", timeout=150} < If you want to exclude visual selections from highlighting on yank, use > - au TextYankPost * silent! lua vim.highlight.on_yank {on_visual=false} + au TextYankPost * silent! lua vim.highlight.on_yank {on_visual=false} < vim.highlight.on_yank({opts}) *vim.highlight.on_yank()* - Highlights the yanked text. The fields of the optional dict {opts} - control the highlight: - - {higroup} highlight group for yanked region (default |hl-IncSearch|) - - {timeout} time in ms before highlight is cleared (default `150`) - - {on_macro} highlight when executing macro (default `false`) - - {on_visual} highlight when yanking visual selection (default `true`) - - {event} event structure (default |v:event|) + Highlights the yanked text. The fields of the optional dict {opts} + control the highlight: + - {higroup} highlight group for yanked region (default |hl-IncSearch|) + - {timeout} time in ms before highlight is cleared (default `150`) + - {on_macro} highlight when executing macro (default `false`) + - {on_visual} highlight when yanking visual selection (default `true`) + - {event} event structure (default |v:event|) vim.highlight.range({bufnr}, {ns}, {hlgroup}, {start}, {finish}, {opts}) *vim.highlight.range()* - Apply highlight group to range of text. - - Parameters: ~ - {bufnr} buffer number - {ns} namespace for highlights - {hlgroup} highlight group name - {start} starting position (tuple {line,col}) - {finish} finish position (tuple {line,col}) - {opts} optional parameters: - • `regtype`: type of range (characterwise, linewise, - or blockwise, see |setreg|), default `'v'` - • `inclusive`: range includes end position, - default `false` - • `priority`: priority of highlight, default - `vim.highlight.user` (see below) + Apply highlight group to range of text. + + Parameters: ~ + {bufnr} buffer number + {ns} namespace for highlights + {hlgroup} highlight group name + {start} starting position (tuple {line,col}) + {finish} finish position (tuple {line,col}) + {opts} optional parameters: + • `regtype`: type of range (characterwise, linewise, + or blockwise, see |setreg|), default `'v'` + • `inclusive`: range includes end position, + default `false` + • `priority`: priority of highlight, default + `vim.highlight.user` (see below) 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 - • `diagnostics`: `150`, used for code analysis such as diagnostics - • `user`: `200`, used for user-triggered highlights such as LSP - document symbols or `on_yank` autocommands + Table with default priorities used for highlighting: + • `syntax`: `50`, used for standard syntax highlighting + • `treesitter`: `100`, used for tree-sitter-based highlighting + • `diagnostics`: `150`, used for code analysis such as diagnostics + • `user`: `200`, used for user-triggered highlights such as LSP document + symbols or `on_yank` autocommands ------------------------------------------------------------------------------ VIM.REGEX *lua-regex* @@ -689,94 +685,89 @@ 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|. + Parse the Vim regex {re} and return a regex object. Regexes are "magic" + and case-sensitive by default, regardless of 'magic' and 'ignorecase'. + They can be controlled with flags, see |/magic| and |/ignorecase|. Methods on the regex object: regex:match_str({str}) *regex:match_str()* - Match the string against the regex. If the string should match the - regex precisely, surround the regex with `^` and `$`. - If the was a match, the byte indices for the beginning and end of - the match is returned. When there is no match, `nil` is returned. - As any integer is truth-y, `regex:match()` can be directly used - as a condition in an if-statement. + Match the string against the regex. If the string should match the regex + precisely, surround the regex with `^` and `$`. If the was a match, the + byte indices for the beginning and end of the match is returned. When + there is no match, `nil` is returned. As any integer is truth-y, + `regex:match()` can be directly used as a condition in an if-statement. regex:match_line({bufnr}, {line_idx} [, {start}, {end}]) *regex:match_line()* - Match line {line_idx} (zero-based) in buffer {bufnr}. If {start} and - {end} are supplied, match only this byte index range. Otherwise see - |regex:match_str()|. If {start} is used, then the returned byte - indices will be relative {start}. + Match line {line_idx} (zero-based) in buffer {bufnr}. If {start} and {end} + are supplied, match only this byte index range. Otherwise see + |regex:match_str()|. If {start} is used, then the returned byte indices + will be relative {start}. ------------------------------------------------------------------------------ VIM.DIFF *lua-diff* vim.diff({a}, {b}, {opts}) *vim.diff()* - Run diff on strings {a} and {b}. Any indices returned by this - function, either directly or via callback arguments, are - 1-based. - - Examples: > - - vim.diff('a\n', 'b\nc\n') - --> - @@ -1 +1,2 @@ - -a - +b - +c - - vim.diff('a\n', 'b\nc\n', {result_type = 'indices'}) - --> - { - {1, 1, 1, 2} - } + Run diff on strings {a} and {b}. Any indices returned by this function, + either directly or via callback arguments, are 1-based. + + Examples: > + + vim.diff('a\n', 'b\nc\n') + --> + @@ -1 +1,2 @@ + -a + +b + +c + + vim.diff('a\n', 'b\nc\n', {result_type = 'indices'}) + --> + { + {1, 1, 1, 2} + } < - Parameters: ~ - {a} First string to compare - {b} Second string to compare - {opts} Optional parameters: - • `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. - • `algorithm` (string): - Diff algorithm to use. Values: - • "myers" the default algorithm - • "minimal" spend extra time to generate the - smallest possible diff - • "patience" patience diff algorithm - • "histogram" histogram diff algorithm - • `ctxlen` (integer): Context length - • `interhunkctxlen` (integer): - Inter hunk context length - • `ignore_whitespace` (boolean): - Ignore whitespace - • `ignore_whitespace_change` (boolean): - Ignore whitespace change - • `ignore_whitespace_change_at_eol` (boolean) - Ignore whitespace change at end-of-line. - • `ignore_cr_at_eol` (boolean) - Ignore carriage return at end-of-line - • `ignore_blank_lines` (boolean) - Ignore blank lines - • `indent_heuristic` (boolean): - Use the indent heuristic for the internal - diff library. - - Return: ~ - See {opts.result_type}. nil if {opts.on_hunk} is given. + Parameters: ~ + {a} First string to compare + {b} Second string to compare + {opts} Optional parameters: + • `on_hunk` (callback): + Invoked for each hunk in the diff. Return a negative number + to cancel the callback for any remaining hunks. + Args: + • `start_a` (integer): Start line of hunk in {a}. + • `count_a` (integer): Hunk size in {a}. + • `start_b` (integer): Start line of hunk in {b}. + • `count_b` (integer): Hunk size in {b}. + • `result_type` (string): Form of the returned diff: + • "unified": (default) String in unified format. + • "indices": Array of hunk locations. + Note: This option is ignored if `on_hunk` is used. + • `algorithm` (string): + Diff algorithm to use. Values: + • "myers" the default algorithm + • "minimal" spend extra time to generate the + smallest possible diff + • "patience" patience diff algorithm + • "histogram" histogram diff algorithm + • `ctxlen` (integer): Context length + • `interhunkctxlen` (integer): + Inter hunk context length + • `ignore_whitespace` (boolean): + Ignore whitespace + • `ignore_whitespace_change` (boolean): + Ignore whitespace change + • `ignore_whitespace_change_at_eol` (boolean) + Ignore whitespace change at end-of-line. + • `ignore_cr_at_eol` (boolean) + Ignore carriage return at end-of-line + • `ignore_blank_lines` (boolean) + Ignore blank lines + • `indent_heuristic` (boolean): + Use the indent heuristic for the internal + diff library. + + Return: ~ + See {opts.result_type}. nil if {opts.on_hunk} is given. ------------------------------------------------------------------------------ VIM.MPACK *lua-mpack* @@ -785,115 +776,114 @@ The *vim.mpack* module provides encoding and decoding of Lua objects to and from msgpack-encoded strings. Supports |vim.NIL| and |vim.empty_dict()|. vim.mpack.encode({obj}) *vim.mpack.encode* - Encodes (or "packs") Lua object {obj} as msgpack in a Lua string. + Encodes (or "packs") Lua object {obj} as msgpack in a Lua string. vim.mpack.decode({str}) *vim.mpack.decode* - Decodes (or "unpacks") the msgpack-encoded {str} to a Lua object. + Decodes (or "unpacks") the msgpack-encoded {str} to a Lua object. ------------------------------------------------------------------------------ VIM.SPELL *lua-spell* vim.spell.check({str}) *vim.spell.check()* - Check {str} for spelling errors. Similar to the Vimscript function - |spellbadword()|. + Check {str} for spelling errors. Similar to the Vimscript function + |spellbadword()|. - Note: The behaviour of this function is dependent on: 'spelllang', - 'spellfile', 'spellcapcheck' and 'spelloptions' which can all be - local to the buffer. Consider calling this with |nvim_buf_call()|. + Note: The behaviour of this function is dependent on: 'spelllang', + 'spellfile', 'spellcapcheck' and 'spelloptions' which can all be local to + the buffer. Consider calling this with |nvim_buf_call()|. - Example: > + Example: > - vim.spell.check("the quik brown fox") - --> - { - {'quik', 'bad', 4} - } + vim.spell.check("the quik brown fox") + --> + { + {'quik', 'bad', 4} + } < - Parameters: ~ - {str} String to spell check. - - Return: ~ - List of tuples with three items: - - The badly spelled word. - - The type of the spelling error: - "bad" spelling mistake - "rare" rare word - "local" word only valid in another region - "caps" word should start with Capital - - The position in {str} where the word begins. + Parameters: ~ + {str} String to spell check. + + Return: ~ + List of tuples with three items: + - The badly spelled word. + - The type of the spelling error: + "bad" spelling mistake + "rare" rare word + "local" word only valid in another region + "caps" word should start with Capital + - The position in {str} where the word begins. ------------------------------------------------------------------------------ VIM *lua-builtin* vim.api.{func}({...}) *vim.api* - Invokes Nvim |API| function {func} with arguments {...}. - Example: call the "nvim_get_current_line()" API function: > - print(tostring(vim.api.nvim_get_current_line())) + Invokes Nvim |API| function {func} with arguments {...}. + Example: call the "nvim_get_current_line()" API function: > + print(tostring(vim.api.nvim_get_current_line())) vim.version() *vim.version* - Gets the version of the current Nvim build. + Gets the version of the current Nvim build. vim.in_fast_event() *vim.in_fast_event()* - Returns true if the code is executing as part of a "fast" event - handler, where most of the API is disabled. These are low-level events - (e.g. |lua-loop-callbacks|) which can be invoked whenever Nvim polls - for input. When this is `false` most API functions are callable (but - may be subject to other restrictions such as |textlock|). + Returns true if the code is executing as part of a "fast" event handler, + where most of the API is disabled. These are low-level events (e.g. + |lua-loop-callbacks|) which can be invoked whenever Nvim polls for input. + When this is `false` most API functions are callable (but may be subject + to other restrictions such as |textlock|). vim.NIL *vim.NIL* - 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"}`. + Special value representing NIL in |RPC| and |v:null| in Vimscript + conversion, and similar cases. Lua `nil` cannot be used as part of a Lua + table representing a Dictionary or Array, because it is treated as + missing: `{"foo", nil}` is the same as `{"foo"}`. vim.empty_dict() *vim.empty_dict()* - Creates a special empty table (marked with a metatable), which Nvim - converts to an empty dictionary when translating Lua values to - Vimscript or API types. Nvim by default converts an empty table `{}` - without this metatable to an list/array. + Creates a special empty table (marked with a metatable), which Nvim to an + empty dictionary when translating Lua values to Vimscript or API types. + Nvim by default converts an empty table `{}` without this metatable to an + list/array. - Note: If numeric keys are present in the table, Nvim ignores the - metatable marker and converts the dict to a list/array anyway. + Note: If numeric keys are present in the table, Nvim ignores the metatable + marker and converts the dict to a list/array anyway. vim.rpcnotify({channel}, {method} [, {args}...]) *vim.rpcnotify()* - Sends {event} to {channel} via |RPC| and returns immediately. If - {channel} is 0, the event is broadcast to all channels. + 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|. + This function also works in a fast callback |lua-loop-callbacks|. vim.rpcrequest({channel}, {method} [, {args}...]) *vim.rpcrequest()* - Sends a request to {channel} to invoke {method} via |RPC| and blocks - until a response is received. + Sends a request to {channel} to invoke {method} via |RPC| and blocks until + a response is received. - Note: NIL values as part of the return value is represented as - |vim.NIL| special value + Note: NIL values as part of the return value is represented as |vim.NIL| + special value vim.stricmp({a}, {b}) *vim.stricmp()* - Compares strings case-insensitively. Returns 0, 1 or -1 if strings - are equal, {a} is greater than {b} or {a} is lesser than {b}, - respectively. + Compares strings case-insensitively. Returns 0, 1 or -1 if strings are + equal, {a} is greater than {b} or {a} is lesser than {b}, respectively. vim.str_utfindex({str} [, {index}]) *vim.str_utfindex()* - Convert byte index to UTF-32 and UTF-16 indices. If {index} is not - supplied, the length of the string is used. All indices are zero-based. - Returns two values: the UTF-32 and UTF-16 indices respectively. + Convert byte index to UTF-32 and UTF-16 indices. If {index} is not + supplied, the length of the string is used. All indices are zero-based. + Returns two values: the UTF-32 and UTF-16 indices respectively. - Embedded NUL bytes are treated as terminating the string. Invalid - UTF-8 bytes, and embedded surrogates are counted as one code - point each. An {index} in the middle of a UTF-8 sequence is rounded - upwards to the end of that sequence. + Embedded NUL bytes are treated as terminating the string. Invalid UTF-8 + bytes, and embedded surrogates are counted as one code point each. An + {index} in the middle of a UTF-8 sequence is rounded upwards to the end of + that sequence. 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 - supplied, it defaults to false (use UTF-32). Returns the byte index. + Convert UTF-32 or UTF-16 {index} to byte index. If {use_utf16} is not + supplied, it defaults to false (use UTF-32). Returns the byte index. - Invalid UTF-8 and NUL is treated like by |vim.str_byteindex()|. - An {index} in the middle of a UTF-16 sequence is rounded upwards to - the end of that sequence. + Invalid UTF-8 and NUL is treated like by |vim.str_byteindex()|. + An {index} in the middle of a UTF-16 sequence is rounded upwards to + the end of that sequence. vim.schedule({callback}) *vim.schedule()* - Schedules {callback} to be invoked soon by the main event-loop. Useful - to avoid |textlock| or other temporary restrictions. + Schedules {callback} to be invoked soon by the main event-loop. Useful + to avoid |textlock| or other temporary restrictions. vim.defer_fn({fn}, {timeout}) *vim.defer_fn* @@ -911,11 +901,11 @@ vim.defer_fn({fn}, {timeout}) *vim.defer_fn* |vim.loop|.new_timer() object vim.wait({time} [, {callback}, {interval}, {fast_only}]) *vim.wait()* - Wait for {time} in milliseconds until {callback} returns `true`. + Wait for {time} in milliseconds until {callback} returns `true`. - Executes {callback} immediately and at approximately {interval} - milliseconds (default 200). Nvim still processes other events during - this time. + Executes {callback} immediately and at approximately {interval} + milliseconds (default 200). Nvim still processes other events during + this time. Parameters: ~ {time} Number of milliseconds to wait @@ -962,49 +952,48 @@ vim.wait({time} [, {callback}, {interval}, {fast_only}]) *vim.wait()* < 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. + Type index for use in |lua-special-tbl|. Specifying one of the values from + |vim.types| allows typing the empty table (it is unclear whether empty Lua + table represents empty list or empty array) and forcing integral numbers + to be |Float|. See |lua-special-tbl| for more details. vim.val_idx *vim.val_idx* - Value index for tables representing |Float|s. A table representing - floating-point value 1.0 looks like this: > - { - [vim.type_idx] = vim.types.float, - [vim.val_idx] = 1.0, - } -< See also |vim.type_idx| and |lua-special-tbl|. + Value index for tables representing |Float|s. A table representing + floating-point value 1.0 looks like this: > + { + [vim.type_idx] = vim.types.float, + [vim.val_idx] = 1.0, + } +< See also |vim.type_idx| and |lua-special-tbl|. vim.types *vim.types* - Table with possible values for |vim.type_idx|. Contains two sets of - key-value pairs: first maps possible values for |vim.type_idx| to - human-readable strings, second maps human-readable type names to - values for |vim.type_idx|. Currently contains pairs for `float`, - `array` and `dictionary` types. - - Note: One must expect that values corresponding to `vim.types.float`, - `vim.types.array` and `vim.types.dictionary` fall under only two - following assumptions: - 1. Value may serve both as a key and as a value in a table. Given the - properties of Lua tables this basically means “value is not `nil`”. - 2. For each value in `vim.types` table `vim.types[vim.types[value]]` - is the same as `value`. - No other restrictions are put on types, and it is not guaranteed that - values corresponding to `vim.types.float`, `vim.types.array` and - `vim.types.dictionary` will not change or that `vim.types` table will - only contain values for these three types. + Table with possible values for |vim.type_idx|. Contains two sets of + key-value pairs: first maps possible values for |vim.type_idx| to + human-readable strings, second maps human-readable type names to values + for |vim.type_idx|. Currently contains pairs for `float`, `array` and + `dictionary` types. + + Note: One must expect that values corresponding to `vim.types.float`, + `vim.types.array` and `vim.types.dictionary` fall under only two following + assumptions: + 1. Value may serve both as a key and as a value in a table. Given the + properties of Lua tables this basically means “value is not `nil`”. + 2. For each value in `vim.types` table `vim.types[vim.types[value]]` is the + same as `value`. + No other restrictions are put on types, and it is not guaranteed that + values corresponding to `vim.types.float`, `vim.types.array` and + `vim.types.dictionary` will not change or that `vim.types` table will only + contain values for these three types. *log_levels* *vim.log.levels* Log levels are one of the values defined in `vim.log.levels`: - vim.log.levels.DEBUG - vim.log.levels.ERROR - vim.log.levels.INFO - vim.log.levels.TRACE - vim.log.levels.WARN - vim.log.levels.OFF + vim.log.levels.DEBUG + vim.log.levels.ERROR + vim.log.levels.INFO + vim.log.levels.TRACE + vim.log.levels.WARN + vim.log.levels.OFF ------------------------------------------------------------------------------ LUA-VIMSCRIPT BRIDGE *lua-vimscript* @@ -1014,32 +1003,32 @@ editor commands and options. See also https://github.com/nanotee/nvim-lua-guide. vim.call({func}, {...}) *vim.call()* - Invokes |vim-function| or |user-function| {func} with arguments {...}. - See also |vim.fn|. - Equivalent to: > - vim.fn[func]({...}) + Invokes |vim-function| or |user-function| {func} with arguments {...}. + See also |vim.fn|. + Equivalent to: > + vim.fn[func]({...}) vim.cmd({command}) - See |vim.cmd()|. + See |vim.cmd()|. vim.fn.{func}({...}) *vim.fn* - Invokes |vim-function| or |user-function| {func} with arguments {...}. - To call autoload functions, use the syntax: > - vim.fn['some#function']({...}) + Invokes |vim-function| or |user-function| {func} with arguments {...}. + To call autoload functions, use the syntax: > + vim.fn['some#function']({...}) < - Unlike vim.api.|nvim_call_function()| this converts directly between Vim - objects and Lua objects. If the Vim function returns a float, it will - be represented directly as a Lua number. Empty lists and dictionaries - both are represented by an empty table. + Unlike vim.api.|nvim_call_function()| this converts directly between Vim + objects and Lua objects. If the Vim function returns a float, it will be + represented directly as a Lua number. Empty lists and dictionaries both + are represented by an empty table. - Note: |v:null| values as part of the return value is represented as - |vim.NIL| special value + Note: |v:null| values as part of the return value is represented as + |vim.NIL| special value - Note: vim.fn keys are generated lazily, thus `pairs(vim.fn)` only - enumerates functions that were called at least once. + Note: vim.fn keys are generated lazily, thus `pairs(vim.fn)` only + enumerates functions that were called at least once. - Note: The majority of functions cannot run in |api-fast| callbacks with some - undocumented exceptions which are allowed. + Note: The majority of functions cannot run in |api-fast| callbacks with some + undocumented exceptions which are allowed. *lua-vim-variables* The Vim editor global dictionaries |g:| |w:| |b:| |t:| |v:| can be accessed @@ -1055,35 +1044,35 @@ Example: > vim.b[2].foo = 6 -- Set b:foo for buffer 2 < vim.g *vim.g* - Global (|g:|) editor variables. - Key with no value returns `nil`. + Global (|g:|) editor variables. + Key with no value returns `nil`. vim.b *vim.b* - Buffer-scoped (|b:|) variables for the current buffer. - Invalid or unset key returns `nil`. Can be indexed with - an integer to access variables for a specific buffer. + Buffer-scoped (|b:|) variables for the current buffer. + Invalid or unset key returns `nil`. Can be indexed with + an integer to access variables for a specific buffer. vim.w *vim.w* - Window-scoped (|w:|) variables for the current window. - Invalid or unset key returns `nil`. Can be indexed with - an integer to access variables for a specific window. + Window-scoped (|w:|) variables for the current window. + Invalid or unset key returns `nil`. Can be indexed with + an integer to access variables for a specific window. vim.t *vim.t* - Tabpage-scoped (|t:|) variables for the current tabpage. - Invalid or unset key returns `nil`. Can be indexed with - an integer to access variables for a specific tabpage. + Tabpage-scoped (|t:|) variables for the current tabpage. + Invalid or unset key returns `nil`. Can be indexed with + an integer to access variables for a specific tabpage. vim.v *vim.v* - |v:| variables. - Invalid or unset key returns `nil`. + |v:| variables. + Invalid or unset key returns `nil`. vim.env *vim.env* - Environment variables defined in the editor session. - See |expand-env| and |:let-environment| for the Vimscript behavior. - Invalid or unset key returns `nil`. - Example: > - vim.env.FOO = 'bar' - print(vim.env.TERM) + Environment variables defined in the editor session. + See |expand-env| and |:let-environment| for the Vimscript behavior. + Invalid or unset key returns `nil`. + Example: > + vim.env.FOO = 'bar' + print(vim.env.TERM) < *lua-vim-options* @@ -1248,877 +1237,848 @@ vim.bo/vim.wo :setlocal - set vim.go :setglobal set - vim.o *vim.o* - Get or set editor options, like |:set|. Invalid key is an error. - Example: > - vim.o.cmdheight = 4 - print(vim.o.columns) + Get or set editor options, like |:set|. Invalid key is an error. + + Example: > + vim.o.cmdheight = 4 + print(vim.o.columns) + print(vim.o.foo) -- error: invalid key < vim.go *vim.go* - Get or set an |option|. Invalid key is an error. + Get or set an |option|. Invalid key is an error. - This is a wrapper around |nvim_set_option()| and |nvim_get_option()|. + This is a wrapper around |nvim_set_option_value()| and + |nvim_get_option_value()|. - NOTE: This is different than |vim.o| because this ONLY sets the global - option, which generally produces confusing behavior for options with - |global-local| values. + NOTE: This is different from |vim.o| because this ONLY sets the global + option, which generally produces confusing behavior for options with + |global-local| values. - Example: > - vim.go.cmdheight = 4 + Example: > + vim.go.cmdheight = 4 + print(vim.go.columns) + print(vim.go.bar) -- error: invalid key < -vim.bo *vim.bo* - Get or set buffer-scoped |local-options|. Invalid key is an error. - - This is a wrapper around |nvim_buf_set_option()| and - |nvim_buf_get_option()|. - - Example: > - vim.bo.buflisted = true - print(vim.bo.comments) +vim.bo[{bufnr}] *vim.bo* + Get or set buffer-scoped |local-options| for the buffer with number {bufnr}. + If [{bufnr}] is omitted, use the current buffer. Invalid {bufnr} or key is + an error. + + This is a wrapper around |nvim_set_option_value()| and + |nvim_get_option_value()| with `opts = {scope = local, buf = bufnr}` . + + Example: > + local bufnr = vim.api.nvim_get_current_buf() + vim.bo[bufnr].buflisted = true -- same as vim.bo.buflisted = true + print(vim.bo.comments) + print(vim.bo.baz) -- error: invalid key < -vim.wo *vim.wo* - Get or set window-scoped |local-options|. Invalid key is an error. - - This is a wrapper around |nvim_win_set_option()| and - |nvim_win_get_option()|. - - Example: > - vim.wo.cursorcolumn = true - print(vim.wo.foldmarker) +vim.wo[{winid}] *vim.wo* + Get or set window-scoped |local-options| for the window with handle {winid}. + If [{winid}] is omitted, use the current window. Invalid {winid} or key + is an error. + + This is a wrapper around |nvim_set_option_value()| and + |nvim_get_option_value()| with `opts = {scope = local, win = winid}` . + + Example: > + local winid = vim.api.nvim_get_current_win() + vim.wo[winid].number = true -- same as vim.wo.number = true + print(vim.wo.foldmarker) + print(vim.wo.quux) -- error: invalid key < ============================================================================== Lua module: vim *lua-vim* cmd({command}) *vim.cmd()* - Execute Vim script commands. - - Note that `vim.cmd` can be indexed with a command name to - return a callable function to the command. - - Example: > - - vim.cmd('echo 42') - vim.cmd([[ - augroup My_group - autocmd! - autocmd FileType c setlocal cindent - augroup END - ]]) - - -- Ex command :echo "foo" - -- Note string literals need to be double quoted. - vim.cmd('echo "foo"') - vim.cmd { cmd = 'echo', args = { '"foo"' } } - vim.cmd.echo({ args = { '"foo"' } }) - vim.cmd.echo('"foo"') - - -- Ex command :write! myfile.txt - vim.cmd('write! myfile.txt') - vim.cmd { cmd = 'write', args = { "myfile.txt" }, bang = true } - vim.cmd.write { args = { "myfile.txt" }, bang = true } - vim.cmd.write { "myfile.txt", bang = true } - - -- Ex command :colorscheme blue - vim.cmd('colorscheme blue') - vim.cmd.colorscheme('blue') + Execute Vim script commands. + + Note that `vim.cmd` can be indexed with a command name to return a + callable function to the command. + + Example: > + + vim.cmd('echo 42') + vim.cmd([[ + augroup My_group + autocmd! + autocmd FileType c setlocal cindent + augroup END + ]]) + + -- Ex command :echo "foo" + -- Note string literals need to be double quoted. + vim.cmd('echo "foo"') + vim.cmd { cmd = 'echo', args = { '"foo"' } } + vim.cmd.echo({ args = { '"foo"' } }) + vim.cmd.echo('"foo"') + + -- Ex command :write! myfile.txt + vim.cmd('write! myfile.txt') + vim.cmd { cmd = 'write', args = { "myfile.txt" }, bang = true } + vim.cmd.write { args = { "myfile.txt" }, bang = true } + vim.cmd.write { "myfile.txt", bang = true } + + -- Ex command :colorscheme blue + vim.cmd('colorscheme blue') + vim.cmd.colorscheme('blue') < - 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_exec()|, where `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. + 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_exec()|, where `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| + See also: ~ + |ex-cmd-index| *vim.connection_failure_errmsg()* connection_failure_errmsg({consequence}) - TODO: Documentation + TODO: Documentation defer_fn({fn}, {timeout}) *vim.defer_fn()* - Defers calling `fn` until `timeout` ms passes. + Defers calling `fn` until `timeout` ms passes. - Use to do a one-shot timer that calls `fn` Note: The {fn} is |schedule_wrap|ped automatically, so API - functions are safe to call. + Use to do a one-shot timer that calls `fn` Note: The {fn} is |schedule_wrap|ped automatically, so API functions are + safe to call. - Parameters: ~ - {fn} Callback to call once `timeout` expires - {timeout} Number of milliseconds to wait before calling - `fn` + Parameters: ~ + {fn} Callback to call once `timeout` expires + {timeout} Number of milliseconds to wait before calling `fn` - Return: ~ - timer luv timer object + Return: ~ + timer luv timer object *vim.deprecate()* deprecate({name}, {alternative}, {version}, {plugin}, {backtrace}) - Display a deprecation notification to the user. - - Parameters: ~ - {name} string Deprecated function. - {alternative} (string|nil) Preferred alternative - function. - {version} string Version in which the deprecated - function will be removed. - {plugin} string|nil Plugin name that the function - will be removed from. Defaults to "Nvim". - {backtrace} boolean|nil Prints backtrace. Defaults to - true. + Display a deprecation notification to the user. + + Parameters: ~ + {name} string Deprecated function. + {alternative} (string|nil) Preferred alternative function. + {version} string Version in which the deprecated function will be + removed. + {plugin} string|nil Plugin name that the function will be + removed from. Defaults to "Nvim". + {backtrace} boolean|nil Prints backtrace. Defaults to true. inspect({object}, {options}) *vim.inspect()* - Return a human-readable representation of the given object. + Return a human-readable representation of the given object. - See also: ~ - https://github.com/kikito/inspect.lua - https://github.com/mpeterv/vinspect + See also: ~ + https://github.com/kikito/inspect.lua + https://github.com/mpeterv/vinspect notify({msg}, {level}, {opts}) *vim.notify()* - Display a notification to the user. + Display a notification to the user. - This function can be overridden by plugins to display - notifications using a custom provider (such as the system - notification provider). By default, writes to |:messages|. + This function can be overridden by plugins to display notifications using + a custom provider (such as the system notification provider). By default, + writes to |:messages|. - Parameters: ~ - {msg} (string) Content of the notification to show to - the user. - {level} (number|nil) One of the values from - |vim.log.levels|. - {opts} (table|nil) Optional parameters. Unused by - default. + Parameters: ~ + {msg} (string) Content of the notification to show to the user. + {level} (number|nil) One of the values from |vim.log.levels|. + {opts} (table|nil) Optional parameters. Unused by default. notify_once({msg}, {level}, {opts}) *vim.notify_once()* - Display a notification only one time. + Display a notification only one time. - Like |vim.notify()|, but subsequent calls with the same - message will not display a notification. + Like |vim.notify()|, but subsequent calls with the same message will not + display a notification. - Parameters: ~ - {msg} (string) Content of the notification to show to - the user. - {level} (number|nil) One of the values from - |vim.log.levels|. - {opts} (table|nil) Optional parameters. Unused by - default. + Parameters: ~ + {msg} (string) Content of the notification to show to the user. + {level} (number|nil) One of the values from |vim.log.levels|. + {opts} (table|nil) Optional parameters. Unused by default. - Return: ~ - (boolean) true if message was displayed, else false + Return: ~ + (boolean) true if message was displayed, else false on_key({fn}, {ns_id}) *vim.on_key()* - Adds Lua function {fn} with namespace id {ns_id} as a listener - to every, yes every, input key. + Adds Lua function {fn} with namespace id {ns_id} as a listener to every, + yes every, input key. - The Nvim command-line option |-w| is related but does not - support callbacks and cannot be toggled dynamically. + The Nvim command-line option |-w| is related but does not support + callbacks and cannot be toggled dynamically. - Note: - {fn} will not be cleared by |nvim_buf_clear_namespace()| + Note: + {fn} will not be cleared by |nvim_buf_clear_namespace()| - Note: - {fn} will receive the keys after mappings have been - evaluated + Note: + {fn} will receive the keys after mappings have been evaluated - Parameters: ~ - {fn} function: Callback function. It should take one - string argument. On each key press, Nvim passes - the key char to fn(). |i_CTRL-V| If {fn} is nil, - it removes the callback for the associated - {ns_id} - {ns_id} number? Namespace ID. If nil or 0, generates and - returns a new |nvim_create_namespace()| id. + Parameters: ~ + {fn} function: Callback function. It should take one string + argument. On each key press, Nvim passes the key char to + fn(). |i_CTRL-V| If {fn} is nil, it removes the callback for + the associated {ns_id} + {ns_id} number? Namespace ID. If nil or 0, generates and returns a + new |nvim_create_namespace()| id. - Return: ~ - (number) Namespace id associated with {fn}. Or count of - all callbacks if on_key() is called without arguments. + Return: ~ + (number) Namespace id associated with {fn}. Or count of all callbacks + if on_key() is called without arguments. - Note: - {fn} will be removed if an error occurs while calling. + Note: + {fn} will be removed if an error occurs while calling. paste({lines}, {phase}) *vim.paste()* - Paste handler, invoked by |nvim_paste()| when a conforming UI - (such as the |TUI|) pastes text into the editor. - - Example: To remove ANSI color codes when pasting: > - - vim.paste = (function(overridden) - return function(lines, phase) - for i,line in ipairs(lines) do - -- Scrub ANSI color codes from paste input. - lines[i] = line:gsub('\27%[[0-9;mK]+', '') - end - overridden(lines, phase) - end - end)(vim.paste) + Paste handler, invoked by |nvim_paste()| when a conforming UI (such as the + |TUI|) pastes text into the editor. + + Example: To remove ANSI color codes when pasting: > + + vim.paste = (function(overridden) + return function(lines, phase) + for i,line in ipairs(lines) do + -- Scrub ANSI color codes from paste input. + lines[i] = line:gsub('\27%[[0-9;mK]+', '') + end + overridden(lines, phase) + end + end)(vim.paste) < - Parameters: ~ - {lines} |readfile()|-style list of lines to paste. - |channel-lines| - {phase} -1: "non-streaming" paste: the call contains all - lines. If paste is "streamed", `phase` indicates the stream state: - • 1: starts the paste (exactly once) - • 2: continues the paste (zero or more times) - • 3: ends the paste (exactly once) + Parameters: ~ + {lines} |readfile()|-style list of lines to paste. |channel-lines| + {phase} -1: "non-streaming" paste: the call contains all lines. If + paste is "streamed", `phase` indicates the stream state: + • 1: starts the paste (exactly once) + • 2: continues the paste (zero or more times) + • 3: ends the paste (exactly once) - Return: ~ - false if client should cancel the paste. + Return: ~ + false if client should cancel the paste. - See also: ~ - |paste| + See also: ~ + |paste| pretty_print({...}) *vim.pretty_print()* - Prints given arguments in human-readable format. Example: > - -- Print highlight group Normal and store it's contents in a variable. - local hl_normal = vim.pretty_print(vim.api.nvim_get_hl_by_name("Normal", true)) + Prints given arguments in human-readable format. Example: > + -- Print highlight group Normal and store it's contents in a variable. + local hl_normal = vim.pretty_print(vim.api.nvim_get_hl_by_name("Normal", true)) < - Return: ~ - given arguments. + Return: ~ + given arguments. - See also: ~ - |vim.inspect()| + See also: ~ + |vim.inspect()| region({bufnr}, {pos1}, {pos2}, {regtype}, {inclusive}) *vim.region()* - Get a table of lines with start, end columns for a region - marked by two points + Get a table of lines with start, end columns for a region marked by two + points - Parameters: ~ - {bufnr} (number) of buffer - {pos1} (line, column) tuple marking beginning of - region - {pos2} (line, column) tuple marking end of region - {regtype} type of selection (:help setreg) - {inclusive} (boolean) indicating whether the selection is - end-inclusive + Parameters: ~ + {bufnr} (number) of buffer + {pos1} (line, column) tuple marking beginning of region + {pos2} (line, column) tuple marking end of region + {regtype} type of selection (:help setreg) + {inclusive} (boolean) indicating whether the selection is + end-inclusive - Return: ~ - region lua table of the form {linenr = {startcol,endcol}} + Return: ~ + region lua table of the form {linenr = {startcol,endcol}} schedule_wrap({cb}) *vim.schedule_wrap()* - Defers callback `cb` until the Nvim API is safe to call. + Defers callback `cb` until the Nvim API is safe to call. - See also: ~ - |lua-loop-callbacks| - |vim.schedule()| - |vim.in_fast_event()| + See also: ~ + |lua-loop-callbacks| + |vim.schedule()| + |vim.in_fast_event()| deep_equal({a}, {b}) *vim.deep_equal()* - Deep compare values for equality + 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 + Parameters: ~ + {a} any First value + {b} any Second value - Return: ~ - (boolean) `true` if values are equals, else `false` + Return: ~ + (boolean) `true` if values are equals, else `false` deepcopy({orig}) *vim.deepcopy()* - Returns a deep copy of the given object. Non-table objects are - copied as in a typical Lua assignment, whereas table objects - are copied recursively. Functions are naively copied, so - functions in the copied table point to the same functions as - those in the input table. Userdata and threads are not copied - and will throw an error. + 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. - Parameters: ~ - {orig} (table) Table to copy + Parameters: ~ + {orig} (table) Table to copy - Return: ~ - (table) Table of copied keys and (nested) values. + Return: ~ + (table) Table of copied keys and (nested) values. endswith({s}, {suffix}) *vim.endswith()* - Tests if `s` ends with `suffix`. + Tests if `s` ends with `suffix`. - Parameters: ~ - {s} (string) String - {suffix} (string) Suffix to match + Parameters: ~ + {s} (string) String + {suffix} (string) Suffix to match - Return: ~ - (boolean) `true` if `suffix` is a suffix of `s` + Return: ~ + (boolean) `true` if `suffix` is a suffix of `s` gsplit({s}, {sep}, {plain}) *vim.gsplit()* - Splits a string at each instance of a separator. + Splits a string at each instance of a separator. - Parameters: ~ - {s} (string) String to split - {sep} (string) Separator or pattern - {plain} (boolean) If `true` use `sep` literally (passed - to string.find) + Parameters: ~ + {s} (string) String to split + {sep} (string) Separator or pattern + {plain} (boolean) If `true` use `sep` literally (passed to + string.find) - Return: ~ - (function) Iterator over the split components + Return: ~ + (function) Iterator over the split components - See also: ~ - |vim.split()| - https://www.lua.org/pil/20.2.html - http://lua-users.org/wiki/StringLibraryTutorial + See also: ~ + |vim.split()| + https://www.lua.org/pil/20.2.html + http://lua-users.org/wiki/StringLibraryTutorial is_callable({f}) *vim.is_callable()* - Returns true if object `f` can be called as a function. + Returns true if object `f` can be called as a function. - Parameters: ~ - {f} any Any object + Parameters: ~ + {f} any Any object - Return: ~ - (boolean) `true` if `f` is callable, else `false` + Return: ~ + (boolean) `true` if `f` is callable, else `false` list_extend({dst}, {src}, {start}, {finish}) *vim.list_extend()* - Extends a list-like table with the values of another list-like - table. + Extends a list-like table with the values of another list-like table. - NOTE: This mutates dst! + NOTE: This mutates dst! - Parameters: ~ - {dst} (table) List which will be modified and appended - to - {src} (table) List from which values will be inserted - {start} (number) Start index on src. Defaults to 1 - {finish} (number) Final index on src. Defaults to `#src` + Parameters: ~ + {dst} (table) List which will be modified and appended to + {src} (table) List from which values will be inserted + {start} (number) Start index on src. Defaults to 1 + {finish} (number) Final index on src. Defaults to `#src` - Return: ~ - (table) dst + Return: ~ + (table) dst - See also: ~ - |vim.tbl_extend()| + See also: ~ + |vim.tbl_extend()| list_slice({list}, {start}, {finish}) *vim.list_slice()* - Creates a copy of a table containing only elements from start - to end (inclusive) + Creates a copy of a table containing only elements from start to end + (inclusive) - Parameters: ~ - {list} (table) Table - {start} (number) Start range of slice - {finish} (number) End range of slice + Parameters: ~ + {list} (table) Table + {start} (number) Start range of slice + {finish} (number) End range of slice - Return: ~ - (table) Copy of table sliced from start to finish - (inclusive) + Return: ~ + (table) Copy of table sliced from start to finish (inclusive) pesc({s}) *vim.pesc()* - Escapes magic chars in a Lua pattern. + Escapes magic chars in |lua-patterns|. - Parameters: ~ - {s} (string) String to escape + Parameters: ~ + {s} (string) String to escape - Return: ~ - (string) %-escaped pattern string + Return: ~ + (string) %-escaped pattern string - See also: ~ - https://github.com/rxi/lume + See also: ~ + https://github.com/rxi/lume split({s}, {sep}, {kwargs}) *vim.split()* - Splits a string at each instance of a separator. + Splits a string at each instance of a separator. - Examples: > + Examples: > - split(":aa::b:", ":") --> {'','aa','','b',''} - split("axaby", "ab?") --> {'','x','y'} - split("x*yz*o", "*", {plain=true}) --> {'x','yz','o'} - split("|x|y|z|", "|", {trimempty=true}) --> {'x', 'y', 'z'} + split(":aa::b:", ":") --> {'','aa','','b',''} + split("axaby", "ab?") --> {'','x','y'} + split("x*yz*o", "*", {plain=true}) --> {'x','yz','o'} + split("|x|y|z|", "|", {trimempty=true}) --> {'x', 'y', 'z'} < - Parameters: ~ - {s} (string) String to split - {sep} (string) Separator or pattern - {kwargs} (table) Keyword arguments: - • plain: (boolean) If `true` use `sep` literally - (passed to string.find) - • trimempty: (boolean) If `true` remove empty - items from the front and back of the list + Parameters: ~ + {s} (string) String to split + {sep} (string) Separator or pattern + {kwargs} (table) Keyword arguments: + • plain: (boolean) If `true` use `sep` literally (passed to + string.find) + • trimempty: (boolean) If `true` remove empty items from the + front and back of the list - Return: ~ - (table) List of split components + Return: ~ + (table) List of split components - See also: ~ - |vim.gsplit()| + See also: ~ + |vim.gsplit()| startswith({s}, {prefix}) *vim.startswith()* - Tests if `s` starts with `prefix`. + Tests if `s` starts with `prefix`. - Parameters: ~ - {s} (string) String - {prefix} (string) Prefix to match + Parameters: ~ + {s} (string) String + {prefix} (string) Prefix to match - Return: ~ - (boolean) `true` if `prefix` is a prefix of `s` + Return: ~ + (boolean) `true` if `prefix` is a prefix of `s` 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 }` + 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. + Note that this modifies the input. - Parameters: ~ - {o} (table) Table to add the reverse to + Parameters: ~ + {o} (table) Table to add the reverse to - Return: ~ - (table) o + Return: ~ + (table) o tbl_contains({t}, {value}) *vim.tbl_contains()* - Checks if a list-like (vector) table contains `value`. + Checks if a list-like (vector) table contains `value`. - Parameters: ~ - {t} (table) Table to check - {value} any Value to compare + Parameters: ~ + {t} (table) Table to check + {value} any Value to compare - Return: ~ - (boolean) `true` if `t` contains `value` + Return: ~ + (boolean) `true` if `t` contains `value` tbl_count({t}) *vim.tbl_count()* - Counts the number of non-nil values in table `t`. + Counts the number of non-nil values in table `t`. > vim.tbl_count({ a=1, b=2 }) => 2 vim.tbl_count({ 1, 2 }) => 2 < - Parameters: ~ - {t} (table) Table + Parameters: ~ + {t} (table) Table - Return: ~ - (number) Number of non-nil values in table + Return: ~ + (number) Number of non-nil values in table - See also: ~ - https://github.com/Tieske/Penlight/blob/master/lua/pl/tablex.lua + See also: ~ + https://github.com/Tieske/Penlight/blob/master/lua/pl/tablex.lua tbl_deep_extend({behavior}, {...}) *vim.tbl_deep_extend()* - Merges recursively two or more map-like tables. + Merges recursively two or more map-like tables. - Parameters: ~ - {behavior} (string) Decides what to do if a key is found - in more than one map: - • "error": raise an error - • "keep": use value from the leftmost map - • "force": use value from the rightmost map - {...} (table) Two or more map-like tables + Parameters: ~ + {behavior} (string) Decides what to do if a key is found in more than + one map: + • "error": raise an error + • "keep": use value from the leftmost map + • "force": use value from the rightmost map + {...} (table) Two or more map-like tables - Return: ~ - (table) Merged table + Return: ~ + (table) Merged table - See also: ~ - |tbl_extend()| + See also: ~ + |tbl_extend()| tbl_extend({behavior}, {...}) *vim.tbl_extend()* - Merges two or more map-like tables. + Merges two or more map-like tables. - Parameters: ~ - {behavior} (string) Decides what to do if a key is found - in more than one map: - • "error": raise an error - • "keep": use value from the leftmost map - • "force": use value from the rightmost map - {...} (table) Two or more map-like tables + Parameters: ~ + {behavior} (string) Decides what to do if a key is found in more than + one map: + • "error": raise an error + • "keep": use value from the leftmost map + • "force": use value from the rightmost map + {...} (table) Two or more map-like tables - Return: ~ - (table) Merged table + Return: ~ + (table) Merged table - See also: ~ - |extend()| + See also: ~ + |extend()| tbl_filter({func}, {t}) *vim.tbl_filter()* - Filter a table using a predicate function + Filter a table using a predicate function - Parameters: ~ - {func} function|table Function or callable table - {t} (table) Table + Parameters: ~ + {func} function|table Function or callable table + {t} (table) Table - Return: ~ - (table) Table of filtered values + Return: ~ + (table) Table of filtered values 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. + 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 + Parameters: ~ + {t} (table) List-like table - Return: ~ - (table) Flattened copy of the given list-like table + Return: ~ + (table) Flattened copy of the given list-like table - See also: ~ - From https://github.com/premake/premake-core/blob/master/src/base/table.lua + See also: ~ + From https://github.com/premake/premake-core/blob/master/src/base/table.lua tbl_get({o}, {...}) *vim.tbl_get()* - Index into a table (first argument) via string keys passed as - subsequent arguments. Return `nil` if the key does not exist. + Index into a table (first argument) via string keys passed as subsequent + arguments. Return `nil` if the key does not exist. - Examples: > + Examples: > - vim.tbl_get({ key = { nested_key = true }}, 'key', 'nested_key') == true - vim.tbl_get({ key = {}}, 'key', 'nested_key') == nil + vim.tbl_get({ key = { nested_key = true }}, 'key', 'nested_key') == true + vim.tbl_get({ key = {}}, 'key', 'nested_key') == nil < - Parameters: ~ - {o} (table) Table to index - {...} (string) Optional strings (0 or more, variadic) via - which to index the table + Parameters: ~ + {o} (table) Table to index + {...} (string) Optional strings (0 or more, variadic) via which to + index the table - Return: ~ - any Nested value indexed by key (if it exists), else nil + Return: ~ + any Nested value indexed by key (if it exists), else nil tbl_isempty({t}) *vim.tbl_isempty()* - Checks if a table is empty. + Checks if a table is empty. - Parameters: ~ - {t} (table) Table to check + Parameters: ~ + {t} (table) Table to check - Return: ~ - (boolean) `true` if `t` is empty + Return: ~ + (boolean) `true` if `t` is empty - See also: ~ - https://github.com/premake/premake-core/blob/master/src/base/table.lua + See also: ~ + https://github.com/premake/premake-core/blob/master/src/base/table.lua tbl_islist({t}) *vim.tbl_islist()* - Tests if a Lua table can be treated as an array. + Tests if a Lua table can be treated as an array. - Empty table `{}` is assumed to be an array, unless it was - created by |vim.empty_dict()| or returned as a dict-like |API| - or Vimscript result, for example from |rpcrequest()| or - |vim.fn|. + Empty table `{}` is assumed to be an array, unless it was created by + |vim.empty_dict()| or returned as a dict-like |API| or Vimscript result, + for example from |rpcrequest()| or |vim.fn|. - Parameters: ~ - {t} (table) Table + Parameters: ~ + {t} (table) Table - Return: ~ - (boolean) `true` if array-like table, else `false` + Return: ~ + (boolean) `true` if array-like table, else `false` tbl_keys({t}) *vim.tbl_keys()* - Return a list of all keys used in a table. However, the order - of the return table of keys is not guaranteed. + Return a list of all keys used in a table. However, the order of the + return table of keys is not guaranteed. - Parameters: ~ - {t} (table) Table + Parameters: ~ + {t} (table) Table - Return: ~ - (table) List of keys + Return: ~ + (table) List of keys - See also: ~ - From https://github.com/premake/premake-core/blob/master/src/base/table.lua + See also: ~ + From https://github.com/premake/premake-core/blob/master/src/base/table.lua tbl_map({func}, {t}) *vim.tbl_map()* - Apply a function to all values of a table. + Apply a function to all values of a table. - Parameters: ~ - {func} function|table Function or callable table - {t} (table) Table + Parameters: ~ + {func} function|table Function or callable table + {t} (table) Table - Return: ~ - (table) Table of transformed values + Return: ~ + (table) Table of transformed values 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. + 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 + Parameters: ~ + {t} (table) Table - Return: ~ - (table) List of values + Return: ~ + (table) List of values trim({s}) *vim.trim()* - Trim whitespace (Lua pattern "%s") from both sides of a - string. + Trim whitespace (Lua pattern "%s") from both sides of a string. - Parameters: ~ - {s} (string) String to trim + Parameters: ~ + {s} (string) String to trim - Return: ~ - (string) String with whitespace removed from its beginning - and end + Return: ~ + (string) String with whitespace removed from its beginning and end - See also: ~ - https://www.lua.org/pil/20.2.html + See also: ~ + https://www.lua.org/pil/20.2.html validate({opt}) *vim.validate()* - Validates a parameter specification (types and values). - - Usage example: > - - function user.new(name, age, hobbies) - vim.validate{ - name={name, 'string'}, - age={age, 'number'}, - hobbies={hobbies, 'table'}, - } - ... - end + Validates a parameter specification (types and values). + + Usage example: > + + function user.new(name, age, hobbies) + vim.validate{ + name={name, 'string'}, + age={age, 'number'}, + hobbies={hobbies, 'table'}, + } + ... + end < - Examples with explicit argument values (can be run directly): > + Examples with explicit argument values (can be run directly): > - vim.validate{arg1={{'foo'}, 'table'}, arg2={'foo', 'string'}} - => NOP (success) + vim.validate{arg1={{'foo'}, 'table'}, arg2={'foo', 'string'}} + => NOP (success) - vim.validate{arg1={1, 'table'}} - => error('arg1: expected table, got number') + vim.validate{arg1={1, 'table'}} + => error('arg1: expected table, got number') - vim.validate{arg1={3, function(a) return (a % 2) == 0 end, 'even number'}} - => error('arg1: expected even number, got 3') + vim.validate{arg1={3, function(a) return (a % 2) == 0 end, 'even number'}} + => error('arg1: expected even number, got 3') < - If multiple types are valid they can be given as a list. > + If multiple types are valid they can be given as a list. > - vim.validate{arg1={{'foo'}, {'table', 'string'}}, arg2={'foo', {'table', 'string'}}} - => NOP (success) + vim.validate{arg1={{'foo'}, {'table', 'string'}}, arg2={'foo', {'table', 'string'}}} + => NOP (success) - vim.validate{arg1={1, {'string', table'}}} - => error('arg1: expected string|table, got number') + vim.validate{arg1={1, {'string', table'}}} + => error('arg1: expected string|table, got number') < - Parameters: ~ - {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 - • type_name: string|table type name, one of: - ("table", "t", "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 and only if the argument is - valid. Can optionally return an additional - informative error message as the second - returned value. - • msg: (optional) error string if validation - fails + Parameters: ~ + {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 + • type_name: string|table type name, one of: ("table", "t", + "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 + and only if the argument is valid. Can optionally return + an additional informative error message as the second + returned value. + • msg: (optional) error string if validation fails ============================================================================== Lua module: uri *lua-uri* uri_from_bufnr({bufnr}) *vim.uri_from_bufnr()* - Get a URI from a bufnr + Get a URI from a bufnr - Parameters: ~ - {bufnr} (number) + Parameters: ~ + {bufnr} (number) - Return: ~ - (string) URI + Return: ~ + (string) URI uri_from_fname({path}) *vim.uri_from_fname()* - Get a URI from a file path. + Get a URI from a file path. - Parameters: ~ - {path} (string) Path to file + Parameters: ~ + {path} (string) Path to file - Return: ~ - (string) URI + Return: ~ + (string) URI uri_to_bufnr({uri}) *vim.uri_to_bufnr()* - Get the buffer for a uri. Creates a new unloaded buffer if no - buffer for the uri already exists. + Get the buffer for a uri. Creates a new unloaded buffer if no buffer for + the uri already exists. - Parameters: ~ - {uri} (string) + Parameters: ~ + {uri} (string) - Return: ~ - (number) bufnr + Return: ~ + (number) bufnr uri_to_fname({uri}) *vim.uri_to_fname()* - Get a filename from a URI + Get a filename from a URI - Parameters: ~ - {uri} (string) + Parameters: ~ + {uri} (string) - Return: ~ - (string) filename or unchanged URI for non-file URIs + Return: ~ + (string) filename or unchanged URI for non-file URIs ============================================================================== Lua module: ui *lua-ui* input({opts}, {on_confirm}) *vim.ui.input()* - Prompts the user for input + Prompts the user for input - Example: > + Example: > - vim.ui.input({ prompt = 'Enter value for shiftwidth: ' }, function(input) - vim.o.shiftwidth = tonumber(input) - end) + vim.ui.input({ prompt = 'Enter value for shiftwidth: ' }, function(input) + vim.o.shiftwidth = tonumber(input) + end) < - Parameters: ~ - {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 supported for input. Supported - types are the same that can be supplied to - a user-defined command using the - "-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 confirms or abort the input. - `input` is what the user typed. `nil` if the - user aborted the dialog. + Parameters: ~ + {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 + supported for input. Supported types are the same that + can be supplied to a user-defined command using the + "-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 + confirms or abort the input. `input` is what the user + typed. `nil` if the user aborted the dialog. select({items}, {opts}, {on_choice}) *vim.ui.select()* - Prompts the user to pick a single item from a collection of - entries - - Example: > - - vim.ui.select({ 'tabs', 'spaces' }, { - prompt = 'Select tabs or spaces:', - format_item = function(item) - return "I'd like to choose " .. item - end, - }, function(choice) - if choice == 'spaces' then - vim.o.expandtab = true - else - vim.o.expandtab = false - end - end) + Prompts the user to pick a single item from a collection of entries + + Example: > + + vim.ui.select({ 'tabs', 'spaces' }, { + prompt = 'Select tabs or spaces:', + format_item = function(item) + return "I'd like to choose " .. item + end, + }, function(choice) + if choice == 'spaces' then + vim.o.expandtab = true + else + vim.o.expandtab = false + end + end) < - Parameters: ~ - {items} (table) Arbitrary items - {opts} (table) Additional options - • prompt (string|nil) Text of the prompt. - Defaults to `Select one of:` - • format_item (function item -> text) - Function to format an individual item from - `items`. Defaults to `tostring`. - • kind (string|nil) Arbitrary hint string - indicating the 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` within `items`. `nil` - if the user aborted the dialog. + Parameters: ~ + {items} (table) Arbitrary items + {opts} (table) Additional options + • prompt (string|nil) Text of the prompt. Defaults to + `Select one of:` + • format_item (function item -> text) Function to format + an individual item from `items`. Defaults to + `tostring`. + • kind (string|nil) Arbitrary hint string indicating the + 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` + within `items`. `nil` if the user aborted the dialog. ============================================================================== Lua module: filetype *lua-filetype* add({filetypes}) *vim.filetype.add()* - Add new filetype mappings. - - Filetype mappings can be added either by extension or by - filename (either the "tail" or the full file path). The full - file path is checked first, followed by the file name. If a - match is not found using the filename, then the filename is - matched against the list of |lua-patterns| (sorted by - priority) until a match is found. Lastly, if pattern matching - does not find a filetype, then the file extension is used. - - The filetype can be either a string (in which case it is used - as the filetype directly) or a function. If a function, it - takes the full path and buffer number of the file as arguments - (along with captures from the matched pattern, if any) and - should return a string that will be used as the buffer's - filetype. Optionally, the function can return a second - function value which, when called, modifies the state of the - buffer. This can be used to, for example, set - filetype-specific buffer variables. - - Filename patterns can specify an optional priority to resolve - cases when a file path matches multiple patterns. Higher - priorities are matched first. When omitted, the priority - defaults to 0. - - See $VIMRUNTIME/lua/vim/filetype.lua for more examples. - - Note that Lua filetype detection is disabled when - |g:do_legacy_filetype| is set. - - Example: > - - vim.filetype.add({ - extension = { - foo = 'fooscript', - bar = function(path, bufnr) - if some_condition() then - return 'barscript', function(bufnr) - -- Set a buffer variable - vim.b[bufnr].barscript_version = 2 - end - end - return 'bar' - end, - }, - filename = { - ['.foorc'] = 'toml', - ['/etc/foo/config'] = 'toml', - }, - pattern = { - ['.*/etc/foo/.*'] = 'fooscript', - -- Using an optional priority - ['.*/etc/foo/.*%.conf'] = { 'dosini', { priority = 10 } }, - ['README.(a+)$'] = function(path, bufnr, ext) - if ext == 'md' then - return 'markdown' - elseif ext == 'rst' then - return 'rst' - end - end, - }, - }) + Add new filetype mappings. + + Filetype mappings can be added either by extension or by filename (either + the "tail" or the full file path). The full file path is checked first, + followed by the file name. If a match is not found using the filename, + then the filename is matched against the list of |lua-patterns| (sorted by + priority) until a match is found. Lastly, if pattern matching does not + find a filetype, then the file extension is used. + + The filetype can be either a string (in which case it is used as the + filetype directly) or a function. If a function, it takes the full path + and buffer number of the file as arguments (along with captures from the + matched pattern, if any) and should return a string that will be used as + the buffer's filetype. Optionally, the function can return a second + function value which, when called, modifies the state of the buffer. This + can be used to, for example, set filetype-specific buffer variables. + + Filename patterns can specify an optional priority to resolve cases when a + file path matches multiple patterns. Higher priorities are matched first. + When omitted, the priority defaults to 0. + + See $VIMRUNTIME/lua/vim/filetype.lua for more examples. + + Note that Lua filetype detection is disabled when |g:do_legacy_filetype| + is set. + + Example: > + + vim.filetype.add({ + extension = { + foo = 'fooscript', + bar = function(path, bufnr) + if some_condition() then + return 'barscript', function(bufnr) + -- Set a buffer variable + vim.b[bufnr].barscript_version = 2 + end + end + return 'bar' + end, + }, + filename = { + ['.foorc'] = 'toml', + ['/etc/foo/config'] = 'toml', + }, + pattern = { + ['.*/etc/foo/.*'] = 'fooscript', + -- Using an optional priority + ['.*/etc/foo/.*%.conf'] = { 'dosini', { priority = 10 } }, + ['README.(a+)$'] = function(path, bufnr, ext) + if ext == 'md' then + return 'markdown' + elseif ext == 'rst' then + return 'rst' + end + end, + }, + }) < - To add a fallback match on contents (see - |new-filetype-scripts|), use > - - vim.filetype.add { - pattern = { - ['.*'] = { - priority = -math.huge, - function(path, bufnr) - local content = vim.filetype.getlines(bufnr, 1) - if vim.filetype.matchregex(content, [[^#!.*\<mine\>]]) then - return 'mine' - elseif vim.filetype.matchregex(content, [[\<drawing\>]]) then - return 'drawing' - end - end, - }, - }, - } + To add a fallback match on contents (see |new-filetype-scripts|), use > + + vim.filetype.add { + pattern = { + ['.*'] = { + priority = -math.huge, + function(path, bufnr) + local content = vim.filetype.getlines(bufnr, 1) + if vim.filetype.matchregex(content, [[^#!.*\<mine\>]]) then + return 'mine' + elseif vim.filetype.matchregex(content, [[\<drawing\>]]) then + return 'drawing' + end + end, + }, + }, + } < - Parameters: ~ - {filetypes} (table) A table containing new filetype maps - (see example). + Parameters: ~ + {filetypes} (table) A table containing new filetype maps (see + example). match({args}) *vim.filetype.match()* - Perform filetype detection. - - The filetype can be detected using one of three methods: - 1. Using an existing buffer - 2. Using only a file name - 3. Using only file contents - - Of these, option 1 provides the most accurate result as it - uses both the buffer's filename and (optionally) the buffer - contents. Options 2 and 3 can be used without an existing - buffer, but may not always provide a match in cases where the - filename (or contents) cannot unambiguously determine the - filetype. - - Each of the three options is specified using a key to the - single argument of this function. Example: + Perform filetype detection. + + The filetype can be detected using one of three methods: + 1. Using an existing buffer + 2. Using only a file name + 3. Using only file contents + + Of these, option 1 provides the most accurate result as it uses both the + buffer's filename and (optionally) the buffer contents. Options 2 and 3 + can be used without an existing buffer, but may not always provide a match + in cases where the filename (or contents) cannot unambiguously determine + the filetype. + + Each of the three options is specified using a key to the single argument + of this function. Example: > -- Using a buffer number @@ -2134,230 +2094,218 @@ match({args}) *vim.filetype.match()* vim.filetype.match({ contents = {'#!/usr/bin/env bash'} }) < - Parameters: ~ - {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 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 to use for matching. Can be used - with {filename}. Mutually exclusive with {buf}. - - Return: ~ - (string|nil) If a match was found, the matched filetype. - (function|nil) 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. + Parameters: ~ + {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 + 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 to use for matching. Can be used with {filename}. + Mutually exclusive with {buf}. + + Return: ~ + (string|nil) If a match was found, the matched filetype. + (function|nil) 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. ============================================================================== Lua module: keymap *lua-keymap* del({modes}, {lhs}, {opts}) *vim.keymap.del()* - Remove an existing mapping. Examples: > + Remove an existing mapping. Examples: > - vim.keymap.del('n', 'lhs') + vim.keymap.del('n', 'lhs') - vim.keymap.del({'n', 'i', 'v'}, '<leader>w', { buffer = 5 }) + vim.keymap.del({'n', 'i', 'v'}, '<leader>w', { buffer = 5 }) < - Parameters: ~ - {opts} (table) A table of optional arguments: - • buffer: (number or boolean) Remove a mapping - from the given buffer. When "true" or 0, use the - current buffer. + Parameters: ~ + {opts} (table) A table of optional arguments: + • buffer: (number or boolean) Remove a mapping from the given + buffer. When "true" or 0, use the current buffer. - See also: ~ - |vim.keymap.set()| + See also: ~ + |vim.keymap.set()| set({mode}, {lhs}, {rhs}, {opts}) *vim.keymap.set()* - Add a new |mapping|. Examples: > + Add a new |mapping|. Examples: > - -- Can add mapping to Lua functions - vim.keymap.set('n', 'lhs', function() print("real lua function") end) + -- Can add mapping to Lua functions + vim.keymap.set('n', 'lhs', function() print("real lua function") end) - -- Can use it to map multiple modes - vim.keymap.set({'n', 'v'}, '<leader>lr', vim.lsp.buf.references, { buffer=true }) + -- Can use it to map multiple modes + vim.keymap.set({'n', 'v'}, '<leader>lr', vim.lsp.buf.references, { buffer=true }) - -- Can add mapping for specific buffer - vim.keymap.set('n', '<leader>w', "<cmd>w<cr>", { silent = true, buffer = 5 }) + -- Can add mapping for specific buffer + vim.keymap.set('n', '<leader>w', "<cmd>w<cr>", { silent = true, buffer = 5 }) - -- Expr mappings - vim.keymap.set('i', '<Tab>', function() - return vim.fn.pumvisible() == 1 and "<C-n>" or "<Tab>" - end, { expr = true }) - -- <Plug> mappings - vim.keymap.set('n', '[%', '<Plug>(MatchitNormalMultiBackward)') + -- Expr mappings + vim.keymap.set('i', '<Tab>', function() + return vim.fn.pumvisible() == 1 and "<C-n>" or "<Tab>" + end, { expr = true }) + -- <Plug> mappings + vim.keymap.set('n', '[%', '<Plug>(MatchitNormalMultiBackward)') < - Note that in a mapping like: > + Note that in a mapping like: > - vim.keymap.set('n', 'asdf', require('jkl').my_fun) + vim.keymap.set('n', 'asdf', require('jkl').my_fun) < - the `require('jkl')` gets evaluated during this call in order to access the - function. If you want to avoid this cost at startup you can - wrap it in a function, for example: > + the `require('jkl')` gets evaluated during this call in order to access the function. If you + want to avoid this cost at startup you can wrap it in a function, for + example: > - vim.keymap.set('n', 'asdf', function() return require('jkl').my_fun() end) + vim.keymap.set('n', 'asdf', function() return require('jkl').my_fun() end) < - Parameters: ~ - {mode} string|table Same mode short names as - |nvim_set_keymap()|. Can also be list of modes to - create mapping on multiple modes. - {lhs} (string) Left-hand side |{lhs}| of the mapping. - {rhs} string|function Right-hand side |{rhs}| of the - mapping. Can also be a Lua function. - {opts} (table) A table of |:map-arguments| such as - "silent". In addition to the options listed in - |nvim_set_keymap()|, this table also accepts the - following keys: - • buffer: (number or boolean) Add a mapping to the - given buffer. When "true" or 0, use the current - buffer. - • remap: (boolean) Make the mapping recursive. - This is the inverse of the "noremap" option from - |nvim_set_keymap()|. Default `false`. - • replace_keycodes: (boolean) defaults to true if - "expr" is true. - - See also: ~ - |nvim_set_keymap()| + Parameters: ~ + {mode} string|table Same mode short names as |nvim_set_keymap()|. Can + also be list of modes to create mapping on multiple modes. + {lhs} (string) Left-hand side |{lhs}| of the mapping. + {rhs} string|function Right-hand side |{rhs}| of the mapping. Can + also be a Lua function. + {opts} (table) A table of |:map-arguments|. + • Accepts options accepted by the {opts} parameter in + |nvim_set_keymap()|, with the following notable differences: + • replace_keycodes: Defaults to `true` if "expr" is `true`. + • noremap: Always overridden with the inverse of "remap" + (see below). + + • In addition to those options, the table accepts the + following keys: + • buffer: (number or boolean) Add a mapping to the given + buffer. When `0` or `true`, use the current buffer. + • remap: (boolean) Make the mapping recursive. This is the + inverse of the "noremap" option from |nvim_set_keymap()|. + Defaults to `false`. + + See also: ~ + |nvim_set_keymap()| ============================================================================== Lua module: fs *lua-fs* basename({file}) *vim.fs.basename()* - Return the basename of the given file or directory + Return the basename of the given file or directory - Parameters: ~ - {file} (string) File or directory + Parameters: ~ + {file} (string) File or directory - Return: ~ - (string) Basename of {file} + Return: ~ + (string) Basename of {file} dir({path}) *vim.fs.dir()* - Return an iterator over the files and directories located in - {path} + Return an iterator over the files and directories located in {path} - Parameters: ~ - {path} (string) An absolute or relative path to the - directory to iterate over. The path is first - normalized |vim.fs.normalize()|. + Parameters: ~ + {path} (string) An absolute or relative path to the directory to + iterate over. The path is first normalized + |vim.fs.normalize()|. - Return: ~ - Iterator over files and directories in {path}. Each - iteration yields two values: name and type. Each "name" is - the basename of the file or directory relative to {path}. - Type is one of "file" or "directory". + Return: ~ + Iterator over files and directories in {path}. Each iteration yields + two values: name and type. Each "name" is the basename of the file or + directory relative to {path}. Type is one of "file" or "directory". dirname({file}) *vim.fs.dirname()* - Return the parent directory of the given file or directory + Return the parent directory of the given file or directory - Parameters: ~ - {file} (string) File or directory + Parameters: ~ + {file} (string) File or directory - Return: ~ - (string) Parent directory of {file} + Return: ~ + (string) Parent directory of {file} find({names}, {opts}) *vim.fs.find()* - Find files or directories in the given path. - - Finds any files or directories given in {names} starting from - {path}. If {upward} is "true" then the search traverses upward - through parent directories; otherwise, the search traverses - downward. Note that downward searches are recursive and may - search through many directories! If {stop} is non-nil, then - the search stops when the directory given in {stop} is - reached. The search terminates when {limit} (default 1) - matches are found. The search can be narrowed to find only - files or or only directories by specifying {type} to be "file" - or "directory", respectively. - - Parameters: ~ - {names} (string|table) Names of the files and directories - to find. Must be base names, paths and globs are - not supported. - {opts} (table) Optional keyword arguments: - • path (string): Path to begin searching from. If - omitted, the current working directory is used. - • upward (boolean, default false): If true, - search upward through parent directories. - Otherwise, search through child directories - (recursively). - • stop (string): Stop searching when this - directory is reached. The directory itself is - not searched. - • type (string): Find only files ("file") or - directories ("directory"). If omitted, both - files and directories that match {name} 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. - - Return: ~ - (table) The paths of all matching files or directories + Find files or directories in the given path. + + Finds any files or directories given in {names} starting from {path}. If + {upward} is "true" then the search traverses upward through parent + directories; otherwise, the search traverses downward. Note that downward + searches are recursive and may search through many directories! If {stop} + is non-nil, then the search stops when the directory given in {stop} is + reached. The search terminates when {limit} (default 1) matches are found. + The search can be narrowed to find only files or or only directories by + specifying {type} to be "file" or "directory", respectively. + + Parameters: ~ + {names} (string|table) Names of the files and directories to find. + Must be base names, paths and globs are not supported. + {opts} (table) Optional keyword arguments: + • path (string): Path to begin searching from. If omitted, + the current working directory is used. + • upward (boolean, default false): If true, search upward + through parent directories. Otherwise, search through child + directories (recursively). + • stop (string): Stop searching when this directory is + reached. The directory itself is not searched. + • type (string): Find only files ("file") or directories + ("directory"). If omitted, both files and directories that + match {name} 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. + + Return: ~ + (table) The paths of all matching files or directories normalize({path}) *vim.fs.normalize()* - Normalize a path to a standard format. A tilde (~) character - at the beginning of the path is expanded to the user's home - directory and any backslash (\) characters are converted to - forward slashes (/). Environment variables are also expanded. + Normalize a path to a standard format. A tilde (~) character at the + beginning of the path is expanded to the user's home directory and any + backslash (\) characters are converted to forward slashes (/). Environment + variables are also expanded. - Example: > + Example: > - vim.fs.normalize('C:\Users\jdoe') - => 'C:/Users/jdoe' + vim.fs.normalize('C:\Users\jdoe') + => 'C:/Users/jdoe' - vim.fs.normalize('~/src/neovim') - => '/home/jdoe/src/neovim' + vim.fs.normalize('~/src/neovim') + => '/home/jdoe/src/neovim' - vim.fs.normalize('$XDG_CONFIG_HOME/nvim/init.vim') - => '/Users/jdoe/.config/nvim/init.vim' + vim.fs.normalize('$XDG_CONFIG_HOME/nvim/init.vim') + => '/Users/jdoe/.config/nvim/init.vim' < - Parameters: ~ - {path} (string) Path to normalize + Parameters: ~ + {path} (string) Path to normalize - Return: ~ - (string) Normalized path + Return: ~ + (string) Normalized path parents({start}) *vim.fs.parents()* - Iterate over all the parents of the given file or directory. + Iterate over all the parents of the given file or directory. - Example: > + Example: > - local root_dir - for dir in vim.fs.parents(vim.api.nvim_buf_get_name(0)) do - if vim.fn.isdirectory(dir .. "/.git") == 1 then - root_dir = dir - break - end - end + local root_dir + for dir in vim.fs.parents(vim.api.nvim_buf_get_name(0)) do + if vim.fn.isdirectory(dir .. "/.git") == 1 then + root_dir = dir + break + end + end - if root_dir then - print("Found git repository at", root_dir) - end + if root_dir then + print("Found git repository at", root_dir) + end < - Parameters: ~ - {start} (string) Initial file or directory. + Parameters: ~ + {start} (string) Initial file or directory. - Return: ~ - (function) Iterator + Return: ~ + (function) Iterator - vim:tw=78:ts=8:ft=help:norl: + vim:tw=78:ts=8:sw=4:sts=4:et:ft=help:norl: diff --git a/runtime/doc/luaref.txt b/runtime/doc/luaref.txt new file mode 100644 index 0000000000..9dbd2d4de5 --- /dev/null +++ b/runtime/doc/luaref.txt @@ -0,0 +1,4966 @@ +*luaref.txt* Nvim + *luaref* *Lua-Reference* + + LUA REFERENCE MANUAL + + + Version 0.3.0 + August 7th, 2022 + + + Vimdoc version (c) 2006 by Luis Carvalho + <lexcarvalho at gmail dot com> + + Adapted from "Lua: 5.1 reference manual" + R. Ierusalimschy, L. H. de Figueiredo, W. Celes + Copyright (c) 2006 Lua.org, PUC-Rio. + + + See |luaref-doc| for information on this manual. + See |luaref-copyright| for copyright and licenses. + + + CONTENTS + ============ + + 1 INTRODUCTION........................|luaref-intro| + + 2 THE LANGUAGE........................|luaref-language| + 2.1 Lexical Conventions...............|luaref-langLexConv| + 2.2 Values and Types..................|luaref-langValTypes| + 2.2.1 Coercion........................|luaref-langCoercion| + 2.3 Variables.........................|luaref-langVariables| + 2.4 Statements........................|luaref-langStats| + 2.4.1 Chunks..........................|luaref-langChunks| + 2.4.2 Blocks..........................|luaref-langBlocks| + 2.4.3 Assignment......................|luaref-langAssign| + 2.4.4 Control Structures..............|luaref-langContStructs| + 2.4.5 For Statement...................|luaref-langForStat| + 2.4.6 Function Calls as Statements....|luaref-langFuncStat| + 2.4.7 Local Declarations..............|luaref-langLocalDec| + 2.5 Expressions.......................|luaref-langExpressions| + 2.5.1 Arithmetic Operators............|luaref-langArithOp| + 2.5.2 Relational Operators............|luaref-langRelOp| + 2.5.3 Logical Operators...............|luaref-langLogOp| + 2.5.4 Concatenation...................|luaref-langConcat| + 2.5.5 The Length Operator.............|luaref-langLength| + 2.5.6 Precedence......................|luaref-langPrec| + 2.5.7 Table Constructors..............|luaref-langTableConst| + 2.5.8 Function Calls..................|luaref-langFuncCalls| + 2.5.9 Function Definitions............|luaref-langFuncDefs| + 2.6 Visibility Rules..................|luaref-langVisibRules| + 2.7 Error Handling....................|luaref-langError| + 2.8 Metatables........................|luaref-langMetatables| + 2.9 Environments......................|luaref-langEnvironments| + 2.10 Garbage Collection...............|luaref-langGC| + 2.10.1 Garbage-Collection Metamethods.|luaref-langGCMeta| + 2.10.2 Weak Tables....................|luaref-langWeaktables| + 2.11 Coroutines.......................|luaref-langCoro| + + 3 THE APPLICATION PROGRAM INTERFACE...|luaref-api| + 3.1 The Stack.........................|luaref-apiStack| + 3.2 Stack Size........................|luaref-apiStackSize| + 3.3 Pseudo-Indices....................|luaref-apiPseudoIndices| + 3.4 C Closures........................|luaref-apiCClosures| + 3.5 Registry..........................|luaref-apiRegistry| + 3.6 Error Handling in C...............|luaref-apiError| + 3.7 Functions and Types...............|luaref-apiFunctions| + 3.8 The Debug Interface...............|luaref-apiDebug| + + 4 THE AUXILIARY LIBRARY...............|luaref-aux| + 4.1 Functions and Types...............|luaref-auxFunctions| + + 5 STANDARD LIBRARIES..................|luaref-lib| + 5.1 Basic Functions...................|luaref-libBasic| + 5.2 Coroutine Manipulation............|luaref-libCoro| + 5.3 Modules...........................|luaref-libModule| + 5.4 String Manipulation...............|luaref-libString| + 5.4.1 Patterns........................|luaref-libStringPat| + 5.5 Table Manipulation................|luaref-libTable| + 5.6 Mathematical Functions............|luaref-libMath| + 5.7 Input and Output Facilities.......|luaref-libIO| + 5.8 Operating System Facilities.......|luaref-libOS| + 5.9 The Debug Library.................|luaref-libDebug| + + A BIBLIOGRAPHY........................|luaref-bibliography| + B COPYRIGHT & LICENSES................|luaref-copyright| + C LUAREF DOC..........................|luaref-doc| + + +============================================================================== +1 INTRODUCTION *luaref-intro* +============================================================================== + +Lua is an extension programming language designed to support general +procedural programming with data description facilities. It also offers good +support for object-oriented programming, functional programming, and +data-driven programming. Lua is intended to be used as a powerful, +light-weight scripting language for any program that needs one. Lua is +implemented as a library, written in clean C (that is, in the common subset of +ANSI C and C++). + +Being an extension language, Lua has no notion of a "main" program: it only +works embedded in a host client, called the embedding program or simply the +host. This host program can invoke functions to execute a piece of Lua code, +can write and read Lua variables, and can register C functions to be called by +Lua code. Through the use of C functions, Lua can be augmented to cope with a +wide range of different domains, thus creating customized programming +languages sharing a syntactical framework. + +Lua is free software, and is provided as usual with no guarantees, as stated +in its license. The implementation described in this manual is available at +Lua's official web site, www.lua.org. + +Like any other reference manual, this document is dry in places. For a +discussion of the decisions behind the design of Lua, see references at +|luaref-bibliography|. For a detailed introduction to programming in Lua, see +Roberto's book, Programming in Lua. + +Lua means "moon" in Portuguese and is pronounced LOO-ah. + +============================================================================== +2 THE LANGUAGE *luaref-language* +============================================================================== + +This section describes the lexis, the syntax, and the semantics of Lua. In +other words, this section describes which tokens are valid, how they can be +combined, and what their combinations mean. + +The language constructs will be explained using the usual extended BNF +notation, in which { `a` } means 0 or more `a`'s, and [ `a` ] means an optional `a`. + +============================================================================== +2.1 Lexical Conventions *luaref-langLexConv* + + *luaref-names* *luaref-identifiers* +Names (also called identifiers) in Lua can be any string of letters, digits, +and underscores, not beginning with a digit. This coincides with the +definition of identifiers in most languages. (The definition of letter depends +on the current locale: any character considered alphabetic by the current +locale can be used in an identifier.) Identifiers are used to name variables +and table fields. + +The following keywords are reserved and cannot be used as names: +> + and break do else elseif + end false for function if + in local nil not or + repeat return then true until while +< +Lua is a case-sensitive language: `and` is a reserved word, but `And` and `AND` are +two different, valid names. As a convention, names starting with an underscore +followed by uppercase letters (such as `_VERSION`) are reserved for internal +global variables used by Lua. + +The following strings denote other tokens: +> + + - * / % ^ # + == ~= <= >= < > = + ( ) { } [ ] + ; : , . .. ... +< + *luaref-literal* +Literal strings can be delimited by matching single or double quotes, and can +contain the following C-like escape sequences: + + - `\a` bell + - `\b` backspace + - `\f` form feed + - `\n` newline + - `\r` carriage return + - `\t` horizontal tab + - `\v` vertical tab + - `\\` backslash + - `\"` quotation mark (double quote) + - `\'` apostrophe (single quote) + +Moreover, a backslash followed by a real newline results in a newline in the +string. A character in a string may also be specified by its numerical value +using the escape sequence `\ddd`, where `ddd` is a sequence of up to three +decimal digits. (Note that if a numerical escape is to be followed by a digit, +it must be expressed using exactly three digits.) Strings in Lua may contain +any 8-bit value, including embedded zeros, which can be specified as `\0`. + +To put a double (single) quote, a newline, a backslash, or an embedded zero +inside a literal string enclosed by double (single) quotes you must use an +escape sequence. Any other character may be directly inserted into the +literal. (Some control characters may cause problems for the file system, but +Lua has no problem with them.) + +Literal strings can also be defined using a long format enclosed by long +brackets. We define an opening long bracket of level n as an opening square +bracket followed by n equal signs followed by another opening square bracket. +So, an opening long bracket of level 0 is written as `[[`, an opening long +bracket of level 1 is written as `[=[`, and so on. +A closing long bracket is defined similarly; for instance, a closing long +bracket of level 4 is written as `]====]`. A long string starts with an +opening long bracket of any level and ends at the first closing long bracket +of the same level. Literals in this bracketed form may run for several lines, +do not interpret any escape sequences, and ignore long brackets of any other +level. They may contain anything except a closing bracket of the proper level. + +For convenience, when the opening long bracket is immediately followed by a +newline, the newline is not included in the string. As an example, in a system +using ASCII (in which `a` is coded as 97, newline is coded as 10, and `1` is +coded as 49), the five literals below denote the same string: +> + a = 'alo\n123"' + a = "alo\n123\"" + a = '\97lo\10\04923"' + a = [[alo + 123"]] + a = [==[ + alo + 123"]==] +< + *luaref-numconstant* +A numerical constant may be written with an optional decimal part and an +optional decimal exponent. Lua also accepts integer hexadecimal constants, by +prefixing them with `0x`. Examples of valid numerical constants are +> + 3 3.0 3.1416 314.16e-2 0.31416E1 0xff 0x56 +< + *luaref-comment* +A comment starts with a double hyphen (`--`) anywhere outside a string. If the +text immediately after `--` is not an opening long bracket, the comment is a +short comment, which runs until the end of the line. Otherwise, it is a long +comment, which runs until the corresponding closing long bracket. Long +comments are frequently used to disable code temporarily. + +============================================================================== +2.2 Values and Types *luaref-langValTypes* + +Lua is a dynamically typed language. This means that variables do not have +types; only values do. There are no type definitions in the language. All +values carry their own type. + +All values in Lua are first-class values. This means that all values can be +stored in variables, passed as arguments to other functions, and returned as +results. + + *luaref-types* *luaref-nil* + *luaref-true* *luaref-false* + *luaref-number* *luaref-string* +There are eight basic types in Lua: `nil`, `boolean`, `number`, `string`, +`function`, `userdata`, `thread`, and `table`. Nil is the type of the value +`nil`, whose main property is to be different from any other value; it usually +represents the absence of a useful value. Boolean is the type of the values +`false` and `true`. Both `nil` and `false` make a condition false; any other +value makes it true. Number represents real (double-precision floating-point) +numbers. (It is easy to build Lua interpreters that use other internal +representations for numbers, such as single-precision float or long integers; +see file `luaconf.h`.) String represents arrays of characters. Lua is 8-bit +clean: strings may contain any 8-bit character, including embedded zeros +(`\0`) (see |luaref-literal|). + +Lua can call (and manipulate) functions written in Lua and functions written +in C (see |luaref-langFuncCalls|). + + *luaref-userdatatype* +The type userdata is provided to allow arbitrary C data to be stored in Lua +variables. This type corresponds to a block of raw memory and has no +pre-defined operations in Lua, except assignment and identity test. However, +by using metatables, the programmer can define operations for userdata values +(see |luaref-langMetatables|). Userdata values cannot be created or modified +in Lua, only through the C API. This guarantees the integrity of data owned by +the host program. + + *luaref-thread* +The type `thread` represents independent threads of execution and it is used to +implement coroutines (see |luaref-langCoro|). Do not confuse Lua threads with +operating-system threads. Lua supports coroutines on all systems, even those +that do not support threads. + + *luaref-table* +The type `table` implements associative arrays, that is, arrays that can be +indexed not only with numbers, but with any value (except `nil`). Tables can +be heterogeneous; that is, they can contain values of all types (except +`nil`). Tables are the sole data structuring mechanism in Lua; they may be +used to represent ordinary arrays, symbol tables, sets, records, graphs, +trees, etc. To represent records, Lua uses the field name as an index. The +language supports this representation by providing `a.name` as syntactic sugar +for `a["name"]`. There are several convenient ways to create tables in Lua +(see |luaref-langTableConst|). + +Like indices, the value of a table field can be of any type (except `nil`). In +particular, because functions are first-class values, table fields may contain +functions. Thus tables may also carry methods (see |luaref-langFuncDefs|). + +Tables, functions, threads and (full) userdata values are objects: variables +do not actually contain these values, only references to them. Assignment, +parameter passing, and function returns always manipulate references to such +values; these operations do not imply any kind of copy. + +The library function `type` returns a string describing the type of a given +value (see |luaref-type|). + +------------------------------------------------------------------------------ +2.2.1 Coercion *luaref-langCoercion* + +Lua provides automatic conversion between string and number values at run +time. Any arithmetic operation applied to a string tries to convert that +string to a number, following the usual conversion rules. Conversely, whenever +a number is used where a string is expected, the number is converted to a +string, in a reasonable format. For complete control of how numbers are +converted to strings, use the `format` function from the string library (see +|luaref-string.format|). + +============================================================================== +2.3 Variables *luaref-langVariables* + +Variables are places that store values. There are three kinds of variables in +Lua: global variables, local variables, and table fields. + +A single name can denote a global variable or a local variable (or a +function's formal parameter, which is a particular form of local variable): +> + var ::= Name +< +Name denotes identifiers, as defined in |luaref-langLexConv|. + +Any variable is assumed to be global unless explicitly declared as a local +(see |luaref-langLocalDec|). Local variables are lexically scoped: local +variables can be freely accessed by functions defined inside their scope (see +|luaref-langVisibRules|). + +Before the first assignment to a variable, its value is `nil`. + +Square brackets are used to index a table: +> + var ::= prefixexp [ exp ] +< +The first expression (`prefixexp`) should result in a table value; the second +expression (`exp`) identifies a specific entry inside that table. The +expression denoting the table to be indexed has a restricted syntax; see +|luaref-langExpressions| for details. + +The syntax `var.NAME` is just syntactic sugar for `var["NAME"]` : +> + var ::= prefixexp . Name +< +All global variables live as fields in ordinary Lua tables, called environment +tables or simply environments (see |luaref-langEnvironments|). Each function +has its own reference to an environment, so that all global variables in this +function will refer to this environment table. When a function is created, it +inherits the environment from the function that created it. To get the +environment table of a Lua function, you call `getfenv` (see +|luaref-getfenv|). To replace it, you call `setfenv` (see |luaref-setfenv|). +(You can only manipulate the environment of C functions through the debug +library; see |luaref-libDebug|.) + +An access to a global variable `x` is equivalent to `_env.x`, which in turn is +equivalent to +> + gettable_event(_env, "x") +< +where `_env` is the environment of the running function. (The `_env` variable is +not defined in Lua. We use it here only for explanatory purposes.) + +The meaning of accesses to global variables and table fields can be changed +via metatables. An access to an indexed variable `t[i]` is equivalent to a +call `gettable_event(t,i)`. (See |luaref-langMetatables| for a complete +description of the `gettable_event` function. This function is not defined or +callable in Lua. We use it here only for explanatory purposes.) + +============================================================================== +2.4 Statements *luaref-langStats* + +Lua supports an almost conventional set of statements, similar to those in +Pascal or C. This set includes assignment, control structures, function +calls, and variable declarations. + +------------------------------------------------------------------------------ +2.4.1 Chunks *luaref-chunk* *luaref-langChunks* + +The unit of execution of Lua is called a chunk. A chunk is simply a sequence +of statements, which are executed sequentially. Each statement can be +optionally followed by a semicolon: +> + chunk ::= {stat [ ; ]} +< +There are no empty statements and thus `;;` is not legal. + +Lua handles a chunk as the body of an anonymous function with a variable +number of arguments (see |luaref-langFuncDefs|). As such, chunks can define +local variables, receive arguments, and return values. + +A chunk may be stored in a file or in a string inside the host program. When a +chunk is executed, first it is pre-compiled into instructions for a virtual +machine, and then the compiled code is executed by an interpreter for the +virtual machine. + +Chunks may also be pre-compiled into binary form; see program `luac` for +details. Programs in source and compiled forms are interchangeable; Lua +automatically detects the file type and acts accordingly. + +------------------------------------------------------------------------------ +2.4.2 Blocks *luaref-block* *luaref-langBlocks* + +A block is a list of statements; syntactically, a block is the same as a +chunk: +> + block ::= chunk +< + *luaref-do* *luaref-end* +A block may be explicitly delimited to produce a single statement: +> + stat ::= do block end +< +Explicit blocks are useful to control the scope of variable declarations. +Explicit blocks are also sometimes used to add a `return` or `break` statement +in the middle of another block (see |luaref-langContStructs|). + +------------------------------------------------------------------------------ +2.4.3 Assignment *luaref-langAssign* + +Lua allows multiple assignment. Therefore, the syntax for assignment defines a +list of variables on the left side and a list of expressions on the right +side. The elements in both lists are separated by commas: +> + stat ::= varlist1 = explist1 + varlist1 ::= var { , var } + explist1 ::= exp { , exp } +< +Expressions are discussed in |luaref-langExpressions|. + +Before the assignment, the list of values is adjusted to the length of the +list of variables. If there are more values than needed, the excess values are +thrown away. If there are fewer values than needed, the list is extended with +as many `nil`s as needed. If the list of expressions ends with a function +call, then all values returned by this call enter in the list of values, +before the adjustment (except when the call is enclosed in parentheses; see +|luaref-langExpressions|). + +The assignment statement first evaluates all its expressions and only then are +the assignments performed. Thus the code +> + i = 3 + i, a[i] = i+1, 20 +< +sets `a[3]` to 20, without affecting `a[4]` because the `i` in `a[i]` is evaluated (to +3) before it is assigned 4. Similarly, the line +> + x, y = y, x +< +exchanges the values of `x` and `y`. + +The meaning of assignments to global variables and table fields can be changed +via metatables. An assignment to an indexed variable `t[i] = val` is +equivalent to `settable_event(t,i,val)`. (See |luaref-langMetatables| for a +complete description of the `settable_event` function. This function is not +defined or callable in Lua. We use it here only for explanatory purposes.) + +An assignment to a global variable `x = val` is equivalent to the +assignment `_env.x = val`, which in turn is equivalent to +> + settable_event(_env, "x", val) +< +where `_env` is the environment of the running function. (The `_env` variable is +not defined in Lua. We use it here only for explanatory purposes.) + +------------------------------------------------------------------------------ +2.4.4 Control Structures *luaref-langContStructs* + + *luaref-if* *luaref-then* *luaref-else* *luaref-elseif* + *luaref-while* *luaref-repeat* *luaref-until* +The control structures `if`, `while`, and `repeat` have the usual meaning and +familiar syntax: +> + stat ::= while exp do block end + stat ::= repeat block until exp + stat ::= if exp then block { elseif exp then block } + [ else block ] end +< +Lua also has a `for` statement, in two flavors (see |luaref-langForStat|). + +The condition expression of a control structure may return any value. +Both `false` and `nil` are considered false. All values different +from `nil` and `false` are considered true (in particular, the number 0 and the +empty string are also true). + +In the `repeat-until` loop, the inner block does not end at the `until` keyword, +but only after the condition. So, the condition can refer to local variables +declared inside the loop block. + + *luaref-return* +The `return` statement is used to return values from a function or a chunk +(which is just a function). Functions and chunks may return more than one +value, so the syntax for the `return` statement is + + `stat ::=` `return` `[explist1]` + + *luaref-break* +The `break` statement is used to terminate the execution of a `while`, `repeat`, +or `for` loop, skipping to the next statement after the loop: + + `stat ::=` `break` + +A `break` ends the innermost enclosing loop. + +The `return` and `break` statements can only be written as the `last` +statement of a block. If it is really necessary to `return` or `break` in the +middle of a block, then an explicit inner block can be used, as in the idioms +`do return end` and `do break end`, because now `return` and `break` are +the last statements in their (inner) blocks. + +------------------------------------------------------------------------------ +2.4.5 For Statement *luaref-for* *luaref-langForStat* + +The `for` statement has two forms: one numeric and one generic. + +The numeric `for` loop repeats a block of code while a control variable runs +through an arithmetic progression. It has the following syntax: +> + stat ::= for Name = exp , exp [ , exp ] do block end +< +The `block` is repeated for `name` starting at the value of the first `exp`, until +it passes the second `exp` by steps of the third `exp`. More precisely, +a `for` statement like + + `for var =` `e1, e2, e3` `do` `block` `end` + +is equivalent to the code: + + `do` + `local` `var, limit, step` `= tonumber(e1), tonumber(e2), tonumber(e3)` + `if not (` `var` `and` `limit` `and` `step` `) then error() end` + `while (` `step` `>0 and` `var` `<=` `limit` `)` + `or (` `step` `<=0 and` `var` `>=` `limit` `) do` + `block` + `var` `=` `var` `+` `step` + `end` + `end` + +Note the following: + + - All three control expressions are evaluated only once, before the loop + starts. They must all result in numbers. + - `var`, `limit` and `step` are invisible variables. The names are here for + explanatory purposes only. + - If the third expression (the step) is absent, then a step of 1 is used. + - You can use `break` to exit a `for` loop. + - The loop variable `var` is local to the loop; you cannot use its value + after the `for` ends or is broken. If you need this value, assign it to + another variable before breaking or exiting the loop. + + *luaref-in* +The generic `for` statement works over functions, called iterators. On each +iteration, the iterator function is called to produce a new value, stopping +when this new value is `nil`. The generic `for` loop has the following syntax: +> + stat ::= for namelist in explist1 do block end + namelist ::= Name { , Name } +< +A `for` statement like + + `for` `var1, ..., varn` `in` `explist` `do` `block` `end` + +is equivalent to the code: + + `do` + `local` `f, s, var` `=` `explist` + `while true do` + `local` `var1, ..., varn` `=` `f(s, var)` + `var` `=` `var1` + `if` `var` `== nil then break end` + `block` + `end` + `end` + +Note the following: + + - `explist` is evaluated only once. Its results are an iterator function, + a `state`, and an initial value for the first iterator variable. + - `f`, `s`, and `var` are invisible variables. The names are here for + explanatory purposes only. + - You can use `break` to exit a `for` loop. + - The loop variables `var1, ..., varn` are local to the loop; you cannot use + their values after the `for` ends. If you need these values, then assign + them to other variables before breaking or exiting the loop. + +------------------------------------------------------------------------------ +2.4.6 Function Calls as Statements *luaref-langFuncStat* + +To allow possible side-effects, function calls can be executed as statements: +> + stat ::= functioncall +< +In this case, all returned values are thrown away. Function calls are +explained in |luaref-langFuncCalls|. + +------------------------------------------------------------------------------ +2.4.7 Local Declarations *luaref-local* *luaref-langLocalDec* + +Local variables may be declared anywhere inside a block. The declaration may +include an initial assignment: +> + stat ::= local namelist [ = explist1 ] + namelist ::= Name { , Name } +< +If present, an initial assignment has the same semantics of a multiple +assignment (see |luaref-langAssign|). Otherwise, all variables are initialized +with `nil`. + +A chunk is also a block (see |luaref-langChunks|), and so local variables can be +declared in a chunk outside any explicit block. The scope of such local +variables extends until the end of the chunk. + +The visibility rules for local variables are explained in +|luaref-langVisibRules|. + +============================================================================== +2.5 Expressions *luaref-langExpressions* + +The basic expressions in Lua are the following: +> + exp ::= prefixexp + exp ::= nil | false | true + exp ::= Number + exp ::= String + exp ::= function + exp ::= tableconstructor + exp ::= ... + exp ::= exp binop exp + exp ::= unop exp + prefixexp ::= var | functioncall | ( exp ) +< +Numbers and literal strings are explained in |luaref-langLexConv|; variables are +explained in |luaref-langVariables|; function definitions are explained in +|luaref-langFuncDefs|; function calls are explained in |luaref-langFuncCalls|; +table constructors are explained in |luaref-langTableConst|. Vararg expressions, +denoted by three dots (`...`), can only be used inside vararg functions; +they are explained in |luaref-langFuncDefs|. + +Binary operators comprise arithmetic operators (see |luaref-langArithOp|), +relational operators (see |luaref-langRelOp|), logical operators (see +|luaref-langLogOp|), and the concatenation operator (see |luaref-langConcat|). +Unary operators comprise the unary minus (see |luaref-labgArithOp|), the unary +`not` (see |luaref-langLogOp|), and the unary length operator (see +|luaref-langLength|). + +Both function calls and vararg expressions may result in multiple values. If +the expression is used as a statement (see |luaref-langFuncStat|) +(only possible for function calls), then its return list is adjusted to zero +elements, thus discarding all returned values. If the expression is used as +the last (or the only) element of a list of expressions, then no adjustment is +made (unless the call is enclosed in parentheses). In all other contexts, Lua +adjusts the result list to one element, discarding all values except the first +one. + +Here are some examples: +> + f() -- adjusted to 0 results + g(f(), x) -- f() is adjusted to 1 result + g(x, f()) -- g gets x plus all results from f() + a,b,c = f(), x -- f() is adjusted to 1 result (c gets nil) + a,b = ... -- a gets the first vararg parameter, b gets + -- the second (both a and b may get nil if there + -- is no corresponding vararg parameter) + + a,b,c = x, f() -- f() is adjusted to 2 results + a,b,c = f() -- f() is adjusted to 3 results + return f() -- returns all results from f() + return ... -- returns all received vararg parameters + return x,y,f() -- returns x, y, and all results from f() + {f()} -- creates a list with all results from f() + {...} -- creates a list with all vararg parameters + {f(), nil} -- f() is adjusted to 1 result +< +An expression enclosed in parentheses always results in only one value. Thus, +`(f(x,y,z))` is always a single value, even if `f` returns several values. +(The value of `(f(x,y,z))` is the first value returned by `f` or `nil` if `f` does not +return any values.) + +------------------------------------------------------------------------------ +2.5.1 Arithmetic Operators *luaref-langArithOp* + +Lua supports the usual arithmetic operators: the binary `+` (addition), +`-` (subtraction), `*` (multiplication), `/` (division), `%` (modulo) +and `^` (exponentiation); and unary `-` (negation). If the operands are numbers, +or strings that can be converted to numbers (see |luaref-langCoercion|), then all +operations have the usual meaning. Exponentiation works for any exponent. For +instance, `x^(-0.5)` computes the inverse of the square root of `x`. Modulo is +defined as +> + a % b == a - math.floor(a/b)*b +< +That is, it is the remainder of a division that rounds the quotient towards +minus infinity. + +------------------------------------------------------------------------------ +2.5.2 Relational Operators *luaref-langRelOp* + +The relational operators in Lua are +> + == ~= < > <= >= +< +These operators always result in `false` or `true`. + +Equality (`==`) first compares the type of its operands. If the types are +different, then the result is `false`. Otherwise, the values of the operands +are compared. Numbers and strings are compared in the usual way. Objects +(tables, userdata, threads, and functions) are compared by reference: two +objects are considered equal only if they are the same object. Every time you +create a new object (a table, userdata, or function), this new object is +different from any previously existing object. + +You can change the way that Lua compares tables and userdata using the "eq" +metamethod (see |luaref-langMetatables|). + +The conversion rules of coercion |luaref-langCoercion| do not apply to +equality comparisons. Thus, `"0"==0` evaluates to `false`, and `t[0]` and +`t["0"]` denote different entries in a table. + +The operator `~=` is exactly the negation of equality (`==`). + +The order operators work as follows. If both arguments are numbers, then they +are compared as such. Otherwise, if both arguments are strings, then their +values are compared according to the current locale. Otherwise, Lua tries to +call the "lt" or the "le" metamethod (see |luaref-langMetatables|). + +------------------------------------------------------------------------------ +2.5.3 Logical Operators *luaref-langLogOp* + +The logical operators in Lua are +> + and or not +< +Like the control structures (see |luaref-langContStructs|), all logical operators +consider both `false` and `nil` as false and anything else as true. + + *luaref-not* *luaref-and* *luaref-or* +The negation operator `not` always returns `false` or `true`. The conjunction +operator `and` returns its first argument if this value is `false` or `nil`; +otherwise, `and` returns its second argument. The disjunction +operator `or` returns its first argument if this value is different +from `nil` and `false`; otherwise, `or` returns its second argument. +Both `and` and `or` use short-cut evaluation, that is, the second operand is +evaluated only if necessary. Here are some examples: +> + 10 or 20 --> 10 + 10 or error() --> 10 + nil or "a" --> "a" + nil and 10 --> nil + false and error() --> false + false and nil --> false + false or nil --> nil + 10 and 20 --> 20 +< +(In this manual, `-->` indicates the result of the preceding expression.) + +------------------------------------------------------------------------------ +2.5.4 Concatenation *luaref-langConcat* + +The string concatenation operator in Lua is denoted by two dots (`..`). +If both operands are strings or numbers, then they are converted to strings +according to the rules mentioned in |luaref-langCoercion|. Otherwise, the +"concat" metamethod is called (see |luaref-langMetatables|). + +------------------------------------------------------------------------------ +2.5.5 The Length Operator *luaref-langLength* + +The length operator is denoted by the unary operator `#`. The length of a +string is its number of bytes (that is, the usual meaning of string length +when each character is one byte). + +The length of a table `t` is defined to be any integer index `n` such that `t[n]` is +not `nil` and `t[n+1]` is `nil`; moreover, if `t[1]` is `nil`, `n` may be zero. For a +regular array, with non-nil values from 1 to a given `n`, its length is exactly +that `n`, the index of its last value. If the array has "holes" (that +is, `nil` values between other non-nil values), then `#t` may be any of the +indices that directly precedes a `nil` value (that is, it may consider any +such `nil` value as the end of the array). + +------------------------------------------------------------------------------ +2.5.6 Precedence *luaref-langPrec* + +Operator precedence in Lua follows the table below, from lower to higher +priority: +> + or + and + < > <= >= ~= == + .. + + - + * / + not # - (unary) + ^ +< +As usual, you can use parentheses to change the precedences in an expression. +The concatenation (`..`) and exponentiation (`^`) operators are right +associative. All other binary operators are left associative. + +------------------------------------------------------------------------------ +2.5.7 Table Constructors *luaref-langTableConst* + +Table constructors are expressions that create tables. Every time a +constructor is evaluated, a new table is created. Constructors can be used to +create empty tables, or to create a table and initialize some of its fields. +The general syntax for constructors is +> + tableconstructor ::= { [ fieldlist ] } + fieldlist ::= field { fieldsep field } [ fieldsep ] + field ::= [ exp ] = exp | Name = exp | exp + fieldsep ::= , | ; +< +Each field of the form `[exp1] = exp2` adds to the new table an entry with +key `exp1` and value `exp2`. A field of the form `name = exp` is equivalent to +`["name"] = exp`. Finally, fields of the form `exp` are equivalent to +`[i] = exp`, where `i` are consecutive numerical integers, starting with 1. +Fields in the other formats do not affect this counting. For example, +> + a = { [f(1)] = g; "x", "y"; x = 1, f(x), [30] = 23; 45 } +< +is equivalent to +> + do + local t = {} + t[f(1)] = g + t[1] = "x" -- 1st exp + t[2] = "y" -- 2nd exp + t.x = 1 -- temp["x"] = 1 + t[3] = f(x) -- 3rd exp + t[30] = 23 + t[4] = 45 -- 4th exp + a = t + end +< +If the last field in the list has the form `exp` and the expression is a +function call, then all values returned by the call enter the list +consecutively (see |luaref-langFuncCalls|). To avoid this, enclose the function +call in parentheses (see |luaref-langExpressions|). + +The field list may have an optional trailing separator, as a convenience for +machine-generated code. + +------------------------------------------------------------------------------ +2.5.8 Function Calls *luaref-function* *luaref-langFuncCalls* + +A function call in Lua has the following syntax: +> + functioncall ::= prefixexp args +< +In a function call, first `prefixexp` and `args` are evaluated. If the value +of `prefixexp` has type `function`, then this function is called with the given +arguments. Otherwise, the `prefixexp` "call" metamethod is called, having as +first parameter the value of `prefixexp`, followed by the original call +arguments (see |luaref-langMetatables|). + +The form +> + functioncall ::= prefixexp : Name args +< +can be used to call "methods". A call `v:name(` `args` `)` is syntactic sugar +for `v.name(v,` `args` `)`, except that `v` is evaluated only once. + +Arguments have the following syntax: +> + args ::= ( [ explist1 ] ) + args ::= tableconstructor + args ::= String +< +All argument expressions are evaluated before the call. A call of the +form `f{` `fields` `}` is syntactic sugar for `f({` `fields` `})`, that is, the +argument list is a single new table. A call of the form `f'` `string` `'` +(or `f"` `string` `"` or `f[[` `string` `]]`) is syntactic sugar for +`f('` `string` `')`, that is, the argument list is a single literal string. + +As an exception to the free-format syntax of Lua, you cannot put a line break +before the `(` in a function call. This restriction avoids some ambiguities +in the language. If you write +> + a = f + (g).x(a) +< +Lua would see that as a single statement, `a = f(g).x(a)`. So, if you want two +statements, you must add a semi-colon between them. If you actually want to +call `f`, you must remove the line break before `(g)`. + + *luaref-tailcall* +A call of the form `return` `functioncall` is called a tail call. Lua +implements proper tail calls (or proper tail recursion): in a tail call, the +called function reuses the stack entry of the calling function. Therefore, +there is no limit on the number of nested tail calls that a program can +execute. However, a tail call erases any debug information about the calling +function. Note that a tail call only happens with a particular syntax, where +the `return` has one single function call as argument; this syntax makes the +calling function return exactly the returns of the called function. So, none +of the following examples are tail calls: +> + return (f(x)) -- results adjusted to 1 + return 2 * f(x) + return x, f(x) -- additional results + f(x); return -- results discarded + return x or f(x) -- results adjusted to 1 +< + +------------------------------------------------------------------------------ +2.5.9 Function Definitions *luaref-langFuncDefs* + +The syntax for function definition is +> + function ::= function funcbody + funcbody ::= ( [ parlist1 ] ) block end +< +The following syntactic sugar simplifies function definitions: +> + stat ::= function funcname funcbody + stat ::= local function Name funcbody + funcname ::= Name { . Name } [ : Name ] +< +The statement + + `function f ()` `body` `end` + +translates to + + `f = function ()` `body` `end` + +The statement + + `function t.a.b.c.f ()` `body` `end` + +translates to + + `t.a.b.c.f = function ()` `body` `end` + +The statement + + `local function f ()` `body` `end` + +translates to + + `local f; f = function f ()` `body` `end` + +not to + + `local f = function f ()` `body` `end` + +(This only makes a difference when the body of the function contains +references to `f`.) + + *luaref-closure* +A function definition is an executable expression, whose value has type +`function`. When Lua pre-compiles a chunk, all its function bodies are +pre-compiled too. Then, whenever Lua executes the function definition, the +function is instantiated (or closed). This function instance (or closure) is +the final value of the expression. Different instances of the same function +may refer to different external local variables and may have different +environment tables. + +Parameters act as local variables that are initialized with the argument +values: +> + parlist1 ::= namelist [ , ... ] | ... +< + *luaref-vararg* +When a function is called, the list of arguments is adjusted to the length of +the list of parameters, unless the function is a variadic or vararg function, +which is indicated by three dots (`...`) at the end of its parameter list. A +vararg function does not adjust its argument list; instead, it collects all +extra arguments and supplies them to the function through a vararg expression, +which is also written as three dots. The value of this expression is a list of +all actual extra arguments, similar to a function with multiple results. If a +vararg expression is used inside another expression or in the middle of a list +of expressions, then its return list is adjusted to one element. If the +expression is used as the last element of a list of expressions, then no +adjustment is made (unless the call is enclosed in parentheses). + +As an example, consider the following definitions: +> + function f(a, b) end + function g(a, b, ...) end + function r() return 1,2,3 end +< +Then, we have the following mapping from arguments to parameters and to the +vararg expression: +> + CALL PARAMETERS + + f(3) a=3, b=nil + f(3, 4) a=3, b=4 + f(3, 4, 5) a=3, b=4 + f(r(), 10) a=1, b=10 + f(r()) a=1, b=2 + + g(3) a=3, b=nil, ... --> (nothing) + g(3, 4) a=3, b=4, ... --> (nothing) + g(3, 4, 5, 8) a=3, b=4, ... --> 5 8 + g(5, r()) a=5, b=1, ... --> 2 3 +< +Results are returned using the `return` statement (see |luaref-langContStructs|). +If control reaches the end of a function without encountering +a `return` statement, then the function returns with no results. + + *luaref-colonsyntax* +The colon syntax is used for defining methods, that is, functions that have an +implicit extra parameter `self`. Thus, the statement + + `function t.a.b.c:f (` `params` `)` `body` `end` + +is syntactic sugar for + + `t.a.b.c:f = function (self, (` `params` `)` `body` `end` + +============================================================================== +2.6 Visibility Rules *luaref-langVisibRules* + +Lua is a lexically scoped language. The scope of variables begins at the first +statement after their declaration and lasts until the end of the innermost +block that includes the declaration. Consider the following example: +> + x = 10 -- global variable + do -- new block + local x = x -- new `x`, with value 10 + print(x) --> 10 + x = x+1 + do -- another block + local x = x+1 -- another `x` + print(x) --> 12 + end + print(x) --> 11 + end + print(x) --> 10 (the global one) +< +Notice that, in a declaration like `local x = x`, the new `x` being declared is +not in scope yet, and so the second `x` refers to the outside variable. + + *luaref-upvalue* +Because of the lexical scoping rules, local variables can be freely accessed +by functions defined inside their scope. A local variable used by an inner +function is called an upvalue, or external local variable, inside the inner +function. + +Notice that each execution of a local statement defines new local variables. +Consider the following example: +> + a = {} + local x = 20 + for i=1,10 do + local y = 0 + a[i] = function () y=y+1; return x+y end + end +< +The loop creates ten closures (that is, ten instances of the anonymous +function). Each of these closures uses a different `y` variable, while all of +them share the same `x`. + +============================================================================== +2.7 Error Handling *luaref-langError* + +Because Lua is an embedded extension language, all Lua actions start from +C code in the host program calling a function from the Lua library (see +|luaref-lua_pcall|). Whenever an error occurs during Lua compilation or +execution, control returns to C, which can take appropriate measures (such as +print an error message). + +Lua code can explicitly generate an error by calling the `error` function (see +|luaref-error|). If you need to catch errors in Lua, you can use +the `pcall` function (see |luaref-pcall|). + +============================================================================== +2.8 Metatables *luaref-metatable* *luaref-langMetatables* + +Every value in Lua may have a metatable. This metatable is an ordinary Lua +table that defines the behavior of the original table and userdata under +certain special operations. You can change several aspects of the behavior of +an object by setting specific fields in its metatable. For instance, when a +non-numeric value is the operand of an addition, Lua checks for a function in +the field `"__add"` in its metatable. If it finds one, Lua calls that function +to perform the addition. + +We call the keys in a metatable events and the values metamethods. In the +previous example, the event is "add" and the metamethod is the function that +performs the addition. + +You can query the metatable of any value through the `getmetatable` function +(see |luaref-getmetatable|). + +You can replace the metatable of tables through the `setmetatable` function (see +|luaref-setmetatable|). You cannot change the metatable of other types from Lua +(except using the debug library); you must use the C API for that. + +Tables and userdata have individual metatables (although multiple tables and +userdata can share a same table as their metatable); values of all other types +share one single metatable per type. So, there is one single metatable for all +numbers, and for all strings, etc. + +A metatable may control how an object behaves in arithmetic operations, order +comparisons, concatenation, length operation, and indexing. A metatable can +also define a function to be called when a userdata is garbage collected. For +each of those operations Lua associates a specific key called an event. When +Lua performs one of those operations over a value, it checks whether this +value has a metatable with the corresponding event. If so, the value +associated with that key (the metamethod) controls how Lua will perform the +operation. + +Metatables control the operations listed next. Each operation is identified by +its corresponding name. The key for each operation is a string with its name +prefixed by two underscores, `__`; for instance, the key for operation "add" +is the string "__add". The semantics of these operations is better explained +by a Lua function describing how the interpreter executes that operation. + +The code shown here in Lua is only illustrative; the real behavior is hard +coded in the interpreter and it is much more efficient than this simulation. +All functions used in these descriptions (`rawget`, `tonumber`, etc.) are +described in |luaref-libBasic|. In particular, to retrieve the metamethod of a +given object, we use the expression +> + metatable(obj)[event] +< +This should be read as +> + rawget(metatable(obj) or {}, event) +< +That is, the access to a metamethod does not invoke other metamethods, and the +access to objects with no metatables does not fail (it simply results +in `nil`). + +"add": *__add()* +------ +the `+` operation. + +The function `getbinhandler` below defines how Lua chooses a handler for a +binary operation. First, Lua tries the first operand. If its type does not +define a handler for the operation, then Lua tries the second operand. +> + function getbinhandler (op1, op2, event) + return metatable(op1)[event] or metatable(op2)[event] + end +< +By using this function, the behavior of the `op1 + op2` is +> + function add_event (op1, op2) + local o1, o2 = tonumber(op1), tonumber(op2) + if o1 and o2 then -- both operands are numeric? + return o1 + o2 -- `+` here is the primitive `add` + else -- at least one of the operands is not numeric + local h = getbinhandler(op1, op2, "__add") + if h then + -- call the handler with both operands + return h(op1, op2) + else -- no handler available: default behavior + error(...) + end + end + end +< +"sub": *__sub()* +------ +the `-` operation. Behavior similar to the "add" operation. + +"mul": *__mul()* +------ +the `*` operation. Behavior similar to the "add" operation. + +"div": *__div()* +------ +the `/` operation. Behavior similar to the "add" operation. + +"mod": *__mod()* +------ +the `%` operation. Behavior similar to the "add" operation, with the +operation `o1 - floor(o1/o2)*o2` as the primitive operation. + +"pow": *__pow()* +------ +the `^` (exponentiation) operation. Behavior similar to the "add" operation, +with the function `pow` (from the C math library) as the primitive operation. + +"unm": *__unm()* +------ +the unary `-` operation. +> + function unm_event (op) + local o = tonumber(op) + if o then -- operand is numeric? + return -o -- `-` here is the primitive `unm` + else -- the operand is not numeric. + -- Try to get a handler from the operand + local h = metatable(op).__unm + if h then + -- call the handler with the operand + return h(op) + else -- no handler available: default behavior + error(...) + end + end + end +< +"concat": *__concat()* +--------- +the `..` (concatenation) operation. +> + function concat_event (op1, op2) + if (type(op1) == "string" or type(op1) == "number") and + (type(op2) == "string" or type(op2) == "number") then + return op1 .. op2 -- primitive string concatenation + else + local h = getbinhandler(op1, op2, "__concat") + if h then + return h(op1, op2) + else + error(...) + end + end + end +< +"len": *__len()* +------ +the `#` operation. +> + function len_event (op) + if type(op) == "string" then + return strlen(op) -- primitive string length + elseif type(op) == "table" then + return #op -- primitive table length + else + local h = metatable(op).__len + if h then + -- call the handler with the operand + return h(op) + else -- no handler available: default behavior + error(...) + end + end + end +< +"eq": *__eq()* +----- +the `==` operation. + +The function `getcomphandler` defines how Lua chooses a metamethod for +comparison operators. A metamethod only is selected when both objects being +compared have the same type and the same metamethod for the selected +operation. +> + function getcomphandler (op1, op2, event) + if type(op1) ~= type(op2) then return nil end + local mm1 = metatable(op1)[event] + local mm2 = metatable(op2)[event] + if mm1 == mm2 then return mm1 else return nil end + end +< +The "eq" event is defined as follows: +> + function eq_event (op1, op2) + if type(op1) ~= type(op2) then -- different types? + return false -- different objects + end + if op1 == op2 then -- primitive equal? + return true -- objects are equal + end + -- try metamethod + local h = getcomphandler(op1, op2, "__eq") + if h then + return h(op1, op2) + else + return false + end + end +< +`a ~= b` is equivalent to `not (a == b)`. + +"lt": *__lt()* +----- +the `<` operation. +> + function lt_event (op1, op2) + if type(op1) == "number" and type(op2) == "number" then + return op1 < op2 -- numeric comparison + elseif type(op1) == "string" and type(op2) == "string" then + return op1 < op2 -- lexicographic comparison + else + local h = getcomphandler(op1, op2, "__lt") + if h then + return h(op1, op2) + else + error(...); + end + end + end +< +`a > b` is equivalent to `b < a`. + +"le": *__le()* +----- +the `<=` operation. +> + function le_event (op1, op2) + if type(op1) == "number" and type(op2) == "number" then + return op1 <= op2 -- numeric comparison + elseif type(op1) == "string" and type(op2) == "string" then + return op1 <= op2 -- lexicographic comparison + else + local h = getcomphandler(op1, op2, "__le") + if h then + return h(op1, op2) + else + h = getcomphandler(op1, op2, "__lt") + if h then + return not h(op2, op1) + else + error(...); + end + end + end + end +< +`a >= b` is equivalent to `b <= a`. Note that, in the absence of a "le" +metamethod, Lua tries the "lt", assuming that `a <= b` is equivalent +to `not (b < a)`. + +"index": *__index()* +-------- +The indexing access `table[key]`. +> + function gettable_event (table, key) + local h + if type(table) == "table" then + local v = rawget(table, key) + if v ~= nil then return v end + h = metatable(table).__index + if h == nil then return nil end + else + h = metatable(table).__index + if h == nil then + error(...); + end + end + if type(h) == "function" then + return h(table, key) -- call the handler + else return h[key] -- or repeat operation on it + end +< +"newindex": *__newindex()* +----------- +The indexing assignment `table[key] = value`. +> + function settable_event (table, key, value) + local h + if type(table) == "table" then + local v = rawget(table, key) + if v ~= nil then rawset(table, key, value); return end + h = metatable(table).__newindex + if h == nil then rawset(table, key, value); return end + else + h = metatable(table).__newindex + if h == nil then + error(...); + end + end + if type(h) == "function" then + return h(table, key,value) -- call the handler + else h[key] = value -- or repeat operation on it + end +< +"call": *__call()* +------- +called when Lua calls a value. +> + function function_event (func, ...) + if type(func) == "function" then + return func(...) -- primitive call + else + local h = metatable(func).__call + if h then + return h(func, ...) + else + error(...) + end + end + end +< + +============================================================================== +2.9 Environments *luaref-environment* *luaref-langEnvironments* + +Besides metatables, objects of types thread, function, and userdata have +another table associated with them, called their environment. Like metatables, +environments are regular tables and multiple objects can share the same +environment. + +Environments associated with userdata have no meaning for Lua. It is only a +convenience feature for programmers to associate a table to a userdata. + +Environments associated with threads are called global environments. They are +used as the default environment for their threads and non-nested functions +created by the thread (through `loadfile` |luaref-loadfile|, `loadstring` +|luaref-loadstring| or `load` |luaref-load|) and can be directly accessed by C +code (see |luaref-apiPseudoIndices|). + +Environments associated with C functions can be directly accessed by C code +(see |luaref-apiPseudoIndices|). They are used as the default environment for +other C functions created by the function. + +Environments associated with Lua functions are used to resolve all accesses to +global variables within the function (see |luaref-langVariables|). They are +used as the default environment for other Lua functions created by the +function. + +You can change the environment of a Lua function or the running thread by +calling `setfenv` (see |luaref-setenv|). You can get the environment of a Lua +function or the running thread by calling `getfenv` (see |luaref-getfenv|). To +manipulate the environment of other objects (userdata, C functions, other +threads) you must use the C API. + +============================================================================== +2.10 Garbage Collection *luaref-langGC* + +Lua performs automatic memory management. This means that you do not have to +worry neither about allocating memory for new objects nor about freeing it +when the objects are no longer needed. Lua manages memory automatically by +running a garbage collector from time to time to collect all dead objects +(that is, these objects that are no longer accessible from Lua). All objects +in Lua are subject to automatic management: tables, userdata, functions, +threads, and strings. + +Lua implements an incremental mark-and-sweep collector. It uses two numbers to +control its garbage-collection cycles: the garbage-collector pause and the +garbage-collector step multiplier. + +The garbage-collector pause controls how long the collector waits before +starting a new cycle. Larger values make the collector less aggressive. Values +smaller than 1 mean the collector will not wait to start a new cycle. A value +of 2 means that the collector waits for the total memory in use to double +before starting a new cycle. + +The step multiplier controls the relative speed of the collector relative to +memory allocation. Larger values make the collector more aggressive but also +increase the size of each incremental step. Values smaller than 1 make the +collector too slow and may result in the collector never finishing a cycle. +The default, 2, means that the collector runs at "twice" the speed of memory +allocation. + +You can change these numbers by calling `lua_gc` (see |luaref-lua_gc|) in C or +`collectgarbage` (see |luaref-collectgarbage|) in Lua. Both get percentage +points as arguments (so an argument of 100 means a real value of 1). With +these functions you can also control the collector directly (e.g., stop and +restart it). + +------------------------------------------------------------------------------ +2.10.1 Garbage-Collection Metamethods *luaref-langGCMeta* + +Using the C API, you can set garbage-collector metamethods for userdata (see +|luaref-langMetatables|). These metamethods are also called finalizers. +Finalizers allow you to coordinate Lua's garbage collection with external +resource management (such as closing files, network or database connections, +or freeing your own memory). + + *__gc* +Garbage userdata with a field `__gc` in their metatables are not collected +immediately by the garbage collector. Instead, Lua puts them in a list. After +the collection, Lua does the equivalent of the following function for each +userdata in that list: +> + function gc_event (udata) + local h = metatable(udata).__gc + if h then + h(udata) + end + end +< +At the end of each garbage-collection cycle, the finalizers for userdata are +called in reverse order of their creation, among these collected in that +cycle. That is, the first finalizer to be called is the one associated with +the userdata created last in the program. + +------------------------------------------------------------------------------ +2.10.2 - Weak Tables *luaref-weaktable* *luaref-langWeaktables* + +A weak table is a table whose elements are weak references. A weak reference +is ignored by the garbage collector. In other words, if the only references to +an object are weak references, then the garbage collector will collect this +object. + + *__mode* +A weak table can have weak keys, weak values, or both. A table with weak keys +allows the collection of its keys, but prevents the collection of its values. +A table with both weak keys and weak values allows the collection of both keys +and values. In any case, if either the key or the value is collected, the +whole pair is removed from the table. The weakness of a table is controlled by +the value of the `__mode` field of its metatable. If the `__mode` field is a +string containing the character `k`, the keys in the table are weak. +If `__mode` contains `v`, the values in the table are weak. + +After you use a table as a metatable, you should not change the value of its +field `__mode`. Otherwise, the weak behavior of the tables controlled by this +metatable is undefined. + +============================================================================== +2.11 Coroutines *luaref-coroutine* *luaref-langCoro* + +Lua supports coroutines, also called collaborative multithreading. A coroutine +in Lua represents an independent thread of execution. Unlike threads in +multithread systems, however, a coroutine only suspends its execution by +explicitly calling a yield function. + +You create a coroutine with a call to `coroutine.create` (see +|luaref-coroutine.create|). Its sole argument is a function that is the main +function of the coroutine. The `create` function only creates a new coroutine +and returns a handle to it (an object of type `thread`); it does not start the +coroutine execution. + +When you first call `coroutine.resume` (see |luaref-coroutine.resume|), +passing as its first argument the thread returned by `coroutine.create`, the +coroutine starts its execution, at the first line of its main function. Extra +arguments passed to `coroutine.resume` are passed on to the coroutine main +function. After the coroutine starts running, it runs until it terminates or +`yields`. + +A coroutine can terminate its execution in two ways: normally, when its main +function returns (explicitly or implicitly, after the last instruction); and +abnormally, if there is an unprotected error. In the first case, +`coroutine.resume` returns `true`, plus any values returned by the coroutine +main function. In case of errors, `coroutine.resume` returns `false` plus an +error message. + +A coroutine yields by calling `coroutine.yield` (see +|luaref-coroutine.yield|). When a coroutine yields, the corresponding +`coroutine.resume` returns immediately, even if the yield happens inside +nested function calls (that is, not in the main function, but in a function +directly or indirectly called by the main function). In the case of a yield, +`coroutine.resume` also returns `true`, plus any values passed to +`coroutine.yield`. The next time you resume the same coroutine, it continues +its execution from the point where it yielded, with the call to +`coroutine.yield` returning any extra arguments passed to `coroutine.resume`. + +Like `coroutine.create`, the `coroutine.wrap` function (see +|luaref-coroutine.wrap|) also creates a coroutine, but instead of returning +the coroutine itself, it returns a function that, when called, resumes the +coroutine. Any arguments passed to this function go as extra arguments to +`coroutine.resume`. `coroutine.wrap` returns all the values returned by +`coroutine.resume`, except the first one (the boolean error code). Unlike +`coroutine.resume`, `coroutine.wrap` does not catch errors; any error is +propagated to the caller. + +As an example, consider the next code: +> + function foo1 (a) + print("foo", a) + return coroutine.yield(2*a) + end + + co = coroutine.create(function (a,b) + print("co-body", a, b) + local r = foo1(a+1) + print("co-body", r) + local r, s = coroutine.yield(a+b, a-b) + print("co-body", r, s) + return b, "end" + end) + + print("main", coroutine.resume(co, 1, 10)) + print("main", coroutine.resume(co, "r")) + print("main", coroutine.resume(co, "x", "y")) + print("main", coroutine.resume(co, "x", "y")) +< +When you run it, it produces the following output: +> + co-body 1 10 + foo 2 + main true 4 + co-body r + main true 11 -9 + co-body x y + main true 10 end + main false cannot resume dead coroutine +< + +============================================================================== +3 THE APPLICATION PROGRAM INTERFACE *luaref-API* +============================================================================== + +This section describes the C API for Lua, that is, the set of C functions +available to the host program to communicate with Lua. All API functions and +related types and constants are declared in the header file `lua.h`. + +Even when we use the term "function", any facility in the API may be provided +as a `macro` instead. All such macros use each of its arguments exactly once +(except for the first argument, which is always a Lua state), and so do not +generate hidden side-effects. + +As in most C libraries, the Lua API functions do not check their arguments for +validity or consistency. However, you can change this behavior by compiling +Lua with a proper definition for the macro `luai_apicheck`,in file +`luaconf.h`. + +============================================================================== +3.1 The Stack *luaref-stack* *luaref-apiStack* + +Lua uses a virtual stack to pass values to and from C. Each element in this +stack represents a Lua value (`nil`, number, string, etc.). + +Whenever Lua calls C, the called function gets a new stack, which is +independent of previous stacks and of stacks of C functions that are still +active. This stack initially contains any arguments to the C function and it +is where the C function pushes its results to be returned to the caller (see +|luaref-lua_CFunction|). + + *luaref-stackindex* +For convenience, most query operations in the API do not follow a strict stack +discipline. Instead, they can refer to any element in the stack by using an +index: a positive index represents an absolute stack position (starting at 1); +a negative index represents an offset from the top of the stack. More +specifically, if the stack has `n` elements, then index 1 represents the first +element (that is, the element that was pushed onto the stack first) and index +`n` represents the last element; index `-1` also represents the last element +(that is, the element at the top) and index `-n` represents the first element. +We say that an index is valid if it lies between 1 and the stack top (that is, +if `1 <= abs(index) <= top`). + +============================================================================== +3.2 Stack Size *luaref-apiStackSize* + +When you interact with Lua API, you are responsible for ensuring consistency. +In particular, you are responsible for controlling stack overflow. You can +use the function `lua_checkstack` to grow the stack size (see +|luaref-lua_checkstack|). + +Whenever Lua calls C, it ensures that at least `LUA_MINSTACK` stack positions +are available. `LUA_MINSTACK` is defined as 20, so that usually you do not +have to worry about stack space unless your code has loops pushing elements +onto the stack. + +Most query functions accept as indices any value inside the available stack +space, that is, indices up to the maximum stack size you have set through +`lua_checkstack`. Such indices are called acceptable indices. More formally, +we define an acceptable index as follows: +> + (index < 0 && abs(index) <= top) || (index > 0 && index <= stackspace) +< +Note that 0 is never an acceptable index. + +============================================================================== +3.3 Pseudo-Indices *luaref-pseudoindex* *luaref-apiPseudoIndices* + +Unless otherwise noted, any function that accepts valid indices can also be +called with pseudo-indices, which represent some Lua values that are +accessible to the C code but which are not in the stack. Pseudo-indices are +used to access the thread environment, the function environment, the registry, +and the upvalues of a C function (see |luaref-apiCClosures|). + +The thread environment (where global variables live) is always at pseudo-index +`LUA_GLOBALSINDEX`. The environment of the running C function is always at +pseudo-index `LUA_ENVIRONINDEX`. + +To access and change the value of global variables, you can use regular table +operations over an environment table. For instance, to access the value of a +global variable, do +> + lua_getfield(L, LUA_GLOBALSINDEX, varname); +< + +============================================================================== +3.4 C Closures *luaref-cclosure* *luaref-apiCClosures* + +When a C function is created, it is possible to associate some values with it, +thus creating a C closure; these values are called upvalues and are accessible +to the function whenever it is called (see |luaref-lua_pushcclosure|). + +Whenever a C function is called, its upvalues are located at specific +pseudo-indices. These pseudo-indices are produced by the macro +`lua_upvalueindex` (see |luaref-lua_upvalueindex|). The first value associated +with a function is at position `lua_upvalueindex(1)`, and so on. Any access to +`lua_upvalueindex(` `n` `)`, where `n` is greater than the number of upvalues of +the current function, produces an acceptable (but invalid) index. + +============================================================================== +3.5 Registry *luaref-registry* *luaref-apiRegistry* + +Lua provides a registry, a pre-defined table that can be used by any C code to +store whatever Lua value it needs to store. This table is always located at +pseudo-index `LUA_REGISTRYINDEX`. Any C library can store data into this +table, but it should take care to choose keys different from those used by +other libraries, to avoid collisions. Typically, you should use as key a +string containing your library name or a light userdata with the address of a +C object in your code. + +The integer keys in the registry are used by the reference mechanism, +implemented by the auxiliary library, and therefore should not be used for +other purposes. + +============================================================================== +3.6 Error Handling in C *luaref-apiError* + +Internally, Lua uses the C `longjmp` facility to handle errors. (You can also +choose to use exceptions if you use C++; see file `luaconf.h`.) When Lua faces +any error (such as memory allocation errors, type errors, syntax errors, and +runtime errors) it raises an error; that is, it does a long jump. A protected +environment uses `setjmp` to set a recover point; any error jumps to the most +recent active recover point. + +Almost any function in the API may raise an error, for instance due to a +memory allocation error. The following functions run in protected mode (that +is, they create a protected environment to run), so they never raise an error: +`lua_newstate`, `lua_close`, `lua_load`, `lua_pcall`, and `lua_cpcall` (see +|luaref-lua_newstate|, |luaref-lua_close|, |luaref-lua_load|, +|luaref-lua_pcall|, and |luaref-lua_cpcall|). + +Inside a C function you can raise an error by calling `lua_error` (see +|luaref-lua_error|). + +============================================================================== +3.7 Functions and Types *luaref-apiFunctions* + +Here we list all functions and types from the C API in alphabetical order. + +lua_Alloc *lua_Alloc()* +> + typedef void * (*lua_Alloc) (void *ud, + void *ptr, + size_t osize, + size_t nsize); +< + The type of the memory-allocation function used by Lua states. The + allocator function must provide a functionality similar to `realloc`, + but not exactly the same. Its arguments are `ud`, an opaque pointer + passed to `lua_newstate` (see |luaref-lua_newstate|); `ptr`, a pointer + to the block being allocated/reallocated/freed; `osize`, the original + size of the block; `nsize`, the new size of the block. `ptr` is `NULL` + if and only if `osize` is zero. When `nsize` is zero, the allocator + must return `NULL`; if `osize` is not zero, it should free the block + pointed to by `ptr`. When `nsize` is not zero, the allocator returns + `NULL` if and only if it cannot fill the request. When `nsize` is not + zero and `osize` is zero, the allocator should behave like `malloc`. + When `nsize` and `osize` are not zero, the allocator behaves like + `realloc`. Lua assumes that the allocator never fails when `osize >= + nsize`. + + Here is a simple implementation for the allocator function. It is used + in the auxiliary library by `luaL_newstate` (see + |luaref-luaL_newstate|). +> + static void *l_alloc (void *ud, void *ptr, size_t osize, + size_t nsize) { + (void)ud; (void)osize; /* not used */ + if (nsize == 0) { + free(ptr); + return NULL; + } + else + return realloc(ptr, nsize); + } +< + This code assumes that `free(NULL)` has no effect and that + `realloc(NULL, size)` is equivalent to `malloc(size)`. ANSI C ensures both + behaviors. + +lua_atpanic *lua_atpanic()* +> + lua_CFunction lua_atpanic (lua_State *L, lua_CFunction panicf); +< + Sets a new panic function and returns the old one. + + If an error happens outside any protected environment, Lua calls a + `panic` `function` and then calls `exit(EXIT_FAILURE)`, thus exiting + the host application. Your panic function may avoid this exit by never + returning (e.g., doing a long jump). + + The panic function can access the error message at the top of the + stack. + +lua_call *lua_call()* +> + void lua_call (lua_State *L, int nargs, int nresults); +< + Calls a function. + + To call a function you must use the following protocol: first, the + function to be called is pushed onto the stack; then, the arguments to + the function are pushed in direct order; that is, the first argument + is pushed first. Finally you call `lua_call`; `nargs` is the number of + arguments that you pushed onto the stack. All arguments and the + function value are popped from the stack when the function is called. + The function results are pushed onto the stack when the function + returns. The number of results is adjusted to `nresults`, unless + `nresults` is `LUA_MULTRET`. In this case, `all` results from the + function are pushed. Lua takes care that the returned values fit into + the stack space. The function results are pushed onto the stack in + direct order (the first result is pushed first), so that after the + call the last result is on the top of the stack. + + Any error inside the called function is propagated upwards (with a + `longjmp`). + + The following example shows how the host program may do the equivalent + to this Lua code: +> + a = f("how", t.x, 14) +< + Here it is in C: +> + lua_getfield(L, LUA_GLOBALSINDEX, "f"); // function to be called + lua_pushstring(L, "how"); // 1st argument + lua_getfield(L, LUA_GLOBALSINDEX, "t"); // table to be indexed + lua_getfield(L, -1, "x"); // push result of t.x (2nd arg) + lua_remove(L, -2); // remove 't' from the stack + lua_pushinteger(L, 14); // 3rd argument + lua_call(L, 3, 1); // call 'f' with 3 arguments and 1 result + lua_setfield(L, LUA_GLOBALSINDEX, "a"); // set global 'a' +< + Note that the code above is "balanced": at its end, the stack is back + to its original configuration. This is considered good programming + practice. + +lua_CFunction *luaref-cfunction* *lua_CFunction()* +> + typedef int (*lua_CFunction) (lua_State *L); +< + Type for C functions. + + In order to communicate properly with Lua, a C function must use the + following protocol, which defines the way parameters and results are + passed: a C function receives its arguments from Lua in its stack in + direct order (the first argument is pushed first). So, when the + function starts, `lua_gettop(L)` (see |luaref-lua_gettop|) returns the + number of arguments received by the function. The first argument (if + any) is at index 1 and its last argument is at index `lua_gettop(L)`. + To return values to Lua, a C function just pushes them onto the stack, + in direct order (the first result is pushed first), and returns the + number of results. Any other value in the stack below the results will + be properly discarded by Lua. Like a Lua function, a C function called + by Lua can also return many results. + + *luaref-cfunctionexample* + As an example, the following function receives a variable number of + numerical arguments and returns their average and sum: +> + static int foo (lua_State *L) { + int n = lua_gettop(L); /* number of arguments */ + lua_Number sum = 0; + int i; + for (i = 1; i <= n; i++) { + if (!lua_isnumber(L, i)) { + lua_pushstring(L, "incorrect argument"); + lua_error(L); + } + sum += lua_tonumber(L, i); + } + lua_pushnumber(L, sum/n); /* first result */ + lua_pushnumber(L, sum); /* second result */ + return 2; /* number of results */ + } +< + +lua_checkstack *lua_checkstack()* +> + int lua_checkstack (lua_State *L, int extra); +< + Ensures that there are at least `extra` free stack slots in the stack. + It returns false if it cannot grow the stack to that size. This + function never shrinks the stack; if the stack is already larger than + the new size, it is left unchanged. + +lua_close *lua_close()* +> + void lua_close (lua_State *L); +< + Destroys all objects in the given Lua state (calling the corresponding + garbage-collection metamethods, if any) and frees all dynamic memory + used by this state. On several platforms, you may not need to call + this function, because all resources are naturally released when the + host program ends. On the other hand, long-running programs, such as a + daemon or a web server, might need to release states as soon as they + are not needed, to avoid growing too large. + +lua_concat *lua_concat()* +> + void lua_concat (lua_State *L, int n); +< + Concatenates the `n` values at the top of the stack, pops them, and + leaves the result at the top. If `n` is 1, the result is the single + string on the stack (that is, the function does nothing); if `n` is 0, + the result is the empty string. Concatenation is done following the + usual semantics of Lua (see |luaref-langConcat|). + +lua_cpcall *lua_cpcall()* +> + int lua_cpcall (lua_State *L, lua_CFunction func, void *ud); +< + Calls the C function `func` in protected mode. `func` starts with only + one element in its stack, a light userdata containing `ud`. In case of + errors, `lua_cpcall` returns the same error codes as `lua_pcall` (see + |luaref-lua_pcall|), plus the error object on the top of the stack; + otherwise, it returns zero, and does not change the stack. All values + returned by `func` are discarded. + +lua_createtable *lua_createtable()* +> + void lua_createtable (lua_State *L, int narr, int nrec); +< + Creates a new empty table and pushes it onto the stack. The new table + has space pre-allocated for `narr` array elements and `nrec` non-array + elements. This pre-allocation is useful when you know exactly how many + elements the table will have. Otherwise you can use the function + `lua_newtable` (see |luaref-lua_newtable|). + +lua_dump *lua_dump()* +> + int lua_dump (lua_State *L, lua_Writer writer, void *data); +< + Dumps a function as a binary chunk. Receives a Lua function on the top + of the stack and produces a binary chunk that, if loaded again, + results in a function equivalent to the one dumped. As it produces + parts of the chunk, `lua_dump` calls function `writer` (see + |luaref-lua_Writer|) with the given `data` to write them. + + The value returned is the error code returned by the last call to the + writer; 0 means no errors. + + This function does not pop the Lua function from the stack. + +lua_equal *lua_equal()* +> + int lua_equal (lua_State *L, int index1, int index2); +< + Returns 1 if the two values in acceptable indices `index1` and + `index2` are equal, following the semantics of the Lua `==` operator + (that is, may call metamethods). Otherwise returns 0. Also returns 0 + if any of the indices is non valid. + +lua_error *lua_error()* +> + int lua_error (lua_State *L); +< + Generates a Lua error. The error message (which can actually be a Lua + value of any type) must be on the stack top. This function does a long + jump, and therefore never returns (see |luaref-luaL_error|). + +lua_gc *lua_gc()* +> + int lua_gc (lua_State *L, int what, int data); +< + Controls the garbage collector. + + This function performs several tasks, according to the value of the + parameter `what`: + + `LUA_GCSTOP` stops the garbage collector. + `LUA_GCRESTART` restarts the garbage collector. + `LUA_GCCOLLECT` performs a full garbage-collection cycle. + `LUA_GCCOUNT` returns the current amount of memory (in Kbytes) in + use by Lua. + `LUA_GCCOUNTB` returns the remainder of dividing the current + amount of bytes of memory in use by Lua by 1024. + `LUA_GCSTEP` performs an incremental step of garbage collection. + The step "size" is controlled by `data` (larger + values mean more steps) in a non-specified way. If + you want to control the step size you must + experimentally tune the value of `data`. The + function returns 1 if the step finished a + garbage-collection cycle. + `LUA_GCSETPAUSE` sets `data` /100 as the new value for the + `pause` of the collector (see |luaref-langGC|). + The function returns the previous value of the + pause. + `LUA_GCSETSTEPMUL` sets `data` /100 as the new value for the + `step` `multiplier` of the collector (see + |luaref-langGC|). The function returns the + previous value of the step multiplier. + +lua_getallocf *lua_getallocf()* +> + lua_Alloc lua_getallocf (lua_State *L, void **ud); +< + Returns the memory-allocation function of a given state. If `ud` is + not `NULL`, Lua stores in `*ud` the opaque pointer passed to + `lua_newstate` (see |luaref-lua_newstate|). + +lua_getfenv *lua_getfenv()* +> + void lua_getfenv (lua_State *L, int index); +< + Pushes onto the stack the environment table of the value at the given + index. + +lua_getfield *lua_getfield()* +> + void lua_getfield (lua_State *L, int index, const char *k); +< + Pushes onto the stack the value `t[k]`, where `t` is the value at the + given valid index `index`. As in Lua, this function may trigger a + metamethod for the "index" event (see |luaref-langMetatables|). + +lua_getglobal *lua_getglobal()* +> + void lua_getglobal (lua_State *L, const char *name); +< + Pushes onto the stack the value of the global `name`. It is defined as + a macro: +> + #define lua_getglobal(L,s) lua_getfield(L, LUA_GLOBALSINDEX, s) +< + +lua_getmetatable *lua_getmetatable()* +> + int lua_getmetatable (lua_State *L, int index); +< + Pushes onto the stack the metatable of the value at the given + acceptable index. If the index is not valid, or if the value does not + have a metatable, the function returns 0 and pushes nothing on the + stack. + +lua_gettable *lua_gettable()* +> + void lua_gettable (lua_State *L, int index); +< + Pushes onto the stack the value `t[k]`, where `t` is the value at the + given valid index `index` and `k` is the value at the top of the + stack. + + This function pops the key from the stack (putting the resulting value + in its place). As in Lua, this function may trigger a metamethod for + the "index" event (see |luaref-langMetatables|). + +lua_gettop *lua_gettop()* +> + int lua_gettop (lua_State *L); +< + Returns the index of the top element in the stack. Because indices + start at 1, this result is equal to the number of elements in the + stack (and so + 0 means an empty stack). + +lua_insert *lua_insert()* +> + void lua_insert (lua_State *L, int index); +< + Moves the top element into the given valid index, shifting up the + elements above this index to open space. Cannot be called with a + pseudo-index, because a pseudo-index is not an actual stack position. + +lua_Integer *lua_Integer()* +> + typedef ptrdiff_t lua_Integer; +< + The type used by the Lua API to represent integral values. + + By default it is a `ptrdiff_t`, which is usually the largest integral + type the machine handles "comfortably". + +lua_isboolean *lua_isboolean()* +> + int lua_isboolean (lua_State *L, int index); +< + Returns 1 if the value at the given acceptable index has type boolean, + and 0 otherwise. + +lua_iscfunction *lua_iscfunction()* +> + int lua_iscfunction (lua_State *L, int index); +< + Returns 1 if the value at the given acceptable index is a C function, + and 0 otherwise. + +lua_isfunction *lua_isfunction()* +> + int lua_isfunction (lua_State *L, int index); +< + Returns 1 if the value at the given acceptable index is a function + (either C or Lua), and 0 otherwise. + +lua_islightuserdata *lua_islightuserdata()* +> + int lua_islightuserdata (lua_State *L, int index); +< + Returns 1 if the value at the given acceptable index is a light + userdata, and 0 otherwise. + +lua_isnil *lua_isnil()* +> + int lua_isnil (lua_State *L, int index); +< + Returns 1 if the value at the given acceptable index is `nil`, and 0 + otherwise. + +lua_isnumber *lua_isnumber()* +> + int lua_isnumber (lua_State *L, int index); +< + Returns 1 if the value at the given acceptable index is a number or a + string convertible to a number, and 0 otherwise. + +lua_isstring *lua_isstring()* +> + int lua_isstring (lua_State *L, int index); +< + Returns 1 if the value at the given acceptable index is a string or a + number (which is always convertible to a string), and 0 otherwise. + +lua_istable *lua_istable()* +> + int lua_istable (lua_State *L, int index); +< + Returns 1 if the value at the given acceptable index is a table, and + 0 otherwise. + +lua_isthread *lua_isthread()* +> + int lua_isthread (lua_State *L, int index); +< + Returns 1 if the value at the given acceptable index is a thread, and + 0 otherwise. + +lua_isuserdata *lua_isuserdata()* +> + int lua_isuserdata (lua_State *L, int index); +< + Returns 1 if the value at the given acceptable index is a userdata + (either full or light), and 0 otherwise. + +lua_lessthan *lua_lessthan()* +> + int lua_lessthan (lua_State *L, int index1, int index2); +< + Returns 1 if the value at acceptable index `index1` is smaller than + the value at acceptable index `index2`, following the semantics of the + Lua `<` operator (that is, may call metamethods). Otherwise returns 0. + Also returns 0 if any of the indices is non valid. + +lua_load *lua_load()* +> + int lua_load (lua_State *L, + lua_Reader reader, + void *data, + const char *chunkname); +< + Loads a Lua chunk. If there are no errors, `lua_load` pushes the + compiled chunk as a Lua function on top of the stack. Otherwise, it + pushes an error message. The return values of `lua_load` are: + + - `0`: no errors; + - `LUA_ERRSYNTAX` : syntax error during pre-compilation; + - `LUA_ERRMEM` : memory allocation error. + + This function only loads a chunk; it does not run it. + + `lua_load` automatically detects whether the chunk is text or binary, + and loads it accordingly (see program `luac`, |luaref-luac|). + + The `lua_load` function uses a user-supplied `reader` function to read + the chunk (see |luaref-lua_Reader|). The `data` argument is an opaque + value passed to the reader function. + + The `chunkname` argument gives a name to the chunk, which is used for + error messages and in debug information (see |luaref-apiDebug|). + +lua_newstate *lua_newstate()* +> + lua_State *lua_newstate (lua_Alloc f, void *ud); +< + Creates a new, independent state. Returns `NULL` if cannot create the + state (due to lack of memory). The argument `f` is the allocator + function; Lua does all memory allocation for this state through this + function. The second argument, `ud`, is an opaque pointer that Lua + simply passes to the allocator in every call. + +lua_newtable *lua_newtable()* +> + void lua_newtable (lua_State *L); +< + Creates a new empty table and pushes it onto the stack. It is + equivalent to `lua_createtable(L, 0, 0)` (see + |luaref-lua_createtable|). + +lua_newthread *lua_newthread()* +> + lua_State *lua_newthread (lua_State *L); +< + Creates a new thread, pushes it on the stack, and returns a pointer to + a `lua_State` (see |luaref-lua_State|) that represents this new + thread. The new state returned by this function shares with the + original state all global objects (such as tables), but has an + independent execution stack. + + There is no explicit function to close or to destroy a thread. Threads + are subject to garbage collection, like any Lua object. + +lua_newuserdata *lua_newuserdata()* +> + void *lua_newuserdata (lua_State *L, size_t size); +< + This function allocates a new block of memory with the given size, + pushes onto the stack a new full userdata with the block address, and + returns this address. + *luaref-userdata* + Userdata represents C values in Lua. A full userdata represents a + block of memory. It is an object (like a table): you must create it, + it can have its own metatable, and you can detect when it is being + collected. A full userdata is only equal to itself (under raw + equality). + + When Lua collects a full userdata with a `gc` metamethod, Lua calls + the metamethod and marks the userdata as finalized. When this userdata + is collected again then Lua frees its corresponding memory. + +lua_next *lua_next()* +> + int lua_next (lua_State *L, int index); +< + Pops a key from the stack, and pushes a key-value pair from the table + at the given index (the "next" pair after the given key). If there are + no more elements in the table, then `lua_next` returns 0 (and pushes + nothing). + + *luaref-tabletraversal* + A typical traversal looks like this: +> + /* table is in the stack at index 't' */ + lua_pushnil(L); /* first key */ + while (lua_next(L, t) != 0) { + /* uses 'key' (at index -2) and 'value' (at index -1) */ + printf("%s - %s\n", + lua_typename(L, lua_type(L, -2)), + lua_typename(L, lua_type(L, -1))); + /* removes 'value'; keeps 'key' for next iteration */ + lua_pop(L, 1); + } +< + While traversing a table, do not call `lua_tolstring` (see + |luaref-lua_tolstring|) directly on a key, unless you know that the + key is actually a string. Recall that `lua_tolstring` `changes` the + value at the given index; this confuses the next call to `lua_next`. + +lua_Number *lua_Number()* +> + typedef double lua_Number; +< + The type of numbers in Lua. By default, it is double, but that can be + changed in `luaconf.h`. + + Through the configuration file you can change Lua to operate with + another type for numbers (e.g., float or long). + +lua_objlen *lua_objlen()* +> + size_t lua_objlen (lua_State *L, int index); +< + Returns the "length" of the value at the given acceptable index: for + strings, this is the string length; for tables, this is the result of + the length operator (`#`); for userdata, this is the size of the + block of memory allocated for the userdata; for other values, it is 0. + +lua_pcall *lua_pcall()* +> + lua_pcall (lua_State *L, int nargs, int nresults, int errfunc); +< + Calls a function in protected mode. + + Both `nargs` and `nresults` have the same meaning as in `lua_call` + (see |luaref-lua_call|). If there are no errors during the call, + `lua_pcall` behaves exactly like `lua_call`. However, if there is any + error, `lua_pcall` catches it, pushes a single value on the stack (the + error message), and returns an error code. Like `lua_call`, + `lua_pcall` always removes the function and its arguments from the + stack. + + If `errfunc` is 0, then the error message returned on the stack is + exactly the original error message. Otherwise, `errfunc` is the stack + index of an `error` `handler function`. (In the current + implementation, this index cannot be a pseudo-index.) In case of + runtime errors, this function will be called with the error message + and its return value will be the message returned on the stack by + `lua_pcall`. + + Typically, the error handler function is used to add more debug + information to the error message, such as a stack traceback. Such + information cannot be gathered after the return of `lua_pcall`, since + by then the stack has unwound. + + The `lua_pcall` function returns 0 in case of success or one of the + following error codes (defined in `lua.h`): + + - `LUA_ERRRUN` a runtime error. + - `LUA_ERRMEM` memory allocation error. For such errors, Lua does + not call the error handler function. + - `LUA_ERRERR` error while running the error handler function. + +lua_pop *lua_pop()* +> + void lua_pop (lua_State *L, int n); +< + Pops `n` elements from the stack. + +lua_pushboolean *lua_pushboolean()* +> + void lua_pushboolean (lua_State *L, int b); +< + Pushes a boolean value with value `b` onto the stack. + +lua_pushcclosure *lua_pushcclosure()* +> + void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n); +< + Pushes a new C closure onto the stack. + + When a C function is created, it is possible to associate some values + with it, thus creating a C closure (see |luaref-apiCClosures|); these + values are then accessible to the function whenever it is called. To + associate values with a C function, first these values should be + pushed onto the stack (when there are multiple values, the first value + is pushed first). Then `lua_pushcclosure` is called to create and push + the C function onto the stack, with the argument `n` telling how many + values should be associated with the function. `lua_pushcclosure` also + pops these values from the stack. + +lua_pushcfunction *lua_pushcfunction()* +> + void lua_pushcfunction (lua_State *L, lua_CFunction f); +< + Pushes a C function onto the stack. This function receives a pointer + to a C function and pushes onto the stack a Lua value of type + `function` that, when called, invokes the corresponding C function. + + Any function to be registered in Lua must follow the correct protocol + to receive its parameters and return its results (see + |luaref-lua_CFunction|). + + `lua_pushcfunction` is defined as a macro: +> + #define lua_pushcfunction(L,f) lua_pushcclosure(L,f,0) +< + +lua_pushfstring *lua_pushfstring()* +> + const char *lua_pushfstring (lua_State *L, const char *fmt, ...); +< + Pushes onto the stack a formatted string and returns a pointer to this + string. It is similar to the C function `sprintf`, but has some + important differences: + + - You do not have to allocate space for the result: the result is a + Lua string and Lua takes care of memory allocation (and + deallocation, through garbage collection). + - The conversion specifiers are quite restricted. There are no flags, + widths, or precisions. The conversion specifiers can only be `%%` + (inserts a `%` in the string), `%s` (inserts a zero-terminated + string, with no size restrictions), `%f` (inserts a + `lua_Number`), `%p` (inserts a pointer as a hexadecimal numeral), + `%d` (inserts an `int`), and `%c` (inserts an `int` as a + character). + +lua_pushinteger *lua_pushinteger()* +> + void lua_pushinteger (lua_State *L, lua_Integer n); +< + Pushes a number with value `n` onto the stack. + +lua_pushlightuserdata *lua_pushlightuserdata()* +> + void lua_pushlightuserdata (lua_State *L, void *p); +< + Pushes a light userdata onto the stack. + *luaref-lightuserdata* + Userdata represents C values in Lua. A light userdata represents a + pointer. It is a value (like a number): you do not create it, it has + no individual metatable, and it is not collected (as it was never + created). A light userdata is equal to "any" light userdata with the + same C address. + +lua_pushlstring *lua_pushlstring()* +> + void lua_pushlstring (lua_State *L, const char *s, size_t len); +< + Pushes the string pointed to by `s` with size `len` onto the stack. + Lua makes (or reuses) an internal copy of the given string, so the + memory at `s` can be freed or reused immediately after the function + returns. The string can contain embedded zeros. + +lua_pushnil *lua_pushnil()* +> + void lua_pushnil (lua_State *L); +< + Pushes a nil value onto the stack. + +lua_pushnumber *lua_pushnumber()* +> + void lua_pushnumber (lua_State *L, lua_Number n); +< + Pushes a number with value `n` onto the stack. + +lua_pushstring *lua_pushstring()* +> + void lua_pushstring (lua_State *L, const char *s); +< + Pushes the zero-terminated string pointed to by `s` onto the stack. + Lua makes (or reuses) an internal copy of the given string, so the + memory at `s` can be freed or reused immediately after the function + returns. The string cannot contain embedded zeros; it is assumed to + end at the first zero. + +lua_pushthread *lua_pushthread()* +> + int lua_pushthread (lua_State *L); +< + Pushes the thread represented by `L` onto the stack. Returns 1 if this + thread is the main thread of its state. + +lua_pushvalue *lua_pushvalue()* +> + void lua_pushvalue (lua_State *L, int index); +< + Pushes a copy of the element at the given valid index onto the stack. + +lua_pushvfstring *lua_pushvfstring()* +> + const char *lua_pushvfstring (lua_State *L, + const char *fmt, + va_list argp); +< + Equivalent to `lua_pushfstring` (see |luaref-pushfstring|), except + that it receives a `va_list` instead of a variable number of + arguments. + +lua_rawequal *lua_rawequal()* +> + int lua_rawequal (lua_State *L, int index1, int index2); +< + Returns 1 if the two values in acceptable indices `index1` and + `index2` are primitively equal (that is, without calling metamethods). + Otherwise returns 0. Also returns 0 if any of the indices are non + valid. + +lua_rawget *lua_rawget()* +> + void lua_rawget (lua_State *L, int index); +< + Similar to `lua_gettable` (see |luaref-lua_gettable|), but does a raw + access (i.e., without metamethods). + +lua_rawgeti *lua_rawgeti()* +> + void lua_rawgeti (lua_State *L, int index, int n); +< + Pushes onto the stack the value `t[n]`, where `t` is the value at the + given valid index `index`. The access is raw; that is, it does not + invoke metamethods. + +lua_rawset *lua_rawset()* +> + void lua_rawset (lua_State *L, int index); +< + Similar to `lua_settable` (see |luaref-lua_settable|), but does a raw + assignment (i.e., without metamethods). + +lua_rawseti *lua_rawseti()* +> + void lua_rawseti (lua_State *L, int index, int n); +< + Does the equivalent of `t[n] = v`, where `t` is the value at the given + valid index `index` and `v` is the value at the top of the stack. + + This function pops the value from the stack. The assignment is raw; + that is, it does not invoke metamethods. + +lua_Reader *lua_Reader()* +> + typedef const char * (*lua_Reader) (lua_State *L, + void *data, + size_t *size); +< + The reader function used by `lua_load` (see |luaref-lua_load|). Every + time it needs another piece of the chunk, `lua_load` calls the reader, + passing along its `data` parameter. The reader must return a pointer + to a block of memory with a new piece of the chunk and set `size` to + the block size. The block must exist until the reader function is + called again. To signal the end of the chunk, the reader must return + `NULL`. The reader function may return pieces of any size greater than + zero. + +lua_register *lua_register()* +> + void lua_register (lua_State *L, + const char *name, + lua_CFunction f); +< + Sets the C function `f` as the new value of global `name`. It is + defined as a macro: +> + #define lua_register(L,n,f) \ + (lua_pushcfunction(L, f), lua_setglobal(L, n)) +< + +lua_remove *lua_remove()* +> + void lua_remove (lua_State *L, int index); +< + Removes the element at the given valid index, shifting down the + elements above this index to fill the gap. Cannot be called with a + pseudo-index, because a pseudo-index is not an actual stack position. + +lua_replace *lua_replace()* +> + void lua_replace (lua_State *L, int index); +< + Moves the top element into the given position (and pops it), without + shifting any element (therefore replacing the value at the given + position). + +lua_resume *lua_resume()* +> + int lua_resume (lua_State *L, int narg); +< + Starts and resumes a coroutine in a given thread. + + To start a coroutine, you first create a new thread (see + |luaref-lua_newthread|); then you push onto its stack the main + function plus any arguments; then you call `lua_resume` (see + |luaref-lua_resume|) with `narg` being the number of arguments. This + call returns when the coroutine suspends or finishes its execution. + When it returns, the stack contains all values passed to `lua_yield` + (see |luaref-lua_yield|), or all values returned by the body function. + `lua_resume` returns `LUA_YIELD` if the coroutine yields, 0 if the + coroutine finishes its execution without errors, or an error code in + case of errors (see |luaref-lua_pcall|). In case of errors, the stack + is not unwound, so you can use the debug API over it. The error + message is on the top of the stack. To restart a coroutine, you put on + its stack only the values to be passed as results from `lua_yield`, + and then call `lua_resume`. + +lua_setallocf *lua_setallocf()* +> + void lua_setallocf (lua_State *L, lua_Alloc f, void *ud); +< + Changes the allocator function of a given state to `f` with user data + `ud`. + +lua_setfenv *lua_setfenv()* +> + int lua_setfenv (lua_State *L, int index); +< + Pops a table from the stack and sets it as the new environment for the + value at the given index. If the value at the given index is neither a + function nor a thread nor a userdata, `lua_setfenv` returns 0. + Otherwise it returns 1. + +lua_setfield *lua_setfield()* +> + void lua_setfield (lua_State *L, int index, const char *k); +< + Does the equivalent to `t[k] = v`, where `t` is the value at the given + valid index `index` and `v` is the value at the top of the stack. + + This function pops the value from the stack. As in Lua, this function + may trigger a metamethod for the "newindex" event (see + |luaref-langMetatables|). + +lua_setglobal *lua_setglobal()* +> + void lua_setglobal (lua_State *L, const char *name); +< + Pops a value from the stack and sets it as the new value of global + `name`. It is defined as a macro: +> + #define lua_setglobal(L,s) lua_setfield(L, LUA_GLOBALSINDEX, s) +< + +lua_setmetatable *lua_setmetatable()* +> + int lua_setmetatable (lua_State *L, int index); +< + Pops a table from the stack and sets it as the new metatable for the + value at the given acceptable index. + +lua_settable *lua_settable()* +> + void lua_settable (lua_State *L, int index); +< + Does the equivalent to `t[k] = v`, where `t` is the value at the given + valid index `index`, `v` is the value at the top of the stack, and `k` + is the value just below the top. + + This function pops both the key and the value from the stack. As in + Lua, this function may trigger a metamethod for the "newindex" event + (see |luaref-langMetatables|). + +lua_settop *lua_settop()* +> + void lua_settop (lua_State *L, int index); +< + Accepts any acceptable index, or 0, and sets the stack top to this + index. If the new top is larger than the old one, then the new + elements are filled with `nil`. If `index` is 0, then all stack + elements are removed. + +lua_State *lua_State()* +> + typedef struct lua_State lua_State; +< + Opaque structure that keeps the whole state of a Lua interpreter. The + Lua library is fully reentrant: it has no global variables. All + information about a state is kept in this structure. + + A pointer to this state must be passed as the first argument to every + function in the library, except to `lua_newstate` (see + |luaref-lua_newstate|), which creates a Lua state from scratch. + +lua_status *lua_status()* +> + int lua_status (lua_State *L); +< + Returns the status of the thread `L`. + + The status can be 0 for a normal thread, an error code if the thread + finished its execution with an error, or `LUA_YIELD` if the thread is + suspended. + +lua_toboolean *lua_toboolean()* +> + int lua_toboolean (lua_State *L, int index); +< + Converts the Lua value at the given acceptable index to a C boolean + value (0 or 1). Like all tests in Lua, `lua_toboolean` returns 1 for + any Lua value different from `false` and `nil`; otherwise it returns + 0. It also returns 0 when called with a non-valid index. (If you want + to accept only actual boolean values, use `lua_isboolean` + |luaref-lua_isboolean| to test the value's type.) + +lua_tocfunction *lua_tocfunction()* +> + lua_CFunction lua_tocfunction (lua_State *L, int index); +< + Converts a value at the given acceptable index to a C function. That + value must be a C function; otherwise it returns `NULL`. + +lua_tointeger *lua_tointeger()* +> + lua_Integer lua_tointeger (lua_State *L, int idx); +< + Converts the Lua value at the given acceptable index to the signed + integral type `lua_Integer` (see |luaref-lua_Integer|). The Lua value + must be a number or a string convertible to a number (see + |luaref-langCoercion|); otherwise, `lua_tointeger` returns 0. + + If the number is not an integer, it is truncated in some non-specified + way. + +lua_tolstring *lua_tolstring()* +> + const char *lua_tolstring (lua_State *L, int index, size_t *len); +< + Converts the Lua value at the given acceptable index to a C string. If + `len` is not `NULL`, it also sets `*len` with the string length. The + Lua value must be a string or a number; otherwise, the function + returns `NULL`. If the value is a number, then `lua_tolstring` also + `changes the actual value in the stack to a` `string`. (This change + confuses `lua_next` |luaref-lua_next| when `lua_tolstring` is applied + to keys during a table traversal.) + + `lua_tolstring` returns a fully aligned pointer to a string inside the + Lua state. This string always has a zero (`\0`) after its last + character (as in C), but may contain other zeros in its body. Because + Lua has garbage collection, there is no guarantee that the pointer + returned by `lua_tolstring` will be valid after the corresponding + value is removed from the stack. + +lua_tonumber *lua_tonumber()* +> + lua_Number lua_tonumber (lua_State *L, int index); +< + Converts the Lua value at the given acceptable index to the C type + `lua_Number` (see |luaref-lua_Number|). The Lua value must be a number + or a string convertible to a number (see |luaref-langCoercion|); + otherwise, `lua_tonumber` returns 0. + +lua_topointer *lua_topointer()* +> + const void *lua_topointer (lua_State *L, int index); +< + Converts the value at the given acceptable index to a generic C + pointer (`void*`). The value may be a userdata, a table, a thread, or + a function; otherwise, `lua_topointer` returns `NULL`. Different + objects will give different pointers. There is no way to convert the + pointer back to its original value. + + Typically this function is used only for debug information. + +lua_tostring *lua_tostring()* +> + const char *lua_tostring (lua_State *L, int index); +< + Equivalent to `lua_tolstring` (see |luaref-lua_tolstring|) with `len` + equal to `NULL`. + +lua_tothread *lua_tothread()* +> + lua_State *lua_tothread (lua_State *L, int index); +< + Converts the value at the given acceptable index to a Lua thread + (represented as `lua_State*` |luaref-lua_State|). This value must be a + thread; otherwise, the function returns `NULL`. + +lua_touserdata *lua_touserdata()* +> + void *lua_touserdata (lua_State *L, int index); +< + If the value at the given acceptable index is a full userdata, returns + its block address. If the value is a light userdata, returns its + pointer. Otherwise, it returns `NULL`. + +lua_type *lua_type()* +> + int lua_type (lua_State *L, int index); +< + Returns the type of the value in the given acceptable index, or + `LUA_TNONE` for a non-valid index (that is, an index to an "empty" + stack position). The types returned by `lua_type` are coded by the + following constants defined in `lua.h` : `LUA_TNIL`, `LUA_TNUMBER`, + `LUA_TBOOLEAN`, `LUA_TSTRING`, `LUA_TTABLE`, `LUA_TFUNCTION`, + `LUA_TUSERDATA`, `LUA_TTHREAD`, and `LUA_TLIGHTUSERDATA`. + +lua_typename *lua_typename()* +> + const char *lua_typename (lua_State *L, int tp); +< + Returns the name of the type encoded by the value `tp`, which must be + one the values returned by `lua_type`. + +lua_Writer *lua_Writer()* +> + typedef int (*lua_Writer) (lua_State *L, + const void* p, + size_t sz, + void* ud); +< + The writer function used by `lua_dump` (see |luaref-lua_dump|). Every + time it produces another piece of chunk, `lua_dump` calls the writer, + passing along the buffer to be written (`p`), its size (`sz`), and the + `data` parameter supplied to `lua_dump`. + + The writer returns an error code: 0 means no errors; any other value + means an error and stops `lua_dump` from calling the writer again. + +lua_xmove *lua_xmove()* +> + void lua_xmove (lua_State *from, lua_State *to, int n); +< + Exchange values between different threads of the `same` global state. + + This function pops `n` values from the stack `from`, and pushes them + onto the stack `to`. + +lua_yield *lua_yield()* +> + int lua_yield (lua_State *L, int nresults); +< + Yields a coroutine. + + This function should only be called as the return expression of a C + function, as follows: +> + return lua_yield (L, nresults); +< + When a C function calls `lua_yield` in that way, the running coroutine + suspends its execution, and the call to `lua_resume` (see + |luaref-lua_resume|) that started this coroutine returns. The + parameter `nresults` is the number of values from the stack that are + passed as results to `lua_resume`. + + *luaref-stackexample* + As an example of stack manipulation, if the stack starts as + `10 20 30 40 50*` (from bottom to top; the `*` marks the top), then +> + lua_pushvalue(L, 3) --> 10 20 30 40 50 30* + lua_pushvalue(L, -1) --> 10 20 30 40 50 30 30* + lua_remove(L, -3) --> 10 20 30 40 30 30* + lua_remove(L, 6) --> 10 20 30 40 30* + lua_insert(L, 1) --> 30 10 20 30 40* + lua_insert(L, -1) --> 30 10 20 30 40* (no effect) + lua_replace(L, 2) --> 30 40 20 30* + lua_settop(L, -3) --> 30 40* + lua_settop(L, 6) --> 30 40 nil nil nil nil* +< + +============================================================================== +3.8 The Debug Interface *luaref-apiDebug* + +Lua has no built-in debugging facilities. Instead, it offers a special +interface by means of functions and hooks. This interface allows the +construction of different kinds of debuggers, profilers, and other tools that +need "inside information" from the interpreter. + +lua_Debug *lua_Debug()* + + `typedef struct lua_Debug {` + `int event;` + `const char *name; /* (n) */` + `const char *namewhat; /* (n) */` + `const char *what; /* (S) */` + `const char *source; /* (S) */` + `int currentline; /* (l) */` + `int nups; /* (u) number of upvalues */` + `int linedefined; /* (S) */` + `int lastlinedefined; /* (S) */` + `char short_src[LUA_IDSIZE]; /* (S) */` + `/* private part */` + `other fields` + `} lua_Debug;` + +A structure used to carry different pieces of information about an active +function. `lua_getstack` (see |luaref-lua_getstack|) fills only the private part +of this structure, for later use. To fill the other fields of `lua_Debug` with +useful information, call `lua_getinfo` (see |luaref-lua_getinfo|). + +The fields of `lua_Debug` have the following meaning: + + `source` If the function was defined in a string, then `source` is + that string. If the function was defined in a file, then + `source` starts with a `@` followed by the file name. + `short_src` a "printable" version of `source`, to be used in error messages. + `linedefined` the line number where the definition of the function starts. + `lastlinedefined` the line number where the definition of the function ends. + `what` the string `"Lua"` if the function is a Lua function, + `"C"` if it is a C function, `"main"` if it is the main + part of a chunk, and `"tail"` if it was a function that + did a tail call. In the latter case, Lua has no other + information about the function. + `currentline` the current line where the given function is executing. + When no line information is available, `currentline` is + set to -1. + `name` a reasonable name for the given function. Because + functions in Lua are first-class values, they do not have + a fixed name: some functions may be the value of multiple + global variables, while others may be stored only in a + table field. The `lua_getinfo` function checks how the + function was called to find a suitable name. If it cannot + find a name, then `name` is set to `NULL`. + `namewhat` explains the `name` field. The value of `namewhat` can be + `"global"`, `"local"`, `"method"`, `"field"`, + `"upvalue"`, or `""` (the empty string), according to how + the function was called. (Lua uses the empty string when + no other option seems to apply.) `nups` the number of + upvalues of the function. + +lua_gethook *lua_gethook()* +> + lua_Hook lua_gethook (lua_State *L); +< + Returns the current hook function. + +lua_gethookcount *lua_gethookcount()* +> + int lua_gethookcount (lua_State *L); +< + Returns the current hook count. + +lua_gethookmask *lua_gethookmask()* +> + int lua_gethookmask (lua_State *L); +< + Returns the current hook mask. + +lua_getinfo *lua_getinfo()* +> + int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar); +< + Returns information about a specific function or function invocation. + + To get information about a function invocation, the parameter `ar` + must be a valid activation record that was filled by a previous call + to `lua_getstack` (see |luaref-lua_getstack|) or given as argument to + a hook (see |luaref-lua_Hook|). + + To get information about a function you push it onto the stack and + start the `what` string with the character `>`. (In that case, + `lua_getinfo` pops the function in the top of the stack.) For + instance, to know in which line a function `f` was defined, you can + write the following code: +> + lua_Debug ar; + lua_getfield(L, LUA_GLOBALSINDEX, "f"); /* get global 'f' */ + lua_getinfo(L, ">S", &ar); + printf("%d\n", ar.linedefined); +< + Each character in the string `what` selects some fields of the + structure `ar` to be filled or a value to be pushed on the stack: + + `'n'` fills in the field `name` and `namewhat` + `'S'` fills in the fields `source`, `short_src`, `linedefined`, + `lastlinedefined`, and `what` + `'l'` fills in the field `currentline` + `'u'` fills in the field `nups` + `'f'` pushes onto the stack the function that is running at the + given level + `'L'` pushes onto the stack a table whose indices are the numbers + of the lines that are valid on the function. (A `valid line` is a + line with some associated code, that is, a line where you can put + a break point. Non-valid lines include empty lines and comments.) + + This function returns 0 on error (for instance, an invalid option in + `what`). + +lua_getlocal *lua_getlocal()* +> + const char *lua_getlocal (lua_State *L, lua_Debug *ar, int n); +< + Gets information about a local variable of a given activation record. + The parameter `ar` must be a valid activation record that was filled + by a previous call to `lua_getstack` (see |luaref-lua_getstack|) or + given as argument to a hook (see |luaref-lua_Hook|). The index `n` + selects which local variable to inspect (1 is the first parameter or + active local variable, and so on, until the last active local + variable). `lua_getlocal` pushes the variable's value onto the stack + and returns its name. + + Variable names starting with `(` (open parentheses) represent + internal variables (loop control variables, temporaries, and C + function locals). + + Returns `NULL` (and pushes nothing) when the index is greater than the + number of active local variables. + +lua_getstack *lua_getstack()* +> + int lua_getstack (lua_State *L, int level, lua_Debug *ar); +< + Gets information about the interpreter runtime stack. + + This function fills parts of a `lua_Debug` (see |luaref-lua_Debug|) + structure with an identification of the `activation record` of the + function executing at a given level. Level 0 is the current running + function, whereas level `n+1` is the function that has called level + `n`. When there are no errors, `lua_getstack` returns 1; when called + with a level greater than the stack depth, it returns 0. + +lua_getupvalue *lua_getupvalue()* +> + const char *lua_getupvalue (lua_State *L, int funcindex, int n); +< + Gets information about a closure's upvalue. (For Lua functions, + upvalues are the external local variables that the function uses, and + that are consequently included in its closure.) `lua_getupvalue` gets + the index `n` of an upvalue, pushes the upvalue's value onto the + stack, and returns its name. `funcindex` points to the closure in the + stack. (Upvalues have no particular order, as they are active through + the whole function. So, they are numbered in an arbitrary order.) + + Returns `NULL` (and pushes nothing) when the index is greater than the + number of upvalues. For C functions, this function uses the empty + string `""` as a name for all upvalues. + +lua_Hook *lua_Hook()* +> + typedef void (*lua_Hook) (lua_State *L, lua_Debug *ar); +< + Type for debugging hook functions. + + Whenever a hook is called, its `ar` argument has its field `event` set + to the specific event that triggered the hook. Lua identifies these + events with the following constants: `LUA_HOOKCALL`, `LUA_HOOKRET`, + `LUA_HOOKTAILRET`, `LUA_HOOKLINE`, and `LUA_HOOKCOUNT`. Moreover, for + line events, the field `currentline` is also set. To get the value of + any other field in `ar`, the hook must call `lua_getinfo` (see + |luaref-lua_getinfo|). For return events, `event` may be + `LUA_HOOKRET`, the normal value, or `LUA_HOOKTAILRET`. In the latter + case, Lua is simulating a return from a function that did a tail call; + in this case, it is useless to call `lua_getinfo`. + + While Lua is running a hook, it disables other calls to hooks. + Therefore, if a hook calls back Lua to execute a function or a chunk, + this execution occurs without any calls to hooks. + + +lua_sethook *lua_sethook()* +> + int lua_sethook (lua_State *L, lua_Hook f, int mask, int count); +< + Sets the debugging hook function. + + Argument `f` is the hook function. `mask` specifies on which events + the hook will be called: it is formed by a bitwise `or` of the + constants `LUA_MASKCALL`, `LUA_MASKRET`, `LUA_MASKLINE`, and + `LUA_MASKCOUNT`. The `count` argument is only meaningful when the mask + includes `LUA_MASKCOUNT`. For each event, the hook is called as + explained below: + + - `The call hook`: is called when the interpreter calls a function. + The hook is called just after Lua enters the new function, before + the function gets its arguments. + - `The return hook`: is called when the interpreter returns from a + function. The hook is called just before Lua leaves the function. + You have no access to the values to be returned by the function. + - `The line hook`: is called when the interpreter is about to start + the execution of a new line of code, or when it jumps back in the + code (even to the same line). (This event only happens while Lua is + executing a Lua function.) + - `The count hook`: is called after the interpreter executes every + `count` instructions. (This event only happens while Lua is + executing a Lua function.) + + A hook is disabled by setting `mask` to zero. + +lua_setlocal *lua_setlocal()* +> + const char *lua_setlocal (lua_State *L, lua_Debug *ar, int n); +< + Sets the value of a local variable of a given activation record. + Parameters `ar` and `n` are as in `lua_getlocal` (see + |luaref-lua_getlocal|). `lua_setlocal` assigns the value at the top of + the stack to the variable and returns its name. It also pops the value + from the stack. + + Returns `NULL` (and pops nothing) when the index is greater than the + number of active local variables. + +lua_setupvalue *lua_setupvalue()* +> + const char *lua_setupvalue (lua_State *L, int funcindex, int n); +< + Sets the value of a closure's upvalue. It assigns the value at the top + of the stack to the upvalue and returns its name. It also pops the + value from the stack. Parameters `funcindex` and `n` are as in the + `lua_getupvalue` (see |luaref-lua_getupvalue|). + + Returns `NULL` (and pops nothing) when the index is greater than the + number of upvalues. + + *luaref-debugexample* + As an example, the following function lists the names of all local + variables and upvalues for a function at a given level of the stack: +> + int listvars (lua_State *L, int level) { + lua_Debug ar; + int i; + const char *name; + if (lua_getstack(L, level, &ar) == 0) + return 0; /* failure: no such level in the stack */ + i = 1; + while ((name = lua_getlocal(L, &ar, i++)) != NULL) { + printf("local %d %s\n", i-1, name); + lua_pop(L, 1); /* remove variable value */ + } + lua_getinfo(L, "f", &ar); /* retrieves function */ + i = 1; + while ((name = lua_getupvalue(L, -1, i++)) != NULL) { + printf("upvalue %d %s\n", i-1, name); + lua_pop(L, 1); /* remove upvalue value */ + } + return 1; + } +< + +============================================================================== +4 THE AUXILIARY LIBRARY *luaref-aux* +============================================================================== + +The auxiliary library provides several convenient functions to interface C +with Lua. While the basic API provides the primitive functions for all +interactions between C and Lua, the auxiliary library provides higher-level +functions for some common tasks. + +All functions from the auxiliary library are defined in header file `lauxlib.h` +and have a prefix `luaL_`. + +All functions in the auxiliary library are built on top of the basic API, and +so they provide nothing that cannot be done with this API. + +Several functions in the auxiliary library are used to check C function +arguments. Their names are always `luaL_check*` or `luaL_opt*`. All of these +functions raise an error if the check is not satisfied. Because the error +message is formatted for arguments (e.g., "bad argument #1"), you should not +use these functions for other stack values. + +============================================================================== +4.1 Functions and Types *luaref-auxFunctions* + +Here we list all functions and types from the auxiliary library in +alphabetical order. + +luaL_addchar *luaL_addchar()* +> + void luaL_addchar (luaL_Buffer *B, char c); +< + Adds the character `c` to the buffer `B` (see |luaref-luaL_Buffer|). + +luaL_addlstring *luaL_addlstring()* +> + void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l); +< + Adds the string pointed to by `s` with length `l` to the buffer `B` + (see |luaref-luaL_Buffer|). The string may contain embedded zeros. + +luaL_addsize *luaL_addsize()* +> + void luaL_addsize (luaL_Buffer *B, size_t n); +< + Adds to the buffer `B` (see |luaref-luaL_Buffer|) a string of length + `n` previously copied to the buffer area (see + |luaref-luaL_prepbuffer|). + +luaL_addstring *luaL_addstring()* +> + void luaL_addstring (luaL_Buffer *B, const char *s); +< + Adds the zero-terminated string pointed to by `s` to the buffer `B` + (see |luaref-luaL_Buffer|). The string may not contain embedded zeros. + +luaL_addvalue *luaL_addvalue()* +> + void luaL_addvalue (luaL_Buffer *B); +< + Adds the value at the top of the stack to the buffer `B` (see + |luaref-luaL_Buffer|). Pops the value. + + This is the only function on string buffers that can (and must) be + called with an extra element on the stack, which is the value to be + added to the buffer. + +luaL_argcheck *luaL_argcheck()* +> + void luaL_argcheck (lua_State *L, + int cond, + int narg, + const char *extramsg); +< + Checks whether `cond` is true. If not, raises an error with the + following message, where `func` is retrieved from the call stack: +> + bad argument #<narg> to <func> (<extramsg>) +< + +luaL_argerror *luaL_argerror()* +> + int luaL_argerror (lua_State *L, int narg, const char *extramsg); +< + Raises an error with the following message, where `func` is retrieved + from the call stack: +> + bad argument #<narg> to <func> (<extramsg>) +< + This function never returns, but it is an idiom to use it in C + functions as `return luaL_argerror(` `args` `)`. + +luaL_Buffer *luaL_Buffer()* +> + typedef struct luaL_Buffer luaL_Buffer; +< + Type for a `string buffer`. + + A string buffer allows C code to build Lua strings piecemeal. Its + pattern of use is as follows: + + - First you declare a variable `b` of type `luaL_Buffer`. + - Then you initialize it with a call `luaL_buffinit(L, &b)` (see + |luaref-luaL_buffinit|). + - Then you add string pieces to the buffer calling any of the + `luaL_add*` functions. + - You finish by calling `luaL_pushresult(&b)` (see + |luaref-luaL_pushresult|). This call leaves the final string on the + top of the stack. + + During its normal operation, a string buffer uses a variable number of + stack slots. So, while using a buffer, you cannot assume that you know + where the top of the stack is. You can use the stack between + successive calls to buffer operations as long as that use is balanced; + that is, when you call a buffer operation, the stack is at the same + level it was immediately after the previous buffer operation. (The + only exception to this rule is `luaL_addvalue` + |luaref-luaL_addvalue|.) After calling `luaL_pushresult` the stack is + back to its level when the buffer was initialized, plus the final + string on its top. + +luaL_buffinit *luaL_buffinit()* +> + void luaL_buffinit (lua_State *L, luaL_Buffer *B); +< + Initializes a buffer `B`. This function does not allocate any space; + the buffer must be declared as a variable (see |luaref-luaL_Buffer|). + +luaL_callmeta *luaL_callmeta()* +> + int luaL_callmeta (lua_State *L, int obj, const char *e); +< + Calls a metamethod. + + If the object at index `obj` has a metatable and this metatable has a + field `e`, this function calls this field and passes the object as its + only argument. In this case this function returns 1 and pushes onto + the stack the value returned by the call. If there is no metatable or + no metamethod, this function returns + 0 (without pushing any value on the stack). + +luaL_checkany *luaL_checkany()* +> + void luaL_checkany (lua_State *L, int narg); +< + Checks whether the function has an argument of any type (including + `nil`) at position `narg`. + +luaL_checkint *luaL_checkint()* +> + int luaL_checkint (lua_State *L, int narg); +< + Checks whether the function argument `narg` is a number and returns + this number cast to an `int`. + +luaL_checkinteger *luaL_checkinteger()* +> + lua_Integer luaL_checkinteger (lua_State *L, int narg); +< + Checks whether the function argument `narg` is a number and returns + this number cast to a `lua_Integer` (see |luaref-lua_Integer|). + +luaL_checklong *luaL_checklong()* +> + long luaL_checklong (lua_State *L, int narg); +< + Checks whether the function argument `narg` is a number and returns + this number cast to a `long`. + +luaL_checklstring *luaL_checklstring()* +> + const char *luaL_checklstring (lua_State *L, int narg, size_t *l); +< + Checks whether the function argument `narg` is a string and returns + this string; if `l` is not `NULL` fills `*l` with the string's length. + +luaL_checknumber *luaL_checknumber()* +> + lua_Number luaL_checknumber (lua_State *L, int narg); +< + Checks whether the function argument `narg` is a number and returns + this number (see |luaref-lua_Number|). + +luaL_checkoption *luaL_checkoption()* +> + int luaL_checkoption (lua_State *L, + int narg, + const char *def, + const char *const lst[]); +< + Checks whether the function argument `narg` is a string and searches + for this string in the array `lst` (which must be NULL-terminated). + Returns the index in the array where the string was found. Raises an + error if the argument is not a string or if the string cannot be + found. + + If `def` is not `NULL`, the function uses `def` as a default value + when there is no argument `narg` or if this argument is `nil`. + + This is a useful function for mapping strings to C enums. (The usual + convention in Lua libraries is to use strings instead of numbers to + select options.) + +luaL_checkstack *luaL_checkstack()* +> + void luaL_checkstack (lua_State *L, int sz, const char *msg); +< + Grows the stack size to `top + sz` elements, raising an error if the + stack cannot grow to that size. `msg` is an additional text to go into + the error message. + +luaL_checkstring *luaL_checkstring()* +> + const char *luaL_checkstring (lua_State *L, int narg); +< + Checks whether the function argument `narg` is a string and returns + this string. + +luaL_checktype *luaL_checktype()* +> + void luaL_checktype (lua_State *L, int narg, int t); +< + Checks whether the function argument `narg` has type `t` (see + |luaref-lua_type|). + +luaL_checkudata *luaL_checkudata()* +> + void *luaL_checkudata (lua_State *L, int narg, const char *tname); +< + Checks whether the function argument `narg` is a userdata of the type + `tname` (see |luaref-luaL_newmetatable|). + +luaL_dofile *luaL_dofile()* +> + int luaL_dofile (lua_State *L, const char *filename); +< + Loads and runs the given file. It is defined as the following macro: +> + (luaL_loadfile(L, filename) || lua_pcall(L, 0, LUA_MULTRET, 0)) +< + It returns 0 if there are no errors or 1 in case of errors. + +luaL_dostring *luaL_dostring()* +> + int luaL_dostring (lua_State *L, const char *str); +< + Loads and runs the given string. It is defined as the following macro: +> + (luaL_loadstring(L, str) || lua_pcall(L, 0, LUA_MULTRET, 0)) +< + It returns 0 if there are no errors or 1 in case of errors. + +luaL_error *luaL_error()* +> + int luaL_error (lua_State *L, const char *fmt, ...); +< + Raises an error. The error message format is given by `fmt` plus any + extra arguments, following the same rules of `lua_pushfstring` (see + |luaref-lua_pushfstring|). It also adds at the beginning of the + message the file name and the line number where the error occurred, if + this information is available. + + This function never returns, but it is an idiom to use it in C + functions as `return luaL_error(` `args` `)`. + +luaL_getmetafield *luaL_getmetafield()* +> + int luaL_getmetafield (lua_State *L, int obj, const char *e); +< + Pushes onto the stack the field `e` from the metatable of the object + at index `obj`. If the object does not have a metatable, or if the + metatable does not have this field, returns 0 and pushes nothing. + +luaL_getmetatable *luaL_getmetatable()* +> + void luaL_getmetatable (lua_State *L, const char *tname); +< + Pushes onto the stack the metatable associated with name `tname` in + the registry (see |luaref-luaL_newmetatable|). + +luaL_gsub *luaL_gsub()* +> + const char *luaL_gsub (lua_State *L, + const char *s, + const char *p, + const char *r); +< + Creates a copy of string `s` by replacing any occurrence of the string + `p` with the string `r`. Pushes the resulting string on the stack and + returns it. + +luaL_loadbuffer *luaL_loadbuffer()* +> + int luaL_loadbuffer (lua_State *L, + const char *buff, + size_t sz, + const char *name); +< + Loads a buffer as a Lua chunk. This function uses `lua_load` (see + |luaref-lua_load|) to load the chunk in the buffer pointed to by + `buff` with size `sz`. + + This function returns the same results as `lua_load`. `name` is the + chunk name, used for debug information and error messages. + +luaL_loadfile *luaL_loadfile()* +> + int luaL_loadfile (lua_State *L, const char *filename); +< + Loads a file as a Lua chunk. This function uses `lua_load` (see + |luaref-lua_load|) to load the chunk in the file named `filename`. If + `filename` is `NULL`, then it loads from the standard input. The first + line in the file is ignored if it starts with a `#`. + + This function returns the same results as `lua_load`, but it has an + extra error code `LUA_ERRFILE` if it cannot open/read the file. + + As `lua_load`, this function only loads the chunk; it does not run it. + +luaL_loadstring *luaL_loadstring()* +> + int luaL_loadstring (lua_State *L, const char *s); +< + Loads a string as a Lua chunk. This function uses `lua_load` (see + |luaref-lua_load|) to load the chunk in the zero-terminated string + `s`. + + This function returns the same results as `lua_load`. + + Also as `lua_load`, this function only loads the chunk; it does not + run it. + +luaL_newmetatable *luaL_newmetatable()* +> + int luaL_newmetatable (lua_State *L, const char *tname); +< + If the registry already has the key `tname`, returns 0. Otherwise, + creates a new table to be used as a metatable for userdata, adds it to + the registry with key `tname`, and returns 1. + + In both cases pushes onto the stack the final value associated with + `tname` in the registry. + +luaL_newstate *luaL_newstate()* +> + lua_State *luaL_newstate (void); +< + Creates a new Lua state. It calls `lua_newstate` (see + |luaref-lua_newstate|) with an allocator based on the standard C + `realloc` function and then sets a panic function (see + |luaref-lua_atpanic|) that prints an error message to the standard + error output in case of fatal errors. + + Returns the new state, or `NULL` if there is a memory allocation + error. + +luaL_openlibs *luaL_openlibs()* +> + void luaL_openlibs (lua_State *L); +< + Opens all standard Lua libraries into the given state. See also + |luaref-openlibs| for details on how to open individual libraries. + +luaL_optint *luaL_optint()* +> + int luaL_optint (lua_State *L, int narg, int d); +< + If the function argument `narg` is a number, returns this number cast + to an `int`. If this argument is absent or is `nil`, returns `d`. + Otherwise, raises an error. + +luaL_optinteger *luaL_optinteger()* +> + lua_Integer luaL_optinteger (lua_State *L, + int narg, + lua_Integer d); +< + If the function argument `narg` is a number, returns this number cast + to a `lua_Integer` (see |luaref-lua_Integer|). If this argument is + absent or is `nil`, returns `d`. Otherwise, raises an error. + +luaL_optlong *luaL_optlong()* +> + long luaL_optlong (lua_State *L, int narg, long d); +< + If the function argument `narg` is a number, returns this number cast + to a `long`. If this argument is absent or is `nil`, returns `d`. + Otherwise, raises an error. + +luaL_optlstring *luaL_optlstring()* +> + const char *luaL_optlstring (lua_State *L, + int narg, + const char *d, + size_t *l); +< + If the function argument `narg` is a string, returns this string. If + this argument is absent or is `nil`, returns `d`. Otherwise, raises an + error. + + If `l` is not `NULL`, fills the position `*l` with the results' length. + +luaL_optnumber *luaL_optnumber()* +> + lua_Number luaL_optnumber (lua_State *L, int narg, lua_Number d); +< + If the function argument `narg` is a number, returns this number. If + this argument is absent or is `nil`, returns `d`. Otherwise, raises an + error. + +luaL_optstring *luaL_optstring()* +> + const char *luaL_optstring (lua_State *L, + int narg, + const char *d); +< + If the function argument `narg` is a string, returns this string. If + this argument is absent or is `nil`, returns `d`. Otherwise, raises an + error. + +luaL_prepbuffer *luaL_prepbuffer()* +> + char *luaL_prepbuffer (luaL_Buffer *B); +< + Returns an address to a space of size `LUAL_BUFFERSIZE` where you can + copy a string to be added to buffer `B` (see |luaref-luaL_Buffer|). + After copying the string into this space you must call `luaL_addsize` + (see |luaref-luaL_addsize|) with the size of the string to actually + add it to the buffer. + +luaL_pushresult *luaL_pushresult()* +> + void luaL_pushresult (luaL_Buffer *B); +< + Finishes the use of buffer `B` leaving the final string on the top of + the stack. + +luaL_ref *luaL_ref()* +> + int luaL_ref (lua_State *L, int t); +< + Creates and returns a `reference`, in the table at index `t`, for the + object at the top of the stack (and pops the object). + + A reference is a unique integer key. As long as you do not manually + add integer keys into table `t`, `luaL_ref` ensures the uniqueness of + the key it returns. You can retrieve an object referred by reference + `r` by calling `lua_rawgeti(L, t, r)` (see |luaref-lua_rawgeti|). + Function `luaL_unref` (see |luaref-luaL_unref|) frees a reference and + its associated object. + + If the object at the top of the stack is `nil`, `luaL_ref` returns the + constant `LUA_REFNIL`. The constant `LUA_NOREF` is guaranteed to be + different from any reference returned by `luaL_ref`. + +luaL_Reg *luaL_Reg()* +> + typedef struct luaL_Reg { + const char *name; + lua_CFunction func; + } luaL_Reg; +< + Type for arrays of functions to be registered by `luaL_register` (see + |luaref-luaL_register|). `name` is the function name and `func` is a + pointer to the function. Any array of `luaL_Reg` must end with a + sentinel entry in which both `name` and `func` are `NULL`. + +luaL_register *luaL_register()* +> + void luaL_register (lua_State *L, + const char *libname, + const luaL_Reg *l); +< + Opens a library. + + When called with `libname` equal to `NULL`, it simply registers all + functions in the list `l` (see |luaref-luaL_Reg|) into the table on + the top of the stack. + + When called with a non-null `libname`, `luaL_register` creates a new + table `t`, sets it as the value of the global variable `libname`, sets + it as the value of `package.loaded[libname]`, and registers on it all + functions in the list `l`. If there is a table in + `package.loaded[libname]` or in variable `libname`, reuses this table + instead of creating a new one. + + In any case the function leaves the table on the top of the stack. + +luaL_typename *luaL_typename()* +> + const char *luaL_typename (lua_State *L, int idx); +< + Returns the name of the type of the value at index `idx`. + +luaL_typerror *luaL_typerror()* +> + int luaL_typerror (lua_State *L, int narg, const char *tname); +< + Generates an error with a message like the following: + + `location` `: bad argument` `narg` `to` `'func'` `(` `tname` + `expected, got` `rt` `)` + + where `location` is produced by `luaL_where` (see + |luaref-luaL_where|), `func` is the name of the current function, and + `rt` is the type name of the actual argument. + +luaL_unref *luaL_unref()* +> + void luaL_unref (lua_State *L, int t, int ref); +< + Releases reference `ref` from the table at index `t` (see + |luaref-luaL_ref|). The entry is removed from the table, so that the + referred object can be collected. The reference `ref` is also freed to + be used again. + + If `ref` is `LUA_NOREF` or `LUA_REFNIL`, `luaL_unref` does nothing. + +luaL_where *luaL_where()* +> + void luaL_where (lua_State *L, int lvl); +< + Pushes onto the stack a string identifying the current position of the + control at level `lvl` in the call stack. Typically this string has + the following format: + + `chunkname:currentline:` + + Level 0 is the running function, level 1 is the function that called + the running function, etc. + + This function is used to build a prefix for error messages. + +============================================================================== +5 STANDARD LIBRARIES *luaref-Lib* +============================================================================== + +The standard libraries provide useful functions that are implemented directly +through the C API. Some of these functions provide essential services to the +language (e.g., `type` and `getmetatable`); others provide access to "outside" +services (e.g., I/O); and others could be implemented in Lua itself, but are +quite useful or have critical performance requirements that deserve an +implementation in C (e.g., `sort`). + +All libraries are implemented through the official C API and are provided as +separate C modules. Currently, Lua has the following standard libraries: + +- basic library; +- package library; +- string manipulation; +- table manipulation; +- mathematical functions (sin, log, etc.); +- input and output; +- operating system facilities; +- debug facilities. + +Except for the basic and package libraries, each library provides all its +functions as fields of a global table or as methods of its objects. + + *luaref-openlibs* +To have access to these libraries, the C host program should call the +`luaL_openlibs` function, which opens all standard libraries (see +|luaref-luaL_openlibs|). Alternatively, the host program can open the libraries +individually by calling `luaopen_base` (for the basic library), +`luaopen_package` (for the package library), `luaopen_string` (for the string +library), `luaopen_table` (for the table library), `luaopen_math` (for the +mathematical library), `luaopen_io` (for the I/O and the Operating System +libraries), and `luaopen_debug` (for the debug library). These functions are +declared in `lualib.h` and should not be called directly: you must call them +like any other Lua C function, e.g., by using `lua_call` (see |luaref-lua_call|). + +============================================================================== +5.1 Basic Functions *luaref-libBasic* + +The basic library provides some core functions to Lua. If you do not include +this library in your application, you should check carefully whether you need +to provide implementations for some of its facilities. + +assert({v} [, {message}]) *luaref-assert()* + Issues an error when the value of its argument `v` is false (i.e., `nil` or + `false`); otherwise, returns all its arguments. `message` is an error message; + when absent, it defaults to "assertion failed!" + +collectgarbage({opt} [, {arg}]) *luaref-collectgarbage()* + This function is a generic interface to the garbage collector. It + performs different functions according to its first argument, {opt}: + + `"stop"` stops the garbage collector. + `"restart"` restarts the garbage collector. + `"collect"` performs a full garbage-collection cycle. + `"count"` returns the total memory in use by Lua (in Kbytes). + `"step"` performs a garbage-collection step. The step "size" is + controlled by {arg} (larger values mean more steps) in a + non-specified way. If you want to control the step size + you must experimentally tune the value of {arg}. Returns + `true` if the step finished a collection cycle. + `"setpause"` sets {arg} /100 as the new value for the `pause` of + the collector (see |luaref-langGC|). + `"setstepmul"` sets {arg} /100 as the new value for the `step + multiplier` of the collector (see |luaref-langGC|). + +dofile({filename}) *luaref-dofile()* + Opens the named file and executes its contents as a Lua chunk. When + called without arguments, `dofile` executes the contents of the + standard input (`stdin`). Returns all values returned by the chunk. In + case of errors, `dofile` propagates the error to its caller (that is, + `dofile` does not run in protected mode). + +error({message} [, {level}]) *luaref-error()* + Terminates the last protected function called and returns `message` as + the error message. Function {error} never returns. + + Usually, {error} adds some information about the error position at the + beginning of the message. The {level} argument specifies how to get + the error position. With level 1 (the default), the error position is + where the {error} function was called. Level 2 points the error to + where the function that called {error} was called; and so on. Passing + a level 0 avoids the addition of error position information to the + message. + +_G *luaref-_G()* + A global variable (not a function) that holds the global environment + (that is, `_G._G = _G`). Lua itself does not use this variable; + changing its value does not affect any environment, nor vice-versa. + (Use `setfenv` to change environments.) + +getfenv({f}) *luaref-getfenv()* + Returns the current environment in use by the function. {f} can be a + Lua function or a number that specifies the function at that stack + level: Level 1 is the function calling `getfenv`. If the given + function is not a Lua function, or if {f} is 0, `getfenv` returns the + global environment. The default for {f} is 1. + +getmetatable({object}) *luaref-getmetatable()* + If {object} does not have a metatable, returns `nil`. Otherwise, if + the object's metatable has a `"__metatable"` field, returns the + associated value. Otherwise, returns the metatable of the given + object. + +ipairs({t}) *luaref-ipairs()* + Returns three values: an iterator function, the table {t}, and 0, so + that the construction + + `for i,v in ipairs(t) do` `body` `end` + + will iterate over the pairs (`1,t[1]`), (`2,t[2]`), ..., up to the + first integer key absent from the table. + +load({func} [, {chunkname}]) *luaref-load()* + Loads a chunk using function {func} to get its pieces. Each call to + {func} must return a string that concatenates with previous results. A + return of `nil` (or no value) signals the end of the chunk. + + If there are no errors, returns the compiled chunk as a function; + otherwise, returns `nil` plus the error message. The environment of + the returned function is the global environment. + + {chunkname} is used as the chunk name for error messages and debug + information. + +loadfile([{filename}]) *luaref-loadfile()* + Similar to `load` (see |luaref-load|), but gets the chunk from file + {filename} or from the standard input, if no file name is given. + +loadstring({string} [, {chunkname}]) *luaref-loadstring()* + Similar to `load` (see |luaref-load|), but gets the chunk from the + given {string}. + + To load and run a given string, use the idiom +> + assert(loadstring(s))() +< + +next({table} [, {index}]) *luaref-next()* + Allows a program to traverse all fields of a table. Its first argument + is a table and its second argument is an index in this table. `next` + returns the next index of the table and its associated value. When + called with `nil` as its second argument, `next` returns an initial + index and its associated value. When called with the last index, or + with `nil` in an empty table, `next` returns `nil`. If the second + argument is absent, then it is interpreted as `nil`. In particular, + you can use `next(t)` to check whether a table is empty. + + The order in which the indices are enumerated is not specified, `even + for` `numeric indices`. (To traverse a table in numeric order, use a + numerical `for` or the `ipairs` |luaref-ipairs| function.) + + The behavior of `next` is `undefined` if, during the traversal, you + assign any value to a non-existent field in the table. You may however + modify existing fields. In particular, you may clear existing fields. + +pairs({t}) *luaref-pairs()* + Returns three values: the `next` |luaref-next| function, the table + {t}, and `nil`, so that the construction + + `for k,v in pairs(t) do` `body` `end` + + will iterate over all key-value pairs of table {t}. + +pcall({f}, {arg1}, {...}) *luaref-pcall()* + Calls function {f} with the given arguments in `protected mode`. This + means that any error inside {f} is not propagated; instead, `pcall` + catches the error and returns a status code. Its first result is the + status code (a boolean), which is `true` if the call succeeds without + errors. In such case, `pcall` also returns all results from the call, + after this first result. In case of any error, `pcall` returns `false` + plus the error message. + +print({...}) *luaref-print()* + Receives any number of arguments, and prints their values to `stdout`, + using the `tostring` |luaref-tostring| function to convert them to + strings. `print` is not intended for formatted output, but only as a + quick way to show a value, typically for debugging. For formatted + output, use `string.format` (see |luaref-string.format|). + +rawequal({v1}, {v2}) *luaref-rawequal()* + Checks whether {v1} is equal to {v2}, without invoking any metamethod. + Returns a boolean. + +rawget({table}, {index}) *luaref-rawget()* + Gets the real value of `table[index]`, without invoking any + metamethod. {table} must be a table; {index} may be any value. + +rawset({table}, {index}, {value}) *luaref-rawset()* + Sets the real value of `table[index]` to {value}, without invoking any + metamethod. {table} must be a table, {index} any value different from + `nil`, and {value} any Lua value. + + This function returns {table}. + +select({index}, {...}) *luaref-select()* + If {index} is a number, returns all arguments after argument number + {index}. Otherwise, {index} must be the string `"#"`, and `select` + returns the total number of extra arguments it received. + +setfenv({f}, {table}) *luaref-setfenv()* + Sets the environment to be used by the given function. {f} can be a + Lua function or a number that specifies the function at that stack + level: Level 1 is the function calling `setfenv`. `setfenv` returns + the given function. + + As a special case, when {f} is 0 `setfenv` changes the environment of + the running thread. In this case, `setfenv` returns no values. + +setmetatable({table}, {metatable}) *luaref-setmetatable()* + Sets the metatable for the given table. (You cannot change the + metatable of other types from Lua, only from C.) If {metatable} is + `nil`, removes the metatable of the given table. If the original + metatable has a `"__metatable"` field, raises an error. + + This function returns {table}. + +tonumber({e} [, {base}]) *luaref-tonumber()* + Tries to convert its argument to a number. If the argument is already + a number or a string convertible to a number, then `tonumber` returns + this number; otherwise, it returns `nil`. + + An optional argument specifies the base to interpret the numeral. The + base may be any integer between 2 and 36, inclusive. In bases above + 10, the letter `A` (in either upper or lower case) represents 10, `B` + represents 11, and so forth, with `Z'` representing 35. In base 10 + (the default), the number may have a decimal part, as well as an + optional exponent part (see |luaref-langLexConv|). In other bases, + only unsigned integers are accepted. + +tostring({e}) *luaref-tostring()* + Receives an argument of any type and converts it to a string in a + reasonable format. For complete control of how numbers are converted, + use `string.format` (see |luaref-string.format|). + + *__tostring* + If the metatable of {e} has a `"__tostring"` field, `tostring` calls + the corresponding value with {e} as argument, and uses the result of + the call as its result. + +type({v}) *luaref-type()* + Returns the type of its only argument, coded as a string. The possible + results of this function are `"nil"` (a string, not the value `nil`), + `"number"`, `"string"`, `"boolean`, `"table"`, `"function"`, + `"thread"`, and `"userdata"`. + +unpack({list} [, {i} [, {j}]]) *luaref-unpack()* + Returns the elements from the given table. This function is equivalent + to +> + return list[i], list[i+1], ..., list[j] +< + except that the above code can be written only for a fixed number of + elements. By default, {i} is 1 and {j} is the length of the list, as + defined by the length operator(see |luaref-langLength|). + +_VERSION *luaref-_VERSION()* + A global variable (not a function) that holds a string containing the + current interpreter version. The current contents of this string is + `"Lua 5.1"` . + +xpcall({f}, {err}) *luaref-xpcall()* + This function is similar to `pcall` (see |luaref-pcall|), except that + you can set a new error handler. + + `xpcall` calls function {f} in protected mode, using {err} as the + error handler. Any error inside {f} is not propagated; instead, + `xpcall` catches the error, calls the {err} function with the original + error object, and returns a status code. Its first result is the + status code (a boolean), which is true if the call succeeds without + errors. In this case, `xpcall` also returns all results from the call, + after this first result. In case of any error, `xpcall` returns + `false` plus the result from {err}. + +============================================================================== +5.2 Coroutine Manipulation *luaref-libCoro* + +The operations related to coroutines comprise a sub-library of the basic +library and come inside the table `coroutine`. See |luaref-langCoro| for a +general description of coroutines. + +coroutine.create({f}) *coroutine.create()* + Creates a new coroutine, with body {f}. {f} must be a Lua function. + Returns this new coroutine, an object with type `"thread"`. + +coroutine.resume({co} [, {val1}, {...}]) *coroutine.resume()* + Starts or continues the execution of coroutine {co}. The first time + you resume a coroutine, it starts running its body. The values {val1}, + {...} are passed as arguments to the body function. If the coroutine has + yielded, `resume` restarts it; the values {val1}, {...} are passed as + the results from the yield. + + If the coroutine runs without any errors, `resume` returns `true` plus + any values passed to `yield` (if the coroutine yields) or any values + returned by the body function(if the coroutine terminates). If there + is any error, `resume` returns `false` plus the error message. + +coroutine.running() *coroutine.running()* + Returns the running coroutine, or `nil` when called by the main + thread. + +coroutine.status({co}) *coroutine.status()* + Returns the status of coroutine {co}, as a string: `"running"`, if the + coroutine is running (that is, it called `status`); `"suspended"`, if + the coroutine is suspended in a call to `yield`, or if it has not + started running yet; `"normal"` if the coroutine is active but not + running (that is, it has resumed another coroutine); and `"dead"` if + the coroutine has finished its body function, or if it has stopped + with an error. + +coroutine.wrap({f}) *coroutine.wrap()* + Creates a new coroutine, with body {f}. {f} must be a Lua function. + Returns a function that resumes the coroutine each time it is called. + Any arguments passed to the function behave as the extra arguments to + `resume`. Returns the same values returned by `resume`, except the + first boolean. In case of error, propagates the error. + +coroutine.yield({...}) *coroutine.yield()* + Suspends the execution of the calling coroutine. The coroutine cannot + be running a C function, a metamethod, or an iterator. Any arguments + to `yield` are passed as extra results to `resume`. + +============================================================================== +5.3 - Modules *luaref-libModule* + +The package library provides basic facilities for loading and building modules +in Lua. It exports two of its functions directly in the global environment: +`require` and `module` (see |luaref-require| and |luaref-module|). Everything else is +exported in a table `package`. + +module({name} [, {...}]) *luaref-module()* + Creates a module. If there is a table in `package.loaded[name]`, this + table is the module. Otherwise, if there is a global table `t` with + the given name, this table is the module. Otherwise creates a new + table `t` and sets it as the value of the global {name} and the value + of `package.loaded[name]`. This function also initializes `t._NAME` + with the given name, `t._M` with the module (`t` itself), and + `t._PACKAGE` with the package name (the full module name minus last + component; see below). Finally, `module` sets `t` as the new + environment of the current function and the new value of + `package.loaded[name]`, so that `require` (see |luaref-require|) + returns `t`. + + If {name} is a compound name (that is, one with components separated + by dots), `module` creates (or reuses, if they already exist) tables + for each component. For instance, if {name} is `a.b.c`, then `module` + stores the module table in field `c` of field `b` of global `a`. + + This function may receive optional `options` after the module name, + where each option is a function to be applied over the module. + +require({modname}) *luaref-require()* + Loads the given module. The function starts by looking into the + `package.loaded` table to determine whether {modname} is already + loaded. If it is, then `require` returns the value stored at + `package.loaded[modname]`. Otherwise, it tries to find a `loader` for + the module. + + To find a loader, first `require` queries `package.preload[modname]`. + If it has a value, this value (which should be a function) is the + loader. Otherwise `require` searches for a Lua loader using the path + stored in `package.path`. If that also fails, it searches for a C + loader using the path stored in `package.cpath`. If that also fails, + it tries an `all-in-one` loader (see below). + + When loading a C library, `require` first uses a dynamic link facility + to link the application with the library. Then it tries to find a C + function inside this library to be used as the loader. The name of + this C function is the string `"luaopen_"` concatenated with a copy of + the module name where each dot is replaced by an underscore. Moreover, + if the module name has a hyphen, its prefix up to (and including) the + first hyphen is removed. For instance, if the module name is + `a.v1-b.c`, the function name will be `luaopen_b_c`. + + If `require` finds neither a Lua library nor a C library for a module, + it calls the `all-in-one loader`. This loader searches the C path for + a library for the root name of the given module. For instance, when + requiring `a.b.c`, it will search for a C library for `a`. If found, + it looks into it for an open function for the submodule; in our + example, that would be `luaopen_a_b_c`. With this facility, a package + can pack several C submodules into one single library, with each + submodule keeping its original open function. + + Once a loader is found, `require` calls the loader with a single + argument, {modname}. If the loader returns any value, `require` + assigns the returned value to `package.loaded[modname]`. If the loader + returns no value and has not assigned any value to + `package.loaded[modname]`, then `require` assigns `true` to this + entry. In any case, `require` returns the final value of + `package.loaded[modname]`. + + If there is any error loading or running the module, or if it cannot + find any loader for the module, then `require` signals an error. + +package.cpath *package.cpath()* + The path used by `require` to search for a C loader. + + Lua initializes the C path `package.cpath` in the same way it + initializes the Lua path `package.path`, using the environment + variable `LUA_CPATH` (plus another default path defined in + `luaconf.h`). + +package.loaded *package.loaded()* + A table used by `require` to control which modules are already loaded. + When you require a module `modname` and `package.loaded[modname]` is + not false, `require` simply returns the value stored there. + +package.loadlib({libname}, {funcname}) *package.loadlib()* + Dynamically links the host program with the C library {libname}. + Inside this library, looks for a function {funcname} and returns this + function as a C function. (So, {funcname} must follow the protocol + (see |luaref-lua_CFunction|)). + + This is a low-level function. It completely bypasses the package and + module system. Unlike `require`, it does not perform any path + searching and does not automatically adds extensions. {libname} must + be the complete file name of the C library, including if necessary a + path and extension. {funcname} must be the exact name exported by the + C library (which may depend on the C compiler and linker used). + + This function is not supported by ANSI C. As such, it is only + available on some platforms (Windows, Linux, Mac OS X, Solaris, BSD, + plus other Unix systems that support the `dlfcn` standard). + +package.path *package.path()* + The path used by `require` to search for a Lua loader. + + At start-up, Lua initializes this variable with the value of the + environment variable `LUA_PATH` or with a default path defined in + `luaconf.h`, if the environment variable is not defined. Any `";;"` in + the value of the environment variable is replaced by the default path. + + A path is a sequence of `templates` separated by semicolons. For each + template, `require` will change each interrogation mark in the + template by `filename`, which is `modname` with each dot replaced by a + "directory separator" (such as `"/"` in Unix); then it will try to + load the resulting file name. So, for instance, if the Lua path is +> + "./?.lua;./?.lc;/usr/local/?/init.lua" +< + the search for a Lua loader for module `foo` will try to load the + files `./foo.lua`, `./foo.lc`, and `/usr/local/foo/init.lua`, in that + order. + +package.preload *package.preload()* + A table to store loaders for specific modules (see |luaref-require|). + +package.seeall({module}) *package.seeall()* + Sets a metatable for {module} with its `__index` field referring to + the global environment, so that this module inherits values from the + global environment. To be used as an option to function {module}. + +============================================================================== +5.4 - String Manipulation *luaref-libString* + +This library provides generic functions for string manipulation, such as +finding and extracting substrings, and pattern matching. When indexing a +string in Lua, the first character is at position 1 (not at 0, as in C). +Indices are allowed to be negative and are interpreted as indexing backwards, +from the end of the string. Thus, the last character is at position -1, and +so on. + +The string library provides all its functions inside the table `string`. +It also sets a metatable for strings where the `__index` field points to the +`string` table. Therefore, you can use the string functions in object-oriented +style. For instance, `string.byte(s, i)` can be written as `s:byte(i)`. + +string.byte({s} [, {i} [, {j}]]) *string.byte()* + Returns the internal numerical codes of the characters `s[i]`, + `s[i+1]`,..., `s[j]`. The default value for {i} is 1; the default + value for {j} is {i}. + + Note that numerical codes are not necessarily portable across + platforms. + +string.char({...}) *string.char()* + Receives zero or more integers. Returns a string with length equal to + the number of arguments, in which each character has the internal + numerical code equal to its correspondent argument. + + Note that numerical codes are not necessarily portable across + platforms. + +string.dump({function}) *string.dump()* + Returns a string containing a binary representation of the given + function, so that a later |luaref-loadstring| on this string returns a + copy of the function. {function} must be a Lua function without + upvalues. + +string.find({s}, {pattern} [, {init} [, {plain}]]) *string.find()* + Looks for the first match of {pattern} in the string {s}. If it finds + a match, then {find} returns the indices of {s} where this occurrence + starts and ends; otherwise, it returns `nil`. A third, optional + numerical argument {init} specifies where to start the search; its + default value is 1 and may be negative. A value of {true} as a fourth, + optional argument {plain} turns off the pattern matching facilities, + so the function does a plain "find substring" operation, with no + characters in {pattern} being considered "magic". Note that if {plain} + is given, then {init} must be given as well. + + If the pattern has captures, then in a successful match the captured + values are also returned, after the two indices. + +string.format({formatstring}, {...}) *string.format()* + Returns a formatted version of its variable number of arguments + following the description given in its first argument (which must be a + string). The format string follows the same rules as the `printf` + family of standard C functions. The only differences are that the + options/modifiers `*`, `l`, `L`, `n`, `p`, and `h` are not supported + and that there is an extra option, `q`. The `q` option formats a + string in a form suitable to be safely read back by the Lua + interpreter: the string is written between double quotes, and all + double quotes, newlines, embedded zeros, and backslashes in the string + are correctly escaped when written. For instance, the call +> + string.format('%q', 'a string with "quotes" and \n new line') +< + will produce the string: +> + "a string with \"quotes\" and \ + new line" +< + The options `c`, `d`, `E`, `e`, `f`, `g`, `G`, `i`, `o`, `u`, `X`, and + `x` all expect a number as argument, whereas `q` and `s` expect a + string. + + This function does not accept string values containing embedded zeros. + +string.gmatch({s}, {pattern}) *string.gmatch()* + Returns an iterator function that, each time it is called, returns the + next captures from {pattern} over string {s}. + + If {pattern} specifies no captures, then the whole match is produced + in each call. + + As an example, the following loop +> + s = "hello world from Lua" + for w in string.gmatch(s, "%a+") do + print(w) + end +< + will iterate over all the words from string {s}, printing one per + line. The next example collects all pairs `key=value` from the given + string into a table: +> + t = {} + s = "from=world, to=Lua" + for k, v in string.gmatch(s, "(%w+)=(%w+)") do + t[k] = v + end +< + +string.gsub({s}, {pattern}, {repl} [, {n}]) *string.gsu{b}()* + Returns a copy of {s} in which all occurrences of the {pattern} have + been replaced by a replacement string specified by {repl}, which may + be a string, a table, or a function. `gsub` also returns, as its + second value, the total number of substitutions made. + + If {repl} is a string, then its value is used for replacement. The + character `%` works as an escape character: any sequence in {repl} of + the form `%n`, with {n} between 1 and 9, stands for the value of the + {n} -th captured substring (see below). The sequence `%0` stands for + the whole match. The sequence `%%` stands for a single `%`. + + If {repl} is a table, then the table is queried for every match, using + the first capture as the key; if the pattern specifies no captures, + then the whole match is used as the key. + + If {repl} is a function, then this function is called every time a + match occurs, with all captured substrings passed as arguments, in + order; if the pattern specifies no captures, then the whole match is + passed as a sole argument. + + If the value returned by the table query or by the function call is a + string or a number, then it is used as the replacement string; + otherwise, if it is `false` or `nil`, then there is no replacement + (that is, the original match is kept in the string). + + The optional last parameter {n} limits the maximum number of + substitutions to occur. For instance, when {n} is 1 only the first + occurrence of `pattern` is replaced. + + Here are some examples: +> + x = string.gsub("hello world", "(%w+)", "%1 %1") + --> x="hello hello world world" + + x = string.gsub("hello world", "%w+", "%0 %0", 1) + --> x="hello hello world" + + x = string.gsub("hello world from Lua", "(%w+)%s*(%w+)", "%2 %1") + --> x="world hello Lua from" + + x = string.gsub("home = `HOME, user = ` USER", "%$(%w+)", os.getenv) + --> x="home = /home/roberto, user = roberto" + + x = string.gsub("4+5 = `return 4+5` ", "% `(.-)%` ", function (s) + return loadstring(s)() + end) + --> x="4+5 = 9" + + local t = {name="lua", version="5.1"} + x = string.gsub(" `name%-` version.tar.gz", "%$(%w+)", t) + --> x="lua-5.1.tar.gz" +< + +string.len({s}) *string.len()* + Receives a string and returns its length. The empty string `""` has + length 0. Embedded zeros are counted, so `"a\000b\000c"` has length 5. + +string.lower({s}) *string.lower()* + Receives a string and returns a copy of this string with all uppercase + letters changed to lowercase. All other characters are left unchanged. + The definition of what an uppercase letter is depends on the current + locale. + +string.match({s}, {pattern} [, {init}]) *string.match()* + Looks for the first `match` of {pattern} in the string {s}. If it + finds one, then `match` returns the captures from the pattern; + otherwise it returns `nil`. If {pattern} specifies no captures, then + the whole match is returned. A third, optional numerical argument + {init} specifies where to start the search; its default value is 1 and + may be negative. + +string.rep({s}, {n}) *string.rep()* + Returns a string that is the concatenation of {n} copies of the string + {s}. + +string.reverse({s}) *string.reverse()* + Returns a string that is the string {s} reversed. + +string.sub({s}, {i} [, {j}]) *string.sub()* + Returns the substring of {s} that starts at {i} and continues until + {j}; {i} and {j} may be negative. If {j} is absent, then it is assumed + to be equal to `-1` (which is the same as the string length). In + particular, the call `string.sub(s,1,j)` returns a prefix of {s} with + length {j}, and `string.sub(s,-i)` returns a suffix of {s} with length + {i}. + +string.upper({s}) *string.upper()* + Receives a string and returns a copy of that string with all lowercase + letters changed to uppercase. All other characters are left unchanged. + The definition of what a lowercase letter is depends on the current + locale. + +------------------------------------------------------------------------------ +5.4.1 Patterns *luaref-patterns* *luaref-libStringPat* + +A character class is used to represent a set of characters. The following +combinations are allowed in describing a character class: + + - `x` (where `x` is not one of the magic characters `^$()%.[]*+-?`) + represents the character `x` itself. + - `.` (a dot) represents all characters. + - `%a` represents all letters. + - `%c` represents all control characters. + - `%d` represents all digits. + - `%l` represents all lowercase letters. + - `%p` represents all punctuation characters. + - `%s` represents all space characters. + - `%u` represents all uppercase letters. + - `%w` represents all alphanumeric characters. + - `%x` represents all hexadecimal digits. + - `%z` represents the character with representation `0`. + - `%x` (where `x` is any non-alphanumeric character) represents the + character `x`. This is the standard way to escape the magic + characters. Any punctuation character (even the non-magic) can be + preceded by a `%` when used to represent itself in a pattern. + + - `[set]` represents the class which is the union of all characters in + `set`. A range of characters may be specified by separating the end + characters of the range with a `-`. All classes `%x` described + above may also be used as components in `set`. All other characters + in `set` represent themselves. For example, `[%w_]` (or `[_%w]`) + represents all alphanumeric characters plus the underscore, `[0-7]` + represents the octal digits, and `[0-7%l%-]` represents the octal + digits plus the lowercase letters plus the `-` character. + + The interaction between ranges and classes is not defined. Therefore, + patterns like `[%a-z]` or `[a-%%]` have no meaning. + + - `[^set]` represents the complement of `set`, where `set` is interpreted + as above. + +For all classes represented by single letters (`%a`, `%c`, etc.), the +corresponding uppercase letter represents the complement of the class. For +instance, `%S` represents all non-space characters. + +The definitions of letter, space, and other character groups depend on the +current locale. In particular, the class `[a-z]` may not be equivalent to `%l`. + + *luaref-patternitem* +Pattern Item:~ +------------- +A pattern item may be + + - a single character class, which matches any single character in the + class; + - a single character class followed by `*`, which matches 0 or more + repetitions of characters in the class. These repetition items will + always match the longest possible sequence; + - a single character class followed by `+`, which matches 1 or more + repetitions of characters in the class. These repetition items will + always match the longest possible sequence; + - a single character class followed by `-`, which also matches 0 or + more repetitions of characters in the class. Unlike `*`, these + repetition items will always match the shortest possible sequence; + - a single character class followed by `?`, which matches 0 or 1 + occurrences of a character in the class; + - `%n`, for `n` between 1 and 9; such item matches a substring equal to the + `n` -th captured string (see below); + - `%bxy`, where `x` and `y` are two distinct characters; such item matches + strings that start with `x`, end with `y`, and where the `x` and `y` + are balanced. This means that, if one reads the string from left to + right, counting `+1` for an `x` and `-1` for a `y`, the ending `y` is the first + `y` where the count reaches 0. For instance, the item `%b()` matches + expressions with balanced parentheses. + + *luaref-pattern* +Pattern:~ +-------- +A pattern is a sequence of pattern items. A `^` at the beginning of a pattern +anchors the match at the beginning of the subject string. A `$` at the end of +a pattern anchors the match at the end of the subject string. At other +positions, `^` and `$` have no special meaning and represent themselves. + + *luaref-capture* +Captures:~ +--------- +A pattern may contain sub-patterns enclosed in parentheses; they describe +captures. When a match succeeds, the substrings of the subject string that +match captures are stored (captured) for future use. Captures are numbered +according to their left parentheses. For instance, in the pattern +`"(a*(.)%w(%s*))"`, the part of the string matching `"a*(.)%w(%s*)"` is stored +as the first capture (and therefore has number 1); the character matching `.` +is captured with number 2, and the part matching `%s*` has number 3. + +As a special case, the empty capture `()` captures the current string position +(a number). For instance, if we apply the pattern `"()aa()"` on the +string `"flaaap"`, there will be two captures: 3 and 5. + +A pattern cannot contain embedded zeros. Use `%z` instead. + +============================================================================== +5.5 Table Manipulation *luaref-libTable* + +This library provides generic functions for table manipulation. It provides +all its functions inside the table `table`. + +Most functions in the table library assume that the table represents an array +or a list. For those functions, when we talk about the "length" of a table we +mean the result of the length operator. + +table.concat({table} [, {sep} [, {i} [, {j}]]]) *table.concat()* + Given an array where all elements are strings or numbers, returns + `table[i]..sep..table[i+1] ... sep..table[j]`. The default value for + {sep} is the empty string, the default for {i} is 1, and the default + for {j} is the length of the table. If {i} is greater than {j}, + returns the empty string. + +table.foreach({table}, {f}) *table.foreach()* + Executes the given {f} over all elements of {table}. For each element, + {f} is called with the index and respective value as arguments. If {f} + returns a non-`nil` value, then the loop is broken, and this value is + returned as the final value of `table.foreach`. + + See |luaref-next| for extra information about table traversals. + +table.foreachi({table}, {f}) *table.foreachi()* + Executes the given {f} over the numerical indices of {table}. For each + index, {f} is called with the index and respective value as arguments. + Indices are visited in sequential order, from 1 to `n`, where `n` is + the length of the table. If {f} returns a non-`nil` value, then the + loop is broken and this value is returned as the result of + `table.foreachi`. + +table.insert({table}, [{pos},] {value}) *table.insert()* + Inserts element {value} at position {pos} in {table}, shifting up + other elements to open space, if necessary. The default value for + {pos} is `n+1`, where `n` is the length of the table (see + |luaref-langLength|), so that a call `table.insert(t,x)` inserts `x` + at the end of table `t`. + +table.maxn({table}) *table.maxn()* + Returns the largest positive numerical index of the given table, or + zero if the table has no positive numerical indices. (To do its job + this function does a linear traversal of the whole table.) + +table.remove({table} [, {pos}]) *table.remove()* + Removes from {table} the element at position {pos}, shifting down + other elements to close the space, if necessary. Returns the value of + the removed element. The default value for {pos} is `n`, where `n` is + the length of the table (see |luaref-langLength|), so that a call + `table.remove(t)` removes the last element of table `t`. + +table.sort({table} [, {comp}]) *table.sort()* + Sorts table elements in a given order, `in-place`, from `table[1]` to + `table[n]`, where `n` is the length of the table (see + |luaref-langLength|). If {comp} is given, then it must be a function + that receives two table elements, and returns true when the first is + less than the second (so that `not comp(a[i+1],a[i])` will be true + after the sort). If {comp} is not given, then the standard Lua + operator `<` is used instead. + +The sort algorithm is `not` stable, that is, elements considered equal by the +given order may have their relative positions changed by the sort. + +============================================================================== +5.6 Mathematical Functions *luaref-libMath* + +This library is an interface to most of the functions of the standard C math +library. It provides all its functions inside the table `math`. + +math.abs({x}) *math.abs()* + Returns the absolute value of {x}. + +math.acos({x}) *math.acos()* + Returns the arc cosine of {x} (in radians). + +math.asin({x}) *math.asin()* + Returns the arc sine of {x} (in radians). + +math.atan({x}) *math.atan()* + Returns the arc tangent of {x} (in radians). + +math.atan2({x}, {y}) *math.atan2()* + Returns the arc tangent of `x/y` (in radians), but uses the signs of + both parameters to find the quadrant of the result. (It also handles + correctly the case of {y} being zero.) + +math.ceil({x}) *math.ceil()* + Returns the smallest integer larger than or equal to {x}. + +math.cos({x}) *math.cos()* + Returns the cosine of {x} (assumed to be in radians). + +math.cosh({x}) *math.cosh()* + Returns the hyperbolic cosine of {x}. + +math.deg({x}) *math.deg()* + Returns the angle {x} (given in radians) in degrees. + +math.exp({x}) *math.exp()* + Returns the value `e^x`. + +math.floor({x}) *math.floor()* + Returns the largest integer smaller than or equal to {x}. + +math.fmod({x}, {y}) *math.fmod()* + Returns the remainder of the division of {x} by {y}. + +math.frexp({x}) *math.frexp()* + Returns `m` and `e` such that `x = m * 2^e`, `e` is an integer and the + absolute value of `m` is in the range `[0.5, 1)` (or zero when {x} is + zero). + +math.huge *math.huge()* + The value `HUGE_VAL`, a value larger than or equal to any other + numerical value. + +math.ldexp({m}, {e}) *math.ldexp()* + Returns `m * 2^e` (`e` should be an integer). + +math.log({x}) *math.log()* + Returns the natural logarithm of {x}. + +math.log10({x}) *math.log10()* + Returns the base-10 logarithm of {x}. + +math.max({x}, {...}) *math.max()* + Returns the maximum value among its arguments. + +math.min({x}, {...}) *math.min()* + Returns the minimum value among its arguments. + +math.modf({x}) *math.modf()* + Returns two numbers, the integral part of {x} and the fractional part + of {x}. + +math.pi *math.pi()* + The value of `pi`. + +math.pow({x}, {y}) *math.pow()* + Returns `x^y`. (You can also use the expression `x^y` to compute this + value.) + +math.rad({x}) *math.rad()* + Returns the angle {x} (given in degrees) in radians. + +math.random([{m} [, {n}]]) *math.random()* + This function is an interface to the simple pseudo-random generator + function `rand` provided by ANSI C. (No guarantees can be given for + its statistical properties.) + + When called without arguments, returns a pseudo-random real number in + the range `[0,1)`. When called with a number {m}, `math.random` + returns a pseudo-random integer in the range `[1, m]`. When called + with two numbers {m} and {n}, `math.random` returns a pseudo-random + integer in the range `[m, n]`. + +math.randomseed({x}) *math.randomseed()* + Sets {x} as the "seed" for the pseudo-random generator: equal seeds + produce equal sequences of numbers. + +math.sin({x}) *math.sin()* + Returns the sine of {x} (assumed to be in radians). + +math.sinh({x}) *math.sinh()* + Returns the hyperbolic sine of {x}. + +math.sqrt({x}) *math.sqrt()* + Returns the square root of {x}. (You can also use the expression + `x^0.5` to compute this value.) + +math.tan({x}) *math.tan()* + Returns the tangent of {x} (assumed to be in radians). + +math.tanh({x}) *math.tanh()* + Returns the hyperbolic tangent of {x}. + +============================================================================== +5.6 Input and Output Facilities *luaref-libIO* + +The I/O library provides two different styles for file manipulation. The first +one uses implicit file descriptors; that is, there are operations to set a +default input file and a default output file, and all input/output operations +are over these default files. The second style uses explicit file +descriptors. + +When using implicit file descriptors, all operations are supplied by +table `io`. When using explicit file descriptors, the operation `io.open` returns +a file descriptor and then all operations are supplied as methods of the file +descriptor. + +The table `io` also provides three predefined file descriptors with their usual +meanings from C: `io.stdin`, `io.stdout`, and `io.stderr`. + +Unless otherwise stated, all I/O functions return `nil` on failure (plus an +error message as a second result) and some value different from `nil` on +success. + +io.close([{file}]) *io.close()* + Equivalent to `file:close`. Without a {file}, closes the default + output file. + +io.flush() *io.flush()* + Equivalent to `file:flush` over the default output file. + +io.input([{file}]) *io.input()* + When called with a file name, it opens the named file (in text mode), + and sets its handle as the default input file. When called with a file + handle, it simply sets this file handle as the default input file. + When called without parameters, it returns the current default input + file. + + In case of errors this function raises the error, instead of returning + an error code. + +io.lines([{filename}]) *io.lines()* + Opens the given file name in read mode and returns an iterator + function that, each time it is called, returns a new line from the + file. Therefore, the construction + + `for line in io.lines(filename) do` `body` `end` + + will iterate over all lines of the file. When the iterator function + detects the end of file, it returns `nil` (to finish the loop) and + automatically closes the file. + + The call `io.lines()` (without a file name) is equivalent to + `io.input():lines()`; that is, it iterates over the lines of the + default input file. In this case it does not close the file when the + loop ends. + +io.open({filename} [, {mode}]) *io.open()* + This function opens a file, in the mode specified in the string + {mode}. It returns a new file handle, or, in case of errors, `nil` + plus an error message. + + The {mode} string can be any of the following: + + - `"r"` read mode (the default); + - `"w"` write mode; + - `"a"` append mode; + - `"r+"` update mode, all previous data is preserved; + - `"w+"` update mode, all previous data is erased; + - `"a+"` append update mode, previous data is preserved, writing is + only allowed at the end of file. + + The {mode} string may also have a `b` at the end, which is needed in + some systems to open the file in binary mode. This string is exactly + what is used in the standard C function `fopen`. + +io.output([{file}]) *io.output()* + Similar to `io.input`, but operates over the default output file. + +io.popen({prog} [, {mode}]) *io.popen()* + Starts program {prog} in a separated process and returns a file handle + that you can use to read data from this program (if {mode} is `"r"`, + the default) or to write data to this program (if {mode} is `"w"`). + + This function is system dependent and is not available on all + platforms. + +io.read({...}) *io.read()* + Equivalent to `io.input():read`. + +io.tmpfile() *io.tmpfile()* + Returns a handle for a temporary file. This file is opened in update + mode and it is automatically removed when the program ends. + +io.type({obj}) *io.type()* + Checks whether {obj} is a valid file handle. Returns the string + `"file"` if {obj} is an open file handle, `"closed file"` if {obj} is + a closed file handle, or `nil` if {obj} is not a file handle. + +io.write({...}) *io.write()* + Equivalent to `io.output():write`. + +file:close() *luaref-file:close()* + Closes `file`. Note that files are automatically closed when their + handles are garbage collected, but that takes an unpredictable amount + of time to happen. + +file:flush() *luaref-file:flush()* + Saves any written data to `file`. + +file:lines() *luaref-file:lines()* + Returns an iterator function that, each time it is called, returns a + new line from the file. Therefore, the construction + + `for line in file:lines() do` `body` `end` + + will iterate over all lines of the file. (Unlike `io.lines`, this + function does not close the file when the loop ends.) + +file:read({...}) *luaref-file:read()* + Reads the file `file`, according to the given formats, which specify + what to read. For each format, the function returns a string (or a + number) with the characters read, or `nil` if it cannot read data with + the specified format. When called without formats, it uses a default + format that reads the entire next line (see below). + + The available formats are + + `"*n"` reads a number; this is the only format that returns a + number instead of a string. + `"*a"` reads the whole file, starting at the current position. On + end of file, it returns the empty string. + `"*l"` reads the next line (skipping the end of line), returning + `nil` on end of file. This is the default format. + `number` reads a string with up to that number of characters, + returning `nil` on end of file. If number is zero, it reads + nothing and returns an empty string, or `nil` on end of file. + +file:seek([{whence}] [, {offset}]) *luaref-file:seek()* + Sets and gets the file position, measured from the beginning of the + file, to the position given by {offset} plus a base specified by the + string {whence}, as follows: + + - `"set"`: base is position 0 (beginning of the file); + - `"cur"`: base is current position; + - `"end"`: base is end of file; + + In case of success, function `seek` returns the final file position, + measured in bytes from the beginning of the file. If this function + fails, it returns `nil`, plus a string describing the error. + + The default value for {whence} is `"cur"`, and for {offset} is 0. + Therefore, the call `file:seek()` returns the current file position, + without changing it; the call `file:seek("set")` sets the position to + the beginning of the file (and returns 0); and the call + `file:seek("end")` sets the position to the end of the file, and + returns its size. + +file:setvbuf({mode} [, {size}]) *luaref-file:setvbuf()* + Sets the buffering mode for an output file. There are three available + modes: + + `"no"` no buffering; the result of any output operation appears + immediately. + `"full"` full buffering; output operation is performed only when + the buffer is full (or when you explicitly `flush` the file + (see |luaref-io.flush|). + `"line"` line buffering; output is buffered until a newline is + output or there is any input from some special files (such as + a terminal device). + + For the last two cases, {size} specifies the size of the buffer, in + bytes. The default is an appropriate size. + +file:write({...}) *luaref-file:write()* + Writes the value of each of its arguments to `file`. The arguments + must be strings or numbers. To write other values, use `tostring` + |luaref-tostring| or `string.format` |luaref-string.format| before + `write`. + +============================================================================== +5.8 Operating System Facilities *luaref-libOS* + +This library is implemented through table `os`. + +os.clock() *os.clock()* + Returns an approximation of the amount in seconds of CPU time used by + the program. + +os.date([{format} [, {time}]]) *os.date()* + Returns a string or a table containing date and time, formatted + according to the given string {format}. + + If the {time} argument is present, this is the time to be formatted + (see the `os.time` function |luaref-os.time| for a description of this + value). Otherwise, `date` formats the current time. + + If {format} starts with `!`, then the date is formatted in + Coordinated Universal Time. After this optional character, if {format} + is the string `"*t"`, then `date` returns a table with the following + fields: `year` (four digits), `month` (1-12), `day` (1-31), `hour` + (0-23), `min` (0-59), `sec` (0-61), `wday` (weekday, Sunday is 1), + `yday` (day of the year), and `isdst` (daylight saving flag, a + boolean). + + If {format} is not `"*t"`, then `date` returns the date as a string, + formatted according to the same rules as the C function `strftime`. + + When called without arguments, `date` returns a reasonable date and + time representation that depends on the host system and on the current + locale (that is, `os.date()` is equivalent to `os.date("%c")`). + +os.difftime({t2}, {t1}) *os.difftime()* + Returns the number of seconds from time {t1} to time {t2}. In POSIX, + Windows, and some other systems, this value is exactly `t2 - t1` . + +os.execute([{command}]) *os.execute()* + This function is equivalent to the C function `system`. It passes + {command} to be executed by an operating system shell. It returns a + status code, which is system-dependent. If {command} is absent, then + it returns nonzero if a shell is available and zero otherwise. + +os.exit([{code}]) *os.exit()* + Calls the C function `exit`, with an optional {code}, to terminate the + host program. The default value for {code} is the success code. + +os.getenv({varname}) *os.getenv()* + Returns the value of the process environment variable {varname}, or + `nil` if the variable is not defined. + +os.remove({filename}) *os.remove()* + Deletes the file with the given name. Directories must be empty to be + removed. If this function fails, it returns `nil`, plus a string + describing the error. + +os.rename({oldname}, {newname}) *os.rename()* + Renames file named {oldname} to {newname}. If this function fails, it + returns `nil`, plus a string describing the error. + +os.setlocale({locale} [, {category}]) *os.setlocale()* + Sets the current locale of the program. {locale} is a string + specifying a locale; {category} is an optional string describing which + category to change: `"all"`, `"collate"`, `"ctype"`, `"monetary"`, + `"numeric"`, or `"time"`; the default category is `"all"`. The + function returns the name of the new locale, or `nil` if the request + cannot be honored. + +os.time([{table}]) *os.time()* + Returns the current time when called without arguments, or a time + representing the date and time specified by the given table. This + table must have fields `year`, `month`, and `day`, and may have fields + `hour`, `min`, `sec`, and `isdst` (for a description of these fields, + see the `os.date` function |luaref-os.date|). + + The returned value is a number, whose meaning depends on your system. + In POSIX, Windows, and some other systems, this number counts the + number of seconds since some given start time (the "epoch"). In other + systems, the meaning is not specified, and the number returned by + `time` can be used only as an argument to `date` and `difftime`. + +os.tmpname() *os.tmpname()* + Returns a string with a file name that can be used for a temporary + file. The file must be explicitly opened before its use and explicitly + removed when no longer needed. + +============================================================================== +5.9 The Debug Library *luaref-libDebug* + +This library provides the functionality of the debug interface to Lua +programs. You should exert care when using this library. The functions +provided here should be used exclusively for debugging and similar tasks, such +as profiling. Please resist the temptation to use them as a usual programming +tool: they can be very slow. Moreover, several of its functions violate some +assumptions about Lua code (e.g., that variables local to a function cannot be +accessed from outside or that userdata metatables cannot be changed by Lua +code) and therefore can compromise otherwise secure code. + +All functions in this library are provided inside the `debug` table. All +functions that operate over a thread have an optional first argument which is +the thread to operate over. The default is always the current thread. + +debug.debug() *debug.debug()* + Enters an interactive mode with the user, running each string that the + user enters. Using simple commands and other debug facilities, the + user can inspect global and local variables, change their values, + evaluate expressions, and so on. A line containing only the word + `cont` finishes this function, so that the caller continues its + execution. + + Note that commands for `debug.debug` are not lexically nested within + any function, and so have no direct access to local variables. + +debug.getfenv(o) *debug.getfenv()* + Returns the environment of object {o}. + +debug.gethook([{thread}]) *debug.gethook()* + Returns the current hook settings of the thread, as three values: the + current hook function, the current hook mask, and the current hook + count (as set by the `debug.sethook` function). + +debug.getinfo([{thread},] {function} [, {what}]) *debug.getinfo()* + Returns a table with information about a function. You can give the + function directly, or you can give a number as the value of + {function}, which means the function running at level {function} of + the call stack of the given thread: level 0 is the current function + (`getinfo` itself); level 1 is the function that called `getinfo`; and + so on. If {function} is a number larger than the number of active + functions, then `getinfo` returns `nil`. + + The returned table may contain all the fields returned by + `lua_getinfo` (see |luaref-lua_getinfo|), with the string {what} + describing which fields to fill in. The default for {what} is to get + all information available, except the table of valid lines. If + present, the option `f` adds a field named `func` with the function + itself. If present, the option `L` adds a field named `activelines` + with the table of valid lines. + + For instance, the expression `debug.getinfo(1,"n").name` returns the + name of the current function, if a reasonable name can be found, and + `debug.getinfo(print)` returns a table with all available information + about the `print` function. + +debug.getlocal([{thread},] {level}, {local}) *debug.getlocal()* + This function returns the name and the value of the local variable + with index {local} of the function at level {level} of the stack. (The + first parameter or local variable has index 1, and so on, until the + last active local variable.) The function returns `nil` if there is no + local variable with the given index, and raises an error when called + with a {level} out of range. (You can call `debug.getinfo` + |luaref-debug.getinfo| to check whether the level is valid.) + + Variable names starting with `(` (open parentheses) represent + internal variables (loop control variables, temporaries, and C + function locals). + +debug.getmetatable({object}) *debug.getmetatable()* + Returns the metatable of the given {object} or `nil` if it does not + have a metatable. + +debug.getregistry() *debug.getregistry()* + Returns the registry table (see |luaref-apiRegistry|). + +debug.getupvalue({func}, {up}) *debug.getupvalue()* + This function returns the name and the value of the upvalue with index + {up} of the function {func}. The function returns `nil` if there is no + upvalue with the given index. + +debug.setfenv({object}, {table}) *debug.setfenv()* + Sets the environment of the given {object} to the given {table}. + Returns {object}. + +debug.sethook([{thread},] {hook}, {mask} [, {count}]) *debug.sethook()* + Sets the given function as a hook. The string {mask} and the number + {count} describe when the hook will be called. The string mask may + have the following characters, with the given meaning: + + - `"c"` : The hook is called every time Lua calls a function; + - `"r"` : The hook is called every time Lua returns from a function; + - `"l"` : The hook is called every time Lua enters a new line of + code. + + With a {count} different from zero, the hook is called after every + {count} instructions. + + When called without arguments, the `debug.sethook` turns off the hook. + + When the hook is called, its first parameter is a string describing + the event that triggered its call: `"call"`, `"return"` (or `"tail + return"`), `"line"`, and `"count"`. For line events, the hook also + gets the new line number as its second parameter. Inside a hook, you + can call `getinfo` with level 2 to get more information about the + running function (level 0 is the `getinfo` function, and level 1 is + the hook function), unless the event is `"tail return"`. In this case, + Lua is only simulating the return, and a call to `getinfo` will return + invalid data. + +debug.setlocal([{thread},] {level}, {local}, {value}) *debug.setlocal()* + This function assigns the value {value} to the local variable with + index {local} of the function at level {level} of the stack. The + function returns `nil` if there is no local variable with the given + index, and raises an error when called with a {level} out of range. + (You can call `getinfo` to check whether the level is valid.) + Otherwise, it returns the name of the local variable. + +debug.setmetatable({object}, {table}) *debug.setmetatable()* + Sets the metatable for the given {object} to the given {table} (which + can be `nil`). + +debug.setupvalue({func}, {up}, {value}) *debug.setupvalue()* + This function assigns the value {value} to the upvalue with index {up} + of the function {func}. The function returns `nil` if there is no + upvalue with the given index. Otherwise, it returns the name of the + upvalue. + +debug.traceback([{thread},] [{message}] [,{level}]) *debug.traceback()* + Returns a string with a traceback of the call stack. An optional + {message} string is appended at the beginning of the traceback. An + optional {level} number tells at which level to start the traceback + (default is 1, the function calling `traceback`). + +============================================================================== +A BIBLIOGRAPHY *luaref-bibliography* +============================================================================== + +This help file is a minor adaptation from this main reference: + + - R. Ierusalimschy, L. H. de Figueiredo, and W. Celes., + "Lua: 5.1 reference manual", http://www.lua.org/manual/5.1/manual.html + +Lua is discussed in these references: + + - R. Ierusalimschy, L. H. de Figueiredo, and W. Celes., + "Lua --- an extensible extension language". + "Software: Practice & Experience" 26, 6 (1996) 635-652. + + - L. H. de Figueiredo, R. Ierusalimschy, and W. Celes., + "The design and implementation of a language for extending applications". + "Proc. of XXI Brazilian Seminar on Software and Hardware" (1994) 273-283. + + - L. H. de Figueiredo, R. Ierusalimschy, and W. Celes., + "Lua: an extensible embedded language". + "Dr. Dobb's Journal" 21, 12 (Dec 1996) 26-33. + + - R. Ierusalimschy, L. H. de Figueiredo, and W. Celes., + "The evolution of an extension language: a history of Lua". + "Proc. of V Brazilian Symposium on Programming Languages" (2001) B-14-B-28. + +============================================================================== +B COPYRIGHT & LICENSES *luaref-copyright* +============================================================================== + +This help file has the same copyright and license as Lua 5.1 and the Lua 5.1 + manual: + +Copyright (c) 1994-2006 Lua.org, PUC-Rio. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +============================================================================== +C LUAREF DOC *luarefvim* *luarefvimdoc* *luaref-help* *luaref-doc* +============================================================================== + +This is a Vim help file containing a reference for Lua 5.1, and it is -- with +a few exceptions and adaptations -- a copy of the Lua 5.1 Reference Manual +(see |luaref-bibliography|). For usage information, refer to +|luaref-docUsage|. For copyright information, see |luaref-copyright|. + +The main ideas and concepts on how to implement this reference were taken from +Christian Habermann's CRefVim project +(http://www.vim.org/scripts/script.php?script_id=614). + +Adapted for bundled Nvim documentation; the original plugin can be found at +http://www.vim.org/scripts/script.php?script_id=1291 + +------------------------------------------------------------------------------ + vi:tw=78:ts=4:ft=help:norl:et diff --git a/runtime/doc/luvref.txt b/runtime/doc/luvref.txt new file mode 100644 index 0000000000..ee45444b42 --- /dev/null +++ b/runtime/doc/luvref.txt @@ -0,0 +1,3898 @@ +*luvref.txt* Nvim + + + LUV REFERENCE MANUAL + + +This file documents the Lua bindings for the LibUV library which is used for +Nvim's event-loop and is accessible from Lua via |vim.loop| (e.g., |uv.version()| +is exposed as `vim.loop.version()`). + +For information about this manual, see |luv-credits|. + +For further examples, see https://github.com/luvit/luv/tree/master/examples. + +============================================================================== +INTRODUCTION *luv* *luv-intro* *uv* + +The luv (https://github.com/luvit/luv) project provides access to the +multi-platform support library libuv (https://github.com/libuv/libuv) in Lua +code. It was primarily developed for the luvit +(https://github.com/luvit/luvit) project as the built-in `uv` module, but can +be used in other Lua environments. + +More information about the core libuv library can be found at the original +libuv documentation page (https://docs.libuv.org/). + +TCP Echo Server Example~ + +Here is a small example showing a TCP echo server: + + > + local uv = vim.loop + + local server = uv.new_tcp() + server:bind("127.0.0.1", 1337) + server:listen(128, function (err) + assert(not err, err) + local client = uv.new_tcp() + server:accept(client) + client:read_start(function (err, chunk) + assert(not err, err) + if chunk then + client:write(chunk) + else + client:shutdown() + client:close() + end + end) + end) + print("TCP server listening at 127.0.0.1 port 1337") + uv.run() -- an explicit run call is necessary outside of luvit +< + +Module Layout~ + +The luv library contains a single Lua module referred to hereafter as `uv` for +simplicity. This module consists mostly of functions with names corresponding +to their original libuv versions. For example, the libuv function +`uv_tcp_bind` has a luv version at |uv.tcp_bind()|. Currently, only one +non-function field exists: `uv.constants`, which is a table. + +Functions vs Methods~ + +In addition to having simple functions, luv provides an optional method-style +API. For example, `uv.tcp_bind(server, host, port)` can alternatively be +called as `server:bind(host, port)` . Note that the first argument `server` +becomes the object and `tcp_` is removed from the function name. Method forms +are documented below where they exist. + +Synchronous vs Asynchronous Functions~ + +Functions that accept a callback are asynchronous. These functions may +immediately return results to the caller to indicate their initial status, but +their final execution is deferred until at least the next libuv loop +iteration. After completion, their callbacks are executed with any results +passed to it. + +Functions that do not accept a callback are synchronous. These functions +immediately return their results to the caller. + +Some (generally FS and DNS) functions can behave either synchronously or +asynchronously. If a callback is provided to these functions, they behave +asynchronously; if no callback is provided, they behave synchronously. + +Pseudo-Types~ + +Some unique types are defined. These are not actual types in Lua, but they are +used here to facilitate documenting consistent behavior: +- `fail`: an assertable `nil, string, string` tuple (see |luv-error-handling|) +- `callable`: a `function`; or a `table` or `userdata` with a `__call` + metamethod +- `buffer`: a `string` or a sequential `table` of `string`s +- `threadargs`: variable arguments (`...`) of type `nil`, `boolean`, `number`, + `string`, or `userdata` + +============================================================================== +CONTENTS *luv-contents* + +This documentation is mostly a retelling of the libuv API documentation +(http://docs.libuv.org/en/v1.x/api.html) within the context of luv's Lua API. +Low-level implementation details and unexposed C functions and types are not +documented here except for when they are relevant to behavior seen in the Lua +module. + +- |luv-error-handling| — Error handling +- |luv-version-checking| — Version checking +- |uv_loop_t| — Event loop +- |uv_req_t| — Base request +- |uv_handle_t| — Base handle + - |uv_timer_t| — Timer handle + - |uv_prepare_t| — Prepare handle + - |uv_check_t| — Check handle + - |uv_idle_t| — Idle handle + - |uv_async_t| — Async handle + - |uv_poll_t| — Poll handle + - |uv_signal_t| — Signal handle + - |uv_process_t| — Process handle + - |uv_stream_t| — Stream handle + - |uv_tcp_t| — TCP handle + - |uv_pipe_t| — Pipe handle + - |uv_tty_t| — TTY handle + - |uv_udp_t| — UDP handle + - |uv_fs_event_t| — FS Event handle + - |uv_fs_poll_t| — FS Poll handle +- |luv-file-system-operations| — File system operations +- |luv-thread-pool-work-scheduling| — Thread pool work scheduling +- |luv-dns-utility-functions| — DNS utility functions +- |luv-threading-and-synchronization-utilities| — Threading and + synchronization utilities +- |luv-miscellaneous-utilities| — Miscellaneous utilities +- |luv-metrics-operations| — Metrics operations + +============================================================================== +ERROR HANDLING *luv-error-handling* + +In libuv, errors are negative numbered constants; however, these errors and +the functions used to handle them are not exposed to luv users. Instead, if an +internal error is encountered, the luv function will return to the caller an +assertable `nil, err, name` tuple. + +- `nil` idiomatically indicates failure +- `err` is a string with the format `{name}: {message}` + - `{name}` is the error name provided internally by `uv_err_name` + - `{message}` is a human-readable message provided internally by + `uv_strerror` +- `name` is the same string used to construct `err` + +This tuple is referred to below as the `fail` pseudo-type. + +When a function is called successfully, it will return either a value that is +relevant to the operation of the function, or the integer `0` to indicate +success, or sometimes nothing at all. These cases are documented below. + +============================================================================== +VERSION CHECKING *luv-version-checking* + +uv.version() *uv.version()* + + Returns the libuv version packed into a single integer. 8 bits + are used for each component, with the patch number stored in + the 8 least significant bits. For example, this would be + 0x010203 in libuv 1.2.3. + + Returns: `integer` + +uv.version_string() *uv.version_string()* + + Returns the libuv version number as a string. For example, + this would be "1.2.3" in libuv 1.2.3. For non-release + versions, the version suffix is included. + + Returns: `string` + +============================================================================== +`uv_loop_t` — Event loop *luv-event-loop* *uv_loop_t* + +The event loop is the central part of libuv's functionality. It takes care of +polling for I/O and scheduling callbacks to be run based on different sources +of events. + +In luv, there is an implicit uv loop for every Lua state that loads the +library. You can use this library in an multi-threaded environment as long as +each thread has it's own Lua state with its corresponding own uv loop. This +loop is not directly exposed to users in the Lua module. + +uv.loop_close() *uv.loop_close()* + + Closes all internal loop resources. In normal execution, the + loop will automatically be closed when it is garbage collected + by Lua, so it is not necessary to explicitly call + `loop_close()`. Call this function only after the loop has + finished executing and all open handles and requests have been + closed, or it will return `EBUSY`. + + Returns: `0` or `fail` + +uv.run([{mode}]) *uv.run()* + + Parameters: + - `mode`: `string` or `nil` (default: `"default"`) + + This function runs the event loop. It will act differently + depending on the specified mode: + + - `"default"`: Runs the event loop until there are no more + active and referenced handles or requests. Returns `true` + if |uv.stop()| was called and there are still active + handles or requests. Returns `false` in all other cases. + + - `"once"`: Poll for I/O once. Note that this function + blocks if there are no pending callbacks. Returns `false` + when done (no active handles or requests left), or `true` + if more callbacks are expected (meaning you should run the + event loop again sometime in the future). + + - `"nowait"`: Poll for I/O once but don't block if there are + no pending callbacks. Returns `false` if done (no active + handles or requests left), or `true` if more callbacks are + expected (meaning you should run the event loop again + sometime in the future). + + Returns: `boolean` or `fail` + + Note: Luvit will implicitly call `uv.run()` after loading user + code, but if you use the luv bindings directly, you need to + call this after registering your initial set of event + callbacks to start the event loop. + +uv.loop_configure({option}, {...}) *uv.loop_configure()* + + Parameters: + - `option`: `string` + - `...`: depends on `option`, see below + + Set additional loop options. You should normally call this + before the first call to uv_run() unless mentioned otherwise. + + Supported options: + + - `"block_signal"`: Block a signal when polling for new + events. The second argument to loop_configure() is the + signal name (as a lowercase string) or the signal number. + This operation is currently only implemented for + `"sigprof"` signals, to suppress unnecessary wakeups when + using a sampling profiler. Requesting other signals will + fail with `EINVAL`. + - `"metrics_idle_time"`: Accumulate the amount of idle time + the event loop spends in the event provider. This option + is necessary to use `metrics_idle_time()`. + + An example of a valid call to this function is: + + > + uv.loop_configure("block_signal", "sigprof") +< + + Returns: `0` or `fail` + + Note: Be prepared to handle the `ENOSYS` error; it means the + loop option is not supported by the platform. + +uv.loop_mode() *uv.loop_mode()* + + If the loop is running, returns a string indicating the mode + in use. If the loop is not running, `nil` is returned instead. + + Returns: `string` or `nil` + +uv.loop_alive() *uv.loop_alive()* + + Returns `true` if there are referenced active handles, active + requests, or closing handles in the loop; otherwise, `false`. + + Returns: `boolean` or `fail` + +uv.stop() *uv.stop()* + + Stop the event loop, causing |uv.run()| to end as soon as + possible. This will happen not sooner than the next loop + iteration. If this function was called before blocking for + I/O, the loop won't block for I/O on this iteration. + + Returns: Nothing. + +uv.backend_fd() *uv.backend_fd()* + + Get backend file descriptor. Only kqueue, epoll, and event + ports are supported. + + This can be used in conjunction with `uv.run("nowait")` to + poll in one thread and run the event loop's callbacks in + another + + Returns: `integer` or `nil` + + Note: Embedding a kqueue fd in another kqueue pollset doesn't + work on all platforms. It's not an error to add the fd but it + never generates events. + +uv.backend_timeout() *uv.backend_timeout()* + + Get the poll timeout. The return value is in milliseconds, or + -1 for no timeout. + + Returns: `integer` + +uv.now() *uv.now()* + + Returns the current timestamp in milliseconds. The timestamp + is cached at the start of the event loop tick, see + |uv.update_time()| for details and rationale. + + The timestamp increases monotonically from some arbitrary + point in time. Don't make assumptions about the starting + point, you will only get disappointed. + + Returns: `integer` + + Note: Use |uv.hrtime()| if you need sub-millisecond + granularity. + +uv.update_time() *uv.update_time()* + + Update the event loop's concept of "now". Libuv caches the + current time at the start of the event loop tick in order to + reduce the number of time-related system calls. + + You won't normally need to call this function unless you have + callbacks that block the event loop for longer periods of + time, where "longer" is somewhat subjective but probably on + the order of a millisecond or more. + + Returns: Nothing. + +uv.walk({callback}) *uv.walk()* + + Parameters: + - `callback`: `callable` + - `handle`: `userdata` for sub-type of |uv_handle_t| + + Walk the list of handles: `callback` will be executed with + each handle. + + Returns: Nothing. + + > + -- Example usage of uv.walk to close all handles that + -- aren't already closing. + uv.walk(function (handle) + if not handle:is_closing() then + handle:close() + end + end) +< + +============================================================================== +`uv_req_t` — Base request *luv-base-request* *uv_req_t* + +`uv_req_t` is the base type for all libuv request types. + +uv.cancel({req}) *uv.cancel()* + + > method form `req:cancel()` + + Parameters: + - `req`: `userdata` for sub-type of |uv_req_t| + + Cancel a pending request. Fails if the request is executing or + has finished executing. Only cancellation of |uv_fs_t|, + `uv_getaddrinfo_t`, `uv_getnameinfo_t` and `uv_work_t` + requests is currently supported. + + Returns: `0` or `fail` + +uv.req_get_type({req}) *uv.req_get_type()* + + > method form `req:get_type()` + + Parameters: + - `req`: `userdata` for sub-type of |uv_req_t| + + Returns the name of the struct for a given request (e.g. + `"fs"` for |uv_fs_t|) and the libuv enum integer for the + request's type (`uv_req_type`). + + Returns: `string, integer` + +============================================================================== +`uv_handle_t` — Base handle *luv-base-handle* *uv_handle_t* + +`uv_handle_t` is the base type for all libuv handle types. All API functions +defined here work with any handle type. + +uv.is_active({handle}) *uv.is_active()* + + > method form `handle:is_active()` + + Parameters: + - `handle`: `userdata` for sub-type of |uv_handle_t| + + Returns `true` if the handle is active, `false` if it's + inactive. What "active” means depends on the type of handle: + + - A |uv_async_t| handle is always active and cannot be + deactivated, except by closing it with |uv.close()|. + + - A |uv_pipe_t|, |uv_tcp_t|, |uv_udp_t|, etc. + handle - basically any handle that deals with I/O - is + active when it is doing something that involves I/O, like + reading, writing, connecting, accepting new connections, + etc. + + - A |uv_check_t|, |uv_idle_t|, |uv_timer_t|, + etc. handle is active when it has been started with a call + to |uv.check_start()|, |uv.idle_start()|, + |uv.timer_start()| etc. until it has been stopped with a + call to its respective stop function. + + Returns: `boolean` or `fail` + +uv.is_closing({handle}) *uv.is_closing()* + + > method form `handle:is_closing()` + + Parameters: + - `handle`: `userdata` for sub-type of |uv_handle_t| + + Returns `true` if the handle is closing or closed, `false` + otherwise. + + Returns: `boolean` or `fail` + + Note: This function should only be used between the + initialization of the handle and the arrival of the close + callback. + +uv.close({handle} [, {callback}]) *uv.close()* + + > method form `handle:close([callback])` + + Parameters: + - `handle`: `userdata` for sub-type of |uv_handle_t| + - `callback`: `callable` or `nil` + + Request handle to be closed. `callback` will be called + asynchronously after this call. This MUST be called on each + handle before memory is released. + + Handles that wrap file descriptors are closed immediately but + `callback` will still be deferred to the next iteration of the + event loop. It gives you a chance to free up any resources + associated with the handle. + + In-progress requests, like `uv_connect_t` or `uv_write_t`, are + cancelled and have their callbacks called asynchronously with + `ECANCELED`. + + Returns: Nothing. + +uv.ref({handle}) *uv.ref()* + + > method form `handle:ref()` + + Parameters: + - `handle`: `userdata` for sub-type of |uv_handle_t| + + Reference the given handle. References are idempotent, that + is, if a handle is already referenced calling this function + again will have no effect. + + Returns: Nothing. + + See |luv-reference-counting|. + +uv.unref({handle}) *uv.unref()* + + > method form `handle:unref()` + + Parameters: + - `handle`: `userdata` for sub-type of |uv_handle_t| + + Un-reference the given handle. References are idempotent, that + is, if a handle is not referenced calling this function again + will have no effect. + + Returns: Nothing. + +See |luv-reference-counting|. + +uv.has_ref({handle}) *uv.has_ref()* + + > method form `handle:has_ref()` + + Parameters: + - `handle`: `userdata` for sub-type of |uv_handle_t| + + Returns `true` if the handle referenced, `false` if not. + + Returns: `boolean` or `fail` + + See |luv-reference-counting|. + +uv.send_buffer_size({handle} [, {size}]) *uv.send_buffer_size()* + + > method form `handle:send_buffer_size([size])` + + Parameters: + - `handle`: `userdata` for sub-type of |uv_handle_t| + - `size`: `integer` or `nil` (default: `0`) + + Gets or sets the size of the send buffer that the operating + system uses for the socket. + + If `size` is omitted (or `0`), this will return the current + send buffer size; otherwise, this will use `size` to set the + new send buffer size. + + This function works for TCP, pipe and UDP handles on Unix and + for TCP and UDP handles on Windows. + + Returns: + - `integer` or `fail` (if `size` is `nil` or `0`) + - `0` or `fail` (if `size` is not `nil` and not `0`) + + Note: Linux will set double the size and return double the + size of the original set value. + +uv.recv_buffer_size({handle} [, {size}]) *uv.recv_buffer_size()* + + > method form `handle:recv_buffer_size([size])` + + Parameters: + - `handle`: `userdata` for sub-type of |uv_handle_t| + - `size`: `integer` or `nil` (default: `0`) + + Gets or sets the size of the receive buffer that the operating + system uses for the socket. + + If `size` is omitted (or `0`), this will return the current + send buffer size; otherwise, this will use `size` to set the + new send buffer size. + + This function works for TCP, pipe and UDP handles on Unix and + for TCP and UDP handles on Windows. + + Returns: + - `integer` or `fail` (if `size` is `nil` or `0`) + - `0` or `fail` (if `size` is not `nil` and not `0`) + + Note: Linux will set double the size and return double the + size of the original set value. + +uv.fileno({handle}) *uv.fileno()* + + > method form `handle:fileno()` + + Parameters: + - `handle`: `userdata` for sub-type of |uv_handle_t| + + Gets the platform dependent file descriptor equivalent. + + The following handles are supported: TCP, pipes, TTY, UDP and + poll. Passing any other handle type will fail with `EINVAL`. + + If a handle doesn't have an attached file descriptor yet or + the handle itself has been closed, this function will return + `EBADF`. + + Returns: `integer` or `fail` + + WARNING: Be very careful when using this function. libuv + assumes it's in control of the file descriptor so any change + to it may lead to malfunction. + +uv.handle_get_type({handle}) *uv.handle_get_type()* + + > method form `handle:get_type()` + + Parameters: + - `handle`: `userdata` for sub-type of |uv_handle_t| + + Returns the name of the struct for a given handle (e.g. + `"pipe"` for |uv_pipe_t|) and the libuv enum integer for the + handle's type (`uv_handle_type`). + + Returns: `string, integer` + +============================================================================== +REFERENCE COUNTING *luv-reference-counting* + +The libuv event loop (if run in the default mode) will run until there are no +active and referenced handles left. The user can force the loop to exit early +by unreferencing handles which are active, for example by calling |uv.unref()| +after calling |uv.timer_start()|. + +A handle can be referenced or unreferenced, the refcounting scheme doesn't use +a counter, so both operations are idempotent. + +All handles are referenced when active by default, see |uv.is_active()| for a +more detailed explanation on what being active involves. + +============================================================================== +`uv_timer_t` — Timer handle *luv-timer-handle* *uv_timer_t* + +> |uv_handle_t| functions also apply. + +Timer handles are used to schedule callbacks to be called in the future. + +uv.new_timer() *uv.new_timer()* + + Creates and initializes a new |uv_timer_t|. Returns the Lua + userdata wrapping it. + + Returns: `uv_timer_t userdata` or `fail` + + > + -- Creating a simple setTimeout wrapper + local function setTimeout(timeout, callback) + local timer = uv.new_timer() + timer:start(timeout, 0, function () + timer:stop() + timer:close() + callback() + end) + return timer + end + + -- Creating a simple setInterval wrapper + local function setInterval(interval, callback) + local timer = uv.new_timer() + timer:start(interval, interval, function () + callback() + end) + return timer + end + + -- And clearInterval + local function clearInterval(timer) + timer:stop() + timer:close() + end +< + +uv.timer_start({timer}, {timeout}, {repeat}, {callback}) *uv.timer_start()* + + > method form `timer:start(timeout, repeat, callback)` + + Parameters: + - `timer`: `uv_timer_t userdata` + - `timeout`: `integer` + - `repeat`: `integer` + - `callback`: `callable` + + Start the timer. `timeout` and `repeat` are in milliseconds. + + If `timeout` is zero, the callback fires on the next event + loop iteration. If `repeat` is non-zero, the callback fires + first after `timeout` milliseconds and then repeatedly after + `repeat` milliseconds. + + Returns: `0` or `fail` + +uv.timer_stop({timer}) *uv.timer_stop()* + + > method form `timer:stop()` + + Parameters: + - `timer`: `uv_timer_t userdata` + + Stop the timer, the callback will not be called anymore. + + Returns: `0` or `fail` + +uv.timer_again({timer}) *uv.timer_again()* + + > method form `timer:again()` + + Parameters: + - `timer`: `uv_timer_t userdata` + + Stop the timer, and if it is repeating restart it using the + repeat value as the timeout. If the timer has never been + started before it raises `EINVAL`. + + Returns: `0` or `fail` + +uv.timer_set_repeat({timer}, {repeat}) *uv.timer_set_repeat()* + + > method form `timer:set_repeat(repeat)` + + Parameters: + - `timer`: `uv_timer_t userdata` + - `repeat`: `integer` + + Set the repeat interval value in milliseconds. The timer will + be scheduled to run on the given interval, regardless of the + callback execution duration, and will follow normal timer + semantics in the case of a time-slice overrun. + + For example, if a 50 ms repeating timer first runs for 17 ms, + it will be scheduled to run again 33 ms later. If other tasks + consume more than the 33 ms following the first timer + callback, then the callback will run as soon as possible. + + Returns: Nothing. + +uv.timer_get_repeat({timer}) *uv.timer_get_repeat()* + + > method form `timer:get_repeat()` + + Parameters: + - `timer`: `uv_timer_t userdata` + + Get the timer repeat value. + + Returns: `integer` + +uv.timer_get_due_in({timer}) *uv.timer_get_due_in()* + + > method form `timer:get_due_in()` + + Parameters: + - `timer`: `uv_timer_t userdata` + + Get the timer due value or 0 if it has expired. The time is + relative to |uv.now()|. + + Returns: `integer` + + Note: New in libuv version 1.40.0. + +============================================================================== +`uv_prepare_t` — Prepare handle *luv-prepare-handle* *uv_prepare_t* + +> |uv_handle_t| functions also apply. + +Prepare handles will run the given callback once per loop iteration, right +before polling for I/O. + + > + local prepare = uv.new_prepare() + prepare:start(function() + print("Before I/O polling") + end) +< + +uv.new_prepare() *uv.new_prepare()* + + Creates and initializes a new |uv_prepare_t|. Returns the Lua + userdata wrapping it. + + Returns: `uv_prepare_t userdata` or `fail` + +uv.prepare_start({prepare}, {callback}) *uv.prepare_start()* + + > method form `prepare:start(callback)` + + Parameters: + - `prepare`: `uv_prepare_t userdata` + - `callback`: `callable` + + Start the handle with the given callback. + + Returns: `0` or `fail` + +uv.prepare_stop({prepare}) *uv.prepare_stop()* + + > method form `prepare:stop()` + + Parameters: + - `prepare`: `uv_prepare_t userdata` + + Stop the handle, the callback will no longer be called. + + Returns: `0` or `fail` + +============================================================================== +`uv_check_t` — Check handle *luv-check-handle* *uv_check_t* + +> |uv_handle_t| functions also apply. + +Check handles will run the given callback once per loop iteration, right after +polling for I/O. + + > + local check = uv.new_check() + check:start(function() + print("After I/O polling") + end) +< + +uv.new_check() *uv.new_check()* + + Creates and initializes a new |uv_check_t|. Returns the Lua + userdata wrapping it. + + Returns: `uv_check_t userdata` or `fail` + +uv.check_start({check}, {callback}) *uv.check_start()* + + > method form `check:start(callback)` + + Parameters: + - `check`: `uv_check_t userdata` + - `callback`: `callable` + + Start the handle with the given callback. + + Returns: `0` or `fail` + +uv.check_stop({check}) *uv.check_stop()* + + > method form `check:stop()` + + Parameters: + - `check`: `uv_check_t userdata` + + Stop the handle, the callback will no longer be called. + + Returns: `0` or `fail` + +============================================================================== +`uv_idle_t` — Idle handle *luv-idle-handle* *uv_idle_t* + +> |uv_handle_t| functions also apply. + +Idle handles will run the given callback once per loop iteration, right before +the |uv_prepare_t| handles. + +Note: The notable difference with prepare handles is that when there are +active idle handles, the loop will perform a zero timeout poll instead of +blocking for I/O. + +WARNING: Despite the name, idle handles will get their callbacks called on +every loop iteration, not when the loop is actually "idle". + + > + local idle = uv.new_idle() + idle:start(function() + print("Before I/O polling, no blocking") + end) +< + +uv.new_idle() *uv.new_idle()* + + Creates and initializes a new |uv_idle_t|. Returns the Lua + userdata wrapping it. + + Returns: `uv_idle_t userdata` or `fail` + +uv.idle_start({idle}, {callback}) *uv.idle_start()* + + > method form `idle:start(callback)` + + Parameters: + - `idle`: `uv_idle_t userdata` + - `callback`: `callable` + + Start the handle with the given callback. + + Returns: `0` or `fail` + +uv.idle_stop({check}) *uv.idle_stop()* + + > method form `idle:stop()` + + Parameters: + - `idle`: `uv_idle_t userdata` + + Stop the handle, the callback will no longer be called. + + Returns: `0` or `fail` + +============================================================================== +`uv_async_t` — Async handle *luv-async-handle* *uv_async_t* + +> |uv_handle_t| functions also apply. + +Async handles allow the user to "wakeup" the event loop and get a callback +called from another thread. + + > + local async + async = uv.new_async(function() + print("async operation ran") + async:close() + end) + + async:send() +< + +uv.new_async([{callback}]) *uv.new_async()* + + Parameters: + - `callback`: `callable` or `nil` + - `...`: `threadargs` passed to/from + `uv.async_send(async, ...)` + + Creates and initializes a new |uv_async_t|. Returns the Lua + userdata wrapping it. A `nil` callback is allowed. + + Returns: `uv_async_t userdata` or `fail` + + Note: Unlike other handle initialization functions, this + immediately starts the handle. + +uv.async_send({async}, {...}) *uv.async_send()* + + > method form `async:send(...)` + + Parameters: + - `async`: `uv_async_t userdata` + - `...`: `threadargs` + + Wakeup the event loop and call the async handle's callback. + + Returns: `0` or `fail` + + Note: It's safe to call this function from any thread. The + callback will be called on the loop thread. + + WARNING: libuv will coalesce calls to `uv.async_send(async)`, + that is, not every call to it will yield an execution of the + callback. For example: if `uv.async_send()` is called 5 times + in a row before the callback is called, the callback will only + be called once. If `uv.async_send()` is called again after the + callback was called, it will be called again. + +============================================================================== +`uv_poll_t` — Poll handle *luv-poll-handle* *uv_poll_t* + +> |uv_handle_t| functions also apply. + +Poll handles are used to watch file descriptors for readability and +writability, similar to the purpose of poll(2) +(http://linux.die.net/man/2/poll). + +The purpose of poll handles is to enable integrating external libraries that +rely on the event loop to signal it about the socket status changes, like +c-ares or libssh2. Using `uv_poll_t` for any other purpose is not recommended; +|uv_tcp_t|, |uv_udp_t|, etc. provide an implementation that is faster and more +scalable than what can be achieved with `uv_poll_t`, especially on Windows. + +It is possible that poll handles occasionally signal that a file descriptor is +readable or writable even when it isn't. The user should therefore always be +prepared to handle EAGAIN or equivalent when it attempts to read from or write +to the fd. + +It is not okay to have multiple active poll handles for the same socket, this +can cause libuv to busyloop or otherwise malfunction. + +The user should not close a file descriptor while it is being polled by an +active poll handle. This can cause the handle to report an error, but it might +also start polling another socket. However the fd can be safely closed +immediately after a call to |uv.poll_stop()| or |uv.close()|. + +Note: On windows only sockets can be polled with poll handles. On Unix any +file descriptor that would be accepted by poll(2) can be used. + +uv.new_poll({fd}) *uv.new_poll()* + + Parameters: + - `fd`: `integer` + + Initialize the handle using a file descriptor. + + The file descriptor is set to non-blocking mode. + + Returns: `uv_poll_t userdata` or `fail` + +uv.new_socket_poll({fd}) *uv.new_socket_poll()* + + Parameters: + - `fd`: `integer` + + Initialize the handle using a socket descriptor. On Unix this + is identical to |uv.new_poll()|. On windows it takes a SOCKET + handle. + + The socket is set to non-blocking mode. + + Returns: `uv_poll_t userdata` or `fail` + +uv.poll_start({poll}, {events}, {callback}) *uv.poll_start()* + + > method form `poll:start(events, callback)` + + Parameters: + - `poll`: `uv_poll_t userdata` + - `events`: `string` or `nil` (default: `"rw"`) + - `callback`: `callable` + - `err`: `nil` or `string` + - `events`: `string` or `nil` + + Starts polling the file descriptor. `events` are: `"r"`, + `"w"`, `"rw"`, `"d"`, `"rd"`, `"wd"`, `"rwd"`, `"p"`, `"rp"`, + `"wp"`, `"rwp"`, `"dp"`, `"rdp"`, `"wdp"`, or `"rwdp"` where + `r` is `READABLE`, `w` is `WRITABLE`, `d` is `DISCONNECT`, and + `p` is `PRIORITIZED`. As soon as an event is detected the + callback will be called with status set to 0, and the detected + events set on the events field. + + The user should not close the socket while the handle is + active. If the user does that anyway, the callback may be + called reporting an error status, but this is not guaranteed. + + Returns: `0` or `fail` + + Note Calling `uv.poll_start()` on a handle that is already + active is fine. Doing so will update the events mask that is + being watched for. + +uv.poll_stop({poll}) *uv.poll_stop()* + + > method form `poll:stop()` + + Parameters: + - `poll`: `uv_poll_t userdata` + + Stop polling the file descriptor, the callback will no longer + be called. + + Returns: `0` or `fail` + +============================================================================== +`uv_signal_t` — Signal handle *luv-signal-handle* *uv_signal_t* + +> |uv_handle_t| functions also apply. + +Signal handles implement Unix style signal handling on a per-event loop bases. + +Windows Notes: + +Reception of some signals is emulated on Windows: + - SIGINT is normally delivered when the user presses CTRL+C. However, like + on Unix, it is not generated when terminal raw mode is enabled. + - SIGBREAK is delivered when the user pressed CTRL + BREAK. + - SIGHUP is generated when the user closes the console window. On SIGHUP the + program is given approximately 10 seconds to perform cleanup. After that + Windows will unconditionally terminate it. + - SIGWINCH is raised whenever libuv detects that the console has been + resized. SIGWINCH is emulated by libuv when the program uses a uv_tty_t + handle to write to the console. SIGWINCH may not always be delivered in a + timely manner; libuv will only detect size changes when the cursor is + being moved. When a readable |uv_tty_t| handle is used in raw mode, + resizing the console buffer will also trigger a SIGWINCH signal. + - Watchers for other signals can be successfully created, but these signals + are never received. These signals are: SIGILL, SIGABRT, SIGFPE, SIGSEGV, + SIGTERM and SIGKILL. + - Calls to raise() or abort() to programmatically raise a signal are not + detected by libuv; these will not trigger a signal watcher. + +Unix Notes: + + - SIGKILL and SIGSTOP are impossible to catch. + - Handling SIGBUS, SIGFPE, SIGILL or SIGSEGV via libuv results into + undefined behavior. + - SIGABRT will not be caught by libuv if generated by abort(), e.g. through + assert(). + - On Linux SIGRT0 and SIGRT1 (signals 32 and 33) are used by the NPTL + pthreads library to manage threads. Installing watchers for those signals + will lead to unpredictable behavior and is strongly discouraged. Future + versions of libuv may simply reject them. + + > + -- Create a new signal handler + local signal = uv.new_signal() + -- Define a handler function + uv.signal_start(signal, "sigint", function(signal) + print("got " .. signal .. ", shutting down") + os.exit(1) + end) +< + +uv.new_signal() *uv.new_signal()* + + Creates and initializes a new |uv_signal_t|. Returns the Lua + userdata wrapping it. + + Returns: `uv_signal_t userdata` or `fail` + +uv.signal_start({signal}, {signum}, {callback}) *uv.signal_start()* + + > method form `signal:start(signum, callback)` + + Parameters: + - `signal`: `uv_signal_t userdata` + - `signum`: `integer` or `string` + - `callback`: `callable` + - `signum`: `string` + + Start the handle with the given callback, watching for the + given signal. + + Returns: `0` or `fail` + *uv.signal_start_oneshot()* +uv.signal_start_oneshot({signal}, {signum}, {callback}) + + > method form `signal:start_oneshot(signum, callback)` + + Parameters: + - `signal`: `uv_signal_t userdata` + - `signum`: `integer` or `string` + - `callback`: `callable` + - `signum`: `string` + + Same functionality as |uv.signal_start()| but the signal + handler is reset the moment the signal is received. + + Returns: `0` or `fail` + +uv.signal_stop({signal}) *uv.signal_stop()* + + > method form `signal:stop()` + + Parameters: + - `signal`: `uv_signal_t userdata` + + Stop the handle, the callback will no longer be called. + + Returns: `0` or `fail` + +============================================================================== +`uv_process_t` — Process handle *luv-process-handle* *uv_process_t* + +> |uv_handle_t| functions also apply. + +Process handles will spawn a new process and allow the user to control it and +establish communication channels with it using streams. + +uv.disable_stdio_inheritance() *uv.disable_stdio_inheritance()* + + Disables inheritance for file descriptors / handles that this + process inherited from its parent. The effect is that child + processes spawned by this process don't accidentally inherit + these handles. + + It is recommended to call this function as early in your + program as possible, before the inherited file descriptors can + be closed or duplicated. + + Returns: Nothing. + + Note: This function works on a best-effort basis: there is no + guarantee that libuv can discover all file descriptors that + were inherited. In general it does a better job on Windows + than it does on Unix. + +uv.spawn({path}, {options}, {on_exit}) *uv.spawn()* + + Parameters: + - `path`: `string` + - `options`: `table` (see below) + - `on_exit`: `callable` + - `code`: `integer` + - `signal`: `integer` + + Initializes the process handle and starts the process. If the + process is successfully spawned, this function will return the + handle and pid of the child process. + + Possible reasons for failing to spawn would include (but not + be limited to) the file to execute not existing, not having + permissions to use the setuid or setgid specified, or not + having enough memory to allocate for the new process. + + > + local stdin = uv.new_pipe() + local stdout = uv.new_pipe() + local stderr = uv.new_pipe() + + print("stdin", stdin) + print("stdout", stdout) + print("stderr", stderr) + + local handle, pid = uv.spawn("cat", { + stdio = {stdin, stdout, stderr} + }, function(code, signal) -- on exit + print("exit code", code) + print("exit signal", signal) + end) + + print("process opened", handle, pid) + + uv.read_start(stdout, function(err, data) + assert(not err, err) + if data then + print("stdout chunk", stdout, data) + else + print("stdout end", stdout) + end + end) + + uv.read_start(stderr, function(err, data) + assert(not err, err) + if data then + print("stderr chunk", stderr, data) + else + print("stderr end", stderr) + end + end) + + uv.write(stdin, "Hello World") + + uv.shutdown(stdin, function() + print("stdin shutdown", stdin) + uv.close(handle, function() + print("process closed", handle, pid) + end) + end) +< + *uv.spawn-options* + The `options` table accepts the following fields: + + - `options.args` - Command line arguments as a list of + string. The first string should be the path to the + program. On Windows, this uses CreateProcess which + concatenates the arguments into a string. This can cause + some strange errors. (See `options.verbatim` below for + Windows.) + - `options.stdio` - Set the file descriptors that will be + made available to the child process. The convention is + that the first entries are stdin, stdout, and stderr. + (Note: On Windows, file descriptors after the third are + available to the child process only if the child processes + uses the MSVCRT runtime.) + - `options.env` - Set environment variables for the new + process. + - `options.cwd` - Set the current working directory for the + sub-process. + - `options.uid` - Set the child process' user id. + - `options.gid` - Set the child process' group id. + - `options.verbatim` - If true, do not wrap any arguments in + quotes, or perform any other escaping, when converting the + argument list into a command line string. This option is + only meaningful on Windows systems. On Unix it is silently + ignored. + - `options.detached` - If true, spawn the child process in a + detached state - this will make it a process group leader, + and will effectively enable the child to keep running + after the parent exits. Note that the child process will + still keep the parent's event loop alive unless the parent + process calls |uv.unref()| on the child's process handle. + - `options.hide` - If true, hide the subprocess console + window that would normally be created. This option is only + meaningful on Windows systems. On Unix it is silently + ignored. + + The `options.stdio` entries can take many shapes. + + - If they are numbers, then the child process inherits that + same zero-indexed fd from the parent process. + - If |uv_stream_t| handles are passed in, those are used as + a read-write pipe or inherited stream depending if the + stream has a valid fd. + - Including `nil` placeholders means to ignore that fd in + the child process. + + When the child process exits, `on_exit` is called with an exit + code and signal. + + Returns: `uv_process_t userdata`, `integer` + +uv.process_kill({process}, {signum}) *uv.process_kill()* + + > method form `process:kill(signum)` + + Parameters: + - `process`: `uv_process_t userdata` + - `signum`: `integer` or `string` + + Sends the specified signal to the given process handle. Check + the documentation on |uv_signal_t| for signal support, + specially on Windows. + + Returns: `0` or `fail` + +uv.kill({pid}, {signum}) *uv.kill()* + + Parameters: + - `pid`: `integer` + - `signum`: `integer` or `string` + + Sends the specified signal to the given PID. Check the + documentation on |uv_signal_t| for signal support, specially + on Windows. + + Returns: `0` or `fail` + +uv.process_get_pid({process}) *uv.process_get_pid()* + + > method form `process:get_pid()` + + Parameters: + - `process`: `uv_process_t userdata` + + Returns the handle's pid. + + Returns: `integer` + +============================================================================== +`uv_stream_t` — Stream handle *luv-stream-handle* *uv_stream_t* + +> |uv_handle_t| functions also apply. + +Stream handles provide an abstraction of a duplex communication channel. +`uv_stream_t` is an abstract type, libuv provides 3 stream implementations +in the form of |uv_tcp_t|, |uv_pipe_t| and |uv_tty_t|. + +uv.shutdown({stream} [, {callback}]) *uv.shutdown()* + + > method form `stream:shutdown([callback])` + + Parameters: + - `stream`: `userdata` for sub-type of |uv_stream_t| + - `callback`: `callable` or `nil` + - `err`: `nil` or `string` + + Shutdown the outgoing (write) side of a duplex stream. It + waits for pending write requests to complete. The callback is + called after shutdown is complete. + + Returns: `uv_shutdown_t userdata` or `fail` + +uv.listen({stream}, {backlog}, {callback}) *uv.listen()* + + > method form `stream:listen(backlog, callback)` + + Parameters: + - `stream`: `userdata` for sub-type of |uv_stream_t| + - `backlog`: `integer` + - `callback`: `callable` + - `err`: `nil` or `string` + + Start listening for incoming connections. `backlog` indicates + the number of connections the kernel might queue, same as + `listen(2)`. When a new incoming connection is received the + callback is called. + + Returns: `0` or `fail` + +uv.accept({stream}, {client_stream}) *uv.accept()* + + > method form `stream:accept(client_stream)` + + Parameters: + - `stream`: `userdata` for sub-type of |uv_stream_t| + - `client_stream`: `userdata` for sub-type of |uv_stream_t| + + This call is used in conjunction with |uv.listen()| to accept + incoming connections. Call this function after receiving a + callback to accept the connection. + + When the connection callback is called it is guaranteed that + this function will complete successfully the first time. If + you attempt to use it more than once, it may fail. It is + suggested to only call this function once per connection call. + + Returns: `0` or `fail` + + > + server:listen(128, function (err) + local client = uv.new_tcp() + server:accept(client) + end) +< + +uv.read_start({stream}, {callback}) *uv.read_start()* + + > method form `stream:read_start(callback)` + + Parameters: + - `stream`: `userdata` for sub-type of |uv_stream_t| + - `callback`: `callable` + - `err`: `nil` or `string` + - `data`: `string` or `nil` + + Read data from an incoming stream. The callback will be made + several times until there is no more data to read or + |uv.read_stop()| is called. When we've reached EOF, `data` + will be `nil`. + + Returns: `0` or `fail` + + > + stream:read_start(function (err, chunk) + if err then + -- handle read error + elseif chunk then + -- handle data + else + -- handle disconnect + end + end) +< + +uv.read_stop({stream}) *uv.read_stop()* + + > method form `stream:read_stop()` + + Parameters: + - `stream`: `userdata` for sub-type of |uv_stream_t| + + Stop reading data from the stream. The read callback will no + longer be called. + + This function is idempotent and may be safely called on a + stopped stream. + + Returns: `0` or `fail` + +uv.write({stream}, {data} [, {callback}]) *uv.write()* + + > method form `stream:write(data, [callback])` + + Parameters: + - `stream`: `userdata` for sub-type of |uv_stream_t| + - `data`: `buffer` + - `callback`: `callable` or `nil` + - `err`: `nil` or `string` + + Write data to stream. + + `data` can either be a Lua string or a table of strings. If a + table is passed in, the C backend will use writev to send all + strings in a single system call. + + The optional `callback` is for knowing when the write is + complete. + + Returns: `uv_write_t userdata` or `fail` + +uv.write2({stream}, {data}, {send_handle} [, {callback}]) *uv.write2()* + + > method form `stream:write2(data, send_handle, [callback])` + + Parameters: + - `stream`: `userdata` for sub-type of |uv_stream_t| + - `data`: `buffer` + - `send_handle`: `userdata` for sub-type of |uv_stream_t| + - `callback`: `callable` or `nil` + - `err`: `nil` or `string` + + Extended write function for sending handles over a pipe. The + pipe must be initialized with `ipc` option `true`. + + Returns: `uv_write_t userdata` or `fail` + + Note: `send_handle` must be a TCP socket or pipe, which is a + server or a connection (listening or connected state). Bound + sockets or pipes will be assumed to be servers. + +uv.try_write({stream}, {data}) *uv.try_write()* + + > method form `stream:try_write(data)` + + Parameters: + - `stream`: `userdata` for sub-type of |uv_stream_t| + - `data`: `buffer` + + Same as |uv.write()|, but won't queue a write request if it + can't be completed immediately. + + Will return number of bytes written (can be less than the + supplied buffer size). + + Returns: `integer` or `fail` + +uv.try_write2({stream}, {data}, {send_handle}) *uv.try_write2()* + + > method form `stream:try_write2(data, send_handle)` + + Parameters: + - `stream`: `userdata` for sub-type of |uv_stream_t| + - `data`: `buffer` + - `send_handle`: `userdata` for sub-type of |uv_stream_t| + + Like |uv.write2()|, but with the properties of + |uv.try_write()|. Not supported on Windows, where it returns + `UV_EAGAIN`. + + Will return number of bytes written (can be less than the + supplied buffer size). + + Returns: `integer` or `fail` + +uv.is_readable({stream}) *uv.is_readable()* + + > method form `stream:is_readable()` + + Parameters: + - `stream`: `userdata` for sub-type of |uv_stream_t| + + Returns `true` if the stream is readable, `false` otherwise. + + Returns: `boolean` + +uv.is_writable({stream}) *uv.is_writable()* + + > method form `stream:is_writable()` + + Parameters: + - `stream`: `userdata` for sub-type of |uv_stream_t| + + Returns `true` if the stream is writable, `false` otherwise. + + Returns: `boolean` + +uv.stream_set_blocking({stream}, {blocking}) *uv.stream_set_blocking()* + + > method form `stream:set_blocking(blocking)` + + Parameters: + - `stream`: `userdata` for sub-type of |uv_stream_t| + - `blocking`: `boolean` + + Enable or disable blocking mode for a stream. + + When blocking mode is enabled all writes complete + synchronously. The interface remains unchanged otherwise, e.g. + completion or failure of the operation will still be reported + through a callback which is made asynchronously. + + Returns: `0` or `fail` + + WARNING: Relying too much on this API is not recommended. It + is likely to change significantly in the future. Currently + this only works on Windows and only for |uv_pipe_t| handles. + Also libuv currently makes no ordering guarantee when the + blocking mode is changed after write requests have already + been submitted. Therefore it is recommended to set the + blocking mode immediately after opening or creating the + stream. + +uv.stream_get_write_queue_size() *uv.stream_get_write_queue_size()* + + > method form `stream:get_write_queue_size()` + + Returns the stream's write queue size. + + Returns: `integer` + +============================================================================== +`uv_tcp_t` — TCP handle *luv-tcp-handle* *uv_tcp_t* + +> |uv_handle_t| and |uv_stream_t| functions also apply. + +TCP handles are used to represent both TCP streams and servers. + +uv.new_tcp([{flags}]) *uv.new_tcp()* + + Parameters: + - `flags`: `string` or `nil` + + Creates and initializes a new |uv_tcp_t|. Returns the Lua + userdata wrapping it. Flags may be a family string: `"unix"`, + `"inet"`, `"inet6"`, `"ipx"`, `"netlink"`, `"x25"`, `"ax25"`, + `"atmpvc"`, `"appletalk"`, or `"packet"`. + + Returns: `uv_tcp_t userdata` or `fail` + +uv.tcp_open({tcp}, {sock}) *uv.tcp_open()* + + > method form `tcp:open(sock)` + + Parameters: + - `tcp`: `uv_tcp_t userdata` + - `sock`: `integer` + + Open an existing file descriptor or SOCKET as a TCP handle. + + Returns: `0` or `fail` + + Note: The passed file descriptor or SOCKET is not checked for + its type, but it's required that it represents a valid stream + socket. + +uv.tcp_nodelay({tcp}, {enable}) *uv.tcp_nodelay()* + + > method form `tcp:nodelay(enable)` + + Parameters: + - `tcp`: `uv_tcp_t userdata` + - `enable`: `boolean` + + Enable / disable Nagle's algorithm. + + Returns: `0` or `fail` + +uv.tcp_keepalive({tcp}, {enable} [, {delay}]) *uv.tcp_keepalive()* + + > method form `tcp:keepalive(enable, [delay])` + + Parameters: + - `tcp`: `uv_tcp_t userdata` + - `enable`: `boolean` + - `delay`: `integer` or `nil` + + Enable / disable TCP keep-alive. `delay` is the initial delay + in seconds, ignored when enable is `false`. + + Returns: `0` or `fail` + +uv.tcp_simultaneous_accepts({tcp}, {enable}) *uv.tcp_simultaneous_accepts()* + + > method form `tcp:simultaneous_accepts(enable)` + + Parameters: + - `tcp`: `uv_tcp_t userdata` + - `enable`: `boolean` + + Enable / disable simultaneous asynchronous accept requests + that are queued by the operating system when listening for new + TCP connections. + + This setting is used to tune a TCP server for the desired + performance. Having simultaneous accepts can significantly + improve the rate of accepting connections (which is why it is + enabled by default) but may lead to uneven load distribution + in multi-process setups. + + Returns: `0` or `fail` + +uv.tcp_bind({tcp}, {host}, {port} [, {flags}]) *uv.tcp_bind()* + + > method form `tcp:bind(host, port, [flags])` + + Parameters: + - `tcp`: `uv_tcp_t userdata` + - `host`: `string` + - `port`: `integer` + - `flags`: `table` or `nil` + - `ipv6only`: `boolean` + + Bind the handle to an host and port. `host` should be an IP + address and not a domain name. Any `flags` are set with a + table with field `ipv6only` equal to `true` or `false`. + + When the port is already taken, you can expect to see an + `EADDRINUSE` error from either `uv.tcp_bind()`, |uv.listen()| + or |uv.tcp_connect()|. That is, a successful call to this + function does not guarantee that the call to |uv.listen()| or + |uv.tcp_connect()| will succeed as well. + + Use a port of `0` to let the OS assign an ephemeral port. You + can look it up later using |uv.tcp_getsockname()|. + + Returns: `0` or `fail` + +uv.tcp_getpeername({tcp}) *uv.tcp_getpeername()* + + > method form `tcp:getpeername()` + + Parameters: + - `tcp`: `uv_tcp_t userdata` + + Get the address of the peer connected to the handle. + + Returns: `table` or `fail` + - `ip` : `string` + - `family` : `string` + - `port` : `integer` + +uv.tcp_getsockname({tcp}) *uv.tcp_getsockname()* + + > method form `tcp:getsockname()` + + Parameters: + - `tcp`: `uv_tcp_t userdata` + + Get the current address to which the handle is bound. + + Returns: `table` or `fail` + - `ip` : `string` + - `family` : `string` + - `port` : `integer` + +uv.tcp_connect({tcp}, {host}, {port}, {callback}) *uv.tcp_connect()* + + > method form `tcp:connect(host, port, callback)` + + Parameters: + - `tcp`: `uv_tcp_t userdata` + - `host`: `string` + - `port`: `integer` + - `callback`: `callable` + - `err`: `nil` or `string` + + Establish an IPv4 or IPv6 TCP connection. + + Returns: `uv_connect_t userdata` or `fail` + + > + local client = uv.new_tcp() + client:connect("127.0.0.1", 8080, function (err) + -- check error and carry on. + end) +< + +uv.tcp_write_queue_size({tcp}) *uv.tcp_write_queue_size()* + + > method form `tcp:write_queue_size()` + + DEPRECATED: Please use |uv.stream_get_write_queue_size()| + instead. + +uv.tcp_close_reset([{callback}]) *uv.tcp_close_reset()* + + > method form `tcp:close_reset([callback])` + + Parameters: + - `tcp`: `uv_tcp_t userdata` + - `callback`: `callable` or `nil` + + Resets a TCP connection by sending a RST packet. This is + accomplished by setting the SO_LINGER socket option with a + linger interval of zero and then calling |uv.close()|. Due to + some platform inconsistencies, mixing of |uv.shutdown()| and + `uv.tcp_close_reset()` calls is not allowed. + + Returns: `0` or `fail` + *uv.socketpair()* +uv.socketpair([{socktype}, [{protocol}, [{flags1}, [{flags2}]]]]) + + Parameters: + - `socktype`: `string`, `integer` or `nil` (default: `stream`) + - `protocol`: `string`, `integer` or `nil` (default: 0) + - `flags1`: `table` or `nil` + - `nonblock`: `boolean` (default: `false`) + - `flags2`: `table` or `nil` + - `nonblock`: `boolean` (default: `false`) + + Create a pair of connected sockets with the specified + properties. The resulting handles can be passed to + |uv.tcp_open()|, used with |uv.spawn()|, or for any other + purpose. + + When specified as a string, `socktype` must be one of + `"stream"`, `"dgram"`, `"raw"`, `"rdm"`, or `"seqpacket"`. + + When `protocol` is set to 0 or nil, it will be automatically + chosen based on the socket's domain and type. When `protocol` + is specified as a string, it will be looked up using the + `getprotobyname(3)` function (examples: `"ip"`, `"icmp"`, + `"tcp"`, `"udp"`, etc). + + Flags: + - `nonblock`: Opens the specified socket handle for + `OVERLAPPED` or `FIONBIO`/`O_NONBLOCK` I/O usage. This is + recommended for handles that will be used by libuv, and not + usually recommended otherwise. + + Equivalent to `socketpair(2)` with a domain of `AF_UNIX`. + + Returns: `table` or `fail` + - `[1, 2]` : `integer` (file descriptor) + + > + -- Simple read/write with tcp + local fds = uv.socketpair(nil, nil, {nonblock=true}, {nonblock=true}) + + local sock1 = uv.new_tcp() + sock1:open(fds[1]) + + local sock2 = uv.new_tcp() + sock2:open(fds[2]) + + sock1:write("hello") + sock2:read_start(function(err, chunk) + assert(not err, err) + print(chunk) + end) +< + +============================================================================== +`uv_pipe_t` — Pipe handle *luv-pipe-handle* *uv_pipe_t* + +> |uv_handle_t| and |uv_stream_t| functions also apply. + +Pipe handles provide an abstraction over local domain sockets on Unix and +named pipes on Windows. + + > + local pipe = uv.new_pipe(false) + + pipe:bind('/tmp/sock.test') + + pipe:listen(128, function() + local client = uv.new_pipe(false) + pipe:accept(client) + client:write("hello!\n") + client:close() + end) +< + +uv.new_pipe([{ipc}]) *uv.new_pipe()* + + Parameters: + - `ipc`: `boolean` or `nil` (default: `false`) + + Creates and initializes a new |uv_pipe_t|. Returns the Lua + userdata wrapping it. The `ipc` argument is a boolean to + indicate if this pipe will be used for handle passing between + processes. + + Returns: `uv_pipe_t userdata` or `fail` + +uv.pipe_open({pipe}, {fd}) *uv.pipe_open()* + + > method form `pipe:open(fd)` + + Parameters: + - `pipe`: `uv_pipe_t userdata` + - `fd`: `integer` + + Open an existing file descriptor or |uv_handle_t| as a + pipe. + + Returns: `0` or `fail` + + Note: The file descriptor is set to non-blocking mode. + +uv.pipe_bind({pipe}, {name}) *uv.pipe_bind()* + + > method form `pipe:bind(name)` + + Parameters: + - `pipe`: `uv_pipe_t userdata` + - `name`: `string` + + Bind the pipe to a file path (Unix) or a name (Windows). + + Returns: `0` or `fail` + + Note: Paths on Unix get truncated to + sizeof(sockaddr_un.sun_path) bytes, typically between 92 and + 108 bytes. + +uv.pipe_connect({pipe}, {name} [, {callback}]) *uv.pipe_connect()* + + > method form `pipe:connect(name, [callback])` + + Parameters: + - `pipe`: `uv_pipe_t userdata` + - `name`: `string` + - `callback`: `callable` or `nil` + - `err`: `nil` or `string` + + Connect to the Unix domain socket or the named pipe. + + Returns: `uv_connect_t userdata` or `fail` + + Note: Paths on Unix get truncated to + sizeof(sockaddr_un.sun_path) bytes, typically between 92 and + 108 bytes. + +uv.pipe_getsockname({pipe}) *uv.pipe_getsockname()* + + > method form `pipe:getsockname()` + + Parameters: + - `pipe`: `uv_pipe_t userdata` + + Get the name of the Unix domain socket or the named pipe. + + Returns: `string` or `fail` + +uv.pipe_getpeername({pipe}) *uv.pipe_getpeername()* + + > method form `pipe:getpeername()` + + Parameters: + - `pipe`: `uv_pipe_t userdata` + + Get the name of the Unix domain socket or the named pipe to + which the handle is connected. + + Returns: `string` or `fail` + +uv.pipe_pending_instances({pipe}, {count}) *uv.pipe_pending_instances()* + + > method form `pipe:pending_instances(count)` + + Parameters: + - `pipe`: `uv_pipe_t userdata` + - `count`: `integer` + + Set the number of pending pipe instance handles when the pipe + server is waiting for connections. + + Returns: Nothing. + + Note: This setting applies to Windows only. + +uv.pipe_pending_count({pipe}) *uv.pipe_pending_count()* + + > method form `pipe:pending_count()` + + Parameters: + - `pipe`: `uv_pipe_t userdata` + + Returns the pending pipe count for the named pipe. + + Returns: `integer` + +uv.pipe_pending_type({pipe}) *uv.pipe_pending_type()* + + > method form `pipe:pending_type()` + + Parameters: + - `pipe`: `uv_pipe_t userdata` + + Used to receive handles over IPC pipes. + + First - call |uv.pipe_pending_count()|, if it's > 0 then + initialize a handle of the given type, returned by + `uv.pipe_pending_type()` and call `uv.accept(pipe, handle)` . + + Returns: `string` + +uv.pipe_chmod({pipe}, {flags}) *uv.pipe_chmod()* + + > method form `pipe:chmod(flags)` + + Parameters: + - `pipe`: `uv_pipe_t userdata` + - `flags`: `string` + + Alters pipe permissions, allowing it to be accessed from + processes run by different users. Makes the pipe writable or + readable by all users. `flags` are: `"r"`, `"w"`, `"rw"`, or + `"wr"` where `r` is `READABLE` and `w` is `WRITABLE`. This + function is blocking. + + Returns: `0` or `fail` + +uv.pipe({read_flags}, {write_flags}) *uv.pipe()* + + Parameters: + - `read_flags`: `table` or `nil` + - `nonblock`: `boolean` (default: `false`) + - `write_flags`: `table` or `nil` + - `nonblock`: `boolean` (default: `false`) + + Create a pair of connected pipe handles. Data may be written + to the `write` fd and read from the `read` fd. The resulting + handles can be passed to `pipe_open`, used with `spawn`, or + for any other purpose. + + Flags: + - `nonblock`: Opens the specified socket handle for + `OVERLAPPED` or `FIONBIO`/`O_NONBLOCK` I/O usage. This is + recommended for handles that will be used by libuv, and not + usually recommended otherwise. + + Equivalent to `pipe(2)` with the `O_CLOEXEC` flag set. + + Returns: `table` or `fail` + - `read` : `integer` (file descriptor) + - `write` : `integer` (file descriptor) + + > + -- Simple read/write with pipe_open + local fds = uv.pipe({nonblock=true}, {nonblock=true}) + + local read_pipe = uv.new_pipe() + read_pipe:open(fds.read) + + local write_pipe = uv.new_pipe() + write_pipe:open(fds.write) + + write_pipe:write("hello") + read_pipe:read_start(function(err, chunk) + assert(not err, err) + print(chunk) + end) +< + +============================================================================== +`uv_tty_t` — TTY handle *luv-tty-handle* *uv_tty_t* + +> |uv_handle_t| and |uv_stream_t| functions also apply. + +TTY handles represent a stream for the console. + + > + -- Simple echo program + local stdin = uv.new_tty(0, true) + local stdout = uv.new_tty(1, false) + + stdin:read_start(function (err, data) + assert(not err, err) + if data then + stdout:write(data) + else + stdin:close() + stdout:close() + end + end) +< + +uv.new_tty({fd}, {readable}) *uv.new_tty()* + + Parameters: + - `fd`: `integer` + - `readable`: `boolean` + + Initialize a new TTY stream with the given file descriptor. + Usually the file descriptor will be: + + - 0 - stdin + - 1 - stdout + - 2 - stderr + + On Unix this function will determine the path of the fd of the + terminal using ttyname_r(3), open it, and use it if the passed + file descriptor refers to a TTY. This lets libuv put the tty + in non-blocking mode without affecting other processes that + share the tty. + + This function is not thread safe on systems that don’t support + ioctl TIOCGPTN or TIOCPTYGNAME, for instance OpenBSD and + Solaris. + + Returns: `uv_tty_t userdata` or `fail` + + Note: If reopening the TTY fails, libuv falls back to blocking + writes. + +uv.tty_set_mode({tty}, {mode}) *uv.tty_set_mode()* + + > method form `tty:set_mode(mode)` + + Parameters: + - `tty`: `uv_tty_t userdata` + - `mode`: `integer` + + Set the TTY using the specified terminal mode. + + Parameter `mode` is a C enum with the following values: + + - 0 - UV_TTY_MODE_NORMAL: Initial/normal terminal mode + - 1 - UV_TTY_MODE_RAW: Raw input mode (On Windows, + ENABLE_WINDOW_INPUT is also enabled) + - 2 - UV_TTY_MODE_IO: Binary-safe I/O mode for IPC + (Unix-only) + + Returns: `0` or `fail` + +uv.tty_reset_mode() *uv.tty_reset_mode()* + + To be called when the program exits. Resets TTY settings to + default values for the next process to take over. + + This function is async signal-safe on Unix platforms but can + fail with error code `EBUSY` if you call it when execution is + inside |uv.tty_set_mode()|. + + Returns: `0` or `fail` + +uv.tty_get_winsize({tty}) *uv.tty_get_winsize()* + + > method form `tty:get_winsize()` + + Parameters: + - `tty`: `uv_tty_t userdata` + + Gets the current Window width and height. + + Returns: `integer, integer` or `fail` + +uv.tty_set_vterm_state({state}) *uv.tty_set_vterm_state()* + + Parameters: + - `state`: `string` + + Controls whether console virtual terminal sequences are + processed by libuv or console. Useful in particular for + enabling ConEmu support of ANSI X3.64 and Xterm 256 colors. + Otherwise Windows10 consoles are usually detected + automatically. State should be one of: `"supported"` or + `"unsupported"`. + + This function is only meaningful on Windows systems. On Unix + it is silently ignored. + + Returns: none + +uv.tty_get_vterm_state() *uv.tty_get_vterm_state()* + + Get the current state of whether console virtual terminal + sequences are handled by libuv or the console. The return + value is `"supported"` or `"unsupported"`. + + This function is not implemented on Unix, where it returns + `ENOTSUP`. + + Returns: `string` or `fail` + +============================================================================== +`uv_udp_t` — UDP handle *luv-udp-handle* *uv_udp_t* + +> |uv_handle_t| functions also apply. + +UDP handles encapsulate UDP communication for both clients and servers. + +uv.new_udp([{flags}]) *uv.new_udp()* + + Parameters: + - `flags`: `table` or `nil` + - `family`: `string` or `nil` + - `mmsgs`: `integer` or `nil` (default: `1`) + + Creates and initializes a new |uv_udp_t|. Returns the Lua + userdata wrapping it. The actual socket is created lazily. + + When specified, `family` must be one of `"unix"`, `"inet"`, + `"inet6"`, `"ipx"`, `"netlink"`, `"x25"`, `"ax25"`, + `"atmpvc"`, `"appletalk"`, or `"packet"`. + + When specified, `mmsgs` determines the number of messages able + to be received at one time via `recvmmsg(2)` (the allocated + buffer will be sized to be able to fit the specified number of + max size dgrams). Only has an effect on platforms that support + `recvmmsg(2)`. + + Note: For backwards compatibility reasons, `flags` can also be + a string or integer. When it is a string, it will be treated + like the `family` key above. When it is an integer, it will be + used directly as the `flags` parameter when calling + `uv_udp_init_ex`. + + Returns: `uv_udp_t userdata` or `fail` + +uv.udp_get_send_queue_size() *uv.udp_get_send_queue_size()* + + > method form `udp:get_send_queue_size()` + + Returns the handle's send queue size. + + Returns: `integer` + +uv.udp_get_send_queue_count() *uv.udp_get_send_queue_count()* + + > method form `udp:get_send_queue_count()` + + Returns the handle's send queue count. + + Returns: `integer` + +uv.udp_open({udp}, {fd}) *uv.udp_open()* + + > method form `udp:open(fd)` + + Parameters: + - `udp`: `uv_udp_t userdata` + - `fd`: `integer` + + Opens an existing file descriptor or Windows SOCKET as a UDP + handle. + + Unix only: The only requirement of the sock argument is that + it follows the datagram contract (works in unconnected mode, + supports sendmsg()/recvmsg(), etc). In other words, other + datagram-type sockets like raw sockets or netlink sockets can + also be passed to this function. + + The file descriptor is set to non-blocking mode. + + Note: The passed file descriptor or SOCKET is not checked for + its type, but it's required that it represents a valid + datagram socket. + + Returns: `0` or `fail` + +uv.udp_bind({udp}, {host}, {port} [, {flags}]) *uv.udp_bind()* + + > method form `udp:bind(host, port, [flags])` + + Parameters: + - `udp`: `uv_udp_t userdata` + - `host`: `string` + - `port`: `number` + - `flags`: `table` or `nil` + - `ipv6only`: `boolean` + - `reuseaddr`: `boolean` + + Bind the UDP handle to an IP address and port. Any `flags` are + set with a table with fields `reuseaddr` or `ipv6only` equal + to `true` or `false`. + + Returns: `0` or `fail` + +uv.udp_getsockname({udp}) *uv.udp_getsockname()* + + > method form `udp:getsockname()` + + Parameters: + - `udp`: `uv_udp_t userdata` + + Get the local IP and port of the UDP handle. + + Returns: `table` or `fail` + - `ip` : `string` + - `family` : `string` + - `port` : `integer` + +uv.udp_getpeername({udp}) *uv.udp_getpeername()* + + > method form `udp:getpeername()` + + Parameters: + - `udp`: `uv_udp_t userdata` + + Get the remote IP and port of the UDP handle on connected UDP + handles. + + Returns: `table` or `fail` + - `ip` : `string` + - `family` : `string` + - `port` : `integer` + + *uv.udp_set_membership()* +uv.udp_set_membership({udp}, {multicast_addr}, {interface_addr}, {membership}) + + > method form + > `udp:set_membership(multicast_addr, interface_addr, membership)` + + Parameters: + - `udp`: `uv_udp_t userdata` + - `multicast_addr`: `string` + - `interface_addr`: `string` or `nil` + - `membership`: `string` + + Set membership for a multicast address. `multicast_addr` is + multicast address to set membership for. `interface_addr` is + interface address. `membership` can be the string `"leave"` or + `"join"`. + + Returns: `0` or `fail` + + *uv.udp_set_source_membership()* +uv.udp_set_source_membership({udp}, {multicast_addr}, {interface_addr}, {source_addr}, {membership}) + + > method form + > `udp:set_source_membership(multicast_addr, interface_addr, source_addr, membership)` + + Parameters: + - `udp`: `uv_udp_t userdata` + - `multicast_addr`: `string` + - `interface_addr`: `string` or `nil` + - `source_addr`: `string` + - `membership`: `string` + + Set membership for a source-specific multicast group. + `multicast_addr` is multicast address to set membership for. + `interface_addr` is interface address. `source_addr` is source + address. `membership` can be the string `"leave"` or `"join"`. + + Returns: `0` or `fail` + +uv.udp_set_multicast_loop({udp}, {on}) *uv.udp_set_multicast_loop()* + + > method form `udp:set_multicast_loop(on)` + + Parameters: + - `udp`: `uv_udp_t userdata` + - `on`: `boolean` + + Set IP multicast loop flag. Makes multicast packets loop back + to local sockets. + + Returns: `0` or `fail` + +uv.udp_set_multicast_ttl({udp}, {ttl}) *uv.udp_set_multicast_ttl()* + + > method form `udp:set_multicast_ttl(ttl)` + + Parameters: + - `udp`: `uv_udp_t userdata` + - `ttl`: `integer` + + Set the multicast ttl. + + `ttl` is an integer 1 through 255. + + Returns: `0` or `fail` + + *uv.udp_set_multicast_interface()* +uv.udp_set_multicast_interface({udp}, {interface_addr}) + + > method form `udp:set_multicast_interface(interface_addr)` + + Parameters: + - `udp`: `uv_udp_t userdata` + - `interface_addr`: `string` + + Set the multicast interface to send or receive data on. + + Returns: `0` or `fail` + +uv.udp_set_broadcast({udp}, {on}) *uv.udp_set_broadcast()* + + > method form `udp:set_broadcast(on)` + + Parameters: + - `udp`: `uv_udp_t userdata` + - `on`: `boolean` + + Set broadcast on or off. + + Returns: `0` or `fail` + +uv.udp_set_ttl({udp}, {ttl}) *uv.udp_set_ttl()* + + > method form `udp:set_ttl(ttl)` + + Parameters: + - `udp`: `uv_udp_t userdata` + - `ttl`: `integer` + + Set the time to live. + + `ttl` is an integer 1 through 255. + + Returns: `0` or `fail` + +uv.udp_send({udp}, {data}, {host}, {port}, {callback}) *uv.udp_send()* + + > method form `udp:send(data, host, port, callback)` + + Parameters: + - `udp`: `uv_udp_t userdata` + - `data`: `buffer` + - `host`: `string` + - `port`: `integer` + - `callback`: `callable` + - `err`: `nil` or `string` + + Send data over the UDP socket. If the socket has not + previously been bound with |uv.udp_bind()| it will be bound to + `0.0.0.0` (the "all interfaces" IPv4 address) and a random + port number. + + Returns: `uv_udp_send_t userdata` or `fail` + +uv.udp_try_send({udp}, {data}, {host}, {port}) *uv.udp_try_send()* + + > method form `udp:try_send(data, host, port)` + + Parameters: + - `udp`: `uv_udp_t userdata` + - `data`: `buffer` + - `host`: `string` + - `port`: `integer` + + Same as |uv.udp_send()|, but won't queue a send request if it + can't be completed immediately. + + Returns: `integer` or `fail` + +uv.udp_recv_start({udp}, {callback}) *uv.udp_recv_start()* + + > method form `udp:recv_start(callback)` + + Parameters: + - `udp`: `uv_udp_t userdata` + - `callback`: `callable` + - `err`: `nil` or `string` + - `data`: `string` or `nil` + - `addr`: `table` or `nil` + - `ip`: `string` + - `port`: `integer` + - `family`: `string` + - `flags`: `table` + - `partial`: `boolean` or `nil` + - `mmsg_chunk`: `boolean` or `nil` + + Prepare for receiving data. If the socket has not previously + been bound with |uv.udp_bind()| it is bound to `0.0.0.0` (the + "all interfaces" IPv4 address) and a random port number. + + Returns: `0` or `fail` + +uv.udp_recv_stop({udp}) *uv.udp_recv_stop()* + + > method form `udp:recv_stop()` + + Parameters: + - `udp`: `uv_udp_t userdata` + + Stop listening for incoming datagrams. + + Returns: `0` or `fail` + +uv.udp_connect({udp}, {host}, {port}) *uv.udp_connect()* + + > method form `udp:connect(host, port)` + + Parameters: + - `udp`: `uv_udp_t userdata` + - `host`: `string` + - `port`: `integer` + + Associate the UDP handle to a remote address and port, so + every message sent by this handle is automatically sent to + that destination. Calling this function with a NULL addr + disconnects the handle. Trying to call `uv.udp_connect()` on + an already connected handle will result in an `EISCONN` error. + Trying to disconnect a handle that is not connected will + return an `ENOTCONN` error. + + Returns: `0` or `fail` + +============================================================================== +`uv_fs_event_t` — FS Event handle *luv-fs-event-handle* *uv_fs_event_t* + +> |uv_handle_t| functions also apply. + +FS Event handles allow the user to monitor a given path for changes, for +example, if the file was renamed or there was a generic change in it. This +handle uses the best backend for the job on each platform. + +uv.new_fs_event() *uv.new_fs_event()* + + Creates and initializes a new |uv_fs_event_t|. Returns the Lua + userdata wrapping it. + + Returns: `uv_fs_event_t userdata` or `fail` + +uv.fs_event_start({fs_event}, {path}, {flags}, {callback}) *uv.fs_event_start()* + + > method form `fs_event:start(path, flags, callback)` + + Parameters: + - `fs_event`: `uv_fs_event_t userdata` + - `path`: `string` + - `flags`: `table` + - `watch_entry`: `boolean` or `nil` (default: `false`) + - `stat`: `boolean` or `nil` (default: `false`) + - `recursive`: `boolean` or `nil` (default: `false`) + - `callback`: `callable` + - `err`: `nil` or `string` + - `filename`: `string` + - `events`: `table` + - `change`: `boolean` or `nil` + - `rename`: `boolean` or `nil` + + Start the handle with the given callback, which will watch the + specified path for changes. + + Returns: `0` or `fail` + +uv.fs_event_stop() *uv.fs_event_stop()* + + > method form `fs_event:stop()` + + Stop the handle, the callback will no longer be called. + + Returns: `0` or `fail` + +uv.fs_event_getpath() *uv.fs_event_getpath()* + + > method form `fs_event:getpath()` + + Get the path being monitored by the handle. + + Returns: `string` or `fail` + +============================================================================== +`uv_fs_poll_t` — FS Poll handle *luv-fs-poll-handle* *uv_fs_poll_t* + +> |uv_handle_t| functions also apply. + +FS Poll handles allow the user to monitor a given path for changes. Unlike +|uv_fs_event_t|, fs poll handles use `stat` to detect when a file has changed +so they can work on file systems where fs event handles can't. + +uv.new_fs_poll() *uv.new_fs_poll()* + + Creates and initializes a new |uv_fs_poll_t|. Returns the Lua + userdata wrapping it. + + Returns: `uv_fs_poll_t userdata` or `fail` + +uv.fs_poll_start({fs_poll}, {path}, {interval}, {callback}) *uv.fs_poll_start()* + + > method form `fs_poll:start(path, interval, callback)` + + Parameters: + - `fs_event`: `uv_fs_event_t userdata` + - `path`: `string` + - `interval`: `integer` + - `callback`: `callable` + - `err`: `nil` or `string` + - `prev`: `table` or `nil` (see `uv.fs_stat`) + - `curr`: `table` or `nil` (see `uv.fs_stat`) + + Check the file at `path` for changes every `interval` + milliseconds. + + Note: For maximum portability, use multi-second intervals. + Sub-second intervals will not detect all changes on many file + systems. + + Returns: `0` or `fail` + +uv.fs_poll_stop() *uv.fs_poll_stop()* + + > method form `fs_poll:stop()` + + Stop the handle, the callback will no longer be called. + + Returns: `0` or `fail` + +uv.fs_poll_getpath() *uv.fs_poll_getpath()* + + > method form `fs_poll:getpath()` + + Get the path being monitored by the handle. + + Returns: `string` or `fail` + +============================================================================== +FILE SYSTEM OPERATIONS *luv-file-system-operations* *uv_fs_t* + +Most file system functions can operate synchronously or asynchronously. When a +synchronous version is called (by omitting a callback), the function will +immediately return the results of the FS call. When an asynchronous version is +called (by providing a callback), the function will immediately return a +`uv_fs_t userdata` and asynchronously execute its callback; if an error is +encountered, the first and only argument passed to the callback will be the +`err` error string; if the operation completes successfully, the first +argument will be `nil` and the remaining arguments will be the results of the +FS call. + +Synchronous and asynchronous versions of `readFile` (with naive error +handling) are implemented below as an example: + + > + local function readFileSync(path) + local fd = assert(uv.fs_open(path, "r", 438)) + local stat = assert(uv.fs_fstat(fd)) + local data = assert(uv.fs_read(fd, stat.size, 0)) + assert(uv.fs_close(fd)) + return data + end + + local data = readFileSync("main.lua") + print("synchronous read", data) +< + + > + local function readFile(path, callback) + uv.fs_open(path, "r", 438, function(err, fd) + assert(not err, err) + uv.fs_fstat(fd, function(err, stat) + assert(not err, err) + uv.fs_read(fd, stat.size, 0, function(err, data) + assert(not err, err) + uv.fs_close(fd, function(err) + assert(not err, err) + return callback(data) + end) + end) + end) + end) + end + + readFile("main.lua", function(data) + print("asynchronous read", data) + end) +< + +uv.fs_close({fd} [, {callback}]) *uv.fs_close()* + + Parameters: + - `fd`: `integer` + - `callback`: `callable` (async version) or `nil` (sync + version) + - `err`: `nil` or `string` + - `success`: `boolean` or `nil` + + Equivalent to `close(2)`. + + Returns (sync version): `boolean` or `fail` + + Returns (async version): `uv_fs_t userdata` + +uv.fs_open({path}, {flags}, {mode} [, {callback}]) *uv.fs_open()* + + Parameters: + - `path`: `string` + - `flags`: `string` or `integer` + - `mode`: `integer` + - `callback`: `callable` (async version) or `nil` (sync + version) + - `err`: `nil` or `string` + - `fd`: `integer` or `nil` + + Equivalent to `open(2)`. Access `flags` may be an integer or + one of: `"r"`, `"rs"`, `"sr"`, `"r+"`, `"rs+"`, `"sr+"`, + `"w"`, `"wx"`, `"xw"`, `"w+"`, `"wx+"`, `"xw+"`, `"a"`, + `"ax"`, `"xa"`, `"a+"`, `"ax+"`, or "`xa+`". + + Returns (sync version): `integer` or `fail` + + Returns (async version): `uv_fs_t userdata` + + Note: On Windows, libuv uses `CreateFileW` and thus the file + is always opened in binary mode. Because of this, the + `O_BINARY` and `O_TEXT` flags are not supported. + +uv.fs_read({fd}, {size} [, {offset} [, {callback}]]) *uv.fs_read()* + + Parameters: + - `fd`: `integer` + - `size`: `integer` + - `offset`: `integer` or `nil` + - `callback`: `callable` (async version) or `nil` (sync + version) + - `err`: `nil` or `string` + - `data`: `string` or `nil` + + Equivalent to `preadv(2)`. Returns any data. An empty string + indicates EOF. + + If `offset` is nil or omitted, it will default to `-1`, which + indicates 'use and update the current file offset.' + + Note: When `offset` is >= 0, the current file offset will not + be updated by the read. + + Returns (sync version): `string` or `fail` + + Returns (async version): `uv_fs_t userdata` + +uv.fs_unlink({path} [, {callback}]) *uv.fs_unlink()* + + Parameters: + - `path`: `string` + - `callback`: `callable` (async version) or `nil` (sync + version) + - `err`: `nil` or `string` + - `success`: `boolean` or `nil` + + Equivalent to `unlink(2)`. + + Returns (sync version): `boolean` or `fail` + + Returns (async version): `uv_fs_t userdata` + +uv.fs_write({fd}, {data} [, {offset} [, {callback}]]) *uv.fs_write()* + + Parameters: + - `fd`: `integer` + - `data`: `buffer` + - `offset`: `integer` or `nil` + - `callback`: `callable` (async version) or `nil` (sync + version) + - `err`: `nil` or `string` + - `bytes`: `integer` or `nil` + + Equivalent to `pwritev(2)`. Returns the number of bytes + written. + + If `offset` is nil or omitted, it will default to `-1`, which + indicates 'use and update the current file offset.' + + Note: When `offset` is >= 0, the current file offset will not + be updated by the write. + + Returns (sync version): `integer` or `fail` + + Returns (async version): `uv_fs_t userdata` + +uv.fs_mkdir({path}, {mode} [, {callback}]) *uv.fs_mkdir()* + + Parameters: + - `path`: `string` + - `mode`: `integer` + - `callback`: `callable` (async version) or `nil` (sync + version) + - `err`: `nil` or `string` + - `success`: `boolean` or `nil` + + Equivalent to `mkdir(2)`. + + Returns (sync version): `boolean` or `fail` + + Returns (async version): `uv_fs_t userdata` + +uv.fs_mkdtemp({template} [, {callback}]) *uv.fs_mkdtemp()* + + Parameters: + - `template`: `string` + - `callback`: `callable` (async version) or `nil` (sync + version) + - `err`: `nil` or `string` + - `path`: `string` or `nil` + + Equivalent to `mkdtemp(3)`. + + Returns (sync version): `string` or `fail` + + Returns (async version): `uv_fs_t userdata` + +uv.fs_mkstemp({template} [, {callback}]) *uv.fs_mkstemp()* + + Parameters: + - `template`: `string` + - `callback`: `callable` (async version) or `nil` (sync + version) + - `err`: `nil` or `string` + - `fd`: `integer` or `nil` + - `path`: `string` or `nil` + + Equivalent to `mkstemp(3)`. Returns a temporary file handle + and filename. + + Returns (sync version): `integer, string` or `fail` + + Returns (async version): `uv_fs_t userdata` + +uv.fs_rmdir({path} [, {callback}]) *uv.fs_rmdir()* + + Parameters: + - `path`: `string` + - `callback`: `callable` (async version) or `nil` (sync + version) + - `err`: `nil` or `string` + - `success`: `boolean` or `nil` + + Equivalent to `rmdir(2)`. + + Returns (sync version): `boolean` or `fail` + + Returns (async version): `uv_fs_t userdata` + +uv.fs_scandir({path} [, {callback}]) *uv.fs_scandir()* + + Parameters: + - `path`: `string` + - `callback`: `callable` + - `err`: `nil` or `string` + - `success`: `uv_fs_t userdata` or `nil` + + Equivalent to `scandir(3)`, with a slightly different API. + Returns a handle that the user can pass to + |uv.fs_scandir_next()|. + + Note: This function can be used synchronously or + asynchronously. The request userdata is always synchronously + returned regardless of whether a callback is provided and the + same userdata is passed to the callback if it is provided. + + Returns: `uv_fs_t userdata` or `fail` + +uv.fs_scandir_next({fs}) *uv.fs_scandir_next()* + + Parameters: + - `fs`: `uv_fs_t userdata` + + Called on a |uv_fs_t| returned by |uv.fs_scandir()| to get the + next directory entry data as a `name, type` pair. When there + are no more entries, `nil` is returned. + + Note: This function only has a synchronous version. See + |uv.fs_opendir()| and its related functions for an + asynchronous version. + + Returns: `string, string` or `nil` or `fail` + +uv.fs_stat({path} [, {callback}]) *uv.fs_stat()* + + Parameters: + - `path`: `string` + - `callback`: `callable` (async version) or `nil` (sync + version) + - `err`: `nil` or `string` + - `stat`: `table` or `nil` (see below) + + Equivalent to `stat(2)`. + + Returns (sync version): `table` or `fail` + - `dev` : `integer` + - `mode` : `integer` + - `nlink` : `integer` + - `uid` : `integer` + - `gid` : `integer` + - `rdev` : `integer` + - `ino` : `integer` + - `size` : `integer` + - `blksize` : `integer` + - `blocks` : `integer` + - `flags` : `integer` + - `gen` : `integer` + - `atime` : `table` + - `sec` : `integer` + - `nsec` : `integer` + - `mtime` : `table` + - `sec` : `integer` + - `nsec` : `integer` + - `ctime` : `table` + - `sec` : `integer` + - `nsec` : `integer` + - `birthtime` : `table` + - `sec` : `integer` + - `nsec` : `integer` + - `type` : `string` + + Returns (async version): `uv_fs_t userdata` + +uv.fs_fstat({fd} [, {callback}]) *uv.fs_fstat()* + + Parameters: + - `fd`: `integer` + - `callback`: `callable` (async version) or `nil` (sync + version) + - `err`: `nil` or `string` + - `stat`: `table` or `nil` (see `uv.fs_stat`) + + Equivalent to `fstat(2)`. + + Returns (sync version): `table` or `fail` (see `uv.fs_stat`) + + Returns (async version): `uv_fs_t userdata` + +uv.fs_lstat({path} [, {callback}]) *uv.fs_lstat()* + + Parameters: + - `fd`: `integer` + - `callback`: `callable` (async version) or `nil` (sync + version) + - `err`: `nil` or `string` + - `stat`: `table` or `nil` (see `uv.fs_stat`) + + Equivalent to `lstat(2)`. + + Returns (sync version): `table` or `fail` (see |uv.fs_stat()|) + + Returns (async version): `uv_fs_t userdata` + +uv.fs_rename({path}, {new_path} [, {callback}]) *uv.fs_rename()* + + Parameters: + - `path`: `string` + - `new_path`: `string` + - `callback`: `callable` (async version) or `nil` (sync + version) + - `err`: `nil` or `string` + - `success`: `boolean` or `nil` + + Equivalent to `rename(2)`. + + Returns (sync version): `boolean` or `fail` + + Returns (async version): `uv_fs_t userdata` + +uv.fs_fsync({fd} [, {callback}]) *uv.fs_fsync()* + + Parameters: + - `fd`: `integer` + - `callback`: `callable` (async version) or `nil` (sync + version) + - `err`: `nil` or `string` + - `success`: `boolean` or `nil` + + Equivalent to `fsync(2)`. + + Returns (sync version): `boolean` or `fail` + + Returns (async version): `uv_fs_t userdata` + +uv.fs_fdatasync({fd} [, {callback}]) *uv.fs_fdatasync()* + + Parameters: + - `fd`: `integer` + - `callback`: `callable` (async version) or `nil` (sync + version) + - `err`: `nil` or `string` + - `success`: `boolean` or `nil` + + Equivalent to `fdatasync(2)`. + + Returns (sync version): `boolean` or `fail` + + Returns (async version): `uv_fs_t userdata` + +uv.fs_ftruncate({fd}, {offset} [, {callback}]) *uv.fs_ftruncate()* + + Parameters: + - `fd`: `integer` + - `offset`: `integer` + - `callback`: `callable` (async version) or `nil` (sync + version) + - `err`: `nil` or `string` + - `success`: `boolean` or `nil` + + Equivalent to `ftruncate(2)`. + + Returns (sync version): `boolean` or `fail` + + Returns (async version): `uv_fs_t userdata` + + *uv.fs_sendfile()* +uv.fs_sendfile({out_fd}, {in_fd}, {in_offset}, {size} [, {callback}]) + + Parameters: + - `out_fd`: `integer` + - `in_fd`: `integer` + - `in_offset`: `integer` + - `size`: `integer` + - `callback`: `callable` (async version) or `nil` (sync + version) + - `err`: `nil` or `string` + - `bytes`: `integer` or `nil` + + Limited equivalent to `sendfile(2)`. Returns the number of + bytes written. + + Returns (sync version): `integer` or `fail` + + Returns (async version): `uv_fs_t userdata` + +uv.fs_access({path}, {mode} [, {callback}]) *uv.fs_access()* + + Parameters: + - `path`: `string` + - `mode`: `integer` + - `callback`: `callable` (async version) or `nil` (sync + version) + - `err`: `nil` or `string` + - `permission`: `boolean` or `nil` + + Equivalent to `access(2)` on Unix. Windows uses + `GetFileAttributesW()`. Access `mode` can be an integer or a + string containing `"R"` or `"W"` or `"X"`. Returns `true` or + `false` indicating access permission. + + Returns (sync version): `boolean` or `fail` + + Returns (async version): `uv_fs_t userdata` + +uv.fs_chmod({path}, {mode} [, {callback}]) *uv.fs_chmod()* + + Parameters: + - `path`: `string` + - `mode`: `integer` + - `callback`: `callable` (async version) or `nil` (sync + version) + - `err`: `nil` or `string` + - `success`: `boolean` or `nil` + + Equivalent to `chmod(2)`. + + Returns (sync version): `boolean` or `fail` + + Returns (async version): `uv_fs_t userdata` + +uv.fs_fchmod({fd}, {mode} [, {callback}]) *uv.fs_fchmod()* + + Parameters: + - `fd`: `integer` + - `mode`: `integer` + - `callback`: `callable` (async version) or `nil` (sync + version) + - `err`: `nil` or `string` + - `success`: `boolean` or `nil` + + Equivalent to `fchmod(2)`. + + Returns (sync version): `boolean` or `fail` + + Returns (async version): `uv_fs_t userdata` + +uv.fs_utime({path}, {atime}, {mtime} [, {callback}]) *uv.fs_utime()* + + Parameters: + - `path`: `string` + - `atime`: `number` + - `mtime`: `number` + - `callback`: `callable` (async version) or `nil` (sync + version) + - `err`: `nil` or `string` + - `success`: `boolean` or `nil` + + Equivalent to `utime(2)`. + + Returns (sync version): `boolean` or `fail` + + Returns (async version): `uv_fs_t userdata` + +uv.fs_futime({fd}, {atime}, {mtime} [, {callback}]) *uv.fs_futime()* + + Parameters: + - `fd`: `integer` + - `atime`: `number` + - `mtime`: `number` + - `callback`: `callable` (async version) or `nil` (sync + version) + - `err`: `nil` or `string` + - `success`: `boolean` or `nil` + + Equivalent to `futime(2)`. + + Returns (sync version): `boolean` or `fail` + + Returns (async version): `uv_fs_t userdata` + +uv.fs_lutime({path}, {atime}, {mtime} [, {callback}]) *uv.fs_lutime()* + + Parameters: + - `path`: `string` + - `atime`: `number` + - `mtime`: `number` + - `callback`: `callable` (async version) or `nil` (sync + version) + - `err`: `nil` or `string` + - `success`: `boolean` or `nil` + + Equivalent to `lutime(2)`. + + Returns (sync version): `boolean` or `fail` + + Returns (async version): `uv_fs_t userdata` + +uv.fs_link({path}, {new_path} [, {callback}]) *uv.fs_link()* + + Parameters: + - `path`: `string` + - `new_path`: `string` + - `callback`: `callable` (async version) or `nil` (sync + version) + - `err`: `nil` or `string` + - `success`: `boolean` or `nil` + + Equivalent to `link(2)`. + + Returns (sync version): `boolean` or `fail` + + Returns (async version): `uv_fs_t userdata` + +uv.fs_symlink({path}, {new_path} [, {flags} [, {callback}]]) *uv.fs_symlink()* + + Parameters: + - `path`: `string` + - `new_path`: `string` + - `flags`: `table`, `integer`, or `nil` + - `dir`: `boolean` + - `junction`: `boolean` + - `callback`: `callable` (async version) or `nil` (sync + version) + - `err`: `nil` or `string` + - `success`: `boolean` or `nil` + + Equivalent to `symlink(2)`. If the `flags` parameter is + omitted, then the 3rd parameter will be treated as the + `callback`. + + Returns (sync version): `boolean` or `fail` + + Returns (async version): `uv_fs_t userdata` + +uv.fs_readlink({path} [, {callback}]) *uv.fs_readlink()* + + Parameters: + - `path`: `string` + - `callback`: `callable` (async version) or `nil` (sync + version) + - `err`: `nil` or `string` + - `path`: `string` or `nil` + + Equivalent to `readlink(2)`. + + Returns (sync version): `string` or `fail` + + Returns (async version): `uv_fs_t userdata` + +uv.fs_realpath({path} [, {callback}]) *uv.fs_realpath()* + + Parameters: + - `path`: `string` + - `callback`: `callable` (async version) or `nil` (sync + version) + - `err`: `nil` or `string` + - `path`: `string` or `nil` + + Equivalent to `realpath(3)`. + + Returns (sync version): `string` or `fail` + + Returns (async version): `uv_fs_t userdata` + +uv.fs_chown({path}, {uid}, {gid} [, {callback}]) *uv.fs_chown()* + + Parameters: + - `path`: `string` + - `uid`: `integer` + - `gid`: `integer` + - `callback`: `callable` (async version) or `nil` (sync + version) + - `err`: `nil` or `string` + - `success`: `boolean` or `nil` + + Equivalent to `chown(2)`. + + Returns (sync version): `boolean` or `fail` + + Returns (async version): `uv_fs_t userdata` + +uv.fs_fchown({fd}, {uid}, {gid} [, {callback}]) *uv.fs_fchown()* + + Parameters: + - `fd`: `integer` + - `uid`: `integer` + - `gid`: `integer` + - `callback`: `callable` (async version) or `nil` (sync + version) + - `err`: `nil` or `string` + - `success`: `boolean` or `nil` + + Equivalent to `fchown(2)`. + + Returns (sync version): `boolean` or `fail` + + Returns (async version): `uv_fs_t userdata` + +uv.fs_lchown({fd}, {uid}, {gid} [, {callback}]) *uv.fs_lchown()* + + Parameters: + - `fd`: `integer` + - `uid`: `integer` + - `gid`: `integer` + - `callback`: `callable` (async version) or `nil` (sync + version) + - `err`: `nil` or `string` + - `success`: `boolean` or `nil` + + Equivalent to `lchown(2)`. + + Returns (sync version): `boolean` or `fail` + + Returns (async version): `uv_fs_t userdata` + +uv.fs_copyfile({path}, {new_path} [, {flags} [, {callback}]]) *uv.fs_copyfile()* + + Parameters: + - `path`: `string` + - `new_path`: `string` + - `flags`: `table`, `integer`, or `nil` + - `excl`: `boolean` + - `ficlone`: `boolean` + - `ficlone_force`: `boolean` + - `callback`: `callable` (async version) or `nil` (sync + version) + - `err`: `nil` or `string` + - `success`: `boolean` or `nil` + + Copies a file from path to new_path. If the `flags` parameter + is omitted, then the 3rd parameter will be treated as the + `callback`. + + Returns (sync version): `boolean` or `fail` + + Returns (async version): `uv_fs_t userdata` + +uv.fs_opendir({path} [, {callback} [, {entries}]]) *uv.fs_opendir()* + + Parameters: + - `path`: `string` + - `callback`: `callable` (async version) or `nil` (sync + version) + - `err`: `nil` or `string` + - `dir`: `luv_dir_t userdata` or `nil` + - `entries`: `integer` or `nil` + + Opens path as a directory stream. Returns a handle that the + user can pass to |uv.fs_readdir()|. The `entries` parameter + defines the maximum number of entries that should be returned + by each call to |uv.fs_readdir()|. + + Returns (sync version): `luv_dir_t userdata` or `fail` + + Returns (async version): `uv_fs_t userdata` + +uv.fs_readdir({dir} [, {callback}]) *uv.fs_readdir()* + + > method form `dir:readdir([callback])` + + Parameters: + - `dir`: `luv_dir_t userdata` + - `callback`: `callable` (async version) or `nil` (sync + version) + - `err`: `nil` or `string` + - `entries`: `table` or `nil` (see below) + + Iterates over the directory stream `luv_dir_t` returned by a + successful |uv.fs_opendir()| call. A table of data tables is + returned where the number of entries `n` is equal to or less + than the `entries` parameter used in the associated + |uv.fs_opendir()| call. + + Returns (sync version): `table` or `fail` + - `[1, 2, 3, ..., n]` : `table` + - `name` : `string` + - `type` : `string` + + Returns (async version): `uv_fs_t userdata` + +uv.fs_closedir({dir} [, {callback}]) *uv.fs_closedir()* + + > method form `dir:closedir([callback])` + + Parameters: + - `dir`: `luv_dir_t userdata` + - `callback`: `callable` (async version) or `nil` (sync + version) + - `err`: `nil` or `string` + - `success`: `boolean` or `nil` + + Closes a directory stream returned by a successful + |uv.fs_opendir()| call. + + Returns (sync version): `boolean` or `fail` + + Returns (async version): `uv_fs_t userdata` + +uv.fs_statfs({path} [, {callback}]) *uv.fs_statfs()* + + Parameters: + - `path`: `string` + - `callback`: `callable` (async version) or `nil` (sync + version) + - `err`: `nil` or `string` + - `table` or `nil` (see below) + + Equivalent to `statfs(2)`. + + Returns `table` or `nil` + - `type` : `integer` + - `bsize` : `integer` + - `blocks` : `integer` + - `bfree` : `integer` + - `bavail` : `integer` + - `files` : `integer` + - `ffree` : `integer` + +============================================================================== +THREAD POOL WORK SCHEDULING *luv-thread-pool-work-scheduling* + +Libuv provides a threadpool which can be used to run user code and get +notified in the loop thread. This threadpool is internally used to run all +file system operations, as well as `getaddrinfo` and `getnameinfo` requests. + + > + local function work_callback(a, b) + return a + b + end + + local function after_work_callback(c) + print("The result is: " .. c) + end + + local work = uv.new_work(work_callback, after_work_callback) + + work:queue(1, 2) + + -- output: "The result is: 3" +< + +uv.new_work({work_callback}, {after_work_callback}) *uv.new_work()* + + Parameters: + - `work_callback`: `function` + - `...`: `threadargs` passed to/from + `uv.queue_work(work_ctx, ...)` + - `after_work_callback`: `function` + - `...`: `threadargs` returned from `work_callback` + + Creates and initializes a new `luv_work_ctx_t` (not + `uv_work_t`). Returns the Lua userdata wrapping it. + + Returns: `luv_work_ctx_t userdata` + +uv.queue_work({work_ctx}, {...}) *uv.queue_work()* + + > method form `work_ctx:queue(...)` + + Parameters: + - `work_ctx`: `luv_work_ctx_t userdata` + - `...`: `threadargs` + + Queues a work request which will run `work_callback` in a new + Lua state in a thread from the threadpool with any additional + arguments from `...`. Values returned from `work_callback` are + passed to `after_work_callback`, which is called in the main + loop thread. + + Returns: `boolean` or `fail` + +============================================================================== +DNS UTILITY FUNCTIONS *luv-dns-utility-functions* + +uv.getaddrinfo({host}, {service} [, {hints} [, {callback}]]) *uv.getaddrinfo()* + + Parameters: + - `host`: `string` or `nil` + - `service`: `string` or `nil` + - `hints`: `table` or `nil` + - `family`: `string` or `integer` or `nil` + - `socktype`: `string` or `integer` or `nil` + - `protocol`: `string` or `integer` or `nil` + - `addrconfig`: `boolean` or `nil` + - `v4mapped`: `boolean` or `nil` + - `all`: `boolean` or `nil` + - `numerichost`: `boolean` or `nil` + - `passive`: `boolean` or `nil` + - `numericserv`: `boolean` or `nil` + - `canonname`: `boolean` or `nil` + - `callback`: `callable` (async version) or `nil` (sync + version) + - `err`: `nil` or `string` + - `addresses`: `table` or `nil` (see below) + + Equivalent to `getaddrinfo(3)`. Either `node` or `service` may + be `nil` but not both. + + Valid hint strings for the keys that take a string: + - `family`: `"unix"`, `"inet"`, `"inet6"`, `"ipx"`, + `"netlink"`, `"x25"`, `"ax25"`, `"atmpvc"`, `"appletalk"`, + or `"packet"` + - `socktype`: `"stream"`, `"dgram"`, `"raw"`, `"rdm"`, or + `"seqpacket"` + - `protocol`: will be looked up using the `getprotobyname(3)` + function (examples: `"ip"`, `"icmp"`, `"tcp"`, `"udp"`, etc) + + Returns (sync version): `table` or `fail` + - `[1, 2, 3, ..., n]` : `table` + - `addr` : `string` + - `family` : `string` + - `port` : `integer` or `nil` + - `socktype` : `string` + - `protocol` : `string` + - `canonname` : `string` or `nil` + + Returns (async version): `uv_getaddrinfo_t userdata` or `fail` + +uv.getnameinfo({address} [, {callback}]) *uv.getnameinfo()* + + Parameters: + - `address`: `table` + - `ip`: `string` or `nil` + - `port`: `integer` or `nil` + - `family`: `string` or `integer` or `nil` + - `callback`: `callable` (async version) or `nil` (sync + version) + - `err`: `nil` or `sring` + - `host`: `string` or `nil` + - `service`: `string` or `nil` + + Equivalent to `getnameinfo(3)`. + + When specified, `family` must be one of `"unix"`, `"inet"`, + `"inet6"`, `"ipx"`, `"netlink"`, `"x25"`, `"ax25"`, + `"atmpvc"`, `"appletalk"`, or `"packet"`. + + Returns (sync version): `string, string` or `fail` + + Returns (async version): `uv_getnameinfo_t userdata` or `fail` + +============================================================================== +THREADING AND SYNCHRONIZATION UTILITIES *luv-threading-and-synchronization-utilities* + +Libuv provides cross-platform implementations for multiple threading an +synchronization primitives. The API largely follows the pthreads API. + +uv.new_thread([{options}, ] {entry}, {...}) *uv.new_thread()* + + Parameters: + - `options`: `table` or `nil` + - `stack_size`: `integer` or `nil` + - `entry`: `function` + - `...`: `threadargs` passed to `entry` + + Creates and initializes a `luv_thread_t` (not `uv_thread_t`). + Returns the Lua userdata wrapping it and asynchronously + executes `entry`, which can be either a Lua function or a Lua + function dumped to a string. Additional arguments `...` are + passed to the `entry` function and an optional `options` table + may be provided. Currently accepted `option` fields are + `stack_size`. + + Returns: `luv_thread_t userdata` or `fail` + +uv.thread_equal({thread}, {other_thread}) *uv.thread_equal()* + + > method form `thread:equal(other_thread)` + + Parameters: + - `thread`: `luv_thread_t userdata` + - `other_thread`: `luv_thread_t userdata` + + Returns a boolean indicating whether two threads are the same. + This function is equivalent to the `__eq` metamethod. + + Returns: `boolean` + +uv.thread_self() *uv.thread_self()* + + Returns the handle for the thread in which this is called. + + Returns: `luv_thread_t` + +uv.thread_join({thread}) *uv.thread_join()* + + > method form `thread:join()` + + Parameters: + - `thread`: `luv_thread_t userdata` + + Waits for the `thread` to finish executing its entry function. + + Returns: `boolean` or `fail` + +uv.sleep({msec}) *uv.sleep()* + + Parameters: + - `msec`: `integer` + + Pauses the thread in which this is called for a number of + milliseconds. + + Returns: Nothing. + +============================================================================== +MISCELLANEOUS UTILITIES *luv-miscellaneous-utilities* + +uv.exepath() *uv.exepath()* + + Returns the executable path. + + Returns: `string` or `fail` + +uv.cwd() *uv.cwd()* + + Returns the current working directory. + + Returns: `string` or `fail` + +uv.chdir({cwd}) *uv.chdir()* + + Parameters: + - `cwd`: `string` + + Sets the current working directory with the string `cwd`. + + Returns: `0` or `fail` + +uv.get_process_title() *uv.get_process_title()* + + Returns the title of the current process. + + Returns: `string` or `fail` + +uv.set_process_title({title}) *uv.set_process_title()* + + Parameters: + - `title`: `string` + + Sets the title of the current process with the string `title`. + + Returns: `0` or `fail` + +uv.get_total_memory() *uv.get_total_memory()* + + Returns the current total system memory in bytes. + + Returns: `number` + +uv.get_free_memory() *uv.get_free_memory()* + + Returns the current free system memory in bytes. + + Returns: `number` + +uv.get_constrained_memory() *uv.get_constrained_memory()* + + Gets the amount of memory available to the process in bytes + based on limits imposed by the OS. If there is no such + constraint, or the constraint is unknown, 0 is returned. Note + that it is not unusual for this value to be less than or + greater than the total system memory. + + Returns: `number` + +uv.resident_set_memory() *uv.resident_set_memory()* + + Returns the resident set size (RSS) for the current process. + + Returns: `integer` or `fail` + +uv.getrusage() *uv.getrusage()* + + Returns the resource usage. + + Returns: `table` or `fail` + - `utime` : `table` (user CPU time used) + - `sec` : `integer` + - `usec` : `integer` + - `stime` : `table` (system CPU time used) + - `sec` : `integer` + - `usec` : `integer` + - `maxrss` : `integer` (maximum resident set size) + - `ixrss` : `integer` (integral shared memory size) + - `idrss` : `integer` (integral unshared data size) + - `isrss` : `integer` (integral unshared stack size) + - `minflt` : `integer` (page reclaims (soft page faults)) + - `majflt` : `integer` (page faults (hard page faults)) + - `nswap` : `integer` (swaps) + - `inblock` : `integer` (block input operations) + - `oublock` : `integer` (block output operations) + - `msgsnd` : `integer` (IPC messages sent) + - `msgrcv` : `integer` (IPC messages received) + - `nsignals` : `integer` (signals received) + - `nvcsw` : `integer` (voluntary context switches) + - `nivcsw` : `integer` (involuntary context switches) + +uv.available_parallelism() *uv.available_parallelism()* + + Returns an estimate of the default amount of parallelism a + program should use. Always returns a non-zero value. + + On Linux, inspects the calling thread’s CPU affinity mask to + determine if it has been pinned to specific CPUs. + + On Windows, the available parallelism may be underreported on + systems with more than 64 logical CPUs. + + On other platforms, reports the number of CPUs that the + operating system considers to be online. + + Returns: `integer` + +uv.cpu_info() *uv.cpu_info()* + + Returns information about the CPU(s) on the system as a table + of tables for each CPU found. + + Returns: `table` or `fail` + - `[1, 2, 3, ..., n]` : `table` + - `model` : `string` + - `speed` : `number` + - `times` : `table` + - `user` : `number` + - `nice` : `number` + - `sys` : `number` + - `idle` : `number` + - `irq` : `number` + +uv.getpid() *uv.getpid()* + + DEPRECATED: Please use |uv.os_getpid()| instead. + +uv.getuid() *uv.getuid()* + + Returns the user ID of the process. + + Returns: `integer` + + Note: This is not a libuv function and is not supported on + Windows. + +uv.getgid() *uv.getgid()* + + Returns the group ID of the process. + + Returns: `integer` + + Note: This is not a libuv function and is not supported on + Windows. + +uv.setuid({id}) *uv.setuid()* + + Parameters: + - `id`: `integer` + + Sets the user ID of the process with the integer `id`. + + Returns: Nothing. + + Note: This is not a libuv function and is not supported on + Windows. + +uv.setgid({id}) *uv.setgid()* + + Parameters: + - `id`: `integer` + + Sets the group ID of the process with the integer `id`. + + Returns: Nothing. + + Note: This is not a libuv function and is not supported on + Windows. + +uv.hrtime() *uv.hrtime()* + + Returns a current high-resolution time in nanoseconds as a + number. This is relative to an arbitrary time in the past. It + is not related to the time of day and therefore not subject to + clock drift. The primary use is for measuring time between + intervals. + + Returns: `number` + +uv.uptime() *uv.uptime()* + + Returns the current system uptime in seconds. + + Returns: `number` or `fail` + +uv.print_all_handles() *uv.print_all_handles()* + + Prints all handles associated with the main loop to stderr. + The format is `[flags] handle-type handle-address` . Flags are + `R` for referenced, `A` for active and `I` for internal. + + Returns: Nothing. + + Note: This is not available on Windows. + + WARNING: This function is meant for ad hoc debugging, there + are no API/ABI stability guarantees. + +uv.print_active_handles() *uv.print_active_handles()* + + The same as |uv.print_all_handles()| except only active + handles are printed. + + Returns: Nothing. + + Note: This is not available on Windows. + + WARNING: This function is meant for ad hoc debugging, there + are no API/ABI stability guarantees. + +uv.guess_handle({fd}) *uv.guess_handle()* + + Parameters: + - `fd`: `integer` + + Used to detect what type of stream should be used with a given + file descriptor `fd`. Usually this will be used during + initialization to guess the type of the stdio streams. + + Returns: `string` + +uv.gettimeofday() *uv.gettimeofday()* + + Cross-platform implementation of `gettimeofday(2)`. Returns + the seconds and microseconds of a unix time as a pair. + + Returns: `integer, integer` or `fail` + +uv.interface_addresses() *uv.interface_addresses()* + + Returns address information about the network interfaces on + the system in a table. Each table key is the name of the + interface while each associated value is an array of address + information where fields are `ip`, `family`, `netmask`, + `internal`, and `mac`. + + Returns: `table` + - `[name(s)]` : `table` + - `ip` : `string` + - `family` : `string` + - `netmask` : `string` + - `internal` : `boolean` + - `mac` : `string` + +uv.if_indextoname({ifindex}) *uv.if_indextoname()* + + Parameters: + - `ifindex`: `integer` + + IPv6-capable implementation of `if_indextoname(3)`. + + Returns: `string` or `fail` + +uv.if_indextoiid({ifindex}) *uv.if_indextoiid()* + + Parameters: + - `ifindex`: `integer` + + Retrieves a network interface identifier suitable for use in + an IPv6 scoped address. On Windows, returns the numeric + `ifindex` as a string. On all other platforms, + |uv.if_indextoname()| is used. + + Returns: `string` or `fail` + +uv.loadavg() *uv.loadavg()* + + Returns the load average as a triad. Not supported on Windows. + + Returns: `number, number, number` + +uv.os_uname() *uv.os_uname()* + + Returns system information. + + Returns: `table` + - `sysname` : `string` + - `release` : `string` + - `version` : `string` + - `machine` : `string` + +uv.os_gethostname() *uv.os_gethostname()* + + Returns the hostname. + + Returns: `string` + +uv.os_getenv({name} [, {size}]) *uv.os_getenv()* + + Parameters: + - `name`: `string` + - `size`: `integer` (default = `LUAL_BUFFERSIZE`) + + Returns the environment variable specified by `name` as + string. The internal buffer size can be set by defining + `size`. If omitted, `LUAL_BUFFERSIZE` is used. If the + environment variable exceeds the storage available in the + internal buffer, `ENOBUFS` is returned. If no matching + environment variable exists, `ENOENT` is returned. + + Returns: `string` or `fail` + + WARNING: This function is not thread safe. + +uv.os_setenv({name}, {value}) *uv.os_setenv()* + + Parameters: + - `name`: `string` + - `value`: `string` + + Sets the environmental variable specified by `name` with the + string `value`. + + Returns: `boolean` or `fail` + + WARNING: This function is not thread safe. + +uv.os_unsetenv() *uv.os_unsetenv()* + + Returns: `boolean` or `fail` + + WARNING: This function is not thread safe. + +uv.os_environ() *uv.os_environ()* + + Returns all environmental variables as a dynamic table of + names associated with their corresponding values. + + Returns: `table` + + WARNING: This function is not thread safe. + +uv.os_homedir() *uv.os_homedir()* + + Returns: `string` or `fail` + + WARNING: This function is not thread safe. + +uv.os_tmpdir() *uv.os_tmpdir()* + + Returns: `string` or `fail` + + WARNING: This function is not thread safe. + +uv.os_get_passwd() *uv.os_get_passwd()* + + Returns password file information. + + Returns: `table` + - `username` : `string` + - `uid` : `integer` + - `gid` : `integer` + - `shell` : `string` + - `homedir` : `string` + +uv.os_getpid() *uv.os_getpid()* + + Returns the current process ID. + + Returns: `number` + +uv.os_getppid() *uv.os_getppid()* + + Returns the parent process ID. + + Returns: `number` + +uv.os_getpriority({pid}) *uv.os_getpriority()* + + Parameters: + - `pid`: `integer` + + Returns the scheduling priority of the process specified by + `pid`. + + Returns: `number` or `fail` + +uv.os_setpriority({pid}, {priority}) *uv.os_setpriority()* + + Parameters: + - `pid`: `integer` + - `priority`: `integer` + + Sets the scheduling priority of the process specified by + `pid`. The `priority` range is between -20 (high priority) and + 19 (low priority). + + Returns: `boolean` or `fail` + +uv.random({len}, {flags} [, {callback}]) *uv.random()* + + Parameters: + - `len`: `integer` + - `flags`: `nil` (see below) + - `callback`: `callable` (async version) or `nil` (sync + version) + - `err`: `nil` or `string` + - `bytes`: `string` or `nil` + + Fills a string of length `len` with cryptographically strong + random bytes acquired from the system CSPRNG. `flags` is + reserved for future extension and must currently be `nil` or + `0` or `{}`. + + Short reads are not possible. When less than `len` random + bytes are available, a non-zero error value is returned or + passed to the callback. If the callback is omitted, this + function is completed synchronously. + + The synchronous version may block indefinitely when not enough + entropy is available. The asynchronous version may not ever + finish when the system is low on entropy. + + Returns (sync version): `string` or `fail` + + Returns (async version): `0` or `fail` + +uv.translate_sys_error({errcode}) *uv.translate_sys_error()* + + Parameters: + - `errcode`: `integer` + + Returns the libuv error message and error name (both in string + form, see `err` and `name` in |luv-error-handling|) equivalent + to the given platform dependent error code: POSIX error codes + on Unix (the ones stored in errno), and Win32 error codes on + Windows (those returned by GetLastError() or + WSAGetLastError()). + + Returns: `string, string` or `nil` + +============================================================================== +METRICS OPERATIONS *luv-metrics-operations* + +uv.metrics_idle_time() *uv.metrics_idle_time()* + + Retrieve the amount of time the event loop has been idle in + the kernel’s event provider (e.g. `epoll_wait`). The call is + thread safe. + + The return value is the accumulated time spent idle in the + kernel’s event provider starting from when the |uv_loop_t| was + configured to collect the idle time. + + Note: The event loop will not begin accumulating the event + provider’s idle time until calling `loop_configure` with + `"metrics_idle_time"`. + + Returns: `number` + +============================================================================== +CREDITS *luv-credits* + +This document is a reformatted version of the LUV documentation, based on +commit c51e705 (5 May 2022) of the luv repository +https://github.com/luvit/luv/commit/c51e7052ec4f0a25058f70c1b4ee99dd36180e59. + +Included from https://github.com/nanotee/luv-vimdocs with kind permission. + + +vim:tw=78:ts=8:ft=help:norl: diff --git a/runtime/doc/map.txt b/runtime/doc/map.txt index b0ce2d4164..2b2bfec6c7 100644 --- a/runtime/doc/map.txt +++ b/runtime/doc/map.txt @@ -1452,6 +1452,9 @@ Incremental preview ~ Commands can show an 'inccommand' (as-you-type) preview by defining a preview handler (only from Lua, see |nvim_create_user_command()|). +Before the preview callback is executed, Nvim will temporarily disable +'cursorline' and 'cursorcolumn' to avoid highlighting issues. + The preview callback must be a Lua function with this signature: > function cmdpreview(opts, ns, buf) @@ -1463,10 +1466,10 @@ results (for "inccommand=split", or nil for "inccommand=nosplit"). Your command preview routine must implement this protocol: -1. Modify the current buffer as required for the preview (see +1. Modify the target buffers as required for the preview (see |nvim_buf_set_text()| and |nvim_buf_set_lines()|). 2. If preview buffer is provided, add necessary text to the preview buffer. -3. Add required highlights to the current buffer. If preview buffer is +3. Add required highlights to the target buffers. If preview buffer is provided, add required highlights to the preview buffer as well. All highlights must be added to the preview namespace which is provided as an argument to the preview callback (see |nvim_buf_add_highlight()| and @@ -1477,8 +1480,8 @@ Your command preview routine must implement this protocol: 2: Preview is shown and preview window is opened (if "inccommand=split"). For "inccommand=nosplit" this is the same as 1. -After preview ends, Nvim discards all changes to the buffer and all highlights -in the preview namespace. +After preview ends, Nvim discards all changes to all buffers made during the +preview and clears all highlights in the preview namespace. Here's an example of a command to trim trailing whitespace from lines that supports incremental command preview: diff --git a/runtime/doc/motion.txt b/runtime/doc/motion.txt index 9655d07a84..511b1bd7b2 100644 --- a/runtime/doc/motion.txt +++ b/runtime/doc/motion.txt @@ -588,7 +588,8 @@ i) *v_i)* *i)* *i(* i( *vib* *v_ib* *v_i(* *ib* ib "inner block", select [count] blocks, from "[count] [(" to the matching ')', excluding the '(' and ')' (see - |[(|). + |[(|). If the cursor is not inside a () block, then + find the next "(". When used in Visual mode it is made charwise. a> *v_a>* *v_a<* *a>* *a<* diff --git a/runtime/doc/options.txt b/runtime/doc/options.txt index dfb6b746d6..cf099af391 100644 --- a/runtime/doc/options.txt +++ b/runtime/doc/options.txt @@ -591,7 +591,11 @@ A jump table for the options with a short description can be found at |Q_op|. "double": Use twice the width of ASCII characters. *E834* *E835* The value "double" cannot be used if 'listchars' or 'fillchars' - contains a character that would be double width. + contains a character that would be double width. These errors may + also be given when calling setcellwidths(). + + The values are overruled for characters specified with + |setcellwidths()|. There are a number of CJK fonts for which the width of glyphs for those characters are solely based on how many octets they take in @@ -1321,7 +1325,9 @@ A jump table for the options with a short description can be found at |Q_op|. page can have a different value. When 'cmdheight' is zero, there is no command-line unless it is being - used. Any messages will cause the |hit-enter| prompt. + used. Some informative messages will not be displayed, any other + messages will cause the |hit-enter| prompt. Expect some other + unexpected behavior too. *'cmdwinheight'* *'cwh'* 'cmdwinheight' 'cwh' number (default 7) @@ -2141,7 +2147,8 @@ A jump table for the options with a short description can be found at |Q_op|. When on all Unicode emoji characters are considered to be full width. This excludes "text emoji" characters, which are normally displayed as single width. Unfortunately there is no good specification for this - and it has been determined on trial-and-error basis. + and it has been determined on trial-and-error basis. Use the + |setcellwidths()| function to change the behavior. *'encoding'* *'enc'* *E543* 'encoding' 'enc' @@ -3735,8 +3742,8 @@ A jump table for the options with a short description can be found at |Q_op|. *'lispwords'* *'lw'* 'lispwords' 'lw' string (default is very long) global or local to buffer |global-local| - Comma-separated list of words that influence the Lisp indenting. - |'lisp'| + Comma-separated list of words that influence the Lisp indenting when + enabled with the |'lisp'| option. *'list'* *'nolist'* 'list' boolean (default off) @@ -4716,8 +4723,8 @@ A jump table for the options with a short description can be found at |Q_op|. in read-only mode ("vim -R") or when the executable is called "view". When using ":w!" the 'readonly' option is reset for the current buffer, unless the 'Z' flag is in 'cpoptions'. - When using the ":view" command the 'readonly' option is - set for the newly edited buffer. + When using the ":view" command the 'readonly' option is set for the + newly edited buffer. See 'modifiable' for disallowing changes to the buffer. *'redrawdebug'* *'rdb'* @@ -4838,7 +4845,7 @@ A jump table for the options with a short description can be found at |Q_op|. search "/" and "?" commands - This is useful for languages such as Hebrew and Arabic. + This is useful for languages such as Hebrew, Arabic and Farsi. The 'rightleft' option must be set for 'rightleftcmd' to take effect. *'ruler'* *'ru'* *'noruler'* *'noru'* @@ -5874,6 +5881,11 @@ A jump table for the options with a short description can be found at |Q_op|. suggestions is never more than the value of 'lines' minus two. + timeout:{millisec} Limit the time searching for suggestions to + {millisec} milli seconds. Applies to the following + methods. When omitted the limit is 5000. When + negative there is no limit. + file:{filename} Read file {filename}, which must have two columns, separated by a slash. The first column contains the bad word, the second column the suggested good word. @@ -6189,7 +6201,7 @@ A jump table for the options with a short description can be found at |Q_op|. global This option controls the behavior when switching between buffers. Mostly for |quickfix| commands some values are also used for other - commands, as mentioned below. + commands, as mentioned below. Possible values (comma-separated list): useopen If included, jump to the first open window that contains the specified buffer (if there is one). @@ -7139,10 +7151,12 @@ A jump table for the options with a short description can be found at |Q_op|. 'winhighlight' 'winhl' string (default empty) local to window Window-local highlights. Comma-delimited list of highlight - |group-name| pairs "{hl-builtin}:{hl},..." where each {hl-builtin} is - a built-in |highlight-groups| item to be overridden by {hl} group in - the window. Only built-in |highlight-groups| are supported, not - syntax highlighting (use |:ownsyntax| for that). + |group-name| pairs "{hl-from}:{hl-to},..." where each {hl-from} is + a |highlight-groups| item to be overridden by {hl-to} group in + the window. + + Note: highlight namespaces take precedence over 'winhighlight'. + See |nvim_win_set_hl_ns| and |nvim_set_hl|. Highlights of vertical separators are determined by the window to the left of the separator. The 'tabline' highlight of a tabpage is diff --git a/runtime/doc/syntax.txt b/runtime/doc/syntax.txt index 9ed3c37b8c..b74611633f 100644 --- a/runtime/doc/syntax.txt +++ b/runtime/doc/syntax.txt @@ -5250,7 +5250,7 @@ TabLineSel Tab pages line, active tab page label. Title Titles for output from ":set all", ":autocmd" etc. *hl-Visual* Visual Visual mode selection. - *hl-VisualNOS* + *hl-VisualNOS* VisualNOS Visual mode selection when vim is "Not Owning the Selection". *hl-WarningMsg* WarningMsg Warning messages. diff --git a/runtime/doc/treesitter.txt b/runtime/doc/treesitter.txt index eb19bf5934..52531a1525 100644 --- a/runtime/doc/treesitter.txt +++ b/runtime/doc/treesitter.txt @@ -1,15 +1,15 @@ *treesitter.txt* Nvim - NVIM REFERENCE MANUAL + NVIM REFERENCE MANUAL -Tree-sitter integration *treesitter* +Tree-sitter integration *treesitter* Type |gO| to see the table of contents. ------------------------------------------------------------------------------ -VIM.TREESITTER *lua-treesitter* +VIM.TREESITTER *lua-treesitter* Nvim integrates the tree-sitter library for incremental parsing of buffers. @@ -21,7 +21,7 @@ library. The earliest parser ABI version that is supported by the bundled tree-sitter library. -Parser files *treesitter-parsers* +Parser files *treesitter-parsers* Parsers are the heart of tree-sitter. They are libraries that tree-sitter will search for in the `parser` runtime directory. Currently Nvim does not provide @@ -44,9 +44,9 @@ is subject to change. A plugin should keep a reference to the parser object as long as it wants incremental updates. -Parser methods *lua-treesitter-parser* +Parser methods *lua-treesitter-parser* -tsparser:parse() *tsparser:parse()* +tsparser:parse() *tsparser:parse()* Whenever you need to access the current syntax tree, parse the buffer: > tstree = parser:parse() @@ -64,120 +64,119 @@ be very frequent. Rather a plugin that does any kind of analysis on a tree should use a timer to throttle too frequent updates. tsparser:set_included_regions({region_list}) *tsparser:set_included_regions()* - Changes the regions the parser should consider. This is used for - language injection. {region_list} should be of the form - (all zero-based): > - { - {node1, node2}, - ... - } + Changes the regions the parser should consider. This is used for language + injection. {region_list} should be of the form (all zero-based): > + { + {node1, node2}, + ... + } < - `node1` and `node2` are both considered part of the same region and - will be parsed together with the parser in the same context. + `node1` and `node2` are both considered part of the same region and will + be parsed together with the parser in the same context. -Tree methods *lua-treesitter-tree* +Tree methods *lua-treesitter-tree* -tstree:root() *tstree:root()* - Return the root node of this tree. +tstree:root() *tstree:root()* + Return the root node of this tree. -tstree:copy() *tstree:copy()* - Returns a copy of the `tstree`. +tstree:copy() *tstree:copy()* + Returns a copy of the `tstree`. -Node methods *lua-treesitter-node* +Node methods *lua-treesitter-node* -tsnode:parent() *tsnode:parent()* - Get the node's immediate parent. +tsnode:parent() *tsnode:parent()* + Get the node's immediate parent. -tsnode:next_sibling() *tsnode:next_sibling()* - Get the node's next sibling. +tsnode:next_sibling() *tsnode:next_sibling()* + Get the node's next sibling. -tsnode:prev_sibling() *tsnode:prev_sibling()* - Get the node's previous sibling. +tsnode:prev_sibling() *tsnode:prev_sibling()* + Get the node's previous sibling. tsnode:next_named_sibling() *tsnode:next_named_sibling()* - Get the node's next named sibling. + Get the node's next named sibling. -tsnode:prev_named_sibling() *tsnode:prev_named_sibling()* - Get the node's previous named sibling. +tsnode:prev_named_sibling() *tsnode:prev_named_sibling()* + Get the node's previous named sibling. -tsnode:iter_children() *tsnode:iter_children()* - Iterates over all the direct children of {tsnode}, regardless of - whether they are named or not. - Returns the child node plus the eventual field name corresponding to - this child node. +tsnode:iter_children() *tsnode:iter_children()* + Iterates over all the direct children of {tsnode}, regardless of whether + they are named or not. + Returns the child node plus the eventual field name corresponding to this + child node. -tsnode:field({name}) *tsnode:field()* - Returns a table of the nodes corresponding to the {name} field. +tsnode:field({name}) *tsnode:field()* + Returns a table of the nodes corresponding to the {name} field. -tsnode:child_count() *tsnode:child_count()* - Get the node's number of children. +tsnode:child_count() *tsnode:child_count()* + Get the node's number of children. -tsnode:child({index}) *tsnode:child()* - Get the node's child at the given {index}, where zero represents the - first child. +tsnode:child({index}) *tsnode:child()* + Get the node's child at the given {index}, where zero represents the first + child. -tsnode:named_child_count() *tsnode:named_child_count()* - Get the node's number of named children. +tsnode:named_child_count() *tsnode:named_child_count()* + Get the node's number of named children. -tsnode:named_child({index}) *tsnode:named_child()* - Get the node's named child at the given {index}, where zero represents - the first named child. +tsnode:named_child({index}) *tsnode:named_child()* + Get the node's named child at the given {index}, where zero represents the + first named child. -tsnode:start() *tsnode:start()* - Get the node's start position. Return three values: the row, column - and total byte count (all zero-based). +tsnode:start() *tsnode:start()* + Get the node's start position. Return three values: the row, column and + total byte count (all zero-based). -tsnode:end_() *tsnode:end_()* - Get the node's end position. Return three values: the row, column - and total byte count (all zero-based). +tsnode:end_() *tsnode:end_()* + Get the node's end position. Return three values: the row, column and + total byte count (all zero-based). -tsnode:range() *tsnode:range()* - Get the range of the node. Return four values: the row, column - of the start position, then the row, column of the end position. +tsnode:range() *tsnode:range()* + Get the range of the node. Return four values: the row, column of the + start position, then the row, column of the end position. -tsnode:type() *tsnode:type()* - Get the node's type as a string. +tsnode:type() *tsnode:type()* + Get the node's type as a string. -tsnode:symbol() *tsnode:symbol()* - Get the node's type as a numerical id. +tsnode:symbol() *tsnode:symbol()* + Get the node's type as a numerical id. -tsnode:named() *tsnode:named()* - Check if the node is named. Named nodes correspond to named rules in - the grammar, whereas anonymous nodes correspond to string literals - in the grammar. +tsnode:named() *tsnode:named()* + Check if the node is named. Named nodes correspond to named rules in the + grammar, whereas anonymous nodes correspond to string literals in the + grammar. -tsnode:missing() *tsnode:missing()* - Check if the node is missing. Missing nodes are inserted by the - parser in order to recover from certain kinds of syntax errors. +tsnode:missing() *tsnode:missing()* + Check if the node is missing. Missing nodes are inserted by the parser in + order to recover from certain kinds of syntax errors. -tsnode:has_error() *tsnode:has_error()* - Check if the node is a syntax error or contains any syntax errors. +tsnode:has_error() *tsnode:has_error()* + Check if the node is a syntax error or contains any syntax errors. -tsnode:sexpr() *tsnode:sexpr()* - Get an S-expression representing the node as a string. +tsnode:sexpr() *tsnode:sexpr()* + Get an S-expression representing the node as a string. -tsnode:id() *tsnode:id()* - Get an unique identifier for the node inside its own tree. +tsnode:id() *tsnode:id()* + Get an unique identifier for the node inside its own tree. - No guarantees are made about this identifier's internal - representation, except for being a primitive lua type with value - equality (so not a table). Presently it is a (non-printable) string. + No guarantees are made about this identifier's internal representation, + except for being a primitive lua type with value equality (so not a + table). Presently it is a (non-printable) string. - Note: the id is not guaranteed to be unique for nodes from different - trees. + Note: the id is not guaranteed to be unique for nodes from different + trees. - *tsnode:descendant_for_range()* + *tsnode:descendant_for_range()* tsnode:descendant_for_range({start_row}, {start_col}, {end_row}, {end_col}) - Get the smallest node within this node that spans the given range of - (row, column) positions + Get the smallest node within this node that spans the given range of (row, + column) positions - *tsnode:named_descendant_for_range()* + *tsnode:named_descendant_for_range()* tsnode:named_descendant_for_range({start_row}, {start_col}, {end_row}, {end_col}) - Get the smallest named node within this node that spans the given - range of (row, column) positions + Get the smallest named node within this node that spans the given range of + (row, column) positions -Query *lua-treesitter-query* +Query *lua-treesitter-query* Tree-sitter queries are supported, they are a way to do pattern-matching over a tree, using a simple to write lisp-like format. See @@ -195,105 +194,102 @@ and predicates. A `capture` allows you to associate names with a specific node in a pattern. A `predicate` adds arbitrary metadata and conditional data to a match. -Treesitter Query Predicates *lua-treesitter-predicates* +Treesitter Query Predicates *lua-treesitter-predicates* When writing queries for treesitter, one might use `predicates`, that is, special scheme nodes that are evaluated to verify things on a captured node for example, the |eq?| predicate : > - ((identifier) @foo (#eq? @foo "foo")) + ((identifier) @foo (#eq? @foo "foo")) This will only match identifier corresponding to the `"foo"` text. Here is a list of built-in predicates : - `eq?` *ts-predicate-eq?* - This predicate will check text correspondence between nodes or - strings: > - ((identifier) @foo (#eq? @foo "foo")) - ((node1) @left (node2) @right (#eq? @left @right)) + `eq?` *ts-predicate-eq?* + This predicate will check text correspondence between nodes or + strings: > + ((identifier) @foo (#eq? @foo "foo")) + ((node1) @left (node2) @right (#eq? @left @right)) < - `match?` *ts-predicate-match?* - `vim-match?` *ts-predicate-vim-match?* - This will match if the provided vim regex matches the text - corresponding to a node: > - ((identifier) @constant (#match? @constant "^[A-Z_]+$")) -< Note: the `^` and `$` anchors will respectively match the - start and end of the node's text. - - `lua-match?` *ts-predicate-lua-match?* - This will match the same way than |match?| but using lua - regexes. - - `contains?` *ts-predicate-contains?* - Will check if any of the following arguments appears in the - text corresponding to the node: > - ((identifier) @foo (#contains? @foo "foo")) - ((identifier) @foo-bar (#contains @foo-bar "foo" "bar")) + `match?` *ts-predicate-match?* + `vim-match?` *ts-predicate-vim-match?* + This will match if the provided vim regex matches the text + corresponding to a node: > + ((identifier) @constant (#match? @constant "^[A-Z_]+$")) +< Note: the `^` and `$` anchors will respectively match the start and + end of the node's text. + + `lua-match?` *ts-predicate-lua-match?* + This will match the same way than |match?| but using lua regexes. + + `contains?` *ts-predicate-contains?* + Will check if any of the following arguments appears in the text + corresponding to the node: > + ((identifier) @foo (#contains? @foo "foo")) + ((identifier) @foo-bar (#contains @foo-bar "foo" "bar")) < - `any-of?` *ts-predicate-any-of?* - Will check if the text is the same as any of the following - arguments: > - ((identifier) @foo (#any-of? @foo "foo" "bar")) + `any-of?` *ts-predicate-any-of?* + Will check if the text is the same as any of the following arguments: > + ((identifier) @foo (#any-of? @foo "foo" "bar")) < - This is the recommended way to check if the node matches one - of many keywords for example, as it has been optimized for - this. + This is the recommended way to check if the node matches one of many + keywords for example, as it has been optimized for this. < - *lua-treesitter-not-predicate* + *lua-treesitter-not-predicate* Each predicate has a `not-` prefixed predicate that is just the negation of the predicate. - *vim.treesitter.query.add_predicate()* + *vim.treesitter.query.add_predicate()* vim.treesitter.query.add_predicate({name}, {handler}) This adds a predicate with the name {name} to be used in queries. {handler} should be a function whose signature will be : > - handler(match, pattern, bufnr, predicate) + handler(match, pattern, bufnr, predicate) < - *vim.treesitter.query.list_predicates()* + *vim.treesitter.query.list_predicates()* vim.treesitter.query.list_predicates() This lists the currently available predicates to use in queries. -Treesitter Query Directive *lua-treesitter-directives* +Treesitter Query Directive *lua-treesitter-directives* Treesitter queries can also contain `directives`. Directives store metadata for a node or match and perform side effects. For example, the |set!| predicate sets metadata on the match or node : > - ((identifier) @foo (#set! "type" "parameter")) + ((identifier) @foo (#set! "type" "parameter")) Built-in directives: - `set!` *ts-directive-set!* - Sets key/value metadata for a specific match or capture. - Value is accessible as either `metadata[key]` (match - specific) or `metadata[capture_id][key]` (capture specific). + `set!` *ts-directive-set!* + Sets key/value metadata for a specific match or capture. Value is + accessible as either `metadata[key]` (match specific) or + `metadata[capture_id][key]` (capture specific). - Parameters: ~ - {capture_id} (optional) - {key} - {value} + Parameters: ~ + {capture_id} (optional) + {key} + {value} - Examples: > - ((identifier) @foo (#set! @foo "kind" "parameter")) - ((node1) @left (node2) @right (#set! "type" "pair")) + Examples: > + ((identifier) @foo (#set! @foo "kind" "parameter")) + ((node1) @left (node2) @right (#set! "type" "pair")) < - `offset!` *ts-directive-offset!* - Takes the range of the captured node and applies an offset. - This will generate a new range object for the captured node - as `metadata[capture_id].range`. - - Parameters: ~ - {capture_id} - {start_row} - {start_col} - {end_row} - {end_col} - - Example: > - ((identifier) @constant (#offset! @constant 0 1 0 -1)) + `offset!` *ts-directive-offset!* + Takes the range of the captured node and applies an offset. This will + generate a new range object for the captured node as + `metadata[capture_id].range`. + + Parameters: ~ + {capture_id} + {start_row} + {start_col} + {end_row} + {end_col} + + Example: > + ((identifier) @constant (#offset! @constant 0 1 0 -1)) < -Treesitter syntax highlighting (WIP) *lua-treesitter-highlight* +Treesitter syntax highlighting (WIP) *lua-treesitter-highlight* NOTE: This is a partially implemented feature, and not usable as a default solution yet. What is documented here is a temporary interface intended @@ -340,7 +336,7 @@ identical identifiers, highlighting both as |hl-WarningMsg|: > < Treesitter Highlighting Priority *lua-treesitter-highlight-priority* -Tree-sitter uses |nvim_buf_set_extmark()| to set highlights with a default +Tree-sitter uses |nvim_buf_set_extmark()| to set highlights with a default priority of 100. This enables plugins to set a highlighting priority lower or higher than tree-sitter. It is also possible to change the priority of an individual query pattern manually by setting its `"priority"` metadata @@ -357,153 +353,146 @@ attribute: > Lua module: vim.treesitter *lua-treesitter-core* get_parser({bufnr}, {lang}, {opts}) *get_parser()* - Gets the parser for this bufnr / ft combination. + Gets the parser for this bufnr / ft combination. - If needed this will create the parser. Unconditionally attach - the provided callback + If needed this will create the parser. Unconditionally attach the provided + callback - Parameters: ~ - {bufnr} The buffer the parser should be tied to - {lang} The filetype of this parser - {opts} Options object to pass to the created language - tree + Parameters: ~ + {bufnr} The buffer the parser should be tied to + {lang} The filetype of this parser + {opts} Options object to pass to the created language tree - Return: ~ - The parser + Return: ~ + The parser get_string_parser({str}, {lang}, {opts}) *get_string_parser()* - Gets a string parser + Gets a string parser - Parameters: ~ - {str} The string to parse - {lang} The language of this string - {opts} Options to pass to the created language tree + Parameters: ~ + {str} The string to parse + {lang} The language of this string + {opts} Options to pass to the created language tree ============================================================================== Lua module: vim.treesitter.language *treesitter-language* inspect_language({lang}) *inspect_language()* - Inspects the provided language. + Inspects the provided language. - Inspecting provides some useful information on the language - like node names, ... + Inspecting provides some useful information on the language like node + names, ... - Parameters: ~ - {lang} The language. + Parameters: ~ + {lang} The language. require_language({lang}, {path}, {silent}) *require_language()* - Asserts that the provided language is installed, and - optionally provide a path for the parser + Asserts that the provided language is installed, and optionally provide a + path for the parser - Parsers are searched in the `parser` runtime directory. + Parsers are searched in the `parser` runtime directory. - Parameters: ~ - {lang} The language the parser should parse - {path} Optional path the parser is located at - {silent} Don't throw an error if language not found + Parameters: ~ + {lang} The language the parser should parse + {path} Optional path the parser is located at + {silent} Don't throw an error if language not found ============================================================================== Lua module: vim.treesitter.query *treesitter-query* add_directive({name}, {handler}, {force}) *add_directive()* - Adds a new directive to be used in queries + Adds a new directive to be used in queries - Handlers can set match level data by setting directly on the - metadata object `metadata.key = value`, additionally, handlers - can set node level data by using the capture id on the - metadata table `metadata[capture_id].key = value` + Handlers can set match level data by setting directly on the metadata + object `metadata.key = value`, additionally, handlers can set node level + data by using the capture id on the metadata table + `metadata[capture_id].key = value` - Parameters: ~ - {name} the name of the directive, without leading # - {handler} the handler function to be used signature will - be (match, pattern, bufnr, predicate, metadata) + Parameters: ~ + {name} the name of the directive, without leading # + {handler} the handler function to be used signature will be (match, + pattern, bufnr, predicate, metadata) add_predicate({name}, {handler}, {force}) *add_predicate()* - Adds a new predicate to be used in queries + Adds a new predicate to be used in queries - Parameters: ~ - {name} the name of the predicate, without leading # - {handler} the handler function to be used signature will - be (match, pattern, bufnr, predicate) + Parameters: ~ + {name} the name of the predicate, without leading # + {handler} the handler function to be used signature will be (match, + pattern, bufnr, predicate) get_node_text({node}, {source}) *get_node_text()* - Gets the text corresponding to a given node + Gets the text corresponding to a given node - Parameters: ~ - {node} the node - {source} The buffer or string from which the node is - extracted + Parameters: ~ + {node} the node + {source} The buffer or string from which the node is extracted get_query({lang}, {query_name}) *get_query()* - Returns the runtime query {query_name} for {lang}. + Returns the runtime query {query_name} for {lang}. - Parameters: ~ - {lang} The language to use for the query - {query_name} The name of the query (i.e. "highlights") + Parameters: ~ + {lang} The language to use for the query + {query_name} The name of the query (i.e. "highlights") - Return: ~ - The corresponding query, parsed. + Return: ~ + The corresponding query, parsed. *get_query_files()* get_query_files({lang}, {query_name}, {is_included}) - Gets the list of files used to make up a query + Gets the list of files used to make up a query - Parameters: ~ - {lang} The language - {query_name} The name of the query to load - {is_included} Internal parameter, most of the time left - as `nil` + Parameters: ~ + {lang} The language + {query_name} The name of the query to load + {is_included} Internal parameter, most of the time left as `nil` list_directives() *list_directives()* - Lists the currently available directives to use in queries. + Lists the currently available directives to use in queries. - Return: ~ - The list of supported directives. + Return: ~ + The list of supported directives. list_predicates() *list_predicates()* - Return: ~ - The list of supported predicates. + Return: ~ + The list of supported predicates. parse_query({lang}, {query}) *parse_query()* - Parse {query} as a string. (If the query is in a file, the - caller should read the contents into a string before calling). + Parse {query} as a string. (If the query is in a file, the caller should + read the contents into a string before calling). - Returns a `Query` (see |lua-treesitter-query|) object which - can be used to search nodes in the syntax tree for the - patterns defined in {query} using `iter_*` methods below. + Returns a `Query` (see |lua-treesitter-query|) object which can be used to + search nodes in the syntax tree for the patterns defined in {query} using + `iter_*` methods below. - Exposes `info` and `captures` with additional context about {query}. - • `captures` contains the list of unique capture names defined - in {query}. -`info.captures` also points to `captures`. - • `info.patterns` contains information about predicates. + Exposes `info` and `captures` with additional context about {query}. + • `captures` contains the list of unique capture names defined in {query}. + -`info.captures` also points to `captures`. + • `info.patterns` contains information about predicates. - Parameters: ~ - {lang} (string) The language - {query} (string) A string containing the query (s-expr - syntax) + Parameters: ~ + {lang} (string) The language + {query} (string) A string containing the query (s-expr syntax) - Return: ~ - The query + Return: ~ + The query *Query:iter_captures()* Query:iter_captures({self}, {node}, {source}, {start}, {stop}) - Iterate over all captures from all matches inside {node} - - {source} is needed if the query contains predicates, then the - caller must ensure to use a freshly parsed tree consistent - with the current text of the buffer (if relevant). {start_row} - and {end_row} can be used to limit matches inside a row range - (this is typically used with root node as the node, i e to get - syntax highlight matches in the current viewport). When - omitted the start and end row values are used from the given - node. - - The iterator returns three values, a numeric id identifying - the capture, the captured node, and metadata from any - directives processing the match. The following example shows - how to get captures by name: + Iterate over all captures from all matches inside {node} + + {source} is needed if the query contains predicates, then the caller must + ensure to use a freshly parsed tree consistent with the current text of + the buffer (if relevant). {start_row} and {end_row} can be used to limit + matches inside a row range (this is typically used with root node as the + node, i e to get syntax highlight matches in the current viewport). When + omitted the start and end row values are used from the given node. + + The iterator returns three values, a numeric id identifying the capture, + the captured node, and metadata from any directives processing the match. + The following example shows how to get captures by name: > for id, node, metadata in query:iter_captures(tree:root(), bufnr, first, last) do @@ -515,29 +504,28 @@ Query:iter_captures({self}, {node}, {source}, {start}, {stop}) end < - Parameters: ~ - {node} The node under which the search will occur - {source} The source buffer or string to extract text from - {start} The starting line of the search - {stop} The stopping line of the search (end-exclusive) - {self} + Parameters: ~ + {node} The node under which the search will occur + {source} The source buffer or string to extract text from + {start} The starting line of the search + {stop} The stopping line of the search (end-exclusive) + {self} - Return: ~ - The matching capture id - The captured node + Return: ~ + The matching capture id + The captured node *Query:iter_matches()* Query:iter_matches({self}, {node}, {source}, {start}, {stop}) - Iterates the matches of self on a given range. - - Iterate over all matches within a node. The arguments are the - same as for |query:iter_captures()| but the iterated values - are different: an (1-based) index of the pattern in the query, - a table mapping capture indices to nodes, and metadata from - any directives processing the match. If the query has more - than one pattern the capture table might be sparse, and e.g. - `pairs()` method should be used over `ipairs`. Here an example - iterating over all captures in every match: + Iterates the matches of self on a given range. + + Iterate over all matches within a node. The arguments are the same as for + |query:iter_captures()| but the iterated values are different: an + (1-based) index of the pattern in the query, a table mapping capture + indices to nodes, and metadata from any directives processing the match. + If the query has more than one pattern the capture table might be sparse, + and e.g. `pairs()` method should be used over `ipairs`. Here an example + iterating over all captures in every match: > for pattern, match, metadata in cquery:iter_matches(tree:root(), bufnr, first, last) do @@ -552,240 +540,220 @@ Query:iter_matches({self}, {node}, {source}, {start}, {stop}) end < - Parameters: ~ - {node} The node under which the search will occur - {source} The source buffer or string to search - {start} The starting line of the search - {stop} The stopping line of the search (end-exclusive) - {self} + Parameters: ~ + {node} The node under which the search will occur + {source} The source buffer or string to search + {start} The starting line of the search + {stop} The stopping line of the search (end-exclusive) + {self} - Return: ~ - The matching pattern id - The matching match + Return: ~ + The matching pattern id + The matching match set_query({lang}, {query_name}, {text}) *set_query()* - Sets the runtime query {query_name} for {lang} + Sets the runtime query {query_name} for {lang} - This allows users to override any runtime files and/or - configuration set by plugins. + This allows users to override any runtime files and/or configuration set + by plugins. - Parameters: ~ - {lang} string: The language to use for the query - {query_name} string: The name of the query (i.e. - "highlights") - {text} string: The query text (unparsed). + Parameters: ~ + {lang} string: The language to use for the query + {query_name} string: The name of the query (i.e. "highlights") + {text} string: The query text (unparsed). ============================================================================== Lua module: vim.treesitter.highlighter *treesitter-highlighter* new({tree}, {opts}) *highlighter.new()* - Creates a new highlighter using + Creates a new highlighter using - Parameters: ~ - {tree} The language tree to use for highlighting - {opts} Table used to configure the highlighter - • queries: Table to overwrite queries used by the - highlighter + Parameters: ~ + {tree} The language tree to use for highlighting + {opts} Table used to configure the highlighter + • queries: Table to overwrite queries used by the highlighter TSHighlighter:destroy({self}) *TSHighlighter:destroy()* - Removes all internal references to the highlighter + Removes all internal references to the highlighter - Parameters: ~ - {self} + Parameters: ~ + {self} TSHighlighter:get_query({self}, {lang}) *TSHighlighter:get_query()* - Gets the query used for + Gets the query used for - Parameters: ~ - {lang} A language used by the highlighter. - {self} + Parameters: ~ + {lang} A language used by the highlighter. + {self} ============================================================================== Lua module: vim.treesitter.languagetree *treesitter-languagetree* LanguageTree:add_child({self}, {lang}) *LanguageTree:add_child()* - Adds a child language to this tree. + Adds a child language to this tree. - If the language already exists as a child, it will first be - removed. + If the language already exists as a child, it will first be removed. - Parameters: ~ - {lang} The language to add. - {self} + Parameters: ~ + {lang} The language to add. + {self} LanguageTree:children({self}) *LanguageTree:children()* - Returns a map of language to child tree. + Returns a map of language to child tree. - Parameters: ~ - {self} + Parameters: ~ + {self} LanguageTree:contains({self}, {range}) *LanguageTree:contains()* - Determines whether {range} is contained in this language tree + Determines whether {range} is contained in this language tree - Parameters: ~ - {range} A range, that is a `{ start_line, start_col, - end_line, end_col }` table. - {self} + Parameters: ~ + {range} A range, that is a `{ start_line, start_col, end_line, + end_col }` table. + {self} LanguageTree:destroy({self}) *LanguageTree:destroy()* - Destroys this language tree and all its children. + Destroys this language tree and all its children. - Any cleanup logic should be performed here. + Any cleanup logic should be performed here. - Note: This DOES NOT remove this tree from a parent. Instead, `remove_child` must be called on the parent to remove it. + Note: This DOES NOT remove this tree from a parent. Instead, `remove_child` must be called on the parent to remove it. - Parameters: ~ - {self} + Parameters: ~ + {self} *LanguageTree:for_each_child()* LanguageTree:for_each_child({self}, {fn}, {include_self}) - Invokes the callback for each LanguageTree and it's children - recursively + Invokes the callback for each LanguageTree and it's children recursively - Parameters: ~ - {fn} The function to invoke. This is invoked - with arguments (tree: LanguageTree, lang: - string) - {include_self} Whether to include the invoking tree in - the results. - {self} + Parameters: ~ + {fn} The function to invoke. This is invoked with arguments + (tree: LanguageTree, lang: string) + {include_self} Whether to include the invoking tree in the results. + {self} LanguageTree:for_each_tree({self}, {fn}) *LanguageTree:for_each_tree()* - Invokes the callback for each treesitter trees recursively. + Invokes the callback for each treesitter trees recursively. - Note, this includes the invoking language tree's trees as - well. + Note, this includes the invoking language tree's trees as well. - Parameters: ~ - {fn} The callback to invoke. The callback is invoked - with arguments (tree: TSTree, languageTree: - LanguageTree) - {self} + Parameters: ~ + {fn} The callback to invoke. The callback is invoked with arguments + (tree: TSTree, languageTree: LanguageTree) + {self} LanguageTree:included_regions({self}) *LanguageTree:included_regions()* - Gets the set of included regions + Gets the set of included regions - Parameters: ~ - {self} + Parameters: ~ + {self} LanguageTree:invalidate({self}, {reload}) *LanguageTree:invalidate()* - Invalidates this parser and all its children + Invalidates this parser and all its children - Parameters: ~ - {self} + Parameters: ~ + {self} LanguageTree:is_valid({self}) *LanguageTree:is_valid()* - Determines whether this tree is valid. If the tree is invalid, - call `parse()` . This will return the updated tree. + Determines whether this tree is valid. If the tree is invalid, call `parse()` . This will return the updated tree. - Parameters: ~ - {self} + Parameters: ~ + {self} LanguageTree:lang({self}) *LanguageTree:lang()* - Gets the language of this tree node. + Gets the language of this tree node. - Parameters: ~ - {self} + Parameters: ~ + {self} *LanguageTree:language_for_range()* LanguageTree:language_for_range({self}, {range}) - Gets the appropriate language that contains {range} + Gets the appropriate language that contains {range} - Parameters: ~ - {range} A text range, see |LanguageTree:contains| - {self} + Parameters: ~ + {range} A text range, see |LanguageTree:contains| + {self} LanguageTree:parse({self}) *LanguageTree:parse()* - Parses all defined regions using a treesitter parser for the - language this tree represents. This will run the injection - query for this language to determine if any child languages - should be created. + Parses all defined regions using a treesitter parser for the language this + tree represents. This will run the injection query for this language to + determine if any child languages should be created. - Parameters: ~ - {self} + Parameters: ~ + {self} LanguageTree:register_cbs({self}, {cbs}) *LanguageTree:register_cbs()* - Registers callbacks for the parser. - - Parameters: ~ - {cbs} (table) An |nvim_buf_attach()|-like table argument - with the following keys : - • `on_bytes` : see |nvim_buf_attach()|, but this will be - called after the parsers callback. - • `on_changedtree` : a callback that will be - called every time the tree has syntactical - changes. It will only be passed one argument, - which is a table of the ranges (as node ranges) - that changed. - • `on_child_added` : emitted when a child is added - to the tree. - • `on_child_removed` : emitted when a child is - removed from the tree. - {self} + Registers callbacks for the parser. + + Parameters: ~ + {cbs} (table) An |nvim_buf_attach()|-like table argument with the + following keys : + • `on_bytes` : see |nvim_buf_attach()|, but this will be called after the parsers callback. + • `on_changedtree` : a callback that will be called every time + the tree has syntactical changes. It will only be passed one + argument, which is a table of the ranges (as node ranges) + that changed. + • `on_child_added` : emitted when a child is added to the + tree. + • `on_child_removed` : emitted when a child is removed from + the tree. + {self} LanguageTree:remove_child({self}, {lang}) *LanguageTree:remove_child()* - Removes a child language from this tree. + Removes a child language from this tree. - Parameters: ~ - {lang} The language to remove. - {self} + Parameters: ~ + {lang} The language to remove. + {self} *LanguageTree:set_included_regions()* LanguageTree:set_included_regions({self}, {regions}) - Sets the included regions that should be parsed by this - parser. A region is a set of nodes and/or ranges that will be - parsed in the same context. + Sets the included regions that should be parsed by this parser. A region + is a set of nodes and/or ranges that will be parsed in the same context. - For example, `{ { node1 }, { node2} }` is two separate - regions. This will be parsed by the parser in two different - contexts... thus resulting in two separate trees. + For example, `{ { node1 }, { node2} }` is two separate regions. This will + be parsed by the parser in two different contexts... thus resulting in two + separate trees. - `{ { node1, node2 } }` is a single region consisting of two - nodes. This will be parsed by the parser in a single - context... thus resulting in a single tree. + `{ { node1, node2 } }` is a single region consisting of two nodes. This + will be parsed by the parser in a single context... thus resulting in a + single tree. - This allows for embedded languages to be parsed together - across different nodes, which is useful for templating - languages like ERB and EJS. + This allows for embedded languages to be parsed together across different + nodes, which is useful for templating languages like ERB and EJS. - Note, this call invalidates the tree and requires it to be - parsed again. + Note, this call invalidates the tree and requires it to be parsed again. - Parameters: ~ - {regions} (table) list of regions this tree should manage - and parse. - {self} + Parameters: ~ + {regions} (table) list of regions this tree should manage and parse. + {self} LanguageTree:source({self}) *LanguageTree:source()* - Returns the source content of the language tree (bufnr or - string). + Returns the source content of the language tree (bufnr or string). - Parameters: ~ - {self} + Parameters: ~ + {self} LanguageTree:trees({self}) *LanguageTree:trees()* - Returns all trees this language tree contains. Does not - include child languages. + Returns all trees this language tree contains. Does not include child + languages. - Parameters: ~ - {self} + Parameters: ~ + {self} new({source}, {lang}, {opts}) *languagetree.new()* - Represents a single treesitter parser for a language. The - language can contain child languages with in its range, hence - the tree. - - Parameters: ~ - {source} Can be a bufnr or a string of text to - parse - {lang} The language this tree represents - {opts} Options table - {opts.injections} A table of language to injection query - strings. This is useful for overriding - the built-in runtime file searching for - the injection language query per - language. - - vim:tw=78:ts=8:ft=help:norl: + Represents a single treesitter parser for a language. The language can + contain child languages with in its range, hence the tree. + + Parameters: ~ + {source} Can be a bufnr or a string of text to parse + {lang} The language this tree represents + {opts} Options table + {opts.injections} A table of language to injection query strings. + This is useful for overriding the built-in runtime + file searching for the injection language query per + language. + + vim:tw=78:ts=8:sw=4:sts=4:et:ft=help:norl: diff --git a/runtime/doc/usr_41.txt b/runtime/doc/usr_41.txt index 008b9b4e58..0c907bfb68 100644 --- a/runtime/doc/usr_41.txt +++ b/runtime/doc/usr_41.txt @@ -202,9 +202,9 @@ message when it doesn't, append !: > :unlet! s:count -When a script finishes, the local variables used there will not be -automatically freed. The next time the script executes, it can still use the -old value. Example: > +When a script has been processed to the end, the local variables declared +there will not be deleted. Functions defined in the script can use them. +Example: :if !exists("s:call_count") : let s:call_count = 0 @@ -606,6 +606,7 @@ String manipulation: *string-functions* strtrans() translate a string to make it printable tolower() turn a string to lowercase toupper() turn a string to uppercase + charclass() class of a character match() position where a pattern matches in a string matchend() position where a pattern match ends in a string matchfuzzy() fuzzy matches a string in a list of strings @@ -619,6 +620,7 @@ String manipulation: *string-functions* strchars() length of a string in characters strwidth() size of string when displayed strdisplaywidth() size of string when displayed, deals with tabs + setcellwidths() set character cell width overrides substitute() substitute a pattern match with a string submatch() get a specific match in ":s" and substitute() strpart() get part of a string using byte index @@ -742,6 +744,7 @@ Cursor and mark position: *cursor-functions* *mark-functions* cursor() position the cursor at a line/column screencol() get screen column of the cursor screenrow() get screen row of the cursor + screenpos() screen row and col of a text character getcurpos() get position of the cursor getpos() get position of cursor, mark, etc. setpos() set position of cursor, mark, etc. @@ -851,9 +854,9 @@ Buffers, windows and the argument list: win_gotoid() go to window with ID win_id2tabwin() get tab and window nr from window ID win_id2win() get window nr from window ID - win_splitmove() move window to a split of another window win_move_separator() move window vertical separator win_move_statusline() move window status line + win_splitmove() move window to a split of another window getbufinfo() get a list with buffer information gettabinfo() get a list with tab page information getwininfo() get a list with window information diff --git a/runtime/doc/vim_diff.txt b/runtime/doc/vim_diff.txt index 27c953a460..76beaf9830 100644 --- a/runtime/doc/vim_diff.txt +++ b/runtime/doc/vim_diff.txt @@ -209,7 +209,7 @@ Commands: |:Man| is available by default, with many improvements such as completion |:sign-define| accepts a `numhl` argument, to highlight the line number |:match| can be invoked before highlight group is defined - |:source| works with Lua and anonymous (no file) scripts + |:source| works with Lua User commands can support |:command-preview| to show results as you type Events: @@ -271,7 +271,6 @@ Options: 'signcolumn' supports up to 9 dynamic/fixed columns 'statusline' supports unlimited alignment sections 'tabline' %@Func@foo%X can call any function on mouse-click - 'wildoptions' "pum" flag to use popupmenu for wildmode completion 'winblend' pseudo-transparency in floating windows |api-floatwin| 'winhighlight' window-local highlights @@ -373,6 +372,7 @@ Lua interface (|lua.txt|): Commands: |:doautocmd| does not warn about "No matching autocommands". + |:wincmd| accepts a count. Functions: |input()| and |inputdialog()| support for each other’s features (return on diff --git a/runtime/doc/windows.txt b/runtime/doc/windows.txt index 8062b9e28f..7355cec522 100644 --- a/runtime/doc/windows.txt +++ b/runtime/doc/windows.txt @@ -372,7 +372,7 @@ CTRL-W o *CTRL-W_o* *E445* CTRL-W CTRL-O *CTRL-W_CTRL-O* *:on* *:only* Make the current window the only one on the screen. All other windows are closed. For {count} see the `:quit` command - above |:count_quit|. + above |:count_quit|. When the 'hidden' option is set, all buffers in closed windows become hidden. @@ -442,6 +442,7 @@ position is set to keep the same Visual area selected. These commands can also be executed with ":wincmd": :[count]winc[md] {arg} +:winc[md] [count] {arg} Like executing CTRL-W [count] {arg}. Example: > :wincmd j < Moves to the window below the current one. |