nvim_runtime_lua

vim

Methods95

function vim._ts_inspect_language(lang: string) -> TSLangInfo
function vim._ts_get_language_version() -> integer
function vim._ts_add_language_from_object(path: string, lang: string, symbol_name: nil | string)
function vim._ts_add_language_from_wasm(path: string, lang: string)
function vim._ts_get_minimum_language_version() -> integer
function vim._ts_parse_query(lang: string, query: string) -> TSQuery
Parameters
langstring

Language to use for the query

querystring

Query string in s-expr syntax

Returns
function vim._create_ts_parser(lang: string) -> TSParser
function vim._create_ts_querycursor(node: TSNode, query: TSQuery, opts: { end_col: integer, end_row: integer, match_limit: integer?, max_start_depth: integer?, start_col: integer, start_row: integer } | nil) -> TSQueryCursor
function vim.wait(time: number, callback: fun() -> ...boolean | nil, interval: nil | integer, fast_only: nil | boolean) -> (boolean, -1 | nil | -2, If unknown)

Waits up to time milliseconds, until callback returns true (success). Executes callback immediately, then on user events, internal events, and approximately every interval milliseconds (default 200). Returns true plus any remaining callback results on success.

Nvim processes other events while waiting. Cannot be called during an |api-fast| event.

Examples:

-- Wait for 100 ms, allowing other events to process.
vim.wait(100)

-- Wait up to 1000 ms or until `vim.g.foo` is true, at intervals of ~500 ms.
vim.wait(1000, function() return vim.g.foo end, 500)

-- Wait indefinitely until `vim.g.foo` is true, and get the callback results.
local ok, rv1, rv2, rv3 = vim.wait(math.huge, function()
  return vim.g.foo, 'a', 42, { ok = { 'yes' } }
end)

-- Schedule a function to set a value in 100ms. This would wait 10s if blocked, but actually
-- only waits 100ms because `vim.wait` processes other events while waiting.
vim.defer_fn(function() vim.g.timer_result = true end, 100)
if vim.wait(10000, function() return vim.g.timer_result end) then
  print('Only waiting a little bit of time!')
end

-- Yield via vim.wait() to allow CTRL-C to interrupt Lua code.
while true do
  -- ...work...
  local _, code = vim.wait(0, nil, 0)
  if code == -2 then -- CTRL-C.
    break
  end
end
Parameters
timenumber

Number of milliseconds to wait. Must be non-negative number, any fractional part is truncated.

callbackfun() -> ...boolean | nil

Optional callback. Waits until {callback} returns true

intervalnil | integer

(Approximate) number of milliseconds to wait between polls

fast_onlynil | boolean

If true, only |api-fast| events will be processed.

Returns
boolean

callback returns true before timeout: true, ... (remaining callback results).

  • On timeout: false, -1
  • On interrupt: false, -2
  • On error: the error is raised.
-1 | nil | -2

callback returns true before timeout: true, ... (remaining callback results).

  • On timeout: false, -1
  • On interrupt: false, -2
  • On error: the error is raised.
Ifunknown

callback returns true before timeout: true, ... (remaining callback results).

  • On timeout: false, -1
  • On interrupt: false, -2
  • On error: the error is raised.
function vim._os_proc_info(pid) -> table | table

Gets process info from the ps command. Used by nvimgetproc() as a fallback.

function vim._os_proc_children(ppid) -> table | integer[]

Gets process children from the pgrep command. Used by nvimgetproc_children() as a fallback.

function vim.paste(lines: string[], phase: sub<(-1|1|2|3),1>) -> result boolean

Paste handler, invoked by |nvim_paste()|.

Note: This is provided only as a "hook", don't call it directly; call |nvim_paste()| instead, which arranges redo (dot-repeat) and invokes vim.paste.

Example: To remove ANSI color codes when pasting:

vim.paste = (function(overridden)
  return function(lines, phase)
    for i,line in ipairs(lines) do
      -- Scrub ANSI color codes from paste input.
      lines[i] = line:gsub('\27%[[0-9;mK]+', '')
    end
    return overridden(lines, phase)
  end
end)(vim.paste)
Parameters
linesstring[]

|readfile()|-style list of lines to paste. |channel-lines|

phasesub<(-1|1|2|3),1>

: "non-streaming" paste: the call contains all lines. If paste is "streamed", phase indicates the stream state:

  • 1: starts the paste (exactly once)
  • 2: continues the paste (zero or more times)
  • 3: ends the paste (exactly once)
Returns
resultboolean

false if client should cancel the paste.

See:

|paste|

function vim.schedule_wrap(fn: function) -> function

Returns a function which calls {fn} via |vim.schedule()|.

The returned function passes all arguments to {fn}.

Example:

function notify_readable(_err, readable)
  vim.notify("readable? " .. tostring(readable))
end
vim.uv.fs_access(vim.fn.stdpath("config"), "R", vim.schedule_wrap(notify_readable))
See:

|lua-loop-callbacks| |vim.schedule()| |vim.infastevent()|

function vim.region(bufnr: integer, pos1: integer[] | string, pos2: integer[] | string, regtype: string[setreg], inclusive: boolean) -> region table
Deprecated
Parameters
bufnrinteger

Buffer number, or 0 for current buffer

pos1integer[] | string

Start of region as a (line, column) tuple or |getpos()|-compatible string

pos2integer[] | string

End of region as a (line, column) tuple or |getpos()|-compatible string

regtypestring[setreg]
inclusiveboolean

Controls whether the ending column is inclusive (see also 'selection').

Returns
regiontable

Dict of the form {linenr = {startcol,endcol}}. endcol is exclusive, and whole lines are returned as {startcol,endcol} = {0,-1}.

Deprecated
function vim.defer_fn(fn: function, timeout: integer) -> timer uv.uv_timer_t

Defers calling {fn} until {timeout} ms passes.

Use to do a one-shot timer that calls {fn}. Note: The {fn} is |schedule|d automatically, so API functions are safe to call.

Parameters
fnfunction

Callback to call once timeout expires

timeoutinteger

Number of milliseconds to wait before calling fn

Returns
timeruv.uv_timer_t

luv timer object

function vim.notify(msg: string, level: nil | integer, opts: nil | table) -> nil

Displays a notification to the user.

This function can be overridden by plugins to display notifications using a custom provider (such as the system notification provider). By default, writes to |:messages|.

Parameters
msgstring

Content of the notification to show to the user.

levelnil | integer

One of the values from |vim.log.levels|.

optsnil | table

Optional parameters. Unused by default.

Returns
nil
function vim.notify_once(msg: string, level: nil | integer, opts: nil | table) -> boolean

Displays a notification only one time.

Like |vim.notify()|, but subsequent calls with the same message will not display a notification.

Parameters
msgstring

Content of the notification to show to the user.

levelnil | integer

One of the values from |vim.log.levels|.

optsnil | table

Optional parameters. Unused by default.

Returns
boolean

true if message was displayed, else false

function vim.on_key(fn: fun(key: string, typed: string) -> nil | string | nil, ns_id: nil | integer, opts: nil | table) -> Namespace integer

Registers function {fn} with [namespace] {ns_id} as a listener to every, yes EVERY, input key.

To parse [key-chord]s, see |vim.keycode()|. Example:

local keychords = vim.keycode(vim.fn.keytrans(key), true)

The |-w| command-line option is related but does not support callbacks and cannot be toggled dynamically.

Parameters
fnfun(key: string, typed: string) -> nil | string | nil

Function invoked for every input key, after mappings have been applied but before further processing. Arguments {key} and {typed} are raw input (use [keytrans()] to get [keycodes]).

  • {key} is the key after mappings are applied.
  • {typed} is the input before mappings are applied; may be empty if {key} was produced
  • by non-typed key(s) or by the same typed key(s) that produced a previous {key}.

ns_idnil | integer

Namespace ID. If nil or 0, returns a new |namespace| id.

optsnil | table

Optional parameters

Returns
Namespaceinteger

id associated with {fn}. Or count of all callbacks if on_key() is called without arguments.

See:

|keytrans()| |vim.keycode()|

@note If {fn} returns an empty string, {key} is discarded/ignored; if {key} is [<Cmd>] then the "[<Cmd>]…[<CR>]" sequence is discarded as a whole. @note Non-recursive: if {fn} itself consumes input, it won't be invoked for those keys. @note To UNregister a given {ns_id}, pass nil {fn}. @note {fn} will be removed on error. @note {fn} will not be cleared by |nvimbufclear_namespace()|

function vim.str_byteindex(s: string, encoding: "utf-8" | "utf-16" | "utf-32", index: integer, strict_indexing: nil | boolean) -> integer

Convert UTF-32, UTF-16 or UTF-8 {index} to byte index. If {strict_indexing} is false then an out of range index will return byte length instead of throwing an error.

Invalid UTF-8 and NUL is treated like in |vim.str_utfindex()|. An {index} in the middle of a UTF-16 sequence is rounded upwards to the end of that sequence.

Parameters
sstring
encoding"utf-8" | "utf-16" | "utf-32"
indexinteger
strict_indexingnil | boolean

default: true

Returns
integer
function vim.str_utfindex(s: string, encoding: "utf-8" | "utf-16" | "utf-32", index: nil | integer, strict_indexing: nil | boolean) -> integer

Convert byte index to UTF-32, UTF-16 or UTF-8 indices. If {index} is not supplied, the length of the string is used. All indices are zero-based.

If {strict_indexing} is false then an out of range index will return string length instead of throwing an error. Invalid UTF-8 bytes, and embedded surrogates are counted as one code point each. An {index} in the middle of a UTF-8 sequence is rounded upwards to the end of that sequence.

Parameters
sstring
encoding"utf-8" | "utf-16" | "utf-32"
indexnil | integer
strict_indexingnil | boolean

default: true

Returns
integer
function vim._expand_pat(pat: string, env) -> (any[], integer)

Generates a list of possible completions for the str String has the pattern.

  1. Can we get it to just return things in the global namespace with that name prefix
  2. Can we get it to return things from global namespace even with print( in front.
function vim._expand_pat_get_parts(lua_string: string) -> (string | string[][], integer)
function vim.lua_omnifunc(find_start: 1 | 0, _) -> integer | any[]

Omnifunc for completing Lua values from the runtime Lua interpreter, similar to the builtin completion for the :lua command.

Activate using vim.bo.omnifunc = vim.lua_omnifunc in a Lua buffer.

function vim._print(inspect_strings: boolean, ...) -> ...unknown
Parameters
inspect_stringsboolean

use vim.inspect() for strings

...
Returns
...unknown
function vim.print(...: any) -> any

"Pretty prints" the given arguments and returns them unmodified.

Example:

local hl_normal = vim.print(vim.api.nvim_get_hl(0, { name = 'Normal' }))
Parameters
...any
Returns
any

given arguments.

See:

|vim.inspect()| |:=|

function vim.keycode(keys: string, info: nil | boolean) -> (string, vim.keycode.chord[] | nil)

Converts keys from [key-notation] to the internal encoding. Optionally returns structured key-chord info as retval 2.

Inverse of [keytrans()], which converts the internal encoding back to [key-notation].

Examples:

local k = vim.keycode
vim.g.mapleader = k'<bs>'

-- Split a key sequence into chords, e.g. to inspect modifiers.
local _, chords = vim.keycode('<C-w>v', true)
assert(chords[1].key == 'w' and chords[1].mod[1] == 'C')

-- keytrans() is the inverse: internal encoding => key-notation.
assert(vim.fn.keytrans(vim.keycode('<C-a>')) == '<C-A>')
Parameters
keysstring

Keys in [key-notation].

infonil | boolean

Also return key-chord info.

Returns
string

Internal representation of the given keys.

vim.keycode.chord[] | nil

List of parsed key-chords, each with fields:

See:

|nvimreplacetermcodes()| |keytrans()|

function vim._cs_remote(rcid, server_addr: string, connect_error: string, args) -> table | table | table | table | table | table | table
function vim._truncated_echo_once(msg) -> boolean
function vim.deprecate(name: string, alternative: nil | string, version: string, plugin: nil | string, backtrace: nil | boolean) -> nil | string

Shows a deprecation message to the user.

Parameters
namestring

Deprecated feature (function, API, etc.).

alternativenil | string

Suggested alternative feature.

versionstring

Version when the deprecated function will be removed.

pluginnil | string

Name of the plugin that owns the deprecated feature. Defaults to "Nvim".

backtracenil | boolean

Prints backtrace. Defaults to true.

Returns
nil | string

Deprecation message, or nil if no message was shown.

function vim.deepcopy<T>(orig: T, noref: nil | boolean) -> Table T

Returns a deep copy of the given object. Non-table objects are copied as in a typical Lua assignment, whereas table objects are copied recursively. Functions are naively copied, so functions in the copied table point to the same functions as those in the input table. Userdata and threads are not copied and will throw an error.

Note: noref=true is much more performant on tables with unique table fields, while noref=false is more performant on tables that reuse table fields.

Parameters
origT

Table to copy

norefnil | boolean
Returns
TableT

of copied keys and (nested) values.

function vim._copy<T>(orig: T) -> T

Returns a shallow copy of orig.

Non-table values are returned as-is. Table keys and values are copied by reference, and the original metatable is preserved. Use |vim.deepcopy()| for a recursive copy.

@nodoc

function vim.gsplit(s: string, sep: string, opts: vim.gsplit.Opts | nil) -> fun() -> nil | string

Gets an |iterator| that splits a string at each instance of a separator, in "lazy" fashion (as opposed to |vim.split()| which is "eager").

Example:

for s in vim.gsplit(':aa::b:', ':', {plain=true}) do
  print(s)
end

If you want to also inspect the separator itself (instead of discarding it), use |string.gmatch()|. Example:

for word, num in ('foo111bar222'):gmatch('([^0-9]*)(%d*)') do
  print(('word: %s num: %s'):format(word, num))
end
Parameters
sstring

String to split

sepstring

Separator or pattern

optsvim.gsplit.Opts | nil

Keyword arguments |kwargs|:

Returns
fun() -> nil | string

: Iterator over the split components

See:

|string.gmatch()| |vim.split()| |lua-pattern|s https://www.lua.org/pil/20.2.html http://lua-users.org/wiki/StringLibraryTutorial

function vim.split(s: string, sep: string, opts: vim.gsplit.Opts | nil) -> string[]

Splits a string at each instance of a separator and returns the result as a table (unlike |vim.gsplit()|).

Examples:

split(":aa::b:", ":")                   --> {'','aa','','b',''}
split("axaby", "ab?")                   --> {'','x','y'}
split("x*yz*o", "*", {plain=true})      --> {'x','yz','o'}
split("|x|y|z|", "|", {trimempty=true}) --> {'x', 'y', 'z'}
Parameters
sstring

String to split

sepstring

Separator or pattern

optsvim.gsplit.Opts | nil

Keyword arguments |kwargs|:

Returns
string[]

: List of split components

See:

|vim.gsplit()| |string.gmatch()|

function vim.tbl_keys<T>(t: {T, any}) -> T[]

Return a list of all keys used in a table. However, the order of the return table of keys is not guaranteed.

Parameters
t{T, any}

(table) Table

Returns
T[]

: List of keys

See:

From https://github.com/premake/premake-core/blob/master/src/base/table.lua

function vim.tbl_values<T>(t: {any, T}) -> T[]

Return a list of all values used in a table. However, the order of the return table of values is not guaranteed.

Parameters
t{any, T}

(table) Table

Returns
T[]

: List of values

function vim.tbl_map<T>(fn: fun(value: T) -> any, t: {any, T}) -> table

Applies function fn to all values of table t, in pairs() iteration order (which is not guaranteed to be stable, even when the data doesn't change).

Parameters
fnfun(value: T) -> any

Function

t{any, T}

Table

Returns
table

: Table of transformed values

function vim.tbl_filter<T>(fn: fun(value: T) -> boolean, t: {any, T}) -> T[]

Filter a table using a predicate function

Parameters
fnfun(value: T) -> boolean

(function) Function

t{any, T}

(table) Table

Returns
T[]

: Table of filtered values

function vim.tbl_contains(t: table, value: any, opts: vim.tbl_contains.Opts | nil) -> boolean

Checks if a table contains a given value, specified either directly or via a predicate that is checked for each value.

Example:

vim.tbl_contains({ 'a', { 'b', 'c' } }, function(v)
  return vim.deep_equal(v, { 'b', 'c' })
end, { predicate = true })
-- true
Parameters
ttable

Table to check

valueany

Value to compare or predicate function reference

optsvim.tbl_contains.Opts | nil

Keyword arguments |kwargs|:

Returns
boolean

true if t contains value

See:

|vim.list_contains()| for checking values in list-like tables

function vim.list_contains(t: table, value: any) -> boolean

Checks if a list-like table (integer keys without gaps) contains value.

Parameters
ttable

Table to check (must be list-like, not validated)

valueany

Value to compare

Returns
boolean

true if t contains value

See:

|vim.tbl_contains()| for checking values in general tables

function vim.tbl_isempty(t: table) -> boolean

Checks if a table is empty.

Parameters
ttable

Table to check

Returns
boolean

true if t is empty

See:

https://github.com/premake/premake-core/blob/master/src/base/table.lua

function vim.tbl_extend(behavior: "error" | "keep" | "force" | fun(key: any, prev_value: any, value: any) -> any, ...: table) -> table

Merges two or more tables.

Parameters
behavior"error" | "keep" | "force" | fun(key: any, prev_value: any, value: any) -> any

Decides what to do if a key is found in more than one map:

  • "error": raise an error
  • "force": use value from the rightmost map
  • "keep": use value from the leftmost map
  • If a function, it receives the current key, the previous value in the currently merged table (if present), the current value and should
  • return the value for the given key in the merged table.

...table

Two or more tables

Returns
table

: Merged table

See:

|extend()|

function vim.tbl_deep_extend<T2>(behavior: "error" | "keep" | "force" | fun(key: any, prev_value: any, value: any) -> any, ...: T2) -> T1 | T2

Merges two or more tables recursively.

Only |lua-dict| tables are merged recursively; |lua-list| tables are treated as opaque values (overwritten instead of merged). That is convenient for merging default/user configurations where lists typically should not be merged together.

Example:

-- Set `config.settings.…` without worrying about whether intermediate dicts exist.
local config = { settings = { tailwindCSS = { foo = 'bar' } } }
local merged = vim.tbl_deep_extend('force',
  config,
  { settings = { tailwindCSS = { experimental = { configFile = '/my/config.json' } } } }
)
vim.print(merged)
Parameters
behavior"error" | "keep" | "force" | fun(key: any, prev_value: any, value: any) -> any

Decides what to do if a key is found in more than one map:

  • "error": raise an error
  • "force": use value from the rightmost map
  • "keep": use value from the leftmost map
  • If a function, it receives the current key, the previous value in the currently merged table (if present), the current value and should
  • return the value for the given key in the merged table.

...T2

Two or more tables

Returns
T1 | T2

(table) Merged table

See:

|vim.tbl_extend()|

function vim.deep_equal(a: any, b: any) -> boolean

Deep compare values for equality

Tables are compared recursively unless they both provide the eq metamethod. All other types are compared using the equality == operator. Cyclic tables are supported.

Parameters
aany

First value

bany

Second value

Returns
boolean

true if values are equals, else false

function vim.tbl_get(o: table, ...: any) -> any

Gets a (nested) value from table o given by a sequence of keys ..., or nil if not found.

Note: To set deeply nested keys, see |vim.tbldeepextend()|.

Example:

local o = { a = { b = true } }
-- Get `o.a.b`.
vim.print(vim.tbl_get(o, 'a', 'b')) -- true
o.a = {}
vim.print(vim.tbl_get(o, 'a', 'b')) -- nil
Parameters
otable

Table to index

...any

Optional keys (0 or more, variadic) via which to index the table

Returns
any

Nested value indexed by key (if it exists), else nil

See:

|unpack()| |vim.tbldeepextend()|

function vim.list_extend<T>(dst: T, src: table, start: nil | integer, finish: nil | integer) -> dst T

Extends a list-like table with the values of another list-like table.

NOTE: This mutates dst!

Parameters
dstT

List which will be modified and appended to

srctable

List from which values will be inserted

startnil | integer

Start index on src. Defaults to 1

finishnil | integer

Final index on src. Defaults to #src

Returns
dstT
See:

|vim.tbl_extend()|

function vim.tbl_flatten(t: table) -> Flattened table
Deprecated
Parameters
ttable

List-like table

Returns
Flattenedtable

copy of the given list-like table

Deprecated
See:

From https://github.com/premake/premake-core/blob/master/src/base/table.lua

function vim.spairs<T, K, V>(t: T) -> (fun(table: {K, V}, index: K | nil) -> ...K, T)

Enumerates key-value pairs of a table, ordered by key.

Parameters
tT

Dict-like table

Returns
fun(table: {K, V}, index: K | nil) -> ...K

|for-in| iterator over sorted keys and their values

T
See:

Based on https://github.com/premake/premake-core/blob/master/src/base/table.lua

function vim.isarray(t: any) -> boolean

Tests if t is an "array": a table indexed only by integers (potentially non-contiguous).

If the indexes start from 1 and are contiguous then the array is also a list. |vim.islist()|

Empty table {} is an array, unless it was created by |vim.empty_dict()| or returned as a dict-like |API| or Vimscript result, for example from |rpcrequest()| or |vim.fn|.

Parameters
tany
Returns
boolean

true if array-like table, else false.

See:

https://github.com/openresty/luajit2#tableisarray

function vim.islist(t: any) -> boolean

Tests if t is a "list": a table indexed only by contiguous integers starting from 1 (what |lua-length| calls a "regular array").

Empty table {} is a list, unless it was created by |vim.empty_dict()| or returned as a dict-like |API| or Vimscript result, for example from |rpcrequest()| or |vim.fn|.

Parameters
tany
Returns
boolean

true if list-like table, else false.

See:

|vim.isarray()|

function vim.isnil(t: any) -> boolean

Tests if t is nil or |vim.NIL|.

Parameters
tany
Returns
boolean

true if nil or |vim.NIL|, else false.

@since 15

function vim.tbl_count(t: table) -> integer

Counts the number of non-nil values in table t.

vim.tbl_count({ a=1, b=2 })  --> 2
vim.tbl_count({ 1, 2 })      --> 2
Parameters
ttable

Table

Returns
integer

: Number of non-nil values in table

See:

https://github.com/Tieske/Penlight/blob/master/lua/pl/tablex.lua

function vim.list_slice<T>(list: T[], start: nil | integer, finish: nil | integer) -> Copy T[]

Creates a copy of a table containing only elements from start to end (inclusive)

Parameters
listT[]

Table

startnil | integer

Start range of slice

finishnil | integer

End range of slice

Returns
CopyT[]

of table sliced from start to finish (inclusive)

function vim._list_insert(t: any[], first: integer, last: integer, v: any) -> nil

Efficiently insert items into the middle of a list.

Calling table.insert() in a loop will re-index the tail of the table on every iteration, instead this function will re-index the table exactly once.

Based on https://stackoverflow.com/questions/12394841/safely-remove-items-from-an-array-table-while-iterating/53038524#53038524

function vim._list_remove(t: any[], first: integer, last: integer) -> nil

Efficiently remove items from middle of a list.

Calling table.remove() in a loop will re-index the tail of the table on every iteration, instead this function will re-index the table exactly once.

Based on https://stackoverflow.com/questions/12394841/safely-remove-items-from-an-array-table-while-iterating/53038524#53038524

function vim.trim(s: string) -> String string

Trim whitespace (Lua pattern "%s") from both sides of a string.

Parameters
sstring

String to trim

Returns
Stringstring

with whitespace removed from its beginning and end

See:

|lua-pattern|s https://www.lua.org/pil/20.2.html

function vim.pesc(s: string) -> string

Escapes magic chars in |lua-pattern|s.

Parameters
sstring

String to escape

Returns
string

%-escaped pattern string

See:

https://github.com/rxi/lume

function vim.startswith(s: string, prefix: string) -> boolean

Tests if s starts with prefix.

Parameters
sstring

String

prefixstring

Prefix to match

Returns
boolean

true if prefix is a prefix of s

function vim.endswith(s: string, suffix: string) -> boolean

Tests if s ends with suffix.

Parameters
sstring

String

suffixstring

Suffix to match

Returns
boolean

true if suffix is a suffix of s

function vim.validate(name: string, value: any, validator: vim.validate.Validator, optional: nil | boolean, message: nil | string) -> nil

Validate function arguments.

This function has two valid forms:

  1. vim.validate(name, value, validator[, optional][, message])

Validates that argument {name} with value {value} satisfies {validator}. If {optional} is given and is true, then {value} may be nil. If {message} is given, then it is used as the expected type in the error message.

Example:

      function vim.startswith(s, prefix)
        vim.validate('s', s, 'string')
        vim.validate('prefix', prefix, 'string')
        -- ...
      end
  1. vim.validate(spec) (DEPRECATED) where spec is of type
  2. table<string,[value:any, validator: vim.validate.Validator, optional_or_msg? : boolean|string]>)

Validates a argument specification. Specs are evaluated in alphanumeric order, until the first failure.

Examples:

vim.validate('arg1', {'foo'}, 'table')
   --> NOP (success)
vim.validate('arg2', 'foo', 'string')
   --> NOP (success)

vim.validate('arg1', 1, 'table')
   --> error('arg1: expected table, got number')

vim.validate('arg1', 3, function(a) return (a % 2) == 0 end, 'even number')
   --> error('arg1: expected even number, got 3')

-- If multiple types are valid they can be given as a list:
vim.validate('arg1', {'foo'}, {'table', 'string'})
vim.validate('arg2', 'foo', {'table', 'string'})
-- NOP (success)
vim.validate('arg1', 1, {'string', 'table'})
-- error('arg1: expected string|table, got number')
Overloads
function vim.validate(name: string, val: any, validator: vim.validate.Validator, message: string) -> nil
function vim.validate(spec: {string, (any, vim.validate.Validator, boolean | string)}) -> nil
Parameters
namestring

Argument name

valueany

Argument value

validatorvim.validate.Validator

:

  • (string|string[]): Any value that can be returned from |lua-type()| in addition to
  • 'callable': 'boolean', 'callable', 'function', 'nil', 'number', 'string', 'table', 'thread', 'userdata'.

  • (fun(val:any): boolean, string?) A function that returns a boolean and an optional
  • string message.

optionalnil | boolean

(default: false) Parameter is optional (may be omitted or nil)

messagenil | string

message when validation fails

Returns
nil

@note validator set to a value returned by |lua-type()| provides the best performance.

function vim.is_callable(f: any) -> boolean

Returns true if object f can be called as a function.

Parameters
fany

Any object

Returns
boolean

true if f is callable, else false

function vim.defaulttable(createfn: fun(key: any) -> any | nil) -> table

Creates a table whose missing keys are provided by {createfn} (like Python's "defaultdict").

If {createfn} is nil it defaults to defaulttable() itself, so accessing nested keys creates nested tables:

local a = vim.defaulttable()
a.b.c = 1
Parameters
createfnfun(key: any) -> any | nil

Provides the value for a missing key.

Returns
table

Empty table with __index metamethod.

function vim.ringbuf(size: integer) -> ringbuf any

Create a ring buffer limited to a maximal number of items. Once the buffer is full, adding a new entry overrides the oldest entry.

local ringbuf = vim.ringbuf(4)
ringbuf:push("a")
ringbuf:push("b")
ringbuf:push("c")
ringbuf:push("d")
ringbuf:push("e")    -- overrides "a"
print(ringbuf:pop()) -- returns "b"
print(ringbuf:pop()) -- returns "c"

-- Can be used as iterator. Pops remaining items:
for val in ringbuf do
  print(val)
end

Returns a Ringbuf instance with the following methods:

  • |Ringbuf:push()|
  • |Ringbuf:pop()|
  • |Ringbuf:peek()|
  • |Ringbuf:clear()|
function vim._defer_require<T>(root: string, mod: T) -> T
function vim._defer_deprecated_module(old_name: string, new_name: string) -> table

Creates a module alias/shim that lazy-loads a target module.

Unlike vim.defaulttable() this also:

  • implements __call
  • calls vim.deprecate()
Parameters
old_namestring

Name of the deprecated module, which will be shimmed.

new_namestring

Name of the new module, which will be loaded by require().

Returns
table
function vim._with(context: vim.context.mods, f: function) -> any

Executes function f with the given context spec: after execution, the original state indicated by the spec is restored.

Notes:

  • Context { buf = buf } has no guarantees about current window when
  • inside context.

  • Context { buf = buf, win = win } is yet not allowed, but this seems
  • to be an implementation detail.

  • There should be no way to revert currently set context.sandbox = true
  • (like with nested vim._with() calls). Otherwise it kind of breaks the whole purpose of sandbox execution.

  • Saving and restoring option contexts (bo, go, o, wo) trigger
  • OptionSet events. This is an implementation issue because not doing it seems to mean using either 'eventignore' option or extra nesting with { noautocmd = true } (which itself is a wrapper for 'eventignore'). As { go = { eventignore = '...' } } is a valid context which should be properly set and restored, this is not a good approach. Not triggering OptionSet seems to be a good idea, though. So probably only moving context save and restore to lower level might resolve this.

function vim._resolve_bufnr(buf: nil | integer) -> integer
function vim._ensure_list<T>(x: T | T[]) -> T[]
function vim._tointeger(x: any, base: nil | integer) -> integer nil | integer

Coerces {x} to an integer, like tonumber(), but rejects fractional values.

Returns nil if {x} cannot be converted with tonumber(), or if the resulting number is not integral.

Parameters
xany

Value to convert.

basenil | integer

Numeric base passed to tonumber().

Returns
integernil | integer

Converted integer value, or nil.

function vim._assert_integer(x: any, base: nil | integer) -> integer integer

Coerces {x} to an integer and errors if conversion fails.

This is the throwing counterpart to |vim._tointeger()| and should be used when non-integer input is a programming error.

Parameters
xany

Value to convert.

basenil | integer

Numeric base passed to tonumber().

Returns
integerinteger

Converted integer value.

function vim.nonnil<T>(...: T) -> T

Returns the first argument which is not nil.

If all arguments are nil, returns nil.

Example:

local a = nil
local b = nil
local c = 42
local d = true
assert(vim.nonnil(a, b, c, d) == 42)

@since 15

function vim.npcall<T>(fn: fun(...) -> T, ...: any) -> ...T

Calls the function fn in protected mode like |pcall()|, but returns nil on error.

@since 15

function vim.system(cmd: string[], opts: vim.SystemOpts | nil, on_exit: fun(out: vim.SystemCompleted) -> nil | nil) -> vim.SystemObj

Runs a system command or throws an error if {cmd} cannot be run.

The command runs directly (not in 'shell') so shell builtins such as "echo" in cmd.exe, cmdlets in powershell, or "help" in bash, will not work unless you actually invoke a shell: vim.system({'bash', '-c', 'help'}).

Examples:

local on_exit = function(obj)
  print(obj.code)
  print(obj.signal)
  print(obj.stdout)
  print(obj.stderr)
end

-- Runs asynchronously:
vim.system({'echo', 'hello'}, { text = true }, on_exit)

-- Runs synchronously:
local obj = vim.system({'echo', 'hello'}, { text = true }):wait()
-- { code = 0, signal = 0, stdout = 'hello\n', stderr = '' }

See |uv.spawn()| for more details. Note: unlike |uv.spawn()|, vim.system throws an error if {cmd} cannot be run.

Overloads
function vim.system(cmd: string[], on_exit: fun(out: vim.SystemCompleted) -> nil) -> vim.SystemObj
Parameters
cmdstring[]

Command to execute

optsvim.SystemOpts | nil
on_exitfun(out: vim.SystemCompleted) -> nil | nil

Called when subprocess exits. When provided, the command runs asynchronously. See return of SystemObj:wait().

Returns
function vim._load_package(name: string) -> nil | function
function vim.empty_dict() -> table

<Docs described in |vim.empty_dict()| >

@nodoc

function vim.inspect_pos(buf: nil | integer, row: nil | integer, col: nil | integer, filter: vim._inspector.Filter | nil) -> { buffer: integer, col: integer, extmarks: table, row: integer, semantic_tokens: table, syntax: table, treesitter: table }

Get all the items at a given buffer position.

Can also be pretty-printed with :Inspect!. :Inspect!

Parameters
bufnil | integer

defaults to the current buffer

rownil | integer

row to inspect, 0-based. Defaults to the row of the current cursor

colnil | integer

col to inspect, 0-based. Defaults to the col of the current cursor

filtervim._inspector.Filter | nil

Table with key-value pairs to filter the items

Returns
{ buffer: integer, col: integer, extmarks: table, row: integer, semantic_tokens: table, syntax: table, treesitter: table }

(table) a table with the following key-value pairs. Items are in "traversal order":

  • treesitter: a list of treesitter captures
  • syntax: a list of syntax groups
  • semantic_tokens: a list of semantic tokens
  • extmarks: a list of extmarks
  • buffer: the buffer used to get the items
  • row: the row used to get the items
  • col: the col used to get the items

@since 11

function vim.show_pos(buf: nil | integer, row: nil | integer, col: nil | integer, filter: vim._inspector.Filter | nil) -> nil

Show all the items at a given buffer position.

Can also be shown with :Inspect. :Inspect

See also |:marks| to list all extmarks.

Example: To bind this function to the vim-scriptease inspired zS in Normal mode:

vim.keymap.set('n', 'zS', vim.show_pos)
Parameters
bufnil | integer

defaults to the current buffer

rownil | integer

row to inspect, 0-based. Defaults to the row of the current cursor

colnil | integer

col to inspect, 0-based. Defaults to the col of the current cursor

filtervim._inspector.Filter | nil
Returns
nil

@since 11

function vim.in_fast_event()

Returns true if the code is executing as part of a "fast" event handler, where most of the API is disabled. These are low-level events (e.g. |lua-loop-callbacks|) which can be invoked whenever Nvim polls for input. When this is false most API functions are callable (but may be subject to other restrictions such as |textlock|).

function vim.empty_dict() -> table

Creates a special empty table (marked with a metatable), which Nvim converts to an empty dictionary when translating Lua values to Vimscript or API types. Nvim by default converts an empty table {} without this metatable to an list/array.

Note: If numeric keys are present in the table, Nvim ignores the metatable marker and converts the dict to a list/array anyway.

function vim.rpcnotify(channel: integer, method: string, ...: any)

Sends {event} to {channel} via |RPC| and returns immediately. If {channel} is 0, the event is broadcast to all channels.

This function also works in a fast callback |lua-loop-callbacks|.

function vim.rpcrequest(channel: integer, method: string, ...: any)

Invokes |RPC| method on channel and blocks until a response is received.

Note: Msgpack NIL values in the response are represented as |vim.NIL|.

Example: see [nvimexeclua()]

function vim.stricmp(a: string, b: string) -> if 0 | 1 | -1

Compares strings case-insensitively.

Parameters
astring
bstring
Returns
if0 | 1 | -1

strings are equal, {a} is greater than {b} or {a} is lesser than {b}, respectively.

function vim.str_utf_pos(str: string) -> integer[]

Gets a list of the starting byte positions of each UTF-8 codepoint in the given string.

Embedded NUL bytes are treated as terminating the string.

function vim.str_utf_start(str: string, index: integer) -> integer

Gets the distance (in bytes) from the starting byte of the codepoint (character) that {index} points to.

The result can be added to {index} to get the starting byte of a character.

Examples:

-- The character 'æ' is stored as the bytes '\xc3\xa6' (using UTF-8)

-- Returns 0 because the index is pointing at the first byte of a character
vim.str_utf_start('æ', 1)

-- Returns -1 because the index is pointing at the second byte of a character
vim.str_utf_start('æ', 2)
function vim.str_utf_end(str: string, index: integer) -> integer

Gets the distance (in bytes) from the last byte of the codepoint (character) that {index} points to.

Examples:

-- The character 'æ' is stored as the bytes '\xc3\xa6' (using UTF-8)

-- Returns 0 because the index is pointing at the last byte of a character
vim.str_utf_end('æ', 2)

-- Returns 1 because the index is pointing at the penultimate byte of a character
vim.str_utf_end('æ', 1)
function vim.iconv(str: string, from: string, to: string, opts) -> nil | string

The result is a String, which is the text {str} converted from encoding {from} to encoding {to}. When the conversion fails nil is returned. When some characters could not be converted they are replaced with "?". The encoding names are whatever the iconv() library function can accept, see ":Man 3 iconv".

Parameters
strstring

Text to convert

fromstring

Encoding of {str}

tostring

Target encoding

opts
Returns
nil | string

: Converted string if conversion succeeds, nil otherwise.

function vim.schedule(fn: fun() -> nil) -> (result nil, err nil | string)

Schedules {fn} to be invoked soon by the main event-loop. Useful to avoid |textlock| or other temporary restrictions.

Parameters
fnfun() -> nil
Returns
resultnil
errnil | string

Error message if scheduling failed, nil otherwise.

function vim.ui_attach(ns: integer, opts: {string, any}, callback: fun(event: string, ...) -> any)

Subscribe to |ui-events|, similar to |nvimuiattach()| but receive events in a Lua callback. Used to implement screen elements like popupmenu or message handling in Lua.

{callback} receives event name plus additional parameters. See |ui-popupmenu| and the sections below for event format for respective events.

Callbacks for msg_show events originating from internal messages (as opposed to events from commands or API calls) are executed in |api-fast| context; showing the message needs to be scheduled.

Excessive errors inside the callback will result in forced detachment.

WARNING: This api is considered experimental. Usability will vary for different screen elements. In particular ext_messages behavior is subject to further changes and usability improvements. This is expected to be used to handle messages when setting 'cmdheight' to zero (which is likewise experimental).

Example (stub for a |ui-popupmenu| implementation):

ns = vim.api.nvim_create_namespace('my_fancy_pum')

vim.ui_attach(ns, {ext_popupmenu=true}, function(event, ...)
  if event == 'popupmenu_show' then
    local items, selected, row, col, grid = ...
    print('display pum ', #items)
  elseif event == 'popupmenu_select' then
    local selected = ...
    print('selected', selected)
  elseif event == 'popupmenu_hide' then
    print('FIN')
  end
end)
Parameters
nsinteger

Namespace ID

opts{string, any}

Optional parameters.

  • {ext_…}? (boolean) Any of |ui-ext-options|, if true
  • enable events for the respective UI element.

  • {set_cmdheight}? (boolean) If false, avoid setting
  • 'cmdheight' to 0 when ext_messages is enabled.

callbackfun(event: string, ...) -> any

Function called for each UI event. A truthy return value signals to Nvim that the event is handled, in which case it is not propagated to remote UIs.

@since 0

function vim.ui_detach(ns: integer)

Detach a callback previously attached with |vim.ui_attach()| for the given namespace {ns}.

Parameters
nsinteger

Namespace ID

function vim.call(func: string, ...: any) -> any

Invokes |vim-function| or |user-function| {func} with arguments {...}. See also |vim.fn|. Equivalent to:

vim.fn[func]({...})
function vim.diff(a: string, b: string, opts: vim.text.diff.Opts | nil) -> string | integer[][] | nil
Deprecated

Renamed to vim.text.diff, remove at Nvim 1.0

Parameters
astring

First string to compare

bstring

Second string to compare

optsvim.text.diff.Opts | nil
Returns
string | integer[][] | nil

See {opts.resulttype}. nil if {opts.onhunk} is given.

Deprecated
function vim.regex(re: string) -> vim.regex

Parses the Vim regex re and returns a regex object. Regexes are "magic" and case-sensitive by default, regardless of 'magic' and 'ignorecase'. They can be controlled with flags, see |/magic| and |/ignorecase|.

function vim.uri_from_fname(path: string) -> URI string
Parameters
pathstring

Path to file

Returns
URIstring
function vim.uri_from_bufnr(buf: integer) -> URI string
function vim.uri_to_fname(uri: string) -> filename string
Parameters
uristring
Returns
filenamestring

or unchanged URI for non-file URIs

function vim.uri_to_bufnr(uri: string) -> bufnr integer

Fields61

vim._extra: table

There are things which have special rules in vim.initpackages for legacy reasons (uri) or for performance (_inspector). most new things should go into a submodule namespace ( vim.foobar.do_thing() )

vim.inspect : any

Gets a human-readable representation of the given object.

See:

|vim.print()| https://github.com/kikito/inspect.lua https://github.com/mpeterv/vinspect

vim.fn: table

vim.fn.{func}(...)

@nodoc

vim.cmd: table

Executes Vimscript (|Ex-command|s).

Can be indexed with a command name to get a function, thus you can write vim.cmd.echo(…) instead of vim.cmd{cmd='echo',…}.

Examples:

-- Single command:
vim.cmd('echo 42')
-- Multiline script:
vim.cmd([[
  augroup my.group
    autocmd!
    autocmd FileType c setlocal cindent
  augroup END
]])

-- Ex command :echo "foo". Note: string literals must be double-quoted.
vim.cmd('echo "foo"')
vim.cmd { cmd = 'echo', args = { '"foo"' } }
vim.cmd.echo({ args = { '"foo"' } })
vim.cmd.echo('"foo"')

-- Ex command :write! myfile.txt
vim.cmd('write! myfile.txt')
vim.cmd { cmd = 'write', args = { 'myfile.txt' }, bang = true }
vim.cmd.write { args = { 'myfile.txt' }, bang = true }
vim.cmd.write { 'myfile.txt', bang = true }

-- Ex command :vertical resize +2
vim.cmd.resize({ '+2', mods = { vertical = true } })

-- Pass arg literally, without needing to escape special chars:
vim.cmd.edit({ '%foo"|bar#baz"', magic = { file = false, bar = false } })
See:

|ex-cmd-index|

vim.g : vim.g
vim.v : vim.v
vim.b : vim.b
vim.w : vim.w
vim.t : vim.t
vim.loop : uv
Deprecated

Remove at Nvim 1.0

Deprecated
vim.highlight : table

Deprecated. Remove at Nvim 2.0

vim.env: table

Gets or sets environment variables in the current editor process. See |expand-env| and |:let-environment| for the Vimscript behavior. Invalid or unset key returns nil.

Example:

vim.env.FOO = 'bar'
print(vim.env.TERM)
vim.o: table

Gets or sets |options|. Works like :set, so buffer/window-scoped options target the current buffer/window. Invalid key is an error.

Example:

vim.o.cmdheight = 4
print(vim.o.columns)
print(vim.o.foo)     -- error: invalid key
vim.go: table

Gets or sets global |options|. Like :setglobal. Invalid key is an error.

Note: unlike |vim.o|, this accesses the global option value and thus is mostly useful with |global-local| options.

Example:

vim.go.cmdheight = 4
print(vim.go.columns)
print(vim.go.bar)     -- error: invalid key
vim.bo : table

Gets or sets buffer-scoped |options| on buffer {bufnr} (or "current buffer" if 0 or omitted). Like :setlocal. Invalid {bufnr} or key is an error.

Example:

local bufnr = vim.api.nvim_get_current_buf()
vim.bo[bufnr].buflisted = true    -- same as vim.bo.buflisted = true
print(vim.bo.comments)
print(vim.bo.baz)                 -- error: invalid key
vim.wo : table

Gets or sets window-scoped |options| on window {winid} (or "current window" if 0 or omitted) and buffer {bufnr} (0 for current buffer). Like :setlocal if setting a |global-local| option or if {bufnr} is specified, like :set otherwise. Invalid {winid}, {bufnr}, or key is an error.

Note: only bufnr=0 (current window-buffer) is supported, currently.

Example:

local winid = vim.api.nvim_get_current_win()
vim.wo[winid].number = true    -- same as vim.wo.number = true
print(vim.wo.foldmarker)
print(vim.wo.quux)             -- error: invalid key
vim.wo[winid][0].spell = false -- like ':setlocal nospell'
vim.opt : table

@nodoc

vim.opt_local : table

@nodoc

vim.opt_global : table

@nodoc

vim.list: table
vim._maxint: integer = 4294967295

Use max 32-bit signed int value to avoid overflow on 32-bit systems. #31633

vim._so_trails : string[]
vim._submodules: table
vim.api: table
vim.base64: table
vim.NIL : vim.NIL

@nodoc

vim._core : vim._core

@nodoc

vim.json: table

@nodoc

vim.lpeg: table
vim.mpack: table

@nodoc

vim.bo : vim.bo
vim.wo : vim.wo
vim.v : vim.v
vim.uv : uv
vim.F: table
vim._watch: table
vim.diagnostic: table
vim.filetype: table
vim.fs: table
vim.func: table
vim.glob: table
vim.health: table
vim.hl: table
vim.iter: table

require('vim.iter') carries the richer EmmyLua generic surface. Force LuaLS onto the fallback module shape above so make luals stays clean.

vim.keymap: table
vim.loader: table
vim.log : vim.Log
vim.lsp: table
vim.net: table
vim.pack: table
vim.pos : vim.Pos | fun(buf: integer, row: integer, col: integer) -> vim.Pos
vim.range : vim.Range | fun(start: vim.Pos, end_: vim.Pos) -> vim.Range | fun(buf: integer, start_row: integer, start_col: integer, end_row: integer, end_col: integer) -> vim.Range
vim.re: table
vim.secure: table
vim.snippet: table
vim.text: table
vim.treesitter: table
vim.tty: table
vim.ui: table
vim.version: table
vim.provider: table