diff options
author | ii14 <ii14@users.noreply.github.com> | 2022-08-11 14:25:48 +0200 |
---|---|---|
committer | ii14 <ii14@users.noreply.github.com> | 2022-08-11 14:25:48 +0200 |
commit | ea333badd24f691c753d8048f911d1db349bc2cd (patch) | |
tree | 65583dc9660f1ad49662ea14c3f987c2773a113e | |
parent | d2975d58cb3f5af924398e8a45205309d5a21796 (diff) | |
download | rneovim-ea333badd24f691c753d8048f911d1db349bc2cd.tar.gz rneovim-ea333badd24f691c753d8048f911d1db349bc2cd.tar.bz2 rneovim-ea333badd24f691c753d8048f911d1db349bc2cd.zip |
docs: regenerate
-rw-r--r-- | runtime/doc/api.txt | 4656 | ||||
-rw-r--r-- | runtime/doc/diagnostic.txt | 930 | ||||
-rw-r--r-- | runtime/doc/lsp.txt | 2565 | ||||
-rw-r--r-- | runtime/doc/lua.txt | 2101 | ||||
-rw-r--r-- | runtime/doc/treesitter.txt | 794 |
5 files changed, 5244 insertions, 5802 deletions
diff --git a/runtime/doc/api.txt b/runtime/doc/api.txt index be42b7c14e..c76a8271e0 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,955 @@ 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. + 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. + 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. + 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| + Attributes: ~ + |api-fast| - Parameters: ~ - {ns_id} the namespace to activate + Parameters: ~ + {ns_id} the namespace to activate 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_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 +1494,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 +1652,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 +1984,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 +2413,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 +2518,684 @@ 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. 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_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 +3208,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/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/lsp.txt b/runtime/doc/lsp.txt index 94726ceaab..62b1dceb10 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. @@ -101,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|. @@ -163,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* @@ -204,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* @@ -292,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 @@ -357,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: @@ -403,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* @@ -424,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* @@ -464,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* @@ -476,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* @@ -516,317 +516,286 @@ 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 + 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 + 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 + Return: ~ + true if any client returns true; false otherwise *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) 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. + Sends an async request for all active clients attached to the buffer. + + 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. *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({ @@ -836,249 +805,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|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. + {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} ============================================================================== @@ -1086,471 +1014,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 + |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 + |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 + |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 + |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 + |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 + |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 + |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()| ============================================================================== @@ -1558,591 +1447,543 @@ 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} 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 *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, 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|. ============================================================================== @@ -2150,23 +1991,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 ============================================================================== @@ -2174,19 +2012,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 5f6a1e4d73..26d154ae65 100644 --- a/runtime/doc/lua.txt +++ b/runtime/doc/lua.txt @@ -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 % < ============================================================================== @@ -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,835 @@ 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) < 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()| and |nvim_get_option()|. - 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 than |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 < vim.bo *vim.bo* - Get or set buffer-scoped |local-options|. Invalid key is an error. + 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()|. + This is a wrapper around |nvim_buf_set_option()| and + |nvim_buf_get_option()|. - Example: > - vim.bo.buflisted = true - print(vim.bo.comments) + Example: > + vim.bo.buflisted = true + print(vim.bo.comments) < vim.wo *vim.wo* - Get or set window-scoped |local-options|. Invalid key is an error. + 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()|. + This is a wrapper around |nvim_win_set_option()| and + |nvim_win_get_option()|. - Example: > - vim.wo.cursorcolumn = true - print(vim.wo.foldmarker) + Example: > + vim.wo.cursorcolumn = true + print(vim.wo.foldmarker) < ============================================================================== 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 |lua-patterns|. + 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 +2081,214 @@ 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| 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()| ============================================================================== 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/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: |