Movatterモバイル変換


[0]ホーム

URL:


Api

Nvim:help pages,generated fromsource using thetree-sitter-vimdoc parser.


Nvim APIapi
Nvim exposes a powerful API that can be used by plugins and external processesviaRPC,Lua and Vimscript (eval-api).
Applications can also embed libnvim to work with the C API directly.

API Usageapi-rpcRPCrpc

msgpack-rpc
RPC is the main way to control Nvim programmatically. Nvim implements theMessagePack-RPC protocol with these extra (out-of-spec) constraints:
1. Responses must be given in reverse order of requests (like "unwinding a stack").2. Nvim processes all messages (requests and notifications) in the order they are received.
MessagePack-RPC specification:https://github.com/msgpack-rpc/msgpack-rpc/blob/master/spec.mdhttps://github.com/msgpack/msgpack/blob/0b8f5ac/spec.md
Many clients use the API: user interfaces (GUIs), remote plugins, scripts like"nvr" (https://github.com/mhinz/neovim-remote). Even Nvim itself can controlother Nvim instances. API clients can:
Call any API function
Listen for events
Receive remote calls from Nvim
The RPC API is like a more powerful version of Vim's "clientserver" feature.

CONNECTINGrpc-connecting

Seechannel-intro for various ways to open a channel. Channel-openingfunctions take anrpc key in the options dict. RPC channels can also beopened by other processes connecting to TCP/IP sockets or named pipes listenedto by Nvim.
Nvim creates a default RPC socket atstartup, given byv:servername. Tostart with a TCP/IP socket instead, use--listen with a TCP-style address:
nvim --listen 127.0.0.1:6666
More endpoints can be started withserverstart().
Note that localhost TCP sockets are generally less secure than named pipes,and can lead to vulnerabilities like remote code execution.
Connecting to the socket is the easiest way a programmer can test the API,which can be done through any msgpack-rpc client library or full-featuredapi-client. Here's a Ruby script that prints "hello world!" in the currentNvim instance:
#!/usr/bin/env ruby# Requires msgpack-rpc: gem install msgpack-rpc## To run this script, execute it from a running Nvim instance (notice the# trailing '&' which is required since Nvim won't process events while# running a blocking command):##   :!./hello.rb &## Or from another shell by setting NVIM_LISTEN_ADDRESS:# $ NVIM_LISTEN_ADDRESS=[address] ./hello.rbrequire 'msgpack/rpc'require 'msgpack/rpc/transport/unix'nvim = MessagePack::RPC::Client.new(MessagePack::RPC::UNIXTransport.new, ENV['NVIM_LISTEN_ADDRESS'])result = nvim.call(:nvim_command, 'echo "hello world!"')
A better way is to use the Python REPL with the "pynvim" package, where APIfunctions can be called interactively:
>>> from pynvim import attach>>> nvim = attach('socket', path='[address]')>>> nvim.command('echo "hello world!"')
You can also embed Nvim viajobstart(), and communicate usingrpcrequest()andrpcnotify():
let nvim = jobstart(['nvim', '--embed'], {'rpc': v:true})echo rpcrequest(nvim, 'nvim_eval', '"Hello " . "world!"')call jobstop(nvim)

API Definitionsapi-definitions

api-types
The Nvim C API defines custom types for all function parameters. Some are justtypedefs around C99 standard types, others are Nvim-defined data structures.
Basic types
API Type                              C type------------------------------------------------------------------------NilBoolean                               boolInteger (signed 64-bit integer)       int64_tFloat (IEEE 754 double precision)     doubleString                                {char* data, size_t size} structArray                                 kvecDict (msgpack: map)                   kvecObject                                any of the above
Note:
Empty Array is accepted as a valid Dictionary parameter.
Functions cannot cross RPC boundaries. But API functions (e.g.nvim_create_autocmd()) may support Lua function parameters for non-RPC invocations.
Special types (msgpack EXT)
These are integer typedefs discriminated as separate Object subtypes. They can be treated as opaque integers, but are mutually incompatible: Buffer may be passed as an integer but not as Window or Tabpage.
The EXT object data is the (integer) object handle. The EXT type codes given in theapi-metadatatypes key are stable: they will not change and are thus forward-compatible.
EXT Type      C type                                  Data------------------------------------------------------------------------Buffer        enum value kObjectTypeBuffer            |bufnr()|Window        enum value kObjectTypeWindow            |window-ID|Tabpage       enum value kObjectTypeTabpage           internal handle
api-indexing
Most of the API uses 0-based indices, and ranges are end-exclusive. For theend of a range, -1 denotes the last line/column.
Exception: the following API functions use "mark-like" indexing (1-basedlines, 0-based columns):
nvim_get_mark()
nvim_buf_get_mark()
nvim_buf_set_mark()
nvim_win_get_cursor()
nvim_win_set_cursor()
Exception: the following API functions useextmarks indexing (0-basedindices, end-inclusive):
nvim_buf_del_extmark()
nvim_buf_get_extmark_by_id()
nvim_buf_get_extmarks()
nvim_buf_set_extmark()
api-fast
Most API functions are "deferred": they are queued on the main loop andprocessed sequentially with normal input. So if the editor is waiting foruser input in a "modal" fashion (e.g. thehit-enter-prompt), the requestwill block. Non-deferred (fast) functions such asnvim_get_mode() andnvim_input() are served immediately (i.e. without waiting in the inputqueue). Lua code can usevim.in_fast_event() to detect a fast context.

API metadataapi-metadata

The Nvim C API is automatically exposed to RPC by the build system, whichparses headers in src/nvim/api/* and generates dispatch-functions mapping RPCAPI method names to public C API functions, converting/validating argumentsand return values.
Nvim exposes its API metadata as a Dictionary with these items:
version Nvim version, API level/compatibility
version.api_level API version integerapi-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, containingapi-types info describing the return value and parameters.
ui_eventsUI event signatures
ui_options Supportedui-options
{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 thefunctions map:
Container types may be decorated with type/size constraints, e.g. ArrayOf(Buffer) or ArrayOf(Integer, 2).
Functions considered to be methods that operate on instances of Nvim special types (msgpack EXT) have the "method=true" flag. The receiver type is that of the first argument. Method names are prefixed withnvim_ plus a type name, e.g.nvim_buf_get_lines is theget_lines method of a Buffer instance.dev-api
Global functions have the "method=false" flag and are prefixed with justnvim_, e.g.nvim_list_bufs.
api-mapping
External programs (clients) can use the metadata to discover the API, usingany of these approaches:
1. Connect to a running Nvim instance and callnvim_get_api_info() via msgpack-RPC. This is best for clients written in dynamic languages which can define functions at runtime.
2. Start Nvim with--api-info. Useful for statically-compiled clients. Example (requires Python "pyyaml" and "msgpack-python" modules):
nvim --api-info | python -c 'import msgpack, sys, yaml; yaml.dump(msgpack.unpackb(sys.stdin.buffer.read()), sys.stdout)'
3. Use theapi_info() Vimscript function.
:lua vim.print(vim.fn.api_info())
Example usingfilter() to exclude non-deprecated API functions:
:new|put =map(filter(api_info().functions, '!has_key(v:val,''deprecated_since'')'), 'v:val.name')

API contractapi-contract

The Nvim API is composed of functions and events.
Clients call functions like those described atapi-global.
Clients can subscribe toui-events,api-buffer-updates, etc.
API function names are prefixed with "nvim_".
API event names are prefixed with "nvim_" and suffixed with "_event".
As Nvim evolves the API may change in compliance with this CONTRACT:
New functions and events may be added.
Any such extensions are OPTIONAL: old clients may ignore them.
New functions MAY CHANGE before release. Clients can dynamically checkapi_prerelease,api-metadata.
Function signatures will NOT CHANGE after release, except as follows:
Map/list parameters/results may be EXTENDED (new fields may be added).
Such new fields are OPTIONAL: old clients MAY ignore them.
Existing fields will not be removed.
Return type MAY CHANGE from void to non-void. Old clients MAY ignore the new return value.
An optionalopts parameter may be ADDED.
Optional parameters may be ADDED following anopts parameter.
Event parameters will not be removed or reordered (after release).
Events may be EXTENDED: new parameters may be added.
Deprecated functions will not be removed until Nvim 2.0.
"Private" interfaces are NOT covered by this contract:
Undocumented (not in :help) functions or events of any kind
nvim__x ("double underscore") functions
The idea is "versionless evolution", in the words of Rich Hickey:
Relaxing a requirement should be a compatible change.
Strengthening a promise should be a compatible change.

Global eventsapi-global-events

When a client invokes an API request as an async notification, it is notpossible for Nvim to send an error response. Instead, in case of error, thefollowing notification will be sent to the client:
nvim_error_event
nvim_error_event[{type},{message}]
{type} is a numeric id as defined byapi_info().error_types, and{message} isa string with the error message.

Buffer update eventsapi-buffer-updates

API clients can "attach" to Nvim buffers to subscribe to buffer update events.This is similar toTextChanged but more powerful and granular.
Callnvim_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{changedtick} isv: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)
{changedtick} value ofb:changedtick for the buffer. If you send an API command back to nvim you can check the value ofb: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.
{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.
{more} boolean, true for a "multipart" change notification: the current change was chunked into multiplenvim_buf_lines_event notifications (e.g. because it was too big).
nvim_buf_changedtick_event[{buf},{changedtick}]nvim_buf_changedtick_event
Whenb:changedtick was incremented but no text was changed. Relevant for undo/redo.
Properties:
{buf} API buffer handle (buffer number){changedtick} new value ofb:changedtick for the buffer
nvim_buf_detach_event[{buf}]nvim_buf_detach_event
When buffer is detached (i.e. updates are disabled). Triggered explicitly bynvim_buf_detach() or implicitly in these cases:
Buffer wasabandoned 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)
EXAMPLE
Callingnvim_buf_attach() with send_buffer=true on an empty buffer, emits:
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]
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]
User moves to line 3 and deletes 20 lines using "20dd", emits:
nvim_buf_lines_event[{buf}, {changedtick}, 2, 22, [], v:false]
User selects lines 3-5 usinglinewise-visual mode and then types "p" topaste 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]
User reloads the buffer with ":edit", emits:
nvim_buf_detach_event[{buf}]
LUA
api-buffer-updates-lua
In-process Lua plugins can receive buffer updates in the form of Luacallbacks. These callbacks are called frequently in various contexts;textlock prevents changing buffer contents and window layout (usevim.schedule() to defer such operations to the main loop instead).Moving the cursor is allowed, but it is restored afterwards.
nvim_buf_attach() will take keyword args for the callbacks. "on_lines" willreceive parameters ("lines",{buf},{changedtick},{firstline},{lastline},{new_lastline},{old_byte_size} [,{old_utf32_size},{old_utf16_size}]).Unlike remote channel events the text contents are not passed. The new text canbe accessed inside the callback as
vim.api.nvim_buf_get_lines(buf, firstline, new_lastline, true)
{old_byte_size} is the total size of the replaced region{firstline} to{lastline} in bytes, including the final newline after{lastline}. ifutf_sizes is set to true innvim_buf_attach() keyword args, then theUTF-32 and UTF-16 sizes of the deleted region is also passed as additionalarguments{old_utf32_size} and{old_utf16_size}.
"on_changedtick" is invoked whenb:changedtick was incremented but no textwas changed. The parameters received are ("changedtick",{buf},{changedtick}).
api-lua-detach
In-process Lua callbacks can detach by returningtrue. This will detach allcallbacks attached with the samenvim_buf_attach() call.

Buffer highlightingapi-highlights

Nvim allows plugins to add position-based highlights to buffers. This issimilar tomatchaddpos() but with some key differences. The added highlightsare associated with a buffer and adapts to line insertions and deletions,similar to signs. It is also possible to manage a set of highlights as a groupand delete or replace all at once.
The intended use case are linter or semantic highlighter plugins that monitora buffer for changes, and in the background compute highlights to the buffer.Another use case are plugins that show output in an append-only buffer, andwant to add highlights to the outputs. Highlight data cannot be preservedon writing and loading a buffer to file, nor in undo/redo cycles.
Highlights are registered using thenvim_buf_set_extmark() function, whichadds highlights asextmarks. If highlights need to be tracked or manipulatedafter adding them, the returnedextmark id can be used.
-- create the highlight through an extmarkextid = vim.api.nvim_buf_set_extmark(buf, ns_id, line, col_start, {end_col = col_end, hl_group = hl_group})-- example: modify the extmark's highlight groupvim.api.nvim_buf_set_extmark(buf, ns_id, line, col_start, {end_col = col_end, hl_group = NEW_HL_GROUP, id = extid})-- example: change the highlight's positionvim.api.nvim_buf_set_extmark(buf, ns_id, NEW_LINE, col_start, {end_col = col_end, hl_group = NEW_HL_GROUP, id = extid})
See alsovim.hl.range().

Floating windowsapi-floatwinfloating-windows

Floating windows ("floats") are displayed on top of normal windows. This isuseful to implement simple widgets, such as tooltips displayed next to thecursor. Floats are fully functional windows supporting user editing, commonapi-window calls, and most window options (except'statusline').
Two ways to create a floating window:
nvim_open_win() creates a new window (needs a buffer, seenvim_create_buf())
nvim_win_set_config() reconfigures a normal window into a float
To close it usenvim_win_close() or a command such as:close.
To check whether a window is floating, check whether therelative option inits config is non-empty:
if vim.api.nvim_win_get_config(window_id).relative ~= '' then  -- window with this window_id is floatingend
Buffer text can be highlighted by typical mechanisms (syntax highlighting,api-highlights). Thehl-NormalFloat group highlights normal text;'winhighlight' can be used as usual to override groups locally. Floats inheritoptions from the current window; specifystyle=minimal innvim_open_win()to disable various visual features such as the'number' column.
Other highlight groups specific to floating windows:
hl-FloatBorder for window's border
hl-FloatTitle for window's title
hl-FloatFooter for window's footer
Currently, floating windows don't support some widgets like scrollbar.
The output of:mksession does not include commands for restoring floatingwindows.
Example: create a float with scratch buffer:
let buf = nvim_create_buf(v:false, v:true)call nvim_buf_set_lines(buf, 0, -1, v:true, ["test", "text"])let opts = {'relative': 'cursor', 'width': 10, 'height': 2, 'col': 0,    \ 'row': 1, 'anchor': 'NW', 'style': 'minimal'}let win = nvim_open_win(buf, 0, opts)" optional: change highlight, otherwise Pmenu is usedcall nvim_set_option_value('winhl', 'Normal:MyHighlight', {'win': win})

Extended marksapi-extended-marksextmarksextmark

Extended marks (extmarks) represent buffer annotations that track text changesin the buffer. They can represent cursors, folds, misspelled words, anythingthat needs to track a logical location in the buffer over time.api-indexing
Extmark position works like a "vertical bar" cursor: it exists betweencharacters. Thus, the maximum extmark index on a line is 1 more than thecharacter index:
 f o o b a r      line contents 0 1 2 3 4 5      character positions (0-based)0 1 2 3 4 5 6     extmark positions (0-based)
Extmarks have "forward gravity": if you place the cursor directly on anextmark position and enter some text, the extmark migrates forward.
f o o|b a r      line (| = cursor)     3           extmarkf o o z|b a r    line (| = cursor)       4         extmark (after typing "z")
If an extmark is on the last index of a line and you input a newline at thatpoint, the extmark will accordingly migrate to the next line:
f o o z b a r|   line (| = cursor)             7   extmarkf o o z b a r    first line                 extmarks (none present)|                second line (| = cursor)0                extmark (after typing <CR>)
Example:
Let's set an extmark at the first row (row=0) and third column (column=2).api-indexing Passing id=0 creates a new mark and returns the id:
  01 23456780 ex|ample..    ^ extmark position
let g:mark_ns = nvim_create_namespace('myplugin')let g:mark_id = nvim_buf_set_extmark(0, g:mark_ns, 0, 2, {})
We can get the mark by its id:
echo nvim_buf_get_extmark_by_id(0, g:mark_ns, g:mark_id, {})" => [0, 2]
We can get all marks in a buffer bynamespace (or by a range):
echo nvim_buf_get_extmarks(0, g:mark_ns, 0, -1, {})" => [[1, 0, 2]]
Deleting all surrounding text does NOT remove an extmark! To remove extmarksusenvim_buf_del_extmark(). Deleting "x" in our example:
  0 123456780 e|ample..   ^ extmark position
echo nvim_buf_get_extmark_by_id(0, g:mark_ns, g:mark_id, {})" => [0, 1]
Note: Extmark "gravity" decides how it will shift after a text edit. Seenvim_buf_set_extmark()
Namespaces allow any plugin to manage only its own extmarks, ignoring thosecreated by another plugin.
Extmark positions changed by an edit will be restored on undo/redo. Creatingand deleting extmarks is not a buffer change, thus new undo states are notcreated for extmark changes.

Global Functionsapi-global

nvim_chan_send({chan},{data})nvim_chan_send()
Send data to channelid. For a job, it writes it to the stdin of the process. For the stdio channelchannel-stdio, it writes to Nvim's stdout. For an internal terminal instance (nvim_open_term()) it writes directly to terminal output. Seechannel-bytes for more information.
This function writes raw data, not RPC messages. If the channel was created withrpc=true then the channel expects RPC messages, usevim.rpcnotify() andvim.rpcrequest() instead.
Attributes:
RPC only Luavim.api only Since: 0.5.0
Parameters:
{chan} (integer) id of the channel
{data} (string) data to write. 8-bit clean: can contain NUL bytes.
nvim_create_buf({listed},{scratch})nvim_create_buf()
Creates a new, empty, unnamed buffer.
Attributes:
Since: 0.4.0
Parameters:
{listed} (boolean) Sets'buflisted'
{scratch} (boolean) Creates a "throwaway"scratch-buffer for temporary work (always'nomodified'). Also sets'nomodeline' on the buffer.
Return:
(integer) Buffer id, or 0 on error
See also:
buf_open_scratch
nvim_del_current_line()nvim_del_current_line()
Deletes the current line.
Attributes:
not allowed whentextlock is active Since: 0.1.0
nvim_del_keymap({mode},{lhs})nvim_del_keymap()
Unmaps a globalmapping for the given mode.
To unmap a buffer-local mapping, usenvim_buf_del_keymap().
Attributes:
Since: 0.4.0
Parameters:
{mode} (string)
{lhs} (string)
See also:
nvim_set_keymap()
nvim_del_mark({name})nvim_del_mark()
Deletes an uppercase/file named mark. Seemark-motions.
Note:
Lowercase name (or other buffer-local mark) is an error.
Attributes:
Since: 0.6.0
Parameters:
{name} (string) Mark name
Return:
(boolean) true if the mark was deleted, else false.
See also:
nvim_buf_del_mark()
nvim_get_mark()
nvim_del_var({name})nvim_del_var()
Removes a global (g:) variable.
Attributes:
Since: 0.1.0
Parameters:
{name} (string) Variable name
nvim_echo({chunks},{history},{opts})nvim_echo()
Prints a message given by a list of[text, hl_group] "chunks".
Example:
vim.api.nvim_echo({ { 'chunk1-line1\nchunk1-line2\n' }, { 'chunk2-line1' } }, true, {})
Attributes:
Since: 0.5.0
Parameters:
{chunks} ([string, integer|string?][]) List of[text, hl_group] pairs, where each is atext string highlighted by the (optional) name or IDhl_group.
{history} (boolean) if true, add tomessage-history.
{opts} (vim.api.keyset.echo_opts) Optional parameters.
err: Treat the message like:echoerr. Setshl_group tohl-ErrorMsg by default.
kind: Set theui-messages kind with which this message will be emitted.
verbose: Message is controlled by the'verbose' option. Nvim invoked with-V3log will write the message to the "log" file instead of standard output.
nvim_eval_statusline({str},{opts})nvim_eval_statusline()
Evaluates statusline string.
Attributes:
api-fast Since: 0.6.0
Parameters:
{str} (string) Statusline string (see'statusline').
{opts} (vim.api.keyset.eval_statusline) 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}.
use_statuscol_lnum: (number) Evaluate statuscolumn for this line number instead of statusline.
Return:
(vim.api.keyset.eval_statusline_ret) Dict 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 aDict with these keys:
start: (number) Byte index (0-based) of first character that uses the highlight.
group: (string) Deprecated. Usegroups instead.
groups: (array) Names of stacked highlight groups (highest priority last).
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.
Only statements are executed. To evaluate an expression, prefix it withreturn: return my_function(...)
Attributes:
RPC only Since: 0.5.0
Parameters:
{code} (string) Lua code to execute
{args} (any[]) Arguments to the code
Return:
(any) 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 bymode flags. This is a blocking call, unlikenvim_input().
On execution error: does not fail, but updates v:errmsg.
To input sequences like<C-o> usenvim_replace_termcodes() (typically with escape_ks=false) to replacekeycodes, 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)
Attributes:
Since: 0.1.0
Parameters:
{keys} (string) to be typed
{mode} (string) behavior flags, seefeedkeys()
{escape_ks} (boolean) If true, escape K_SPECIAL bytes inkeys. This should be false if you already usednvim_replace_termcodes(), and true otherwise.
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 theapi-metadata map (Dict).
Attributes:
api-fastRPC only Since: 0.1.0
Return:
([any, any]) 2-tuple[{channel-id}, {api-metadata}]
nvim_get_chan_info({chan})nvim_get_chan_info()
Gets information about a channel.
Seenvim_list_uis() for an example of how to get channel info.
Attributes:
Since: 0.3.0
Parameters:
{chan} (integer) channel_id, or 0 for current channel
Return:
(table<string,any>) Channel info dict 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 unknown, the key will still be present if a pty is used (e.g. for conpty on Windows).
"buffer" (optional) Buffer connected toterminal instance.
"client" (optional) Info about the peer (client on the other end of the channel), as set bynvim_set_client_info().
nvim_get_color_by_name({name})nvim_get_color_by_name()
Returns the 24-bit RGB value of anvim_get_color_map() color name or "#rrggbb" hexadecimal string.
Example:
:echo nvim_get_color_by_name("Pink"):echo nvim_get_color_by_name("#cbcbcb")
Attributes:
Since: 0.1.0
Parameters:
{name} (string) Color name or "#rrggbb" string
Return:
(integer) 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.
Keys are color names (e.g. "Aqua") and values are 24-bit RGB color values (e.g. 65535).
Attributes:
Since: 0.1.0
Return:
(table<string,integer>) Map of color names and RGB values.
nvim_get_context({opts})nvim_get_context()
Gets a map of the current editor state.
Attributes:
Since: 0.4.0
Parameters:
{opts} (vim.api.keyset.context) Optional parameters.
types: List ofcontext-types ("regs", "jumps", "bufs", "gvars", …) to gather, or empty for "all".
Return:
(table<string,any>) map of globalcontext.
nvim_get_current_buf()nvim_get_current_buf()
Gets the current buffer.
Attributes:
Since: 0.1.0
Return:
(integer) Buffer id
nvim_get_current_line()nvim_get_current_line()
Gets the current line.
Attributes:
Since: 0.1.0
Return:
(string) Current line string
nvim_get_current_tabpage()nvim_get_current_tabpage()
Gets the current tabpage.
Attributes:
Since: 0.1.0
Return:
(integer)tab-ID
nvim_get_current_win()nvim_get_current_win()
Gets the current window.
Attributes:
Since: 0.1.0
Return:
(integer)window-ID
nvim_get_hl({ns_id},{opts})nvim_get_hl()
Gets all or specific highlight groups in a namespace.
Note:
When thelink attribute is defined in the highlight definition map, other attributes will not be taking effect (see:hi-link).
Attributes:
Since: 0.9.0
Parameters:
{ns_id} (integer) Get highlight groups for namespace ns_idnvim_get_namespaces(). Use 0 to get global highlight groups:highlight.
{opts} (vim.api.keyset.get_highlight) Options dict:
name: (string) Get a highlight definition by name.
id: (integer) Get a highlight definition by id.
link: (boolean, default true) Show linked group name instead of effective definition:hi-link.
create: (boolean, default true) When highlight group doesn't exist create it.
Return:
(vim.api.keyset.get_hl_info) Highlight groups as a map from group name to a highlight definition map as innvim_set_hl(), or only a single highlight definition map if requested by name or id.
nvim_get_hl_id_by_name({name})nvim_get_hl_id_by_name()
Gets a highlight group by name
similar tohlID(), but allocates a new ID if not present.
Attributes:
Since: 0.5.0
Parameters:
{name} (string)
Return:
(integer)
nvim_get_hl_ns({opts})nvim_get_hl_ns()
Gets the active highlight namespace.
Attributes:
Since: 0.10.0
Parameters:
{opts} (vim.api.keyset.get_ns) Optional parameters
winid: (number)window-ID for retrieving a window's highlight namespace. A value of -1 is returned whennvim_win_set_hl_ns() has not been called for the window (or was called with a namespace of -1).
Return:
(integer) Namespace id, or -1
nvim_get_keymap({mode})nvim_get_keymap()
Gets a list of global (non-buffer-local)mapping definitions.
Attributes:
Since: 0.2.1
Parameters:
{mode} (string) Mode short-name ("n", "i", "v", ...)
Return:
(vim.api.keyset.get_keymap[]) Array ofmaparg()-like dictionaries describing mappings. The "buffer" key is always zero.
nvim_get_mark({name},{opts})nvim_get_mark()
Returns a(row, col, buffer, buffername) tuple representing the position of the uppercase/file named mark. "End of line" column position is returned asv:maxcol (big number). Seemark-motions.
Marks are (1,0)-indexed.api-indexing
Note:
Lowercase name (or other buffer-local mark) is an error.
Attributes:
Since: 0.6.0
Parameters:
{name} (string) Mark name
{opts} (vim.api.keyset.empty) Optional parameters. Reserved for future use.
Return:
([integer, integer, integer, string]) 4-tuple (row, col, buffer, buffername), (0, 0, 0, '') if the mark is not set.
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.
Attributes:
api-fast Since: 0.2.0
Return:
(vim.api.keyset.get_mode) Dict { "mode": String, "blocking": Boolean }
nvim_get_proc({pid})nvim_get_proc()
Gets info describing processpid.
Attributes:
Since: 0.3.0
Parameters:
{pid} (integer)
Return:
(any) Map of process properties, or NIL if process not found.
nvim_get_proc_children({pid})nvim_get_proc_children()
Gets the immediate children of processpid.
Attributes:
Since: 0.3.0
Parameters:
{pid} (integer)
Return:
(any[]) Array of child process ids, empty if process not found.
nvim_get_runtime_file({name},{all})nvim_get_runtime_file()
Finds files in runtime directories, in'runtimepath' order.
"name" can contain wildcards. For examplenvim_get_runtime_file("colors/*.{vim,lua}", 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.
Attributes:
api-fast Since: 0.5.0
Parameters:
{name} (string) pattern of files to search for
{all} (boolean) whether to return all matches or only the first
Return:
(string[]) list of absolute paths to the found files
nvim_get_var({name})nvim_get_var()
Gets a global (g:) variable.
Attributes:
Since: 0.1.0
Parameters:
{name} (string) Variable name
Return:
(any) Variable value
nvim_get_vvar({name})nvim_get_vvar()
Gets a v: variable.
Attributes:
Since: 0.1.0
Parameters:
{name} (string) Variable name
Return:
(any) Variable value
nvim_input({keys})nvim_input()
Queues raw user-input. Unlikenvim_feedkeys(), this uses a low-level input buffer and the call is non-blocking (input is processed asynchronously by the eventloop).
To input blocks of text,nvim_paste() is much faster and should be preferred.
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>.
For mouse events usenvim_input_mouse(). The pseudokey form<LeftMouse><col,row> is deprecated sinceapi-level 6.
Attributes:
api-fast Since: 0.1.0
Parameters:
{keys} (string) to be typed
Return:
(integer) 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>) ofnvim_input() has the same limitation.
Attributes:
api-fast Since: 0.4.0
Parameters:
{button} (string) Mouse button: one of "left", "right", "middle", "wheel", "move", "x1", "x2".
{action} (string) For ordinary buttons, one of "press", "drag", "release". For the wheel, one of "up", "down", "left", "right". Ignored for "move".
{modifier} (string) 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} (integer) Grid number if the client usesui-multigrid, else 0.
{row} (integer) Mouse row-position (zero-based, like redraw events)
{col} (integer) Mouse column-position (zero-based, like redraw events)
nvim_list_bufs()nvim_list_bufs()
Gets the current list of buffers.
Includes unlisted (unloaded/deleted) buffers, like:ls!. Usenvim_buf_is_loaded() to check if a buffer is loaded.
Attributes:
Since: 0.1.0
Return:
(integer[]) List of buffer ids
nvim_list_chans()nvim_list_chans()
Get information about all open channels.
Attributes:
Since: 0.3.0
Return:
(table<string,any>[]) Array of Dictionaries, each describing a channel with the format specified atnvim_get_chan_info().
nvim_list_runtime_paths()nvim_list_runtime_paths()
Gets the paths contained inruntime-search-path.
Attributes:
Since: 0.1.0
Return:
(string[]) List of paths
nvim_list_tabpages()nvim_list_tabpages()
Gets the current list oftab-IDs.
Attributes:
Since: 0.1.0
Return:
(integer[]) List oftab-IDs
nvim_list_uis()nvim_list_uis()
Gets a list of dictionaries representing attached UIs.
Example: The Nvim builtinTUI sets its channel info as described instartup-tui. In particular, it setsclient.name to "nvim-tui". So you can check if the TUI is running by inspecting the client name of each UI:
vim.print(vim.api.nvim_get_chan_info(vim.api.nvim_list_uis()[1].chan).client.name)
Attributes:
Since: 0.3.0
Return:
(table<string,any>[]) 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 impliescterm-colors)
"ext_..." Requested UI extensions, seeui-option
"chan"channel-id of remote UI
nvim_list_wins()nvim_list_wins()
Gets the current list of allwindow-IDs in all tabpages.
Attributes:
Since: 0.1.0
Return:
(integer[]) List ofwindow-IDs
nvim_load_context({dict})nvim_load_context()
Sets the current editor state from the givencontext map.
Attributes:
Since: 0.4.0
Parameters:
{dict} (table<string,any>)Context map.
Return:
(any)
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 sent on the channel will be echoed directly by the terminal. This is useful to display ANSI terminal sequences returned as part of an 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 usingnvim_create_buf(), then display it usingnvim_open_win(), and then call this function. Thennvim_chan_send() can be called immediately to process sequences in a virtual terminal having the intended size.
Example: thisTermHl command can be used to display and highlight raw ANSI termcodes, so you can use Nvim as a "scrollback pager" (for terminals like kitty):ansi-colorizeterminal-scrollback-pager
vim.api.nvim_create_user_command('TermHl', function()  vim.api.nvim_open_term(0, {})end, { desc = 'Highlights ANSI termcodes in curbuf' })
Attributes:
not allowed whentextlock is active Since: 0.5.0
Parameters:
{buffer} (integer) Buffer to use. Buffer contents (if any) will be written to the PTY.
{opts} (vim.api.keyset.open_term) 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 callnvim_chan_send() directly in the callback however.["input", term, bufnr, data]
force_crlf: (boolean, default true) Convert "\n" to "\r\n".
Return:
(integer) Channel id, or 0 on error
nvim_paste({data},{crlf},{phase})nvim_paste()
Pastes at cursor (in any mode), and sets "redo" so dot (.) will repeat the input. UIs call this to implement "paste", but it's also intended for use by scripts to input large, dot-repeatable blocks of text (as opposed tonvim_input() which is subject to mappings/events and is thus much slower).
Invokes thevim.paste() handler, which handles each mode appropriately.
Errors ('nomodifiable',vim.paste() failure, …) are reflected inerr but do not affect the return value (which is strictly decided byvim.paste()). On error or cancel, subsequent calls are ignored ("drained") until the next paste is initiated (phase 1 or -1).
Useful in mappings and scripts to insert multiline text. Example:
vim.keymap.set('n', 'x', function()  vim.api.nvim_paste([[    line1    line2    line3  ]], false, -1)end, { buffer = true })
Attributes:
not allowed whentextlock is active Since: 0.4.0
Parameters:
{data} (string) Multiline input. Lines break at LF ("\n"). May be binary (containing NUL bytes).
{crlf} (boolean) Also break lines at CR and CRLF.
{phase} (integer) -1: paste in a single call (i.e. without streaming). To "stream" a paste, callnvim_paste sequentially with thesephase values:
1: starts the paste (exactly once)
2: continues the paste (zero or more times)
3: ends the paste (exactly once)
Return:
(boolean)
true: Client may continue pasting.
false: Client should cancel the paste.
nvim_put({lines},{type},{after},{follow})nvim_put()
Puts text at cursor, in any mode. For dot-repeatable input, usenvim_paste().
Compare:put andp which are always linewise.
Attributes:
not allowed whentextlock is active Since: 0.4.0
Parameters:
{lines} (string[])readfile()-style list of lines.channel-lines
{type} (string) Edit behavior: anygetregtype() result, or:
"b"blockwise-visual mode (may include width, e.g. "b3")
"c"charwise mode
"l"linewise mode
"" guess by contents, seesetreg()
{after} (boolean) If true insert after cursor (likep), or before (likeP).
{follow} (boolean) If true place cursor at end of inserted text.
nvim_replace_termcodes()
nvim_replace_termcodes({str},{from_part},{do_lt},{special}) Replaces terminal codes andkeycodes (<CR>,<Esc>, ...) in a string with the internal representation.
Attributes:
Since: 0.1.0
Parameters:
{str} (string) String to be converted.
{from_part} (boolean) Legacy Vim parameter. Usually true.
{do_lt} (boolean) Also translate<lt>. Ignored ifspecial is false.
{special} (boolean) Replacekeycodes, e.g.<CR> becomes a "\r" char.
Return:
(string)
See also:
replace_termcodes
cpoptions
nvim_select_popupmenu_item()
nvim_select_popupmenu_item({item},{insert},{finish},{opts}) Selects an item in the completion popup menu.
If neitherins-completion norcmdline-completion popup menu is active this API call is silently ignored. Useful for an external UI usingui-popupmenu to control the popup menu with the mouse. Can also be used in a mapping; use<Cmd>:map-cmd or a Lua mapping to ensure the mapping doesn't end completion mode.
Attributes:
Since: 0.4.0
Parameters:
{item} (integer) Index (zero-based) of the item to select. Value of -1 selects nothing and restores the original text.
{insert} (boolean) Forins-completion, whether the selection should be inserted in the buffer. Ignored forcmdline-completion.
{finish} (boolean) Finish the completion and dismiss the popup menu. Implies{insert}.
{opts} (vim.api.keyset.empty) Optional parameters. Reserved for future use.
nvim_set_client_info()
nvim_set_client_info({name},{version},{type},{methods},{attributes}) Self-identifies the client, and sets optional flags on the channel. Defines theclient object returned bynvim_get_chan_info().
Clients should call this just after connecting, to provide hints for debugging and orchestration. (Note: Something is better than nothing! Fields are optional, but at least setname.)
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.
Attributes:
RPC only Since: 0.3.0
Parameters:
{name} (string) Client short-name. Sets theclient.name field ofnvim_get_chan_info().
{version} (table<string,any>) Dict 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} (string) Must be one of the following values. Client libraries should default to "remote" unless overridden by the user.
"remote" remote client connected "Nvim flavored" MessagePack-RPC (responses must be in reverse order of requests).msgpack-rpc
"msgpack-rpc" remote client connected to Nvim via fully MessagePack-RPC compliant protocol.
"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} (table<string,any>) 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} (table<string,any>) Arbitrary string:string map of informal client properties. Suggested keys:
"pid": Process id.
"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 window's buffer tobuffer.
Attributes:
not allowed whentextlock is active or in thecmdwin Since: 0.1.0
Parameters:
{buffer} (integer) Buffer id
nvim_set_current_dir({dir})nvim_set_current_dir()
Changes the global working directory.
Attributes:
Since: 0.1.0
Parameters:
{dir} (string) Directory path
nvim_set_current_line({line})nvim_set_current_line()
Sets the text on the current line.
Attributes:
not allowed whentextlock is active Since: 0.1.0
Parameters:
{line} (string) Line contents
nvim_set_current_tabpage({tabpage})nvim_set_current_tabpage()
Sets the current tabpage.
Attributes:
not allowed whentextlock is active or in thecmdwin Since: 0.1.0
Parameters:
{tabpage} (integer)tab-ID to focus
nvim_set_current_win({window})nvim_set_current_win()
Sets the current window (and tabpage, implicitly).
Attributes:
not allowed whentextlock is active or in thecmdwin Since: 0.1.0
Parameters:
{window} (integer)window-ID to focus
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'.
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.
Iflink is used in combination with other attributes; only thelink will take effect (see:hi-link).
Attributes:
Since: 0.5.0
Parameters:
{ns_id} (integer) Namespace id for this highlightnvim_create_namespace(). Use 0 to set a highlight group globally:highlight. Highlights from non-global namespaces are not active by default, usenvim_set_hl_ns() ornvim_win_set_hl_ns() to activate them.
{name} (string) Highlight group name, e.g. "ErrorMsg"
{val} (vim.api.keyset.highlight) Highlight definition map, accepts the following keys:
fg: color name or "#RRGGBB", see note.
bg: color name or "#RRGGBB", see note.
sp: 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 colorctermfg
ctermbg: Sets background of cterm colorctermbg
cterm: cterm attribute map, likehighlight-args. If not set, cterm attributes will match those from the attribute map documented above.
force: if true force update the highlight group when it exists.
nvim_set_hl_ns({ns_id})nvim_set_hl_ns()
Set active namespace for highlights defined withnvim_set_hl(). This can be set for a single window, seenvim_win_set_hl_ns().
Attributes:
Since: 0.8.0
Parameters:
{ns_id} (integer) the namespace to use
nvim_set_hl_ns_fast({ns_id})nvim_set_hl_ns_fast()
Set active namespace for highlights defined withnvim_set_hl() while redrawing.
This function meant to be called while redrawing, primarily fromnvim_set_decoration_provider() on_win and on_line callbacks, which are allowed to change the namespace during a redraw cycle.
Attributes:
api-fast Since: 0.8.0
Parameters:
{ns_id} (integer) the namespace to activate
nvim_set_keymap({mode},{lhs},{rhs},{opts})nvim_set_keymap()
Sets a globalmapping for the given mode.
To set a buffer-local mapping, usenvim_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.
Example:
call nvim_set_keymap('n', ' <NL>', '', {'nowait': v:true})
is equivalent to:
nmap <nowait> <Space><NL> <Nop>
Attributes:
Since: 0.4.0
Parameters:
{mode} (string) Mode short-name (map command prefix: "n", "i", "v", "x", …) or "!" for:map!, or empty string for:map. "ia", "ca" or "!a" for abbreviation in Insert mode, Cmdline mode, or both, respectively
{lhs} (string) Left-hand-side{lhs} of the mapping.
{rhs} (string) Right-hand-side{rhs} of the mapping.
{opts} (vim.api.keyset.keymap) Optional parameters map: Accepts all:map-arguments as keys except<buffer>, values are booleans (default false). Also:
"noremap" disablesrecursive_mapping, like:noremap
"desc" human-readable description.
"callback" Lua function called in place of{rhs}.
"replace_keycodes" (boolean) When "expr" is true, replace keycodes in the resulting string (seenvim_replace_termcodes()). Returning nil from the Lua "callback" is equivalent to returning an empty string.
nvim_set_var({name},{value})nvim_set_var()
Sets a global (g:) variable.
Attributes:
Since: 0.1.0
Parameters:
{name} (string) Variable name
{value} (any) Variable value
nvim_set_vvar({name},{value})nvim_set_vvar()
Sets a v: variable, if it is not readonly.
Attributes:
Since: 0.4.0
Parameters:
{name} (string) Variable name
{value} (any) Variable value
nvim_strwidth({text})nvim_strwidth()
Calculates the number of display cells occupied bytext. Control characters including<Tab> count as one cell.
Attributes:
Since: 0.1.0
Parameters:
{text} (string) Some text
Return:
(integer) Number of cells
nvim__complete_set({index},{opts})nvim__complete_set()
EXPERIMENTAL: this API may change in the future.
Sets info for the completion item at the given index. If the info text was shown in a window, returns the window and buffer ids, or empty dict if not shown.
Parameters:
{index} (integer) Completion candidate index
{opts} (vim.api.keyset.complete_set) Optional parameters.
info: (string) info text.
Return:
(table<string,number>) Dict containing these keys:
winid: (number) floating window id
bufnr: (number) buffer id in floating window
nvim__get_runtime({pat},{all},{opts})nvim__get_runtime()
Find files in runtime directories
Attributes:
api-fast Since: 0.6.0
Parameters:
{pat} (string[]) pattern of files to search for
{all} (boolean) whether to return all matches or only the first
{opts} (vim.api.keyset.runtime) is_lua: only search Lua subdirs
Return:
(string[]) list of absolute paths to the found files
nvim__id({obj})nvim__id()
Returns object given as argument.
This API function is used for testing. One should not rely on its presence in plugins.
Parameters:
{obj} (any) Object to return.
Return:
(any) its argument.
nvim__id_array({arr})nvim__id_array()
Returns array given as argument.
This API function is used for testing. One should not rely on its presence in plugins.
Parameters:
{arr} (any[]) Array to return.
Return:
(any[]) its argument.
nvim__id_dict({dct})nvim__id_dict()
Returns dict given as argument.
This API function is used for testing. One should not rely on its presence in plugins.
Parameters:
{dct} (table<string,any>) Dict to return.
Return:
(table<string,any>) its argument.
nvim__id_float({flt})nvim__id_float()
Returns floating-point value given as argument.
This API function is used for testing. One should not rely on its presence in plugins.
Parameters:
{flt} (number) Value to return.
Return:
(number) 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.
Parameters:
{grid} (integer)
{row} (integer)
{col} (integer)
Return:
(any[])
nvim__invalidate_glyph_cache()nvim__invalidate_glyph_cache()
For testing. The condition in schar_cache_clear_if_full is hard to reach, so this function can be used to force a cache clear in a test.
nvim__redraw({opts})nvim__redraw()
EXPERIMENTAL: this API may change in the future.
Instruct Nvim to redraw various components.
Attributes:
Since: 0.10.0
Parameters:
{opts} (vim.api.keyset.redraw) Optional parameters.
win: Target a specificwindow-ID as described below.
buf: Target a specific buffer number as described below.
flush: Update the screen with pending updates.
valid: When present markwin,buf, or all windows for redraw. Whentrue, only redraw changed lines (useful for decoration providers). Whenfalse, forcefully redraw.
range: Redraw a range inbuf, the buffer inwin or the current buffer (useful for decoration providers). Expects a tuple[first, last] with the first and last line number of the range, 0-based end-exclusiveapi-indexing.
cursor: Immediately update cursor position on the screen inwin or the current window.
statuscolumn: Redraw the'statuscolumn' inbuf,win or all windows.
statusline: Redraw the'statusline' inbuf,win or all windows.
winbar: Redraw the'winbar' inbuf,win or all windows.
tabline: Redraw the'tabline'.
See also:
:redraw
nvim__stats()nvim__stats()
Gets internal stats.
Return:
(table<string,any>) Map of various internal stats.

Vimscript Functionsapi-vimscript

nvim_call_dict_function()
nvim_call_dict_function({dict},{fn},{args}) Calls a VimscriptDictionary-function with the given arguments.
On execution error: fails with Vimscript error, updates v:errmsg.
Attributes:
Since: 0.3.0
Parameters:
{dict} (any) Dict, or String evaluating to a Vimscriptself dict
{fn} (string) Name of the function defined on the Vimscript dict
{args} (any[]) Function arguments packed in an Array
Return:
(any) Result of the function call
nvim_call_function({fn},{args})nvim_call_function()
Calls a Vimscript function with the given arguments.
On execution error: fails with Vimscript error, updates v:errmsg.
Attributes:
Since: 0.1.0
Parameters:
{fn} (string) Function to call
{args} (any[]) Function arguments packed in an Array
Return:
(any) Result of the function call
nvim_command({command})nvim_command()
Executes an Ex command.
On execution error: fails with Vimscript error, updates v:errmsg.
Prefernvim_cmd() ornvim_exec2() instead. To modify an Ex command in a structured way before executing it, modify the result ofnvim_parse_cmd() then pass it tonvim_cmd().
Attributes:
Since: 0.1.0
Parameters:
{command} (string) Ex command string
nvim_eval({expr})nvim_eval()
Evaluates a Vimscriptexpression. Dicts and Lists are recursively expanded.
On execution error: fails with Vimscript error, updates v:errmsg.
Attributes:
Since: 0.1.0
Parameters:
{expr} (string) Vimscript expression string
Return:
(any) Evaluation result or expanded object
nvim_exec2({src},{opts})nvim_exec2()
Executes Vimscript (multiline block of Ex commands), like anonymous:source.
Unlikenvim_command() this function supports heredocs, script-scope (s:), etc.
On execution error: fails with Vimscript error, updates v:errmsg.
Attributes:
Since: 0.9.0
Parameters:
{src} (string) Vimscript code
{opts} (vim.api.keyset.exec_opts) Optional parameters.
output: (boolean, default false) Whether to capture and return all (non-error, non-shell:!) output.
Return:
(table<string,any>) Dict containing information about execution, with these keys:
output: (string|nil) Output ifopts.output is true.
See also:
execute()
nvim_command()
nvim_cmd()
nvim_parse_expression()
nvim_parse_expression({expr},{flags},{highlight}) Parse a Vimscript expression.
Attributes:
api-fast Since: 0.3.0
Parameters:
{expr} (string) Expression to parse. Always treated as a single line.
{flags} (string) 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} (boolean) 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:
(table<string,any>)
AST: top-level dict with these keys:
"error": Dict 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 dict 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 this API 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.

Command Functionsapi-command

nvim_buf_create_user_command()
nvim_buf_create_user_command({buffer},{name},{command},{opts}) Creates a buffer-local commanduser-commands.
Attributes:
Since: 0.7.0
Parameters:
{buffer} (integer) Buffer id, or 0 for current buffer.
{name} (string)
{command} (any)
{opts} (vim.api.keyset.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.
Only commands created with:command-buffer ornvim_buf_create_user_command() can be deleted with this function.
Attributes:
Since: 0.7.0
Parameters:
{buffer} (integer) Buffer id, or 0 for current buffer.
{name} (string) Name of the command to delete.
nvim_buf_get_commands({buffer},{opts})nvim_buf_get_commands()
Gets a map of buffer-localuser-commands.
Attributes:
Since: 0.3.0
Parameters:
{buffer} (integer) Buffer id, or 0 for current buffer
{opts} (vim.api.keyset.get_commands) Optional parameters. Currently not used.
Return:
(vim.api.keyset.command_info) Map of maps describing commands.
nvim_cmd({cmd},{opts})nvim_cmd()
Executes an Ex command.
Unlikenvim_command() this command takes a structured Dict 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. Command arguments may also be Number, Boolean or String.
The first argument may also be used instead of count for commands that support it in order to make their usage simpler withvim.cmd(). For example, instead ofvim.cmd.bdelete{ count = 2 }, you may dovim.cmd.bdelete(2).
On execution error: fails with Vimscript error, updates v:errmsg.
Attributes:
Since: 0.8.0
Parameters:
{cmd} (vim.api.keyset.cmd) Command to execute. Must be a Dict that can contain the same values as the return value ofnvim_parse_cmd() except "addr", "nargs" and "nextcmd" which are ignored if provided. All values except for "cmd" are optional.
{opts} (vim.api.keyset.cmd_opts) Optional parameters.
output: (boolean, default false) Whether to return command output.
Return:
(string) Command output (non-error, non-shell:!) ifoutput is true, else empty string.
See also:
nvim_exec2()
nvim_command()
nvim_create_user_command()
nvim_create_user_command({name},{command},{opts}) Creates a globaluser-commands command.
For Lua usage seelua-guide-commands-create.
Example:
:call nvim_create_user_command('SayHello', 'echo "Hello world!"', {'bang': v:true}):SayHelloHello world!
Attributes:
Since: 0.7.0
Parameters:
{name} (string) Name of the new user command. Must begin with an uppercase letter.
{command} (string|fun(args: vim.api.keyset.create_user_command.command_args)) 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:
name: (string) Command name
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>
nargs: (string) Number of arguments:command-nargs
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 ofnvim_parse_cmd().
{opts} (vim.api.keyset.user_command) Optionalcommand-attributes.
Set boolean attributes such as:command-bang or:command-bar to true (but not:command-buffer, usenvim_buf_create_user_command() instead).
"complete":command-complete also accepts a Lua function which works like:command-completion-customlist.
Other 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.
Attributes:
Since: 0.7.0
Parameters:
{name} (string) Name of the command to delete.
nvim_get_commands({opts})nvim_get_commands()
Gets a map of global (non-buffer-local) Ex commands.
Currently onlyuser-commands are supported, not builtin Ex commands.
Attributes:
Since: 0.3.0
Parameters:
{opts} (vim.api.keyset.get_commands) Optional parameters. Currently only supports{"builtin":false}
Return:
(table<string,vim.api.keyset.command_info>) Map of maps describing commands.
See also:
nvim_get_all_options_info()
nvim_parse_cmd({str},{opts})nvim_parse_cmd()
Parse command line.
Doesn't check the validity of command arguments.
Attributes:
api-fast Since: 0.8.0
Parameters:
{str} (string) Command line string to parse. Cannot contain "\n".
{opts} (vim.api.keyset.empty) Optional parameters. Reserved for future use.
Return:
(vim.api.keyset.cmd) Dict containing command information, with these keys:
cmd: (string) Command name.
range: (array) (optional) Command range (<line1><line2>). Omitted if command doesn't accept a range. Otherwise, has no elements if no range was specified, one element if only a single range item was specified, or two elements if both range items were specified.
count: (number) (optional) Command<count>. Omitted if command cannot take a count.
reg: (string) (optional) Command<register>. Omitted 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 or "line" for -addr=lines.
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: (dict) 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: (dict):command-modifiers.
filter: (dict):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.
horizontal: (boolean):horizontal.
keepalt: (boolean):keepalt.
keepjumps: (boolean):keepjumps.
keepmarks: (boolean):keepmarks.
keeppatterns: (boolean):keeppatterns.
lockmarks: (boolean):lockmarks.
noswapfile: (boolean):noswapfile.
tab: (integer):tab. -1 when omitted.
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 Functionsapi-options

nvim_get_all_options_info()nvim_get_all_options_info()
Gets the option information for all options.
The dict has the full option names as keys and option metadata dicts as detailed atnvim_get_option_info2().
Attributes:
Since: 0.5.0
Return:
(table<string,any>) dict of all options
See also:
nvim_get_commands()
nvim_get_option_info2({name},{opts})nvim_get_option_info2()
Gets the option information for one option from arbitrary buffer or window
Resulting dict 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
When{scope} is not provided, the last set information applies to the local value in the current buffer or window if it is available, otherwise the global value information is returned. This behavior can be disabled by explicitly specifying{scope} in the{opts} table.
Attributes:
Since: 0.9.0
Parameters:
{name} (string) Option name
{opts} (vim.api.keyset.option) 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:
(vim.api.keyset.get_option_info) 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}.
Attributes:
Since: 0.7.0
Parameters:
{name} (string) Option name
{opts} (vim.api.keyset.option) 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".
filetype:filetype. Used to get the default option for a specific filetype. Cannot be used with any other option. Note: this will triggerftplugin and allFileType autocommands for the corresponding filetype.
Return:
(any) 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.
Attributes:
Since: 0.7.0
Parameters:
{name} (string) Option name
{value} (any) New option value
{opts} (vim.api.keyset.option) 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.

Buffer Functionsapi-buffer

For more information on buffers, seebuffers.
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 freedfrom 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 asnvim_buf_get_lines() andnvim_buf_line_count() will be affected.
You can usenvim_buf_is_loaded() ornvim_buf_line_count() to checkwhether a buffer is loaded.
nvim_buf_attach({buffer},{send_buffer},{opts})nvim_buf_attach()
Activatesapi-buffer-updates events on a channel, or as Lua callbacks.
Example (Lua): capture buffer updates in a globalevents variable (use "vim.print(events)" to see its contents):
events = {}vim.api.nvim_buf_attach(0, false, {  on_lines = function(...)    table.insert(events, {...})  end,})
Attributes:
Since: 0.3.0
Parameters:
{buffer} (integer) Buffer id, or 0 for current buffer
{send_buffer} (boolean) True if the initial notification should contain the whole buffer: first notification will benvim_buf_lines_event. Else the first notification will benvim_buf_changedtick_event. Not for Lua callbacks.
{opts} (vim.api.keyset.buf_attach) Optional parameters.
on_lines: Lua callback invoked on change. Return a truthy value (notfalse ornil) to detach. Args:
the string "lines"
buffer id
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 (ifutf_sizes is true)
deleted_codeunits (ifutf_sizes is true)
on_bytes: Lua callback invoked on change. This callback receives more granular information about the change compared to on_lines. Return a truthy value (notfalse ornil) to detach. Args:
the string "bytes"
buffer id
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 (offset from start row)
old end column of the changed text (if old end row = 0, offset from start column)
old end byte length of the changed text
new end row of the changed text (offset from start row)
new end column of the changed text (if new end row = 0, offset from start column)
new end byte length of the changed text
on_changedtick: Lua callback invoked on changedtick increment without text change. Args:
the string "changedtick"
buffer id
b:changedtick
on_detach: Lua callback invoked on detach. Args:
the string "detach"
buffer id
on_reload: Lua callback invoked on reload. The entire buffer content should be considered changed. Args:
the string "reload"
buffer id
utf_sizes: include UTF-32 and UTF-16 size of the replaced region, as args toon_lines.
preview: also attach to command preview (i.e.'inccommand') events.
Return:
(boolean) 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.
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, then one of those 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 Vimscript functions that only work with the current buffer/window currently, likejobstart(…, {'term': v:true}).
Attributes:
Luavim.api only Since: 0.5.0
Parameters:
{buffer} (integer) Buffer id, or 0 for current buffer
{fun} (function) Function to call inside the buffer (currently Lua callable only)
Return:
(any) Return value of function.
nvim_buf_del_keymap({buffer},{mode},{lhs})nvim_buf_del_keymap()
Unmaps a buffer-localmapping for the given mode.
Attributes:
Since: 0.4.0
Parameters:
{buffer} (integer) Buffer id, or 0 for current buffer
{mode} (string)
{lhs} (string)
See also:
nvim_del_keymap()
nvim_buf_del_mark({buffer},{name})nvim_buf_del_mark()
Deletes a named mark in the buffer. Seemark-motions.
Note:
only deletes marks set in the buffer, if the mark is not set in the buffer it will return false.
Attributes:
Since: 0.6.0
Parameters:
{buffer} (integer) Buffer to set the mark on
{name} (string) Mark name
Return:
(boolean) true if the mark was deleted, else false.
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
Attributes:
Since: 0.1.0
Parameters:
{buffer} (integer) Buffer id, or 0 for current buffer
{name} (string) Variable name
nvim_buf_delete({buffer},{opts})nvim_buf_delete()
Deletes a buffer and its metadata (like:bwipeout).
To get:bdelete behavior, reset'buflisted' and passunload=true:
vim.bo.buflisted = falsevim.api.nvim_buf_delete(0, { unload = true })
Attributes:
not allowed whentextlock is active or in thecmdwin Since: 0.5.0
Parameters:
{buffer} (integer) Buffer id, or 0 for current buffer
{opts} (vim.api.keyset.buf_delete) Optional parameters. Keys:
force: Force deletion, ignore unsaved changes.
unload: Unloaded only (:bunload), do not delete.
nvim_buf_detach({buffer})nvim_buf_detach()
Deactivates buffer-update events on the channel.
Attributes:
RPC only Since: 0.3.0
Parameters:
{buffer} (integer) Buffer id, or 0 for current buffer
Return:
(boolean) False if detach failed (because the buffer isn't loaded); otherwise True.
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
Attributes:
Since: 0.2.0
Parameters:
{buffer} (integer) Buffer id, or 0 for current buffer
Return:
(integer)b:changedtick value.
nvim_buf_get_keymap({buffer},{mode})nvim_buf_get_keymap()
Gets a list of buffer-localmapping definitions.
Attributes:
Since: 0.2.1
Parameters:
{buffer} (integer) Buffer id, or 0 for current buffer
{mode} (string) Mode short-name ("n", "i", "v", ...)
Return:
(vim.api.keyset.get_keymap[]) Array ofmaparg()-like dictionaries describing mappings. The "buffer" key holds the associated buffer id.
nvim_buf_get_lines()
nvim_buf_get_lines({buffer},{start},{end},{strict_indexing}) 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.
Out-of-bounds indices are clamped to the nearest valid value, unlessstrict_indexing is set.
Attributes:
Since: 0.1.0
Parameters:
{buffer} (integer) Buffer id, or 0 for current buffer
{start} (integer) First line index
{end} (integer) Last line index, exclusive
{strict_indexing} (boolean) Whether out-of-bounds should be an error.
Return:
(string[]) Array of lines, or empty array for unloaded buffer.
See also:
nvim_buf_get_text()
nvim_buf_get_mark({buffer},{name})nvim_buf_get_mark()
Returns a(row,col) tuple representing the position of the named mark. "End of line" column position is returned asv:maxcol (big number). Seemark-motions.
Marks are (1,0)-indexed.api-indexing
Attributes:
Since: 0.1.0
Parameters:
{buffer} (integer) Buffer id, or 0 for current buffer
{name} (string) Mark name
Return:
([integer, integer]) (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()
nvim_buf_get_name({buffer})nvim_buf_get_name()
Gets the full file name for the buffer
Attributes:
Since: 0.1.0
Parameters:
{buffer} (integer) Buffer id, or 0 for current buffer
Return:
(string) Buffer name
nvim_buf_get_offset({buffer},{index})nvim_buf_get_offset()
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'.
Unlikeline2byte(), throws error for out-of-bounds indexing. Returns -1 for unloaded buffer.
Attributes:
Since: 0.3.2
Parameters:
{buffer} (integer) Buffer id, or 0 for current buffer
{index} (integer) Line index
Return:
(integer) 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 (may be partial lines, unlikenvim_buf_get_lines()).
Indexing is zero-based. Row indices are end-inclusive, and column indices are end-exclusive.
Prefernvim_buf_get_lines() when retrieving entire lines.
Attributes:
Since: 0.7.0
Parameters:
{buffer} (integer) Buffer id, or 0 for current buffer
{start_row} (integer) First line index
{start_col} (integer) Starting column (byte offset) on first line
{end_row} (integer) Last line index, inclusive
{end_col} (integer) Ending column (byte offset) on last line, exclusive
{opts} (vim.api.keyset.empty) Optional parameters. Currently unused.
Return:
(string[]) 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.
Attributes:
Since: 0.1.0
Parameters:
{buffer} (integer) Buffer id, or 0 for current buffer
{name} (string) Variable name
Return:
(any) Variable value
nvim_buf_is_loaded({buffer})nvim_buf_is_loaded()
Checks if a buffer is valid and loaded. Seeapi-buffer for more info about unloaded buffers.
Attributes:
Since: 0.3.2
Parameters:
{buffer} (integer) Buffer id, or 0 for current buffer
Return:
(boolean) 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.
Note:
Even if a buffer is valid it may have been unloaded. Seeapi-buffer for more info about unloaded buffers.
Attributes:
Since: 0.1.0
Parameters:
{buffer} (integer) Buffer id, or 0 for current buffer
Return:
(boolean) 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.
Attributes:
Since: 0.1.0
Parameters:
{buffer} (integer) Buffer id, or 0 for current buffer
Return:
(integer) 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-localmapping for the given mode.
Attributes:
Since: 0.4.0
Parameters:
{buffer} (integer) Buffer id, or 0 for current buffer
{mode} (string)
{lhs} (string)
{rhs} (string)
{opts} (vim.api.keyset.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.
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 line use start=-2 and end=-1.
To insert lines at a given index, setstart andend to the same index. To delete a range of lines, setreplacement to an empty array.
Out-of-bounds indices are clamped to the nearest valid value, unlessstrict_indexing is set.
Attributes:
not allowed whentextlock is active Since: 0.1.0
Parameters:
{buffer} (integer) Buffer id, or 0 for current buffer
{start} (integer) First line index
{end} (integer) Last line index, exclusive
{strict_indexing} (boolean) Whether out-of-bounds should be an error.
{replacement} (string[]) Array of lines to use as replacement
See also:
nvim_buf_set_text()
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. Seemark-motions.
Marks are (1,0)-indexed.api-indexing
Note:
Passing 0 as line deletes the mark
Attributes:
Since: 0.6.0
Parameters:
{buffer} (integer) Buffer to set the mark on
{name} (string) Mark name
{line} (integer) Line number
{col} (integer) Column/row number
{opts} (vim.api.keyset.empty) Optional parameters. Reserved for future use.
Return:
(boolean) true if the mark was set, else false.
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, like:file_f
Attributes:
Since: 0.1.0
Parameters:
{buffer} (integer) Buffer id, or 0 for current buffer
{name} (string) 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
This is recommended overnvim_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.
To insert text at a given(row, column) location, usestart_row = end_row = row andstart_col = end_col = col. To delete the text in a range, usereplacement = {}.
Note:
Prefernvim_buf_set_lines() (for performance) to add or delete entire lines.
Prefernvim_paste() ornvim_put() to insert (instead of replace) text at cursor.
Attributes:
not allowed whentextlock is active Since: 0.5.0
Parameters:
{buffer} (integer) Buffer id, or 0 for current buffer
{start_row} (integer) First line index
{start_col} (integer) Starting column (byte offset) on first line
{end_row} (integer) Last line index, inclusive
{end_col} (integer) Ending column (byte offset) on last line, exclusive
{replacement} (string[]) Array of lines to use as replacement
nvim_buf_set_var({buffer},{name},{value})nvim_buf_set_var()
Sets a buffer-scoped (b:) variable
Attributes:
Since: 0.1.0
Parameters:
{buffer} (integer) Buffer id, or 0 for current buffer
{name} (string) Variable name
{value} (any) Variable value

Extmark Functionsapi-extmark

nvim_buf_clear_namespace()
nvim_buf_clear_namespace({buffer},{ns_id},{line_start},{line_end}) Clearsnamespaced 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.
Attributes:
Since: 0.3.2
Parameters:
{buffer} (integer) Buffer id, or 0 for current buffer
{ns_id} (integer) Namespace to clear, or -1 to clear all namespaces.
{line_start} (integer) Start of range of lines to clear
{line_end} (integer) 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 anextmark.
Attributes:
Since: 0.5.0
Parameters:
{buffer} (integer) Buffer id, or 0 for current buffer
{ns_id} (integer) Namespace id fromnvim_create_namespace()
{id} (integer) Extmark id
Return:
(boolean) 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 anextmark.
Attributes:
Since: 0.5.0
Parameters:
{buffer} (integer) Buffer id, or 0 for current buffer
{ns_id} (integer) Namespace id fromnvim_create_namespace()
{id} (integer) Extmark id
{opts} (vim.api.keyset.get_extmark) Optional parameters. Keys:
details: Whether to include the details dict
hl_name: Whether to include highlight group name instead of id, true if omitted
Return:
([integer, integer, vim.api.keyset.extmark_details?]) 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}) Getsextmarks in "traversal order" from acharwise region defined by buffer positions (inclusive, 0-indexedapi-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:
vim.api.nvim_buf_get_extmarks(0, my_ns, 0, -1, {})vim.api.nvim_buf_get_extmarks(0, my_ns, {0,0}, {-1,-1}, {})
Ifend is less thanstart, marks are returned in reverse order. (Useful withlimit, to get the first marks prior to a given position.)
Note: For a reverse range,limit does not actually affect the traversed range, just how many marks are returned
Note: when using extmark ranges (marks with a end_row/end_col position) theoverlap option might be useful. Otherwise only the start position of an extmark will be considered.
Note: legacy signs placed through the:sign commands are implemented as extmarks and will show up here. Their details array will contain asign_name field.
Example:
local api = vim.apilocal pos = api.nvim_win_get_cursor(0)local ns  = api.nvim_create_namespace('my-plugin')-- Create new extmark at line 1, column 1.local m1  = api.nvim_buf_set_extmark(0, ns, 0, 0, {})-- Create new extmark at line 3, column 1.local m2  = api.nvim_buf_set_extmark(0, ns, 2, 0, {})-- Get extmarks only from line 3.local ms  = api.nvim_buf_get_extmarks(0, ns, {2,0}, {2,0}, {})-- Get all marks in this buffer + namespace.local all = api.nvim_buf_get_extmarks(0, ns, 0, -1, {})vim.print(ms)
Attributes:
Since: 0.5.0
Parameters:
{buffer} (integer) Buffer id, or 0 for current buffer
{ns_id} (integer) Namespace id fromnvim_create_namespace() or -1 for all namespaces
{start} (any) Start of range: a 0-indexed (row, col) or valid extmark id (whose position defines the bound).api-indexing
{end} (any) End of range (inclusive): a 0-indexed (row, col) or valid extmark id (whose position defines the bound).api-indexing
{opts} (vim.api.keyset.get_extmarks) Optional parameters. Keys:
limit: Maximum number of marks to return
details: Whether to include the details dict
hl_name: Whether to include highlight group name instead of id, true if omitted
overlap: Also include marks which overlap the range, even if their start position is less thanstart
type: Filter marks by type: "highlight", "sign", "virt_text" and "virt_lines"
Return:
(vim.api.keyset.get_extmark_item[]) 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 anextmark.
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.
If present, the position defined byend_col andend_row should be after the start position in order for the extmark to cover a range. An earlier end position is not an error, but then it behaves like an empty range (no highlighting).
Attributes:
Since: 0.5.0
Parameters:
{buffer} (integer) Buffer id, or 0 for current buffer
{ns_id} (integer) Namespace id fromnvim_create_namespace()
{line} (integer) Line where to place the mark, 0-based.api-indexing
{col} (integer) Column where to place the mark, 0-based.api-indexing
{opts} (vim.api.keyset.set_extmark) 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 : highlight group used for the text range. This and below highlight groups can be supplied either as a string or as an integer, the latter of which can be obtained usingnvim_get_hl_id_by_name(). Multiple highlight groups can be stacked by passing an array (highest priority last).
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 single highlight group, or an array of multiple highlight groups that will be stacked (highest priority last).
virt_text_pos : position of virtual text. Possible values:
"eol": right after eol character (default).
"eol_right_align": display right aligned in the window unless the virtual text is longer than the space available. If the virtual text is too long, it is truncated to fit in the window after the EOL character. If the line is wrapped, the virtual text is shown after the end of the line rather than the previous screen line.
"overlay": display over the specified column, without shifting the underlying text.
"right_align": display right aligned in the window.
"inline": display at the specified column, and shift the buffer text to the right as needed.
virt_text_win_col : position the virtual text at a fixed window column (starting from the first text column of the screen line) instead of "virt_text_pos".
virt_text_hide : hide the virtual text when the background text is selected or hidden because of scrolling with'nowrap' or'smoothscroll'. Currently only affects "overlay" virt_text.
virt_text_repeat_linebreak : repeat the virtual text on wrapped lines.
hl_mode : control how highlights are combined with the highlights of the text. Currently only affects virt_text highlights, but might affecthl_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. Not supported for "inline" virt_text.
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 virtual lines in the leftmost column of the window, bypassing sign and number columns.
virt_lines_overflow: controls how to handle virtual lines wider than the window. Currently takes the one of the following values:
"trunc": truncate virtual lines on the right (default).
"scroll": virtual lines can scroll horizontally with'nowrap', otherwise the same as "trunc".
ephemeral : for use withnvim_set_decoration_provider() callbacks. The mark will only be used for the current redraw cycle, and not be permanently 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.
undo_restore : Restore the exact position of the mark if text around the mark was deleted and then restored by undo. Defaults to true.
invalidate : boolean that indicates whether to hide the extmark if the entirety of its range is deleted. For hidden marks, an "invalid" key is added to the "details" array ofnvim_buf_get_extmarks() and family. If "undo_restore" is false, the extmark is deleted instead.
priority: a priority value for the highlight group, sign attribute or virtual text. For virtual text, item with highest priority is drawn last. 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.
sign_hl_group: highlight group used for the sign column text.
number_hl_group: highlight group used for the number column.
line_hl_group: highlight group used for the whole line.
cursorline_hl_group: highlight group used for the sign column text when the cursor is on the same line as the mark and'cursorline' is enabled.
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 tohl-Conceal.
conceal_lines: string which should be empty. When provided, lines in the range are not drawn at all (according to'conceallevel'); the next unconcealed line is drawn instead.
spell: boolean indicating that spell checking should be performed within this extmark
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.
url: A URL to associate with this extmark. In the TUI, the OSC 8 control sequence is used to generate a clickable hyperlink to this URL.
Return:
(integer) Id of the created/updated extmark
nvim_create_namespace({name})nvim_create_namespace()
Creates a new namespace or gets an existing one.namespace
Namespaces are used for buffer highlights and virtual text, seenvim_buf_set_extmark().
Namespaces can be named or anonymous. Ifname matches an existing namespace, the associated id is returned. Ifname is an empty string a new, anonymous namespace is created.
Attributes:
Since: 0.3.2
Parameters:
{name} (string) Namespace name or empty string
Return:
(integer) Namespace id
nvim_get_namespaces()nvim_get_namespaces()
Gets existing, non-anonymousnamespaces.
Attributes:
Since: 0.3.2
Return:
(table<string,integer>) 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 anamespace
This is a very general purpose interface for having Lua callbacks being triggered during the redraw code.
The expected usage is to setextmarks for the currently redrawn buffer.nvim_buf_set_extmark() can be called to add marks on a per-window or per-lines basis. Use theephemeral 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. theon_start callback can returnfalse to disable the provider until the next redraw. Similarly, returnfalse inon_win will skip theon_line calls for that window (but any extmarks set inon_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 multiplens_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 explicitly forbidden, but is likely to have unexpected consequences (such as 100% CPU consumption). Doingvim.rpcnotify should be OK, butvim.rpcrequest is quite dubious for the moment.
Note: It is not allowed to remove or update extmarks inon_line callbacks.
Attributes:
Luavim.api only Since: 0.5.0
Parameters:
{ns_id} (integer) Namespace id fromnvim_create_namespace()
{opts} (vim.api.keyset.set_decoration_provider) Table of callbacks:
on_start: called first on each screen redraw
["start", tick]
on_buf: called for each buffer being redrawn (once per edit, before window callbacks)
["buf", bufnr, tick]
on_win: called when starting to redraw a specific window.
["win", winid, bufnr, toprow, botrow]
on_line: called for each buffer line being redrawn. (The interaction with fold lines is subject to change)
["line", winid, bufnr, row]
on_end: called at the end of a redraw cycle
["end", tick]
nvim__ns_get({ns_id})nvim__ns_get()
EXPERIMENTAL: this API will change in the future.
Get the properties for namespace
Parameters:
{ns_id} (integer) Namespace
Return:
(vim.api.keyset.ns_opts) Map defining the namespace properties, seenvim__ns_set()
nvim__ns_set({ns_id},{opts})nvim__ns_set()
EXPERIMENTAL: this API will change in the future.
Set some properties for namespace
Parameters:
{ns_id} (integer) Namespace
{opts} (vim.api.keyset.ns_opts) Optional parameters to set:
wins: a list of windows to be scoped in

Window Functionsapi-window

nvim_win_call({window},{fun})nvim_win_call()
Calls a function with window as temporary current window.
Attributes:
Luavim.api only Since: 0.5.0
Parameters:
{window} (integer)window-ID, or 0 for current window
{fun} (function) Function to call inside the window (currently Lua callable only)
Return:
(any) Return value of function.
See also:
win_execute()
nvim_buf_call()
nvim_win_close({window},{force})nvim_win_close()
Closes the window (like:close with awindow-ID).
Attributes:
not allowed whentextlock is active Since: 0.4.0
Parameters:
{window} (integer)window-ID, or 0 for current window
{force} (boolean) 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
Attributes:
Since: 0.1.0
Parameters:
{window} (integer)window-ID, or 0 for current window
{name} (string) Variable name
nvim_win_get_buf({window})nvim_win_get_buf()
Gets the current buffer in a window
Attributes:
Since: 0.1.0
Parameters:
{window} (integer)window-ID, or 0 for current window
Return:
(integer) Buffer id
nvim_win_get_cursor({window})nvim_win_get_cursor()
Gets the (1,0)-indexed, buffer-relative cursor position for a given window (different windows showing the same buffer have independent cursor positions).api-indexing
Attributes:
Since: 0.1.0
Parameters:
{window} (integer)window-ID, or 0 for current window
Return:
([integer, integer]) (row, col) tuple
See also:
getcurpos()
nvim_win_get_height({window})nvim_win_get_height()
Gets the window height
Attributes:
Since: 0.1.0
Parameters:
{window} (integer)window-ID, or 0 for current window
Return:
(integer) Height as a count of rows
nvim_win_get_number({window})nvim_win_get_number()
Gets the window number
Attributes:
Since: 0.1.0
Parameters:
{window} (integer)window-ID, or 0 for current window
Return:
(integer) Window number
nvim_win_get_position({window})nvim_win_get_position()
Gets the window position in display cells. First position is zero.
Attributes:
Since: 0.1.0
Parameters:
{window} (integer)window-ID, or 0 for current window
Return:
([integer, integer]) (row, col) tuple with the window position
nvim_win_get_tabpage({window})nvim_win_get_tabpage()
Gets the window tabpage
Attributes:
Since: 0.1.0
Parameters:
{window} (integer)window-ID, or 0 for current window
Return:
(integer) Tabpage that contains the window
nvim_win_get_var({window},{name})nvim_win_get_var()
Gets a window-scoped (w:) variable
Attributes:
Since: 0.1.0
Parameters:
{window} (integer)window-ID, or 0 for current window
{name} (string) Variable name
Return:
(any) Variable value
nvim_win_get_width({window})nvim_win_get_width()
Gets the window width
Attributes:
Since: 0.1.0
Parameters:
{window} (integer)window-ID, or 0 for current window
Return:
(integer) 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 awindow-ID).
Like:hide the buffer becomes hidden unless another window is editing it, or'bufhidden' isunload,delete orwipe as opposed to:close ornvim_win_close(), which will close the buffer.
Attributes:
not allowed whentextlock is active Since: 0.5.0
Parameters:
{window} (integer)window-ID, or 0 for current window
nvim_win_is_valid({window})nvim_win_is_valid()
Checks if a window is valid
Attributes:
Since: 0.1.0
Parameters:
{window} (integer)window-ID, or 0 for current window
Return:
(boolean) 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
Attributes:
not allowed whentextlock is active Since: 0.3.2
Parameters:
{window} (integer)window-ID, or 0 for current window
{buffer} (integer) Buffer id
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.
Attributes:
Since: 0.1.0
Parameters:
{window} (integer)window-ID, or 0 for current window
{pos} ([integer, integer]) (row, col) tuple representing the new position
nvim_win_set_height({window},{height})nvim_win_set_height()
Sets the window height.
Attributes:
Since: 0.1.0
Parameters:
{window} (integer)window-ID, or 0 for current window
{height} (integer) Height as a count of rows
nvim_win_set_hl_ns({window},{ns_id})nvim_win_set_hl_ns()
Set highlight namespace for a window. This will use highlights defined withnvim_set_hl() for this namespace, but fall back to global highlights (ns=0) when missing.
This takes precedence over the'winhighlight' option.
Attributes:
Since: 0.8.0
Parameters:
{window} (integer)
{ns_id} (integer) the namespace to use
nvim_win_set_var({window},{name},{value})nvim_win_set_var()
Sets a window-scoped (w:) variable
Attributes:
Since: 0.1.0
Parameters:
{window} (integer)window-ID, or 0 for current window
{name} (string) Variable name
{value} (any) 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.
Attributes:
Since: 0.1.0
Parameters:
{window} (integer)window-ID, or 0 for current window
{width} (integer) Width as a count of columns
nvim_win_text_height({window},{opts})nvim_win_text_height()
Computes the number of screen lines occupied by a range of text in a given window. Works for off-screen text and takes folds into account.
Diff filler or virtual lines above a line are counted as a part of that line, unless the line is on "start_row" and "start_vcol" is specified.
Diff filler or virtual lines below the last buffer line are counted in the result when "end_row" is omitted.
Line indexing is similar tonvim_buf_get_text().
Attributes:
Since: 0.10.0
Parameters:
{window} (integer)window-ID, or 0 for current window.
{opts} (vim.api.keyset.win_text_height) Optional parameters:
start_row: Starting line index, 0-based inclusive. When omitted start at the very top.
end_row: Ending line index, 0-based inclusive. When omitted end at the very bottom.
start_vcol: Starting virtual column index on "start_row", 0-based inclusive, rounded down to full screen lines. When omitted include the whole line.
end_vcol: Ending virtual column index on "end_row", 0-based exclusive, rounded up to full screen lines. When 0 only include diff filler and virtual lines above "end_row". When omitted include the whole line.
max_height: Don't add the height of lines below the row for which this height is reached. Useful to e.g. limit the height to the window height, avoiding unnecessary work. Or to find out how many buffer lines beyond "start_row" take up a certain number of logical lines (returned in "end_row" and "end_vcol").
Return:
(vim.api.keyset.win_text_height_ret) Dict containing text height information, with these keys:
all: The total number of screen lines occupied by the range.
fill: The number of diff filler or virtual lines among them.
end_row: The row on which the returned height is reached (first row of a closed fold).
end_vcol: Ending virtual column in "end_row" where "max_height" or the returned height is reached. 0 if "end_row" is a closed fold.
See also:
virtcol() for text width.

Win_config Functionsapi-win_config

nvim_open_win({buffer},{enter},{config})nvim_open_win()
Opens a new split window, or a floating window ifrelative is specified, or an external window (managed by the UI) ifexternal is specified.
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 theui-multigrid extension. External windows are only supported with multigrid GUIs, and are displayed as separate top-level windows.
For a general overview of floats, seeapi-floatwin.
Thewidth andheight of the new window must be specified when opening a floating window, but are optional for normal windows.
Ifrelative andexternal are omitted, a normal "split" window is created. Thewin property determines which window will be split. If nowin is provided orwin == 0, a window will be created adjacent to the current window. If -1 is provided, a top-level split will be created.vertical andsplit are only valid for normal windows, and are used to control split direction. Forvertical, the exact direction is determined by'splitright' and'splitbelow'. Split windows cannot havebufpos/`row`/`col`/`border`/`title`/`footer` properties.
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): vertical split left of the current window
vim.api.nvim_open_win(0, false, {  split = 'left',  win = 0})
Attributes:
not allowed whentextlock is active Since: 0.4.0
Parameters:
{buffer} (integer) Buffer to display, or 0 for current buffer
{enter} (boolean) Enter the window (make it the current window)
{config} (vim.api.keyset.win_config) Map defining the window configuration. Keys:
relative: Sets the window layout to "floating", placed at (row,col) coordinates relative to:
"cursor" Cursor position in current window.
"editor" The global editor grid.
"laststatus"'laststatus' if present, or last row.
"mouse" Mouse position.
"tabline" Tabline if present, or first row.
"win" Window given by thewin field, or current window.
win:window-ID window to split, or relative window when creating a float (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 andcol if given are applied relative to this position, else they default to:
row=1 andcol=0 ifanchor is "NW" or "NE"
row=0 andcol=0 ifanchor 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 bynvim_set_current_win(), or, when themouse field is set to true, by mouse events. Seefocusable.
mouse: Specify how this window interacts with mouse events. Defaults tofocusable value.
If false, mouse events pass through this window.
If true, mouse events interact with this window normally.
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 higherzindex 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: (optional) Configure the appearance of the window. Currently only supports one 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 toauto and'colorcolumn' is cleared.'statuscolumn' is changed to empty. The end-of-buffer region is hidden by settingeob flag of'fillchars' to a space char, and clearing thehl-EndOfBuffer region in'winhighlight'.
border: (string|string[]) (defaults to'winborder' option) Window border. The string form accepts the same values as the'winborder' option. The array form must have a length of eight or any divisor of eight, specifying the chars that form the border in a clockwise fashion starting from the top-left corner. For example, the double-box style can be specified as:
[ "╔", "═" ,"╗", "║", "╝", "═", "╚", "║" ].
If fewer than eight chars are given, they will be repeated. An ASCII border could be specified as:
[ "/", "-", \"\\\\\", "|" ],
Or one char for all sides:
[ "x" ].
Empty string can be used to hide a specific border. This example will show only vertical borders, not horizontal:
[ "", "", "", ">", "", "", "", "<" ]
By default,hl-FloatBorder highlight is used, which links tohl-WinSeparator when not defined. Each border side can specify an optional highlight:
[ ["+", "MyCorner"], ["x", "MyBorder"] ].
title: (optional) Title in window border, string or list. List should consist of[text, highlight] tuples. If string, or a tuple lacks a highlight, the default highlight group isFloatTitle.
title_pos: Title position. Must be set withtitle option. Value can be one of "left", "center", or "right". Default is"left".
footer: (optional) Footer in window border, string or list. List should consist of[text, highlight] tuples. If string, or a tuple lacks a highlight, the default highlight group isFloatFooter.
footer_pos: Footer position. Must be set withfooter option. Value can be one of "left", "center", or "right". Default is"left".
noautocmd: If true then all autocommands are blocked for the duration of the call.
fixed: If true when anchor is NW or SW, the float window would be kept fixed even if the window would be truncated.
hide: If true the floating window will be hidden and the cursor will be invisible when focused on it.
vertical: Split vertically:vertical.
split: Split direction: "left", "right", "above", "below".
_cmdline_offset: (EXPERIMENTAL) When provided, anchor thecmdline-completion popupmenu to this window, with an offset in screen cell width.
Return:
(integer)window-ID, or 0 on error
nvim_win_get_config({window})nvim_win_get_config()
Gets window configuration.
The returned value may be given tonvim_open_win().
relative is empty for normal windows.
Attributes:
Since: 0.4.0
Parameters:
{window} (integer)window-ID, or 0 for current window
Return:
(vim.api.keyset.win_config) Map defining the window configuration, seenvim_open_win()
nvim_win_set_config({window},{config})nvim_win_set_config()
Configures window layout. Cannot be used to move the last window in a tabpage to a different one.
When reconfiguring a window, absent option keys will not be changed.row/`col` andrelative must be reconfigured together.
Attributes:
Since: 0.4.0
Parameters:
{window} (integer)window-ID, or 0 for current window
{config} (vim.api.keyset.win_config) Map defining the window configuration, seenvim_open_win()
See also:
nvim_open_win()

Tabpage Functionsapi-tabpage

nvim_tabpage_del_var({tabpage},{name})nvim_tabpage_del_var()
Removes a tab-scoped (t:) variable
Attributes:
Since: 0.1.0
Parameters:
{tabpage} (integer)tab-ID, or 0 for current tabpage
{name} (string) Variable name
nvim_tabpage_get_number({tabpage})nvim_tabpage_get_number()
Gets the tabpage number
Attributes:
Since: 0.1.0
Parameters:
{tabpage} (integer)tab-ID, or 0 for current tabpage
Return:
(integer) Tabpage number
nvim_tabpage_get_var({tabpage},{name})nvim_tabpage_get_var()
Gets a tab-scoped (t:) variable
Attributes:
Since: 0.1.0
Parameters:
{tabpage} (integer)tab-ID, or 0 for current tabpage
{name} (string) Variable name
Return:
(any) Variable value
nvim_tabpage_get_win({tabpage})nvim_tabpage_get_win()
Gets the current window in a tabpage
Attributes:
Since: 0.1.0
Parameters:
{tabpage} (integer)tab-ID, or 0 for current tabpage
Return:
(integer)window-ID
nvim_tabpage_is_valid({tabpage})nvim_tabpage_is_valid()
Checks if a tabpage is valid
Attributes:
Since: 0.1.0
Parameters:
{tabpage} (integer)tab-ID, or 0 for current tabpage
Return:
(boolean) true if the tabpage is valid, false otherwise
nvim_tabpage_list_wins({tabpage})nvim_tabpage_list_wins()
Gets the windows in a tabpage
Attributes:
Since: 0.1.0
Parameters:
{tabpage} (integer)tab-ID, or 0 for current tabpage
Return:
(integer[]) List of windows intabpage
nvim_tabpage_set_var()
nvim_tabpage_set_var({tabpage},{name},{value}) Sets a tab-scoped (t:) variable
Attributes:
Since: 0.1.0
Parameters:
{tabpage} (integer)tab-ID, or 0 for current tabpage
{name} (string) Variable name
{value} (any) Variable value
nvim_tabpage_set_win({tabpage},{win})nvim_tabpage_set_win()
Sets the current window in a tabpage
Attributes:
Since: 0.10.0
Parameters:
{tabpage} (integer)tab-ID, or 0 for current tabpage
{win} (integer)window-ID, must already belong to{tabpage}

Autocmd Functionsapi-autocmd

nvim_clear_autocmds({opts})nvim_clear_autocmds()
Clears all autocommands selected by{opts}. To delete autocmds seenvim_del_autocmd().
Attributes:
Since: 0.7.0
Parameters:
{opts} (vim.api.keyset.clear_autocmds) 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.
defaults to clearing all patterns.
NOTE: Cannot be used with{buffer}
buffer: (bufnr)
clear onlyautocmd-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.
nvim_create_augroup({name},{opts})nvim_create_augroup()
Create or get an autocommand groupautocmd-groups.
To get an existing group id, do:
local id = vim.api.nvim_create_augroup('my.lsp.config', {    clear = false})
Attributes:
Since: 0.7.0
Parameters:
{name} (string) String: The name of the group
{opts} (vim.api.keyset.create_augroup) Dict Parameters
clear (bool) optional: defaults to true. Clear existing commands if the group already existsautocmd-groups.
Return:
(integer) Integer id of the created group.
See also:
autocmd-groups
nvim_create_autocmd({event},{opts})nvim_create_autocmd()
Creates anautocommand event handler, defined bycallback (Lua function or Vimscript function name string) orcommand (Ex command string).
Example using Lua callback:
vim.api.nvim_create_autocmd({'BufEnter', 'BufWinEnter'}, {  pattern = {'*.c', '*.h'},  callback = function(ev)    print(string.format('event fired: %s', vim.inspect(ev)))  end})
Example using an Ex command as the handler:
vim.api.nvim_create_autocmd({'BufEnter', 'BufWinEnter'}, {  pattern = {'*.c', '*.h'},  command = "echo 'Entering a C or C++ file'",})
Note:pattern is NOT automatically expanded (unlike with:autocmd), thus names like "$HOME" and "~" must be expanded explicitly:
pattern = vim.fn.expand('~') .. '/some/path/*.py'
Attributes:
Since: 0.7.0
Parameters:
{event} (any) (string|array) Event(s) that will trigger the handler (callback orcommand).
{opts} (vim.api.keyset.create_autocmd) Options dict:
group (string|integer) optional: autocommand group name or id to match against.
pattern (string|array) optional: pattern(s) to match literallyautocmd-pattern.
buffer (integer) optional: buffer number for buffer-local autocommandsautocmd-buflocal. Cannot be used with{pattern}.
desc (string) optional: description (for documentation and troubleshooting).
callback (function|string) optional: Lua function (or Vimscript function name, if string) called when the event(s) is triggered. Lua callback can return a truthy value (notfalse ornil) to delete the autocommand, and receives one argument, a table with these keys:event-args
id: (number) autocommand id
event: (string) name of the triggered eventautocmd-events
group: (number|nil) autocommand group id, if any
file: (string)<afile> (not expanded to a full path)
match: (string)<amatch> (expanded to a full path)
buf: (number)<abuf>
data: (any) arbitrary data passed fromnvim_exec_autocmds()event-data
command (string) optional: Vim command to execute on event. Cannot be used with{callback}
once (boolean) optional: defaults to false. Run the autocommand only onceautocmd-once.
nested (boolean) optional: defaults to false. Run nested autocommandsautocmd-nested.
Return:
(integer) Autocommand id (number)
See also:
autocommand
nvim_del_autocmd()
nvim_del_augroup_by_id({id})nvim_del_augroup_by_id()
Delete an autocommand group by id.
To get a group id one can usenvim_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.
Attributes:
Since: 0.7.0
Parameters:
{id} (integer) Integer The id of the group.
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.
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.
Attributes:
Since: 0.7.0
Parameters:
{name} (string) String The name of the group.
See also:
autocmd-groups
nvim_del_autocmd({id})nvim_del_autocmd()
Deletes an autocommand by id.
Attributes:
Since: 0.7.0
Parameters:
{id} (integer) Integer Autocommand id returned bynvim_create_autocmd()
nvim_exec_autocmds({event},{opts})nvim_exec_autocmds()
Execute all autocommands for{event} that match the corresponding{opts}autocmd-execute.
Attributes:
Since: 0.7.0
Parameters:
{event} (any) (String|Array) The event or events to execute
{opts} (vim.api.keyset.exec_autocmds) Dict 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 numberautocmd-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. Seenvim_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 criteriaautocommands = vim.api.nvim_get_autocmds({  group = 'MyGroup',  event = {'BufEnter', 'BufWinEnter'},  pattern = {'*.c', '*.h'}})-- All commands from one groupautocommands = 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.
Attributes:
Since: 0.7.0
Parameters:
{opts} (vim.api.keyset.get_autocmds) Dict with at least one of the following:
buffer: (integer) Buffer number or list of buffer numbers for buffer local autocommandsautocmd-buflocal. Cannot be used with{pattern}
event: (string|table) event or events to match againstautocmd-events.
id: (integer) Autocommand ID to match.
group: (string|table) the autocommand group name or id to match against.
pattern: (string|table) pattern or patterns to match againstautocmd-pattern. Cannot be used with{buffer}
Return:
(vim.api.keyset.get_autocmds.ret[]) Array of autocommands matching the criteria, with each item containing the following fields:
buffer: (integer) the buffer number.
buflocal: (boolean) true if the autocommand is buffer local.
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.
desc: (string) the autocommand description.
event: (string) the autocommand event.
id: (integer) the autocommand id (only when defined with the API).
group: (integer) the autocommand group id.
group_name: (string) the autocommand group name.
once: (boolean) whether the autocommand is only run once.
pattern: (string) the autocommand pattern. If the autocommand is buffer localautocmd-buffer-local:

UI Functionsapi-ui

nvim_ui_attach({width},{height},{options})nvim_ui_attach()
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()
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 Since: 0.1.0
Parameters:
{width} (integer) Requested screen columns
{height} (integer) Requested screen rows
{options} (table<string,any>)ui-option map
nvim_ui_detach()nvim_ui_detach()
Deactivates UI events on the channel.
Removes the client from the list of UIs.nvim_list_uis()
Attributes:
RPC only Since: 0.1.0
nvim_ui_pum_set_bounds()
nvim_ui_pum_set_bounds({width},{height},{row},{col}) Tells Nvim the geometry of the popupmenu, to align floating windows with an external popup menu.
Note that this method is not to be confused withnvim_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 Since: 0.5.0
Parameters:
{width} (number) Popupmenu width.
{height} (number) Popupmenu height.
{row} (number) Popupmenu row.
{col} (number) Popupmenu height.
nvim_ui_pum_set_height({height})nvim_ui_pum_set_height()
Tells Nvim the number of elements displaying in the popupmenu, to decide<PageUp> and<PageDown> movement.
Attributes:
RPC only Since: 0.4.0
Parameters:
{height} (integer) Popupmenu height, must be greater than zero.
nvim_ui_set_focus({gained})nvim_ui_set_focus()
Tells the nvim server if focus was gained or lost by the GUI
Attributes:
RPC only Since: 0.9.0
Parameters:
{gained} (boolean)
nvim_ui_set_option({name},{value})nvim_ui_set_option()
Attributes:
RPC only Since: 0.1.0
Parameters:
{name} (string)
{value} (any)
nvim_ui_term_event({event},{value})nvim_ui_term_event()
Tells Nvim when a terminal event has occurred
The following terminal events are supported:
"termresponse": The terminal sent an OSC, DCS, or APC response sequence to Nvim. The payload is the received response. Setsv:termresponse and firesTermResponse.
Attributes:
RPC only Since: 0.10.0
Parameters:
{event} (string) Event name
{value} (any) Event payload
nvim_ui_try_resize({width},{height})nvim_ui_try_resize()
Attributes:
RPC only Since: 0.1.0
Parameters:
{width} (integer)
{height} (integer)
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.
On invalid grid handle, fails with error.
Attributes:
RPC only Since: 0.4.0
Parameters:
{grid} (integer) The handle of the grid to be changed.
{width} (integer) The new requested width.
{height} (integer) The new requested height.
Main
Commands index
Quick reference

API Usage
CONNECTING
API Definitions
API metadata
API contract
Global events
Buffer update events
Buffer highlighting
Floating windows
Extended marks
Global Functions
Vimscript Functions
Command Functions
Options Functions
Buffer Functions
Extmark Functions
Window Functions
Win_config Functions
Tabpage Functions
Autocmd Functions
UI Functions

[8]ページ先頭

©2009-2025 Movatter.jp