Nvim :help pages, generated
from source
using the tree-sitter-vimdoc parser.
Nvim exposes a powerful API that can be used by plugins and external processes
via
RPC,
Lua and Vimscript (
eval-api).
Applications can also embed libnvim to work with the C API directly.
RPC is the main way to control Nvim programmatically. Nvim implements the
MessagePack-RPC protocol with these extra (out-of-spec) constraints:
Responses must be given in reverse order of requests (like "unwinding
a stack").
Nvim processes all messages (requests and notifications) in the order they
are received.
Many clients use the API: user interfaces (GUIs), remote plugins, scripts like
"nvr" (
https://github.com/mhinz/neovim-remote). Even Nvim itself can control
other 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.
See
channel-intro for various ways to open a channel. Channel-opening
functions take an
rpc key in the options dict. RPC channels can also be
opened by other processes connecting to TCP/IP sockets or named pipes listened
to by Nvim.
Nvim creates a default RPC socket at
startup, given by
v:servername. To
start 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 with
serverstart().
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-featured
api-client. Here's a Ruby script that prints "hello world!" in the current
Nvim instance:
#!/usr/bin/env ruby
# Requires msgpack: gem install msgpack
#
# To run this script, use Nvim's built-in terminal emulator:
#
# :term ruby hello.rb
#
# Or from another shell by setting NVIM:
# :echo v:servername -- this is the unix socket path address
# $ NVIM=[unix_socket_path_address] ruby ./hello.rb
# or if you run the command above: nvim --listen 127.0.0.1:6666 -- tcp socket address
# $ NVIM=127.0.0.1:6666 ruby hello.rb
require 'msgpack'
require 'socket'
sock =
if ENV['NVIM'] =~ /:\d+$/
host, port = ENV['NVIM'].split(':')
TCPSocket.new(host, port)
else
UNIXSocket.new(ENV['NVIM'])
end
sock.write([0, 0, 'nvim_command', ['echo "hello world!"']].to_msgpack)
p MessagePack::Unpacker.new(sock).read.last
Another way is to use the Python REPL with the "pynvim" package, where API
functions can be called interactively (requires
pip install pynvim or
uv add pynvim):
>>> from pynvim import attach
>>> nvim = attach('socket', path='[address]')
>>> nvim.command('echo "hello world!"')
You can also embed Nvim via
jobstart(), and communicate using
rpcrequest()
and
rpcnotify():
let nvim = jobstart(['nvim', '--embed'], {'rpc': v:true})
echo rpcrequest(nvim, 'nvim_eval', '"Hello " . "world!"')
call jobstop(nvim)
The Nvim C API defines custom types for all function parameters. Some are just
typedefs around C99 standard types, others are Nvim-defined data structures.
| API Type | C type |
| Nil | |
| Boolean | bool |
| Integer (signed 64-bit integer) | int64_t |
| Float (IEEE 754 double precision) | double |
| String | {char* data, size_t size} struct |
| Array | kvec |
| Dict (msgpack: map) | kvec |
| Object | 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 the
api-metadata types 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 |
Most of the API uses 0-based indices, and ranges are end-exclusive. For the
end of a range, -1 denotes the last line/column. A column in buffer text is a
byte index, not a character index or screen cell. See
vim.pos,
vim.range
for representing and converting positions.
Exception: the following API functions use "mark-like" indexing (1-based
lines, 0-based columns, see also
vim.pos.mark()):
Most API functions are deferred: they are queued ("scheduled") on the main
loop and processed sequentially with normal input. If the editor is waiting
for user input in a "modal" fashion (e.g. an
input() prompt), a deferred
request will block.
Non-deferred (fast) functions such
nvim_get_mode(),
nvim_input(), or any
Lua callback, are executed immediately (not sequenced in the input queue).
Lua code can use
vim.in_fast_event() to detect a fast context, where it
may interact with Lua state but not "editor" state (
textlock, options,
window layout, …).
The Nvim C API is automatically exposed to RPC by the build system, which
parses headers in src/nvim/api/* and generates dispatch-functions mapping RPC
API method names to public C API functions, converting/validating arguments
and return values.
Nvim exposes its API metadata as a Dictionary with these items:
version Nvim version, API level/compatibility
version.api_level API version integer
api-level
version.api_compatible API is backwards-compatible with this level
version.api_prerelease Declares the API as unstable/unreleased
(version.api_prerelease && fn.since == version.api_level)
functions API function signatures, containing
api-types info
describing the return value and parameters.
ui_events
UI event signatures
{fn}.since API level where function {fn} was introduced
{fn}.deprecated_since API level where function {fn} was deprecated
types Custom handle types defined by Nvim
error_types Possible error types returned by API functions
About the functions map:
Container types may be decorated with type/size constraints, e.g.
ArrayOf(Buffer) or ArrayOf(Integer, 2).
Each function parameters item is a [type, name, optional] tuple.
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 with
nvim_ plus
a type name, e.g.
nvim_buf_get_lines is the
get_lines method of
a Buffer instance.
dev-api
Global functions have the "method=false" flag and are prefixed with just
nvim_, e.g. nvim_list_bufs.
External programs (clients) can use the metadata to discover the API, using
any of these approaches:
Connect to a running Nvim instance and call
nvim_get_api_info() via
msgpack-RPC. This is best for clients written in dynamic languages which
can define functions at runtime.
Use the
--api-info startup arg. 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)'
Use the
api_info() function.
:lua vim.print(vim.fn.api_info())
" Example using filter() to exclude non-deprecated API functions:
:new|put =map(filter(api_info().functions, '!has_key(v:val,''deprecated_since'')'), 'v:val.name')
The Nvim API is composed of functions and events.
Clients call functions like those described at
api-global.
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 check
api_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 optional opts parameter may be ADDED.
Optional parameters may be ADDED following an opts parameter.
The opts parameter and any following parameters MAY BE OMITTED by the
client (equivalent to passing an empty dict). Explicitly passing a nil
value is an error.
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.
API clients can "attach" to Nvim buffers to subscribe to buffer update events.
This is similar to
TextChanged but more powerful and granular.
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} is
v:null this means the screen lines (display)
changed but not the buffer contents.
{linedata} contains the changed
screen lines. This happens when
'inccommand' shows a buffer preview.
Parameters:
{buf} (integer) Buffer id
{changedtick} (
integer) Value of
b:changedtick. If you send an API
command back to Nvim you can check
b:changedtick as
part of your request to ensure that no other changes
have been made.
{firstline} (integer) The first line that was replaced.
Zero-indexed: if line 1 was replaced then {firstline}
will be zero, not one. Always less than or equal to
the number of lines that were in the buffer before the
lines were replaced.
{lastline} (integer) 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. Always less than or equal
to the number of lines that were in the buffer before
the lines were replaced. Will be -1 if the event is
part of the initial update after attaching.
{linedata} (string[]) Contents of the new buffer lines. Newline
characters are omitted; empty lines are sent as empty
strings.
{more} (
boolean) true for a "multipart" change notification:
the current change was chunked into multiple
nvim_buf_lines_event notifications (e.g. because it
was too big).
When
b:changedtick was incremented but no text was changed. Relevant for
undo/redo.
Parameters:
{buf} (integer) Buffer id
When buffer is detached (i.e. updates are disabled). Triggered explicitly by
nvim_buf_detach() or implicitly in these cases:
Generally: whenever the buffer contents are unloaded from memory.
Parameters:
{buf} (integer) Buffer id
Calling
nvim_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 using
linewise-visual mode and then types "p" to
paste a block of 6 lines, emits:
nvim_buf_lines_event[{buf}, {changedtick}, 2, 5,
['pasted line 1', 'pasted line 2', 'pasted line 3', 'pasted line 4',
'pasted line 5', 'pasted line 6'],
v:false
]
User reloads the buffer with ":edit", emits:
nvim_buf_detach_event[{buf}]
LUA
In-process plugins can receive buffer updates via Lua callbacks. These
callbacks are called frequently in various contexts;
textlock prevents
changing buffer contents and window layout (such operations must be
scheduled). Moving the cursor is allowed, but it is restored afterwards.
nvim_buf_attach() will take keyword args for the callbacks. "on_lines" will
receive 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 can
be 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}. if
utf_sizes is set to true in
nvim_buf_attach() keyword args, then the
UTF-32 and UTF-16 sizes of the deleted region is also passed as additional
arguments
{old_utf32_size} and
{old_utf16_size}.
"on_changedtick" is invoked when
b:changedtick was incremented but no text
was changed. The parameters received are ("changedtick",
{buf},
{changedtick}).
In-process Lua callbacks can detach by returning
true. This will detach all
callbacks attached with the same
nvim_buf_attach() call without invoking the
"on_detach" callback.
Nvim allows plugins to add position-based highlights to buffers. This is
similar to
matchaddpos() but with some key differences. The added highlights
are 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 group
and delete or replace all at once.
The intended use case are linter or semantic highlighter plugins that monitor
a 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, and
want to add highlights to the outputs. Highlight data cannot be preserved
on writing and loading a buffer to file, nor in undo/redo cycles.
Highlights are registered using the
nvim_buf_set_extmark() function, which
adds highlights as
extmarks. If highlights need to be tracked or manipulated
after adding them, the returned
extmark id can be used.
-- create the highlight through an extmark
extid = 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 group
vim.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 position
vim.api.nvim_buf_set_extmark(buf, ns_id, NEW_LINE, col_start, {end_col = col_end, hl_group = NEW_HL_GROUP, id = extid})
Floating windows ("floats") are displayed on top of normal windows. This is
useful to implement simple widgets, such as tooltips displayed next to the
cursor. Floats are fully functional windows supporting user editing, common
api-window calls, and most window options (except
'statusline').
Two ways to create a floating window:
To check whether a window is floating, check whether the
relative option in
its config is non-empty:
if vim.api.nvim_win_get_config(window_id).relative ~= '' then
-- window with this window_id is floating
end
Buffer text can be highlighted by typical mechanisms (syntax highlighting,
api-highlights). The
hl-NormalFloat group highlights normal text;
'winhighlight' can be used as usual to override groups locally. Floats inherit
options from the current window; specify
style=minimal in
nvim_open_win()
to disable various visual features such as the
'number' column.
Other highlight groups specific to floating windows:
Currently, floating windows don't support some widgets like scrollbar.
The output of
:mksession does not include commands for restoring floating
windows.
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 used
call nvim_set_option_value('winhl', 'Normal:MyHighlight', {'win': win})
Extended marks (extmarks) represent buffer annotations that track text changes
in the buffer. They can represent cursors, folds, misspelled words, anything
that needs to track a logical location in the buffer over time.
api-indexing
Extmark position works like a "vertical bar" cursor: it exists between
characters. Thus, the maximum extmark index on a line is 1 more than the
character 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 an
extmark position and enter some text, the extmark migrates forward.
f o o|b a r line (| = cursor)
3 extmark
f 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 that
point, the extmark will accordingly migrate to the next line:
f o o z b a r| line (| = cursor)
7 extmark
f 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 2345678
0 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 by
namespace (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 extmarks
use
nvim_buf_del_extmark(). Deleting "x" in our example:
0 12345678
0 e|ample..
^ extmark position
echo nvim_buf_get_extmark_by_id(0, g:mark_ns, g:mark_id)
" => [0, 1]
Namespaces allow any plugin to manage only its own extmarks, ignoring those
created by another plugin.
Extmark positions changed by an edit will be restored on undo/redo. Creating
and deleting extmarks is not a buffer change, thus new undo states are not
created for extmark changes.
Emitted on the client channel if an async API request responds with an
error.
Parameters:
{type} (integer) Error type id as defined by
api_info().error_types.
{msg} (string) Error message.
Emitted by the TUI client to signal when a host-terminal event occurred.
Supports these events:
"termresponse": The host-terminal sent an OSC, DCS, APC, or recognized
CSI (DA1, kitty multiple-cursors) response to Nvim. The payload is the
received response. Sets
v:termresponse and fires
TermResponse.
Attributes:
RPC only
Since: 0.10.0
Parameters:
{event} (string) Event name
{value} (any) Event payload
Sends raw data to channel
chan.
channel-bytes
For a job, it writes it to the stdin of the process.
For an internal terminal instance (
nvim_open_term()) it writes
directly to terminal output.
This function writes raw data, not RPC messages. Use
vim.rpcrequest()
and
vim.rpcnotify() if the channel expects RPC messages (i.e. it was
created with
rpc=true).
Attributes:
RPC only
Lua
vim.api only
Since: 0.5.0
Parameters:
{chan} (integer) Channel id
{data} (string) Data to write. 8-bit clean: may contain NUL bytes.
Parameters:
{chan} (integer) Channel id, or 0 for current (RPC) channel.
{config} (vim.api.keyset.chan_set) Properties:
detach: (boolean, default: true) Closing the channel does
not self-exit Nvim. Nvim self-exits when the last
detach=false RPC channel closes. See also
:detach!.
Creates a new, empty, unnamed buffer.
Return:
(
integer) Buffer id, or 0 on error
Deletes the current line.
Attributes:
not allowed when
textlock is active
Since: 0.1.0
Unmaps a global
mapping for the given mode.
Parameters:
{mode} (string) Mode short-name ("n", "i", "v", ...)
{lhs} (
string) Left-hand-side
{lhs} of the mapping.
{opts} (vim.api.keyset.keymap_del?) Optional parameters.
lhs: When true, only match {lhs}, not {rhs}.
Note:
Lowercase name (or other buffer-local mark) is an error.
Parameters:
{name} (string) Mark name
Return:
(
boolean) true if the mark was deleted, else false.
Removes a global (g:) variable.
Parameters:
{name} (string) Variable name
Prints a message given by a list of
[text, hl_group] "chunks". Emits a
Progress event if
kind='progress'.
Returns a message-id, which can be given in later calls to update an
existing message. The message-id is an autogenerated integer, or a
user-defined string. The id "address space" is global, so plugins
specifying a string id should use qualified names such as "my.msg.id" to
avoid unintentional conflicts.
Example:
vim.api.nvim_echo({ { 'chunk1-line1\nchunk1-line2\n' }, { 'chunk2-line1' } }, true)
Parameters:
{chunks} ([string, integer|string?][]) List of [text, hl_group]
pairs, where each is a text string highlighted by the
(optional) name or ID hl_group.
{opts} (vim.api.keyset.echo_opts?) Optional parameters.
err (
boolean?) Treat the message like
:echoerr. Sets
hl_group to
hl-ErrorMsg by default.
id (integer|string?) Message-id returned by a previous
nvim_echo call, or a user-defined id (string). If
existing message has this id, it will be updated instead
of creating a new message.
percent (
integer?)
progress-message percentage, or
nil to signal "unknown progress".
"success": Process completed successfully.
"running": Process is ongoing.
"failed": Process failed.
"cancel": Process should be cancelled. Progress owner
must handle the
Progress event to perform the
cancellation.
verbose (
boolean?) Message is controlled by the
'verbose' option.
nvim -V3log will write the message to
the "log" file instead of standard output.
Return:
(
integer|string) Message-id, or -1 if message wasn't shown.
Evaluates statusline string.
Parameters:
{opts} (vim.api.keyset.eval_statusline?) Optional parameters.
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.
maxwidth: (number) Maximum width of statusline.
use_statuscol_lnum: (number) Evaluate statuscolumn for this
line number instead of statusline.
use_tabline: (boolean) Evaluate tabline instead of
statusline. When true, {winid} is ignored. Mutually
exclusive with {use_winbar}.
use_winbar: (boolean) Evaluate winbar instead of statusline.
winid: (number)
window-ID of the window to use as context
for 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 a
Dict with these keys:
start: (number) Byte index (0-based) of first character that uses
the highlight.
group: (string) Deprecated. Use groups instead.
groups: (array) Names of stacked highlight groups (highest
priority last).
Executes Lua code. Arguments are available as
... inside the chunk. The
chunk can return a value.
Only statements are executed. To evaluate an expression, prefix it with
"return": return my_function(...)
Example:
local peer = vim.fn.jobstart({ vim.v.progpath, '--clean', '--embed' }, { rpc=true })
vim.print(vim.rpcrequest(peer, 'nvim_exec_lua', [[
local a, b = ...
return ('result: %s'):format(a + b)
]],
{ 1, 3 }
)
)
Attributes:
RPC only
Since: 0.5.0
Parameters:
{code} (string) Lua code to execute.
{args} (any[]) Arguments to the Lua code.
Return:
(
any) Value returned by the Lua code (if any), or NIL.
Sends input-keys to Nvim, subject to various quirks controlled by
mode
flags. This is a blocking call, unlike
nvim_input().
On execution error: does not fail, but updates v:errmsg.
To input keycodes like
<C-o>, pass the result of
nvim_replace_termcodes():
:let key = nvim_replace_termcodes('<C-o>', v:true, v:false, v:true)
:call nvim_feedkeys(key, 'n', v:false)
Parameters:
{keys} (string) Keys to send as input.
{escape_ks} (
boolean) If true, escape K_SPECIAL bytes in
keys.
Should be false if you used
nvim_replace_termcodes(),
else true.
See also:
feedkeys()
vim_strsave_escape_ks
Returns a 2-tuple (Array), where item 0 is the current channel id and item
1 is the
api-metadata map (Dict).
Return:
(
[any, any]) 2-tuple
[{channel-id}, {api-metadata}]
Gets information about a channel.
Parameters:
{chan} (integer) Channel id, or 0 for current (RPC) channel
Return:
(
table<string,any>) Channel info dict with these keys:
"argv" (optional) Job arguments list.
"buf" (optional) Buffer connected to
terminal instance.
"buffer" (optional) Deprecated alias for buf.
"client" (optional) Info about the peer (client on the other end of
the channel), as set by
nvim_set_client_info().
"exitcode" (optional) Exit code of the
terminal process.
"id" Channel id.
"internal" (optional) In-process channel (stream=socket).
"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).
"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.
Example:
:echo nvim_get_color_by_name("Pink")
:echo nvim_get_color_by_name("#cbcbcb")
Parameters:
{name} (string) Color name or "#rrggbb" string
Return:
(
integer) 24-bit RGB value, or -1 for invalid argument.
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).
Return:
(
table<string,integer>) Map of color names and RGB values.
Gets a map (msgpack encoding) of the current editor state:
Parameters:
{opts} (vim.api.keyset.context?) Optional parameters.
types: List of context types (see above) to gather, or empty
for "all".
Return:
(
table<string,any>) Editor state as a msgpack-encoded map.
Return:
(
integer) Buffer id
Return:
(
string) Current line string
Gets the current tabpage.
Gets all or specific highlight groups in a namespace.
Note:
When the
link attribute is defined in the highlight definition map,
other attributes will not be taking effect (see
:hi-link).
Parameters:
{opts} (vim.api.keyset.get_highlight?) Options dict:
create: (boolean, default true) When highlight group
doesn't exist create it.
id: (integer) Get a highlight definition by id.
link: (boolean, default true) Show linked group name
instead of effective definition
:hi-link.
name: (string) Get a highlight definition by name.
Return:
(
vim.api.keyset.get_hl_info) Highlight groups as a map from group
name to a highlight definition map as in
nvim_set_hl(), or only a
single highlight definition map if requested by name or id.
Gets a highlight group by name
similar to
hlID(), but allocates a new ID if not present.
Parameters:
{name} (string)
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 when
nvim_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
Gets a list of global (non-buffer-local)
mapping definitions.
Parameters:
{mode} (string) Mode short-name ("n", "i", "v", ...)
Return:
(
vim.api.keyset.get_keymap[]) Array of
maparg()-like dictionaries
describing mappings. The "buf" key is always zero.
Returns a
(row, col, buffer, buffername) tuple representing the position
of the uppercase/file named mark. "End of line" column position is
returned as
v:maxcol (big number). See
mark-motions.
Note:
Lowercase name (or other buffer-local mark) is an error.
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.
Gets the current mode.
mode() "blocking" is true if Nvim is waiting for
input.
Return:
(
vim.api.keyset.get_mode) Dict { "mode": String, "blocking": Boolean
}
Gets info describing process
pid.
Parameters:
{pid} (integer)
Return:
(
any) Map of process properties, or NIL if process not found.
Gets the immediate children of process
pid.
Parameters:
{pid} (integer)
Return:
(
any[]) Array of child process ids, empty if process not found.
"name" can contain wildcards. For example
nvim_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.
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
Gets a global (g:) variable.
Parameters:
{name} (string) Variable name
Return:
(
any) Variable value
Parameters:
{name} (string) Variable name
Return:
(
any) Variable value
Queues raw user-input. Unlike
nvim_feedkeys(), this uses a low-level
input buffer and the call is non-blocking (input is processed
asynchronously by the eventloop).
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>.
Parameters:
{keys} (string) to be typed
Return:
(
integer) Number of bytes actually written (can be fewer than
requested if the buffer becomes full).
Send mouse event from GUI.
Non-blocking: does not wait on any result, but queues the event to be
processed soon by the event loop.
Note:
Currently this doesn't support "scripting" multiple mouse events by
calling it multiple times in a loop: the intermediate mouse positions
will be ignored. It should be used to implement real-time mouse input
in a GUI. The deprecated pseudokey form (
<LeftMouse><col,row>) of
nvim_input() has the same limitation.
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 (used by
ui-multigrid client),
or 0 to let Nvim decide positioning of windows. For more
information, see
dev-ui-multigrid
{row} (integer) Mouse row-position (zero-based, like redraw
events)
{col} (integer) Mouse column-position (zero-based, like redraw
events)
Gets the current list of buffers.
Includes unlisted (unloaded/deleted) buffers, like
:ls!. Use
nvim_buf_is_loaded() to check if a buffer is loaded.
Return:
(
integer[]) List of buffer ids
Get information about all open channels.
Return:
(
table<string,any>[]) Array of Dictionaries, each describing a
channel with the format specified at
nvim_get_chan_info().
Return:
(
string[]) List of paths
Gets the current list of
tab-IDs.
Return:
(
integer[]) List of
tab-IDs
Gets a list of dictionaries representing attached UIs.
Example: The Nvim builtin
TUI sets its channel info as described in
startup-tui. In particular, it sets
client.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)
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 implies
cterm-colors)
"ext_..." Requested UI extensions, see
ui-option
Gets the current list of all
window-IDs in all tabpages.
Sets the current editor state from the given map.
Parameters:
{dict} (
table<string,any>) Msgpack-encoded editor state, in the
form returned by
nvim_get_context().
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: :ls reports the buffer as "R" (running) until the channel is
closed.
chanclose()
Note: To initialize the terminal size, display the buffer in a window
first. E.g. for a floating display,
Call nvim_open_term().
Then calling
nvim_chan_send() will process sequences in a virtual
terminal with the intended size (defined by the window width/height).
Example: this
TermHl 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-colorize vim.api.nvim_create_user_command('TermHl', function()
vim.api.nvim_open_term(0)
end, { desc = 'Highlights ANSI termcodes in curbuf' })
Attributes:
not allowed when
textlock is active
Since: 0.5.0
Parameters:
{buf} (integer) Buffer which displays the PTY output. The initial
buffer contents (if any) will be written to the PTY.
{opts} (vim.api.keyset.open_term?) Optional parameters.
force_crlf: (boolean, default: true) Convert "\n" to "\r\n".
on_input:
(
fun("input", chan: integer, buf: integer, data: string))
Function invoked when the terminal emits bytes, see above.
textlock applies. May call
nvim_chan_send() directly.
Return:
(
integer) Channel id, or 0 on error
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
to
nvim_input() which is subject to mappings/events and is thus much
slower).
Invokes the
vim.paste() handler, which handles each mode appropriately.
Errors (
'nomodifiable',
vim.paste() failure, …) are reflected in
err
but do not affect the return value (which is strictly decided by
vim.paste()). On error 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, { buf = 0 })
Attributes:
not allowed when
textlock 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, call nvim_paste
sequentially with these phase values:
1: starts the paste (exactly once)
2: continues the paste (zero or more times)
3: ends the paste (exactly once)
Return:
(
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, use
nvim_paste().
Compare
:put and
p which are always linewise.
Attributes:
not allowed when
textlock is active
Since: 0.4.0
Parameters:
{after} (
boolean) If true insert after cursor (like
p), or
before (like
P).
{follow} (boolean) If true place cursor at end of inserted text.
Converts terminal codes and
keycodes (
<CR>,
<Esc>, …) in a key
sequence, to the internal representation. See also Lua
vim.keycode().
Parameters:
{str} (string) String to be converted.
{from_part} (boolean) Legacy Vim parameter. Usually true.
{do_lt} (boolean) Also translate <lt>. Ignored if special is
false.
{special} (
boolean) Replace
keycodes, e.g.
<CR> becomes a "\r"
char.
See also:
replace_termcodes
cpoptions
nvim_select_popupmenu_item({item}, {insert}, {finish}, {opts})
Selects an item in the completion popup menu.
If neither
ins-completion nor
cmdline-completion popup menu is active
this API call is silently ignored. Useful for an external UI using
ui-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.
Parameters:
{item} (integer) Index (zero-based) of the item to select. Value
of -1 selects nothing and restores the original text.
{finish} (boolean) Finish the completion and dismiss the popup
menu. Implies {insert}.
{opts} (vim.api.keyset.empty?) Optional parameters. Reserved for
future use.
Self-identifies the client, and sets optional flags on the channel.
Defines the
client object returned by
nvim_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 set name.)
Can be called more than once; caller should merge old info if appropriate.
Example: a library first identifies the channel, then a plugin using that
library later identifies itself.
Attributes:
RPC only
Since: 0.3.0
Parameters:
{version} (table<string,any>) Dict describing the version, with
these (optional) keys:
"commit" hash or similar identifier of commit
"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"
{type} (string) Must be one of the following values. Client
libraries should default to "remote" unless overridden
by the user.
"embedder" application using Nvim as a component (for
example, IDE/editor implementing a vim mode).
"host" plugin host, typically started by nvim
"msgpack-rpc" remote client connected to Nvim via
fully MessagePack-RPC compliant protocol.
"plugin" single plugin, started by nvim
"remote" remote client connected "Nvim flavored"
MessagePack-RPC (responses must be in reverse order of
requests).
msgpack-rpc
"ui" gui frontend
{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:
"license": License description ("Apache 2", "GPLv3",
"MIT", …)
"logo": URI or path to image, preferably small logo or
icon. .png or .svg format is preferred.
"pid": Process id.
"website": Client homepage URL (e.g. GitHub
repository)
Sets the current window's buffer to
buf.
Attributes:
not allowed when
textlock is active
Since: 0.1.0
Parameters:
{buf} (integer) Buffer id
Changes the global working directory.
Parameters:
{dir} (string) Directory path
Sets the text on the current line.
Attributes:
not allowed when
textlock is active
Since: 0.1.0
Parameters:
{line} (string) Line contents
Sets the current tabpage.
Attributes:
not allowed when
textlock is active
Since: 0.1.0
Parameters:
{tabpage} (
integer)
tab-ID to focus
Navigates to the given window (and tabpage, implicitly).
Attributes:
not allowed when
textlock is active
Since: 0.1.0
Sets a highlight group. By default, replaces the entire definition (e.g.
nvim_set_hl(0, 'Visual', {}) will clear the "Visual" group), unless
update is specified.
Note:
The fg and bg keys also accept the string values "fg" or "bg"
which act as aliases to the corresponding foreground and background
values of the Normal group. If the Normal group has not been defined,
using these values results in an error.
If
link is used in combination with other attributes; only the
link will take effect (see
:hi-link).
Parameters:
{name} (string) Highlight group name, e.g. "ErrorMsg"
{val} (vim.api.keyset.highlight) Highlight definition map,
accepts the following keys:
altfont: boolean
bg: color name or "#RRGGBB", see note.
bg_indexed: boolean. If true, bg is an RGB approximation
of ctermbg (a palette index). UIs rendering cterm
natively may prefer ctermbg.
blend: integer between 0 and 100
blink: boolean
bold: boolean
conceal: boolean Concealment at the UI level (terminal
SGR), unrelated to
:syn-conceal.
cterm: cterm attribute map, like
highlight-args. If not
set, cterm attributes will match those from the attribute
map documented above.
ctermbg: Sets background of cterm color
ctermbg
ctermfg: Sets foreground of cterm color
ctermfg
default: boolean Don't override existing definition
:hi-default
dim: boolean
fg: Color name or "#RRGGBB", see note.
fg_indexed: boolean. Same as bg_indexed, for fg and
ctermfg.
font: GUI font name (string). Sets
highlight-font. Use
"NONE" to clear.
force: (boolean, default: false) Update the highlight group
even if it already exists.
italic: boolean
link: Name of highlight group to link to.
:hi-link
link_global: Like "link", but always resolved in the global
namespace (ns=0).
nocombine: boolean
overline: boolean
reverse: boolean
sp: Color name or "#RRGGBB"
standout: boolean
strikethrough: boolean
undercurl: boolean
underdashed: boolean
underdotted: boolean
underdouble: boolean
underline: boolean
update: (boolean, default: false) Update specified
attributes only, leave others unchanged.
Parameters:
{ns_id} (integer) the namespace to use
Set active namespace for highlights defined with
nvim_set_hl() while
redrawing.
This function is meant to be called while redrawing, primarily from
nvim_set_decoration_provider() on_win and on_line callbacks, which are
allowed to change the namespace during a redraw cycle.
Parameters:
{ns_id} (integer) the namespace to activate
Sets a global
mapping for the given mode.
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>
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:
"callback" Lua function called in place of {rhs}.
"desc" human-readable description.
"replace_keycodes" (boolean) When "expr" is true, replace
keycodes in the resulting string (see
nvim_replace_termcodes()). Returning nil from the Lua
"callback" is equivalent to returning an empty string.
Sets a global (g:) variable.
Parameters:
{name} (string) Variable name
{value} (any) Variable value
Sets a v: variable, if it is not readonly.
Parameters:
{name} (string) Variable name
{value} (any) Variable value
Calculates the number of display cells occupied by
text. Control
characters including
<Tab> count as one cell.
Parameters:
{text} (string) Some text
Return:
(
integer) Number of cells
WARNING: This feature is experimental/unstable.
Records the cmdwin scratchbuf and type, or clears both when type="" /
buf=0. Internal use only.
Attributes:
Since: 0.12.0
Parameters:
{type} (string) ':', '/', '?' (first char only); empty to clear.
{buf} (integer) cmdwin buffer id, or 0 to clear.
WARNING: This feature is experimental/unstable.
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,integer>) Dict containing these keys:
winid: (integer) floating window id
bufnr: (integer) buffer id in floating window
WARNING: This feature is experimental/unstable.
Execute Lua code. Parameters (if any) are available as ... inside the
chunk. The chunk can return a value.
Only statements are executed. To evaluate an expression, prefix it with
return: return my_function(...)
Parameters:
{code} (string) Lua code to execute
{args} (any[]) Arguments to the code
Return:
(
any) Return value of Lua code if present or NIL.
WARNING: This feature is experimental/unstable.
Find files in runtime directories
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
WARNING: This feature is experimental/unstable.
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.
WARNING: This feature is experimental/unstable.
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.
WARNING: This feature is experimental/unstable.
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.
WARNING: This feature is experimental/unstable.
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.
WARNING: This feature is experimental/unstable.
NB: if your UI doesn't use hlstate, this will not return hlstate first
time.
Parameters:
{grid} (integer)
{row} (integer)
{col} (integer)
WARNING: This feature is experimental/unstable.
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.
WARNING: This feature is experimental/unstable.
Instruct Nvim to redraw various components.
Attributes:
Since: 0.10.0
Parameters:
{opts} (vim.api.keyset.redraw?) Optional parameters.
buf: Target a specific buffer number as described below.
cursor: Immediately update cursor position on the screen in
win or the current window.
flush: Update the screen with pending updates.
range: Redraw a range in
buf, the buffer in
win 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-exclusive
api-indexing.
statusline: Redraw the
'statusline' in
buf,
win or all
windows.
valid: When present mark win, buf, or all windows for
redraw. When true, only redraw changed lines (useful for
decoration providers). When false, forcefully redraw.
win: Target a specific
window-ID as described below.
winbar: Redraw the
'winbar' in
buf,
win or all windows.
WARNING: This feature is experimental/unstable.
Parameters:
{progpath} (string)
{argv} (any[])
WARNING: This feature is experimental/unstable.
Gets internal stats.
Return:
(
table<string,any>) Map of various internal stats.
On execution error: fails with Vimscript error, updates v:errmsg.
Parameters:
{dict} (
any) Dict, or String evaluating to a Vimscript
self 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
Calls a Vimscript function with the given arguments.
On execution error: fails with Vimscript error, updates v:errmsg.
Parameters:
{fn} (string) Function to call
{args} (any[]) Function arguments packed in an Array
Return:
(
any) Result of the function call
On execution error: fails with Vimscript error, updates v:errmsg.
Parameters:
{cmd} (string) Ex command string
Evaluates a Vimscript
expression. Dicts and Lists are recursively
expanded.
On execution error: fails with Vimscript error, updates v:errmsg.
Parameters:
{expr} (string) Vimscript expression string
Return:
(
any) Evaluation result or expanded object
Executes Vimscript (multiline block of Ex commands), like anonymous
:source.
Unlike
nvim_command() this function supports heredocs, script-scope
(s:), etc.
On execution error: fails with Vimscript error, updates v:errmsg.
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 if opts.output is true.
Parse a Vimscript expression.
Parameters:
{expr} (string) Expression to parse. Always treated as a single
line.
{flags} (string) Flags:
"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".
"m" if multiple expressions in a row are allowed (only the
first one will be parsed),
Common flag sets:
"E" to parse like for "<C-r>=".
"lm" to parse for ":let".
"m" to parse like for ":echo".
empty string for ":call".
{hl} (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.
Clears all autocommands matching the
{opts} query. To delete autocmds see
nvim_del_autocmd().
Parameters:
{opts} (vim.api.keyset.clear_autocmds?) Optional parameters:
buf: (
integer?) Select
autocmd-buflocal autocommands.
Not allowed with
{pattern}.
event: (vim.api.keyset.events|vim.api.keyset.events[]?)
Examples:
event: "pat1"
event: { "pat1" }
event: { "pat1", "pat2", "pat3" }
group: (string|int?) Group name or id.
NOTE: If not given, matches autocmds not in any group.
pattern: (string|table?) Filter by patterns (exact match).
Not allowed with {buf}.
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.
To get an existing group id, do:
local id = vim.api.nvim_create_augroup('my.lsp.config', {
clear = false
})
Parameters:
{name} (string) Group name
{opts} (vim.api.keyset.create_augroup?) Optional parameters:
clear (
boolean?, default: true) Clear existing commands in
the group
autocmd-groups.
Return:
(
integer) Group id.
Creates an
autocommand event handler, defined by
callback (Lua
function or Vimscript function name string) or
command (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'
Parameters:
{event} (vim.api.keyset.events|vim.api.keyset.events[]) Event(s)
that will trigger the handler (callback or command): one
handler is created for each event name.
{opts} (vim.api.keyset.create_autocmd?) Options dict:
buf (
integer?) Buffer id for buffer-local autocommands
autocmd-buflocal. Not allowed with
{pattern}.
callback (
function|string?) Lua function (or Vimscript
function name, if string) called when the event(s) is
triggered. Lua callback can return
lua-truthy to delete
the autocommand. Callback receives one argument, a table
with keys:
event-args
buf: (integer) <abuf>
event: (
vim.api.keyset.events) Name of the triggered
event
autocmd-events
file: (string) <afile> (not expanded to a full path)
group: (integer?) Group id, if any
id: (integer) Autocommand id
match: (string) <amatch> (expanded to a full path)
win: (
integer) id of the window for the event, see
window-ID
command (string?) Vim command executed on event. Not
allowed with {callback}.
desc (string?) Description (for documentation and
troubleshooting).
group (string|integer?) Group name or id to match
against.
nested (
boolean?, default: false) Run nested autocommands
autocmd-nested.
once (
boolean?, default: false) Handle the event only
once
autocmd-once. If
{event} is a list, each handler
will fire once.
Return:
(
integer) Autocommand id (number)
Delete an autocommand group by id.
NOTE: behavior differs from
:augroup-delete. When deleting a group,
autocommands contained in this group will also be deleted and cleared.
This group will no longer exist.
Parameters:
{id} (integer) Group id.
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.
Parameters:
{name} (string) Group name.
Deletes an autocommand by id.
Executes
{event} handlers matching the
{opts} query, in the context of
{buf} (if given).
autocmd-execute
Parameters:
{event} (vim.api.keyset.events|vim.api.keyset.events[]) Event(s) to
execute.
{opts} (vim.api.keyset.exec_autocmds?) Optional filters:
buf (
integer?) Buffer where the event is applied.
autocmd-buflocal Not allowed with
{pattern}.
group (
string|integer?) Group name or id to match
against.
autocmd-groups.
modeline (boolean?, default: true) Process the modeline
after the autocommands <nomodeline>. Ignored if buf is
given.
pattern (
string|array?, default: current file name)
autocmd-pattern. Not allowed with
{buf}.
Gets all autocommands matching ALL criteria in the
{opts} query.
Note: When multiple patterns or events are provided they have "OR"
semantics (any combination is matched).
Examples:
-- Matches all criteria
autocommands = vim.api.nvim_get_autocmds({
group = 'MyGroup',
event = {'BufEnter', 'BufWinEnter'},
pattern = {'*.c', '*.h'}
})
-- All commands from one group
autocommands = vim.api.nvim_get_autocmds({
group = 'MyGroup',
})
Parameters:
{opts} (vim.api.keyset.get_autocmds?) Dict with at least one of
these keys:
buf: (
integer[]|integer?) Buffer id or list of buffer ids,
for buffer-local autocommands
autocmd-buflocal. Not
allowed with
{pattern}.
event: (
vim.api.keyset.events|vim.api.keyset.events[]?)
Event(s) to match
autocmd-events.
group: (string|table?) Group name or id to match.
id: (integer?) Autocommand ID to match.
pattern: (
string|table?) Pattern(s) to match
autocmd-pattern. Not allowed with
{buf}.
Return:
(
vim.api.keyset.get_autocmds.ret[]) Array of matching autocommands,
where each item has:
callback: (function|string?): Event handler: a Lua function or
Vimscript function name.
command: (string) Event handler: an Ex-command. Empty if a
callback is set.
desc: (string) Description.
event: (vim.api.keyset.events) Event name(s).
group: (integer) Group id.
group_name: (string) Group name.
id: (integer) Autocommand id (only when defined with the API).
pattern: (string) Autocommand pattern.
For more information on buffers, see
buffers.
Buffers may be unloaded by the
:bunload command or the buffer's
'bufhidden' option. When a buffer is unloaded its file contents are freed
from memory and vim cannot operate on the buffer lines until it is reloaded
(usually by opening the buffer again in a new window). API methods such as
nvim_buf_get_lines() and
nvim_buf_line_count() will be affected.
Example (Lua): capture buffer updates in a global
events variable (use
"vim.print(events)" to see its contents):
events = {}
vim.api.nvim_buf_attach(0, false, {
on_lines = function(...)
table.insert(events, {...})
end,
})
Parameters:
{buf} (integer) Buffer id, or 0 for current buffer
{send_buffer} (boolean) True if the initial notification should
contain the whole buffer: first notification will be
nvim_buf_lines_event. Else the first notification
will be nvim_buf_changedtick_event. Not for Lua
callbacks.
{opts} (vim.api.keyset.buf_attach?) Optional parameters.
on_bytes: Called on granular changes (compared to
on_lines). Not called on buffer reload (
:checktime,
:edit, …), see
on_reload. Returning
lua-truthy deletes the callback. 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: Called on
changetick increment
without text change. Args:
the string "changedtick"
buffer id
b:changedtick
on_detach: Called on detach, or when the buffer is
unloaded or deleted. Not called when a callback
returns
lua-truthy to delete itself. Args:
the string "detach"
buffer id
on_lines: Called on linewise changes. Not called on
buffer reload (
:checktime,
:edit, …), see
on_reload. Returning
lua-truthy deletes the
callback. 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 (if utf_sizes is true)
deleted_codeunits (if utf_sizes is true)
on_reload: Called on whole-buffer load (:checktime,
:edit, …). Clients should typically re-fetch the
entire buffer contents. Args:
the string "reload"
buffer id
preview: also attach to command preview (i.e.
'inccommand') events.
utf_sizes: include UTF-32 and UTF-16 size of the
replaced region, as args to on_lines.
Return:
(
boolean) False if attach failed (invalid parameter, or buffer isn't
loaded); otherwise True.
Calls function
fn in the context of buffer
buf and returns its result
(may be multiple values).
This temporarily switches current buffer to buf. If the current window
already shows buf, 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, like jobstart(…, {'term': v:true}).
Attributes:
Lua
vim.api only
Since: 0.5.0
Parameters:
{buf} (integer) Buffer id, or 0 for current buffer.
{fn} (function) Lua function to call inside the buffer.
Return:
(
any) Value(s) returned by
fn().
Unmaps a buffer-local
mapping for the given mode.
Parameters:
{buf} (integer) Buffer id, or 0 for current buffer
{mode} (string) Mode short-name ("n", "i", "v", ...)
{lhs} (
string) Left-hand-side
{lhs} of the mapping.
{opts} (vim.api.keyset.keymap_del?) Optional parameters.
lhs: When true, only match {lhs}, not {rhs}.
Note:
only deletes marks set in the buffer, if the mark is not set in the
buffer it will return false.
Parameters:
{buf} (integer) Buffer to set the mark on
{name} (string) Mark name
Return:
(
boolean) true if the mark was deleted, else false.
Removes a buffer-scoped (b:) variable
Parameters:
{buf} (integer) Buffer id, or 0 for current buffer
{name} (string) Variable name
Deletes a buffer and its metadata (like
:bwipeout).
To get
:bdelete behavior, reset
'buflisted' and pass
unload=true:
vim.bo.buflisted = false
vim.api.nvim_buf_delete(0, { unload = true })
Attributes:
not allowed when
textlock is active
Since: 0.5.0
Parameters:
{buf} (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.
Deactivates buffer-update events on the channel.
Attributes:
RPC only
Since: 0.3.0
Parameters:
{buf} (integer) Buffer id, or 0 for current buffer
Return:
(
boolean) False if detach failed (because the buffer isn't loaded);
otherwise True.
Gets a changed tick of a buffer
Parameters:
{buf} (integer) Buffer id, or 0 for current buffer
Return:
(
integer)
b:changedtick value.
Gets a list of buffer-local
mapping definitions.
Parameters:
{buf} (integer) Buffer id, or 0 for current buffer
{mode} (string) Mode short-name ("n", "i", "v", ...)
Return:
(
vim.api.keyset.get_keymap[]) Array of
maparg()-like dictionaries
describing mappings. The "buf" key holds the associated buffer id.
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, unless
strict_indexing is set.
Parameters:
{buf} (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.
Returns a
(row,col) tuple representing the position of the named mark.
"End of line" column position is returned as
v:maxcol (big number). See
mark-motions.
Parameters:
{buf} (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.
Gets the full/absolute filepath of the buffer, or the buffer name for
non-file buffers.
If the buffer represents a directory, the name ends with a path separator,
unless it was changed by
:file or
nvim_buf_set_name().
Parameters:
{buf} (integer) Buffer id, or 0 for current buffer
Return:
(
string) Buffer name
Line 1 (index=0) has offset 0. UTF-8 bytes are counted. EOL is one byte.
'fileformat' and
'fileencoding' are ignored. The line index just after the
last line gives the total byte-count of the buffer. A final EOL byte is
counted if it would be written, see
'eol'.
Unlike
line2byte(), throws error for out-of-bounds indexing. Returns -1
for unloaded buffer.
Parameters:
{buf} (integer) Buffer id, or 0 for current buffer
{index} (integer) Line index
Return:
(
integer) Integer byte offset, or -1 for unloaded buffer.
Indexing is zero-based. Row indices are end-inclusive, and column indices
are end-exclusive.
Parameters:
{buf} (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.
Gets a buffer-scoped (b:) variable.
Parameters:
{buf} (integer) Buffer id, or 0 for current buffer
{name} (string) Variable name
Return:
(
any) Variable value
Checks if a buffer is valid and loaded. See
api-buffer for more info
about unloaded buffers.
Parameters:
{buf} (integer) Buffer id, or 0 for current buffer
Return:
(
boolean) true if the buffer is valid and loaded, false otherwise.
Checks if a buffer is valid.
Note:
Even if a buffer is valid it may have been unloaded. See
api-buffer
for more info about unloaded buffers.
Parameters:
{buf} (integer) Buffer id, or 0 for current buffer
Return:
(
boolean) true if the buffer is valid, false otherwise.
Returns the number of lines in the given buffer.
Parameters:
{buf} (integer) Buffer id, or 0 for current buffer
Return:
(
integer) Line count, or 0 for unloaded buffer.
api-buffer
Sets a buffer-local
mapping for the given mode.
Parameters:
{buf} (integer) Buffer id, or 0 for current buffer
{mode} (string)
{lhs} (string)
{rhs} (string)
{opts} (vim.api.keyset.keymap?)
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, set start and end to the same index.
To delete a range of lines, set replacement to an empty array.
Out-of-bounds indices are clamped to the nearest valid value, unless
strict_indexing is set.
Attributes:
not allowed when
textlock is active
Since: 0.1.0
Parameters:
{buf} (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
Sets a named mark in the given buffer, all marks are allowed
file/uppercase, visual, last change, etc. See
mark-motions.
Note:
Passing 0 as line deletes the mark
Parameters:
{buf} (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.
Sets the full file name for a buffer, like
:file_f
Parameters:
{buf} (integer) Buffer id, or 0 for current buffer
{name} (string) Buffer name
nvim_buf_set_text(
{buf},
{start_row},
{start_col},
{end_row},
{end_col},
{replacement})
nvim_buf_set_text()
Sets (replaces) a range in the buffer
This is recommended over
nvim_buf_set_lines() when only modifying parts
of a line, as extmarks will be preserved on non-modified parts of the
touched lines.
Indexing is zero-based. Row indices are end-inclusive, and column indices
are end-exclusive.
To insert text at a given (row, column) location, use
start_row = end_row = row and start_col = end_col = col. To delete the
text in a range, use replacement = {}.
Attributes:
not allowed when
textlock is active
Since: 0.5.0
Parameters:
{buf} (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
Sets a buffer-scoped (b:) variable
Parameters:
{buf} (integer) Buffer id, or 0 for current buffer
{name} (string) Variable name
{value} (any) Variable value
Parameters:
{buf} (integer) Buffer id, or 0 for current buffer.
{name} (string)
{cmd} (any)
{opts} (vim.api.keyset.user_command?)
See also:
nvim_create_user_command
Delete a buffer-local user-defined command.
Parameters:
{buf} (integer) Buffer id, or 0 for current buffer.
{name} (string) Name of the command to delete.
Parameters:
{buf} (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.
Executes an Ex command
cmd, specified as a Dict with the same structure
as returned by
nvim_parse_cmd().
Use
magic={…=false} to disable special chars (see also
open-file):
vim.api.nvim_cmd({
cmd = 'edit',
args = { '%foo"|bar#baz"' },
magic = { file = false, bar = false }
},
{}
)
See
nvim_parse_cmd() to parse a cmdline string (which can then be
passed to
nvim_cmd).
On execution error: fails with Vimscript error, updates v:errmsg.
Parameters:
{cmd} (
vim.api.keyset.cmd) Command to execute, a Dict with the
same structure as the return value of
nvim_parse_cmd()
(except "addr", "nargs" and "nextcmd" are ignored). All keys
except "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
:!) if
output is
true, else empty string.
Example:
:call nvim_create_user_command('SayHello', 'echo "Hello world!"', {'bang': v:true})
:SayHello
Hello world!
Parameters:
{name} (string) Command name. First char must be uppercase.
{cmd} (string|fun(args: vim.api.keyset.create_user_command.command_args))
Command or Lua function, executed when the command is invoked.
Lua function receives a table with keys:
args: (string) Args passed to the command, if any. <args>
bang: (boolean) true if the command was executed with "!".
<bang>
count: (number) Count, if any. <count>
fargs: (table) Args split by unescaped whitespace (when more
than one arg is allowed), if any. <f-args>
line1: (number) Start of the command range. <line1>
line2: (number) End of the command range. <line2>
mods: (string) Command modifiers (unstructured string), if
any. <mods>
name: (string) Command name.
nargs: (string) Number of arguments allowed by the command.
:command-nargs
range: (number) Number of items in the command range: 0, 1,
or 2. <range>
reg: (string) Register name, if any. <reg>
smods: (table) Command modifiers (structured), same as
"mods" in
nvim_parse_cmd().
{opts} (vim.api.keyset.user_command?) Optional flags:
desc (string) Command description.
force (boolean, default true) Override the existing
definition, if any.
Delete a user-defined command.
Parameters:
{name} (string) Name of the command to delete.
Gets a map of global (non-buffer-local) Ex commands.
Currently only
user-commands are supported, not builtin Ex commands.
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.
Doesn't check the validity of command arguments.
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.
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.
pattern: (string) Filter pattern. Empty string if there is no
filter.
force: (boolean) Whether filter is inverted or not.
tab: (integer)
:tab. -1 when omitted.
verbose: (integer)
:verbose. -1 when omitted.
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:
Lines are 0-indexed.
api-indexing To clear the namespace in the entire
buffer, specify line_start=0 and line_end=-1.
Parameters:
{buf} (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.
Parameters:
{buf} (integer) Buffer id, or 0 for current buffer
{id} (integer) Extmark id
Return:
(
boolean) true if the extmark was found, else false
Gets the position (0-indexed) of an
extmark.
Parameters:
{buf} (integer) Buffer id, or 0 for current buffer
{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, details?) tuple or empty list () if extmark id was absent.
The optional
details dictionary contains the same keys as
opts in
nvim_buf_set_extmark(), except for
id,
conceal_lines and
ephemeral. It also contains the following keys:
invalid: boolean that indicates whether the mark is hidden because
the entirety of text span range is deleted. See also the key
invalidate in
nvim_buf_set_extmark().
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})
If end is less than start, marks are returned in reverse order.
(Useful with limit, 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
When using extmark ranges (marks with a end_row/end_col position) the
overlap option might be useful. Otherwise only the start position of
an extmark will be considered.
The
:marks command can list extmarks.
Legacy signs placed through the
:sign commands are implemented as
extmarks. Their details array will contain a
sign_name field.
Example:
local api = vim.api
local 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)
Parameters:
{buf} (integer) Buffer id, or 0 for current buffer
{ns_id} (
integer)
namespace id, 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:
details: Whether to include the details dict
hl_name: Whether to include highlight group name instead of
id, true if omitted
limit: Maximum number of marks to return
overlap: Also include marks which overlap the range, even
if their start position is less than start
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, details?] tuples in "traversal order". For
the
details dictionary, see
nvim_buf_get_extmark_by_id().
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 by end_col and end_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).
Parameters:
{buf} (integer) Buffer id, or 0 for current buffer
{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:
conceal: (boolean|string)
string: Single char or empty string, enables conceal
similar to
:syn-conceal. Non-empty char is used as
:syn-cchar. Highlighted with "hl_group" if defined,
else defaults to
hl-Conceal.
boolean: true is equivalent to "", false removes any
existing conceal.
conceal_lines: (string) Line-level conceal. When set to an
empty string (other values reserved for future use), the
lines in the extmark range are not drawn; the next
non-concealed line is drawn in their place. Requires
'conceallevel' >= 2; subject to
'concealcursor' on the
cursor line.
cursorline_hl_group: Highlight group used for the
'signcolumn' text when the cursor is on the same line as
the mark and
'cursorline' is enabled.
end_col: End-column of the mark, 0-based exclusive, or -1
to extend the range to end of line (if strict=false).
end_right_gravity: (boolean, default: false) Indicates
which direction the extmark end-position (if any) will be
shifted when new text is inserted (true=right, false=left).
end_row: End-line of the mark, 0-based inclusive.
ephemeral: For use with
nvim_set_decoration_provider()
callbacks. The mark will only be used for the current
redraw cycle, and not stored in the buffer.
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).
hl_group: Highlight group for the text range. This and
below highlight groups can be given as a string or as an
integer (
nvim_get_hl_id_by_name()). Multiple highlight
groups can be stacked by passing an array (highest-priority
last).
hl_mode: Controls how highlights are combined with the
highlights of the text. Only affects virt_text highlights,
but might affect hl_group in the future.
"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.
id: Update this extmark instead of creating a new one.
invalidate: (boolean) 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 of
nvim_buf_get_extmarks() and family. If "undo_restore" is
false, the extmark is deleted instead.
line_hl_group: Highlight group used for the whole line.
number_hl_group: Highlight group used for the number
column.
priority: Priority of the highlight group, sign attribute
or virtual text. For virtual text, the highest-priority
item is drawn last. For example treesitter highlighting
uses a value of 100.
right_gravity: (boolean, default: true) Indicates which
direction the extmark will be shifted when new text is
inserted (true=right, false=left).
sign_hl_group: Highlight group for sign_text.
spell: (boolean) Indicates that spell checking should be
performed within this extmark.
strict: (boolean, default: true) Indicates extmark should
not be placed if the line or column value is past
end-of-buffer or end-of-line respectively.
ui_watched: (boolean) Indicates the mark should be drawn by
a UI; activates
win_extmark ui-multigrid events.
Note:
the mark is positioned by virt_text attributes. Can be used
with virt_text.
undo_restore: (default: true) Restore the exact position of
the mark if text around the mark was deleted and then
restored by undo.
url: URL stored on this extmark. In the TUI, the OSC 8
control sequence is used to generate a clickable hyperlink
to this URL.
virt_lines: List of virtual lines to place next to the
mark, where each line is a list of
[text_chunk, hl]
tuples. Buffer and window options do not affect the display
of the text, except
'tabstop' is used for hard tabs. The
'wrap' and
'linebreak' options do not take effect, so the
number of extra screen lines will match the list-size (but
see
virt_lines_overflow). By default lines are placed
below the marked line. Special case: If the last
text_chunk is empty, the corresponding
hl will extend
to the end of the line.
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 display of virtual lines
exceeding the viewport:
"auto": Decided by the
'wrap' option.
"scroll": Scroll horizontally with
'nowrap', otherwise
the same as "trunc".
"trunc": Truncate on the right (default).
"wrap": Always wrap (regardless of the
'wrap' option).
virt_text:
virtual-text stored and displayed by this
mark. List of
[text, hl] tuples, each representing a text
chunk with a highlight
hl which may be a single highlight
group or a list of stacked highlight groups
(highest-priority last).
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_pos: Position of virtual text:
"eol": One cell after the line text or its displayed
'listchars' 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
right-shift the buffer text as needed.
virt_text_repeat_linebreak: Repeat the virtual text on
wrapped lines.
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".
Return:
(
integer) Id of the created/updated extmark
Creates a new namespace or gets an existing one.
namespace
Namespaces can be named or anonymous. If name matches an existing
namespace, the associated id is returned. If name is an empty string a
new, anonymous namespace is created.
Parameters:
{name} (string) Namespace name or empty string
Return:
(
integer) Namespace id
Return:
(
table<string,integer>) dict that maps from names to namespace ids.
Set or change decoration provider for a
namespace
This is a very general purpose interface for having Lua callbacks being
triggered during the redraw code.
The expected usage is to set
extmarks for the currently redrawn buffer.
nvim_buf_set_extmark() can be called to add marks on a per-window or
per-lines basis. Use the
ephemeral key to only use the mark for the
current screen redraw (the callback will be called again for the next
redraw).
Note: this function should not be called often. Rather, the callbacks
themselves can be used to throttle unneeded callbacks. the on_start
callback can return false to disable the provider until the next redraw.
Similarly, return false in on_win will skip the on_line and
on_range calls for that window (but any extmarks set in on_win will
still be used). A plugin managing multiple sources of decoration should
ideally only set one provider, and merge the sources internally. You can
use multiple ns_id for the extmarks set/modified inside the callback
anyway.
Note: doing anything other than setting extmarks is considered
experimental. Doing things like changing options are not explicitly
forbidden, but is likely to have unexpected consequences (such as 100% CPU
consumption). Doing vim.rpcnotify should be OK, but vim.rpcrequest is
quite dubious for the moment.
Note: It is not allowed to remove or update extmarks in on_line or
on_range callbacks.
Note: Callbacks will not run for
window-hidden, as they are not redrawn.
Attributes:
Lua
vim.api only
Since: 0.5.0
Parameters:
{opts} (vim.api.keyset.set_decoration_provider?) Table of
callbacks:
on_buf: called for each buffer being redrawn (once per
edit, before window callbacks)
["buf", bufnr, tick]
on_end: called at the end of a redraw cycle
["end", tick]
on_line: (deprecated, use on_range instead)
["line", winid, bufnr, row]
on_range: called for each buffer range being redrawn. Range
is end-exclusive and may span multiple lines. Range bounds
point to the first byte of a character. An end position of
the form (lnum, 0), including (number of lines, 0), is
valid and indicates that EOL of the preceding line is
included.
["range", winid, bufnr, begin_row, begin_col, end_row, end_col]
In addition to returning a boolean, it is also allowed to
return a
skip_row, skip_col pair of integers. This
implies that this function does not need to be called until
a range which continues beyond the skipped position. A
single integer return value
skip_row is short for
skip_row, 0
on_start: called first on each screen redraw
["start", tick]
on_win: called when starting to redraw a specific window.
["win", winid, bufnr, toprow, botrow]
WARNING: This feature is experimental/unstable.
Get the properties for namespace
Parameters:
{ns_id} (integer) Namespace
Return:
(
vim.api.keyset.ns_opts) Map defining the namespace properties, see
nvim__ns_set()
WARNING: This feature is experimental/unstable.
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
Gets the option information for all options.
Return:
(
table<string,any>) dict of all options
Gets the option information for one option from arbitrary buffer or window
Resulting dict has keys:
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", "buf", or "tab"
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.
Parameters:
{name} (string) Option name
{opts} (vim.api.keyset.option?) Optional parameters
buf: Buffer number. Used for getting buffer local options.
Implies {scope} is "local".
win:
window-ID. Used for getting window local options.
Return:
(
vim.api.keyset.get_option_info) Option Information
Gets the value of an option. The behavior of this function matches that of
:set: the local value of an option is returned if it exists; otherwise,
the global value is returned. Local values always correspond to the
current buffer or window, unless "buf" or "win" is set in
{opts}.
Parameters:
{name} (string) Option name
{opts} (vim.api.keyset.option?) Optional parameters
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 trigger
ftplugin and all
FileType
autocommands for the corresponding filetype.
tab:
tab-ID for tab-local options. Currently only supports
"cmdheight". Tabpage
0 means the current tabpage.
win:
window-ID. Used for getting window local options.
Return:
(
any) Option value
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 that win and buf cannot be used together.
Parameters:
{name} (string) Option name
{value} (
any) New option value. May be structured for dict/list
options, e.g.
'formatoptions' accepts
{ 'c', 'r' },
'listchars' accepts
{ eol = '~' }.
{opts} (vim.api.keyset.option?) Optional parameters
buf: Buffer number. Used for setting buffer local option.
dry_run: (boolean?, default: false) If true, validates
the option value without setting it.
operation: (
string?, default: "set") One of "set",
"append", "prepend", or "remove". Corresponds to
:set=,
:set+=,
:set^=, and
:set-=. With "remove", each item
in a structured
value is removed regardless of
order/adjacency.
tab:
tab-ID for tab-local options (currently only
'cmdheight'). Tabpage 0 means the current tabpage. If a
non-current tab is given, the value will take effect when
it is switched-to.
win:
window-ID. Used for setting window local option.
Return:
(
any) Option value
Attributes:
not allowed when
textlock is active
Since: 0.12.0
Parameters:
{buf} (integer) Buffer to open in the first window of the new
tabpage. Use 0 for current buffer.
{enter} (boolean) Enter the tabpage (make it the current tabpage).
{config} (vim.api.keyset.tabpage_config) Configuration for the new
tabpage. Keys:
after: Position to insert tabpage (default: -1; after
current). 0 = first, N = after Nth.
Return:
(
integer)
tab-ID of the new tabpage
Removes a tab-scoped (t:) variable
Parameters:
{tabpage} (
integer)
tab-ID, or 0 for current tabpage
{name} (string) Variable name
Parameters:
{tabpage} (
integer)
tab-ID, or 0 for current tabpage
Return:
(
integer) Tabpage number
Gets a tab-scoped (t:) variable
Parameters:
{tabpage} (
integer)
tab-ID, or 0 for current tabpage
{name} (string) Variable name
Return:
(
any) Variable value
Gets the current window in a tabpage
Parameters:
{tabpage} (
integer)
tab-ID, or 0 for current tabpage
Checks if a tabpage is valid
Parameters:
{tabpage} (
integer)
tab-ID, or 0 for current tabpage
Return:
(
boolean) true if the tabpage is valid, false otherwise
Gets the windows in a tabpage
Parameters:
{tabpage} (
integer)
tab-ID, or 0 for current tabpage
Return:
(
integer[]) List of windows in
tabpage
Sets a tab-scoped (t:) variable
Parameters:
{tabpage} (
integer)
tab-ID, or 0 for current tabpage
{name} (string) Variable name
{value} (any) Variable value
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}
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
Deactivates UI events on the channel.
Attributes:
RPC only
Since: 0.1.0
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 with
nvim_ui_pum_set_height(), which sets the number of visible items in the
popup menu, while this function sets the bounding box of the popup menu,
including visual elements such as borders and sliders. Floats need not use
the same font size, nor be anchored to exact grid corners, so one can set
floating-point numbers to the popup menu geometry.
Attributes:
RPC only
Since: 0.5.0
Parameters:
{width} (number) Popupmenu width.
{height} (number) Popupmenu height.
{row} (number) Popupmenu row.
{col} (number) Popupmenu 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.
Sends arbitrary data to a UI. Use this instead of
nvim_chan_send() or
io.stdout:write(), if you really want to write to the
TUI host
terminal.
Emits a "ui_send" event to all UIs with the "stdout_tty"
ui-option set.
UIs are expected to write the received data to a connected TTY if one
exists.
Attributes:
Since: 0.12.0
Parameters:
{content} (string) Content to write to the TTY
Tells the nvim server if focus was gained or lost by the GUI
Attributes:
RPC only
Since: 0.9.0
Parameters:
{gained} (boolean)
Attributes:
RPC only
Since: 0.1.0
Parameters:
{name} (string)
{value} (any)
Attributes:
RPC only
Since: 0.1.0
Parameters:
{width} (integer)
{height} (integer)
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.
Opens a new split window, floating window, or external window.
Specify
relative to create a floating window. Floats are drawn over
the split layout, relative to a position in some other window. See
api-floatwin.
Floats must specify width and height.
Specify
external to create an external window. External windows are
displayed as separate top-level windows managed by the
ui-multigrid UI
(not Nvim).
If relative and external are omitted, a normal "split" window is
created.
The win key decides which window to split. If nil or 0, the split
will be adjacent to the current window. If -1, a top-level split will
be created.
Use
vertical and
split to control split direction. For
vertical,
the exact direction is determined by
'splitright' and
'splitbelow'.
Split windows cannot have bufpos, row, col, border, title,
footer.
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.
Examples:
-- Window-relative float with 'statusline' enabled:
local w1 = vim.api.nvim_open_win(0, false,
{relative='win', row=3, col=3, width=40, height=4})
vim.wo[w1].statusline = vim.o.statusline
-- Buffer-relative float (travels as buffer is scrolled):
vim.api.nvim_open_win(0, false,
{relative='win', width=40, height=4, bufpos={100,10}})
-- Vertical split left of the current window:
vim.api.nvim_open_win(0, false, { split = 'left', win = 0, })
Attributes:
not allowed when
textlock is active
Since: 0.4.0
Parameters:
{buf} (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:
anchor: Decides which corner of the float to place at
(row,col):
"NW" northwest (default)
"NE" northeast
"SW" southwest
"SE" southeast
border: (
string|string[], default:
'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 to
hl-WinSeparator when not defined. Each border
side can specify an optional highlight:
[ ["+", "MyCorner"], ["x", "MyBorder"] ].
bufpos: Places float relative to buffer text (only when
relative="win"). Takes a tuple of zero-indexed
[line, column]. row and col if given are applied
relative to this position, else they default to:
row=1 and col=0 if anchor is "NW" or "NE"
row=0 and col=0 if anchor is "SW" or "SE" (thus
like a tooltip near the buffer text).
col: Column position in units of screen cell width, may be
fractional.
external: GUI should display the window as an external
top-level window. Currently accepts no other positioning
configuration together with this.
fixed: If true when anchor is NW or SW, the float window
would be kept fixed even if the window would be truncated.
focusable: (default: true) Enable focus by user actions
(wincmds, mouse events). Non-|focusable| windows can be
entered by
nvim_set_current_win(), or by mouse events if
mouse=true.
footer: (string|string[]?) Footer in window border:
string or list of [text, highlight] tuples. Default
highlight group is FloatFooter.
footer_pos: (default: "left") Footer position. One of:
"left", "center", "right". The footer field must be set
also.
height: Window height (in character cells). Minimum of 1.
mouse: (default: focusable value) If true, mouse events
interact with the window normally; if false, they pass
through to the window behind it.
noautocmd: Block all autocommands for the duration of the
call. Cannot be changed by
nvim_win_set_config().
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.
"mouse" Mouse position.
"tabline" Tabline if present, or first row.
"win" Window given by the win field, or current
window.
row: Row position in units of "screen cell height", may be
fractional.
split: Split direction: "left", "right", "above", "below".
style: (optional) Configure the appearance of the window:
"" No special style.
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 is FloatTitle.
title_pos: (default: "left") Title position. One of:
"left", "center", "right". The title field must be set
also.
width: Window width (in character cells). Minimum of 1.
win:
window-ID target window. Can be in a different tab
page. Determines the window to split (negative values act
like
:topleft,
:botright), the relative window for a
relative="win" float, or just the target tab page
(inferred from the window) for others.
zindex: (positive integer, default: 50) Stacking order.
Floats with higher zindex overlay floats with lower
indices. Below 100 is recommended, unless there is a good
reason to overshadow builtin elements. The cursor is
dimmed if an unfocused float above the cursor exceeds the
zindex of the current window by 50. These screen elements
have hard-coded z-indices:
200: message scrollback (
pager)
_cmdline_offset: (EXPERIMENTAL) When provided, anchor the
cmdline-completion popupmenu to this window, with an
offset in screen cell width.
Gets window config as a dict which can be passed to
nvim_open_win() as
the
config parameter.
For non-floating windows,
relative is empty, thus you can check that
field to detect if a window is a floatwin:
vim.print(vim.api.nvim_win_get_config(0).relative == '' and 'non-float' or 'float')
-- Or use win_gettype().
vim.print(vim.fn.win_gettype())
Parameters:
{win} (
integer)
window-ID, or 0 for current window
Return:
(
vim.api.keyset.win_config) Map defining the window configuration,
see
nvim_open_win()
Reconfigures the layout and properties of a window.
Updates only the given keys; unspecified (nil) keys will not be
changed.
Can move a window to another tabpage.
Can transform a window to/from a float.
Keys row / col / relative must be specified together.
Cannot move the last window in a tabpage to a different one.
Example: to convert a floating window to a "normal" split window, specify
the
win field:
vim.api.nvim_win_set_config(0, { split = 'above', win = vim.fn.win_getid(1), })
Parameters:
{win} (
integer)
window-ID, or 0 for current window
{config} (
vim.api.keyset.win_config) Map defining the window
configuration, see
nvim_open_win()
Calls function
fn in the context of window
win and returns its result
(may be multiple values).
Attributes:
Lua
vim.api only
Since: 0.5.0
Parameters:
{win} (
integer)
window-ID, or 0 for current window.
{fn} (function) Lua function to call inside the window.
Return:
(
any) Value(s) returned by
fn().
Attributes:
not allowed when
textlock is active
Since: 0.4.0
Parameters:
{win} (
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.
Removes a window-scoped (w:) variable
Parameters:
{win} (
integer)
window-ID, or 0 for current window
{name} (string) Variable name
Gets the current buffer in a window
Parameters:
{win} (
integer)
window-ID, or 0 for current window
Return:
(
integer) Buffer id
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
Parameters:
{win} (
integer)
window-ID, or 0 for current window
Return:
(
[integer, integer]) (row, col) tuple
Parameters:
{win} (
integer)
window-ID, or 0 for current window
Return:
(
integer) Height as a count of rows
Parameters:
{win} (
integer)
window-ID, or 0 for current window
Return:
(
integer) Window number
Gets the window position in display cells. First position is zero.
Parameters:
{win} (
integer)
window-ID, or 0 for current window
Return:
(
[integer, integer]) (row, col) tuple with the window position
Parameters:
{win} (
integer)
window-ID, or 0 for current window
Return:
(
integer) Tabpage that contains the window
Gets a window-scoped (w:) variable
Parameters:
{win} (
integer)
window-ID, or 0 for current window
{name} (string) Variable name
Return:
(
any) Variable value
Parameters:
{win} (
integer)
window-ID, or 0 for current window
Return:
(
integer) Width as a count of columns
Attributes:
not allowed when
textlock is active
Since: 0.5.0
Parameters:
{win} (
integer)
window-ID, or 0 for current window
Checks if a window is valid
Parameters:
{win} (
integer)
window-ID, or 0 for current window
Return:
(
boolean) true if the window is valid, false otherwise
Resizes a window, anchored to a given edge.
The window first takes space from the non-anchored side, and only then
from the anchored side. The "anchor" decides the fixed edge, so a window
can grow or shrink in any direction.
Can set height, width (only for a vertical split), or both. The "anchor"
applies to the matching axis (top/bottom for height, left/right for
width); the other axis uses its default anchor.
Attributes:
Since: 0.13.0
Parameters:
{win} (
integer)
window-ID, or 0 for current window
{width} (integer) New width (columns), or -1 for "no change".
{height} (integer) New height (rows), or -1 for "no change".
{opts} (vim.api.keyset.win_resize?) Optional parameters.
anchor: Edge that stays fixed while the opposite edge
moves; the neighbor on the moving side is resized first.
One of:
"top" (default) or "bottom"
"left" (default) or "right"
Sets the current buffer in a window.
Attributes:
not allowed when
textlock is active
Since: 0.3.2
Parameters:
{win} (
integer)
window-ID, or 0 for current window
{buf} (integer) Buffer id
Sets the (1,0)-indexed cursor position (byte offset) in the window.
api-indexing This scrolls the window even if it is not the current one.
Parameters:
{win} (
integer)
window-ID, or 0 for current window
{pos} ([integer, integer]) (row, col) tuple representing the new
position
Set highlight namespace for a window. This will use highlights defined
with
nvim_set_hl() for this namespace, but fall back to global
highlights (ns=0) when missing.
Parameters:
{win} (integer)
{ns_id} (integer) the namespace to use
Sets a window-scoped (w:) variable
Parameters:
{win} (
integer)
window-ID, or 0 for current window
{name} (string) Variable name
{value} (any) Variable value
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.
Attributes:
Since: 0.10.0
Parameters:
{win} (
integer)
window-ID, or 0 for current window.
{opts} (vim.api.keyset.win_text_height?) Optional parameters:
end_row: Ending line index, 0-based inclusive. When omitted
end at the very bottom.
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").
start_row: Starting line index, 0-based inclusive. When
omitted start at the very top.
start_vcol: Starting virtual column index on "start_row",
0-based inclusive, rounded down to full screen lines. When
omitted include the whole line.
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.