vim._core.editor
Methods95
function M._ts_inspect_language(lang: string) -> TSLangInfo
function M._ts_get_language_version() -> integer
function M._ts_add_language_from_object(path: string, lang: string, symbol_name: nil | string)
function M._ts_add_language_from_wasm(path: string, lang: string)
function M._ts_get_minimum_language_version() -> integer
function M._ts_parse_query(lang: string, query: string) -> TSQuery
langstringLanguage to use for the query
querystringQuery string in s-expr syntax
function M._create_ts_parser(lang: string) -> TSParser
function M._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 M.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
timenumberNumber of milliseconds to wait. Must be non-negative number, any fractional part is truncated.
callbackfun() -> ...boolean | nilOptional callback. Waits until {callback} returns true
intervalnil | integer(Approximate) number of milliseconds to wait between polls
fast_onlynil | booleanIf true, only |api-fast| events will be processed.
- boolean
callback returns
truebefore timeout:true, ...(remaining callback results).- On timeout:
false, -1 - On interrupt:
false, -2 - On error: the error is raised.
- On timeout:
- -1 | nil | -2
callback returns
truebefore timeout:true, ...(remaining callback results).- On timeout:
false, -1 - On interrupt:
false, -2 - On error: the error is raised.
- On timeout:
Ifunknowncallback returns
truebefore timeout:true, ...(remaining callback results).- On timeout:
false, -1 - On interrupt:
false, -2 - On error: the error is raised.
- On timeout:
function M._os_proc_info(pid) -> table | table
Gets process info from the ps command. Used by nvimgetproc() as a fallback.
function M._os_proc_children(ppid) -> table | integer[]
Gets process children from the pgrep command. Used by nvimgetproc_children() as a fallback.
function M.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)
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",
phaseindicates the stream state:- 1: starts the paste (exactly once)
- 2: continues the paste (zero or more times)
- 3: ends the paste (exactly once)
resultbooleanfalse if client should cancel the paste.
|paste|
function M.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))
|lua-loop-callbacks| |vim.schedule()| |vim.infastevent()|
function M.region(bufnr: integer, pos1: integer[] | string, pos2: integer[] | string, regtype: string[setreg], inclusive: boolean) -> region table
Deprecated
bufnrintegerBuffer number, or 0 for current buffer
pos1integer[] | stringStart of region as a (line, column) tuple or |getpos()|-compatible string
pos2integer[] | stringEnd of region as a (line, column) tuple or |getpos()|-compatible string
regtypestring[setreg]inclusivebooleanControls whether the ending column is inclusive (see also 'selection').
regiontableDict of the form
{linenr = {startcol,endcol}}.endcolis exclusive, and whole lines are returned as{startcol,endcol} = {0,-1}.
function M.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.
fnfunctionCallback to call once
timeoutexpirestimeoutintegerNumber of milliseconds to wait before calling
fn
timeruv.uv_timer_tluv timer object
function M.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|.
msgstringContent of the notification to show to the user.
levelnil | integerOne of the values from |vim.log.levels|.
optsnil | tableOptional parameters. Unused by default.
- nil
function M.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.
msgstringContent of the notification to show to the user.
levelnil | integerOne of the values from |vim.log.levels|.
optsnil | tableOptional parameters. Unused by default.
- boolean
true if message was displayed, else false
function M.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.
fnfun(key: string, typed: string) -> nil | string | nilFunction 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 | integerNamespace ID. If nil or 0, returns a new |namespace| id.
optsnil | tableOptional parameters
Namespaceintegerid associated with {fn}. Or count of all callbacks if on_key() is called without arguments.
|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 M.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.
sstringencoding"utf-8" | "utf-16" | "utf-32"indexintegerstrict_indexingnil | booleandefault: true
- integer
function M.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.
sstringencoding"utf-8" | "utf-16" | "utf-32"indexnil | integerstrict_indexingnil | booleandefault: true
- integer
function M._expand_pat(pat: string, env) -> (any[], integer)
Generates a list of possible completions for the str String has the pattern.
- Can we get it to just return things in the global namespace with that name prefix
- Can we get it to return things from global namespace even with
print(in front.
function M._expand_pat_get_parts(lua_string: string) -> (string | string[][], integer)
function M.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 M._print(inspect_strings: boolean, ...) -> ...unknown
inspect_stringsbooleanuse vim.inspect() for strings
...
- ...unknown
function M.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' }))
...any
- any
given arguments.
|vim.inspect()| |:=|
function M.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>')
keysstringKeys in [key-notation].
infonil | booleanAlso return key-chord info.
- string
Internal representation of the given
keys.- vim.keycode.chord[] | nil
List of parsed key-chords, each with fields:
|nvimreplacetermcodes()| |keytrans()|
function M._cs_remote(rcid, server_addr: string, connect_error: string, args) -> table | table | table | table | table | table | table
function M._truncated_echo_once(msg) -> boolean
function M.deprecate(name: string, alternative: nil | string, version: string, plugin: nil | string, backtrace: nil | boolean) -> nil | string
Shows a deprecation message to the user.
namestringDeprecated feature (function, API, etc.).
alternativenil | stringSuggested alternative feature.
versionstringVersion when the deprecated function will be removed.
pluginnil | stringName of the plugin that owns the deprecated feature. Defaults to "Nvim".
backtracenil | booleanPrints backtrace. Defaults to true.
- nil | string
Deprecation message, or nil if no message was shown.
function M.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.
origTTable to copy
norefnil | boolean
TableTof copied keys and (nested) values.
function M._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 M.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
sstringString to split
sepstringSeparator or pattern
optsvim.gsplit.Opts | nilKeyword arguments |kwargs|:
- fun() -> nil | string
: Iterator over the split components
|string.gmatch()| |vim.split()| |lua-pattern|s https://www.lua.org/pil/20.2.html http://lua-users.org/wiki/StringLibraryTutorial
function M.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'}
sstringString to split
sepstringSeparator or pattern
optsvim.gsplit.Opts | nilKeyword arguments |kwargs|:
- string[]
: List of split components
|vim.gsplit()| |string.gmatch()|
function M.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.
t{T, any}(table) Table
- T[]
: List of keys
From https://github.com/premake/premake-core/blob/master/src/base/table.lua
function M.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.
t{any, T}(table) Table
- T[]
: List of values
function M.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).
fnfun(value: T) -> anyFunction
t{any, T}Table
- table
: Table of transformed values
function M.tbl_filter<T>(fn: fun(value: T) -> boolean, t: {any, T}) -> T[]
Filter a table using a predicate function
fnfun(value: T) -> boolean(function) Function
t{any, T}(table) Table
- T[]
: Table of filtered values
function M.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
ttableTable to check
valueanyValue to compare or predicate function reference
optsvim.tbl_contains.Opts | nilKeyword arguments |kwargs|:
- boolean
trueiftcontainsvalue
|vim.list_contains()| for checking values in list-like tables
function M.list_contains(t: table, value: any) -> boolean
Checks if a list-like table (integer keys without gaps) contains value.
ttableTable to check (must be list-like, not validated)
valueanyValue to compare
- boolean
trueiftcontainsvalue
|vim.tbl_contains()| for checking values in general tables
function M.tbl_isempty(t: table) -> boolean
Checks if a table is empty.
ttableTable to check
- boolean
trueiftis empty
https://github.com/premake/premake-core/blob/master/src/base/table.lua
function M.tbl_extend(behavior: "error" | "keep" | "force" | fun(key: any, prev_value: any, value: any) -> any, ...: table) -> table
Merges two or more tables.
behavior"error" | "keep" | "force" | fun(key: any, prev_value: any, value: any) -> anyDecides 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.
...tableTwo or more tables
- table
: Merged table
|extend()|
function M.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)
behavior"error" | "keep" | "force" | fun(key: any, prev_value: any, value: any) -> anyDecides 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.
...T2Two or more tables
- T1 | T2
(table) Merged table
|vim.tbl_extend()|
function M.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.
aanyFirst value
banySecond value
- boolean
trueif values are equals, elsefalse
function M.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
otableTable to index
...anyOptional keys (0 or more, variadic) via which to index the table
- any
Nested value indexed by key (if it exists), else nil
|unpack()| |vim.tbldeepextend()|
function M.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!
dstTList which will be modified and appended to
srctableList from which values will be inserted
startnil | integerStart index on src. Defaults to 1
finishnil | integerFinal index on src. Defaults to
#src
dstT
|vim.tbl_extend()|
function M.tbl_flatten(t: table) -> Flattened table
Deprecated
ttableList-like table
Flattenedtablecopy of the given list-like table
From https://github.com/premake/premake-core/blob/master/src/base/table.lua
function M.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.
tTDict-like table
- fun(table: {K, V}, index: K | nil) -> ...K
|for-in| iterator over sorted keys and their values
- T
Based on https://github.com/premake/premake-core/blob/master/src/base/table.lua
function M.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|.
tany
- boolean
trueif array-like table, elsefalse.
https://github.com/openresty/luajit2#tableisarray
function M.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|.
tany
- boolean
trueif list-like table, elsefalse.
|vim.isarray()|
function M.isnil(t: any) -> boolean
Tests if t is nil or |vim.NIL|.
tany
- boolean
trueifnilor |vim.NIL|, elsefalse.
@since 15
function M.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
ttableTable
- integer
: Number of non-nil values in table
https://github.com/Tieske/Penlight/blob/master/lua/pl/tablex.lua
function M.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)
listT[]Table
startnil | integerStart range of slice
finishnil | integerEnd range of slice
CopyT[]of table sliced from start to finish (inclusive)
function M._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 M._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 M.trim(s: string) -> String string
Trim whitespace (Lua pattern "%s") from both sides of a string.
sstringString to trim
Stringstringwith whitespace removed from its beginning and end
|lua-pattern|s https://www.lua.org/pil/20.2.html
function M.pesc(s: string) -> string
Escapes magic chars in |lua-pattern|s.
sstringString to escape
- string
%-escaped pattern string
https://github.com/rxi/lume
function M.startswith(s: string, prefix: string) -> boolean
Tests if s starts with prefix.
sstringString
prefixstringPrefix to match
- boolean
trueifprefixis a prefix ofs
function M.endswith(s: string, suffix: string) -> boolean
Tests if s ends with suffix.
sstringString
suffixstringSuffix to match
- boolean
trueifsuffixis a suffix ofs
function M.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:
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
vim.validate(spec)(DEPRECATED) wherespecis of type
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')
function M.validate(name: string, val: any, validator: vim.validate.Validator, message: string) -> nilfunction M.validate(spec: {string, (any, vim.validate.Validator, boolean | string)}) -> nilnamestringArgument name
valueanyArgument value
validatorvim.validate.Validator:
- (
string|string[]): Any value that can be returned from |lua-type()| in addition to - (
fun(val:any): boolean, string?) A function that returns a boolean and an optional
'callable':'boolean','callable','function','nil','number','string','table','thread','userdata'.string message.
- (
optionalnil | boolean(default: false) Parameter is optional (may be omitted or nil)
messagenil | stringmessage when validation fails
- nil
@note validator set to a value returned by |lua-type()| provides the best performance.
function M.is_callable(f: any) -> boolean
Returns true if object f can be called as a function.
fanyAny object
- boolean
trueiffis callable, elsefalse
function M.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
createfnfun(key: any) -> any | nilProvides the value for a missing
key.
- table
Empty table with
__indexmetamethod.
function M.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 M._defer_require<T>(root: string, mod: T) -> T
function M._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()
old_namestringName of the deprecated module, which will be shimmed.
new_namestringName of the new module, which will be loaded by require().
- table
function M._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 - Context
{ buf = buf, win = win }is yet not allowed, but this seems - There should be no way to revert currently set
context.sandbox = true - Saving and restoring option contexts (
bo,go,o,wo) trigger
inside context.
to be an implementation detail.
(like with nested vim._with() calls). Otherwise it kind of breaks the whole purpose of sandbox execution.
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 M._resolve_bufnr(buf: nil | integer) -> integer
function M._ensure_list<T>(x: T | T[]) -> T[]
function M._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.
xanyValue to convert.
basenil | integerNumeric base passed to
tonumber().
integernil | integerConverted integer value, or
nil.
function M._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.
xanyValue to convert.
basenil | integerNumeric base passed to
tonumber().
integerintegerConverted integer value.
function M.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 M.npcall<T>(fn: fun(...) -> T, ...: any) -> ...T
Calls the function fn in protected mode like |pcall()|, but returns nil on error.
@since 15
function M.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.
function M.system(cmd: string[], on_exit: fun(out: vim.SystemCompleted) -> nil) -> vim.SystemObjcmdstring[]Command to execute
optsvim.SystemOpts | nilon_exitfun(out: vim.SystemCompleted) -> nil | nilCalled when subprocess exits. When provided, the command runs asynchronously. See return of SystemObj:wait().
function M._load_package(name: string) -> nil | function
function M.empty_dict() -> table
<Docs described in |vim.empty_dict()| >
@nodoc
function M.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!
bufnil | integerdefaults to the current buffer
rownil | integerrow to inspect, 0-based. Defaults to the row of the current cursor
colnil | integercol to inspect, 0-based. Defaults to the col of the current cursor
filtervim._inspector.Filter | nilTable with key-value pairs to filter the items
- { 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 M.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)
bufnil | integerdefaults to the current buffer
rownil | integerrow to inspect, 0-based. Defaults to the row of the current cursor
colnil | integercol to inspect, 0-based. Defaults to the col of the current cursor
filtervim._inspector.Filter | nil
- nil
@since 11
function M.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 M.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 M.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 M.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 M.stricmp(a: string, b: string) -> if 0 | 1 | -1
Compares strings case-insensitively.
astringbstring
if0 | 1 | -1strings are equal, {a} is greater than {b} or {a} is lesser than {b}, respectively.
function M.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 M.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 M.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 M.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".
strstringText to convert
fromstringEncoding of {str}
tostringTarget encoding
opts
- nil | string
: Converted string if conversion succeeds,
nilotherwise.
function M.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.
fnfun() -> nil
resultnilerrnil | stringError message if scheduling failed,
nilotherwise.
function M.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)
nsintegerNamespace ID
opts{string, any}Optional parameters.
- {ext_…}? (
boolean) Any of |ui-ext-options|, if true - {set_cmdheight}? (
boolean) If false, avoid setting
enable events for the respective UI element.
'cmdheight' to 0 when
ext_messagesis enabled.- {ext_…}? (
callbackfun(event: string, ...) -> anyFunction 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 M.ui_detach(ns: integer)
Detach a callback previously attached with |vim.ui_attach()| for the given namespace {ns}.
nsintegerNamespace ID
function M.call(func: string, ...: any) -> any
Invokes |vim-function| or |user-function| {func} with arguments {...}. See also |vim.fn|. Equivalent to:
vim.fn[func]({...})
function M.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
astringFirst string to compare
bstringSecond string to compare
optsvim.text.diff.Opts | nil
- string | integer[][] | nil
See {opts.resulttype}.
nilif {opts.onhunk} is given.
function M.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 M.uri_from_fname(path: string) -> URI string
pathstringPath to file
URIstring
function M.uri_from_bufnr(buf: integer) -> URI string
function M.uri_to_fname(uri: string) -> filename string
uristring
filenamestringor unchanged URI for non-file URIs
function M.uri_to_bufnr(uri: string) -> bufnr integer
Fields61
M._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() )
M.inspect : any
Gets a human-readable representation of the given object.
|vim.print()| https://github.com/kikito/inspect.lua https://github.com/mpeterv/vinspect
M.fn: table
vim.fn.{func}(...)
@nodoc
M.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 } })
|ex-cmd-index|
M.g : vim.g
M.v : vim.v
M.b : vim.b
M.w : vim.w
M.t : vim.t
M.loop : uv
Deprecated
Remove at Nvim 1.0
M.highlight : table
Deprecated. Remove at Nvim 2.0
M.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)
M.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
M.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
M.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
M.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'
M.opt : table
@nodoc
M.opt_local : table
@nodoc
M.opt_global : table
@nodoc
M.list: table
M._maxint: integer = 4294967295
Use max 32-bit signed int value to avoid overflow on 32-bit systems. #31633
M._so_trails : string[]
M._submodules: table
M.api: table
M.base64: table
M.NIL : vim.NIL
@nodoc
M._core : vim._core
@nodoc
M.json: table
@nodoc
M.lpeg: table
M.mpack: table
@nodoc
M.bo : vim.bo
M.wo : vim.wo
M.v : vim.v
M.uv : uv
M.F: table
M._watch: table
M.diagnostic: table
M.filetype: table
M.fs: table
M.func: table
M.glob: table
M.health: table
M.hl: table
M.iter: table
require('vim.iter') carries the richer EmmyLua generic surface. Force LuaLS onto the fallback module shape above so make luals stays clean.
M.keymap: table
M.loader: table
M.log : vim.Log
M.lsp: table
M.net: table
M.pack: table
M.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
M.re: table
M.secure: table
M.snippet: table
M.text: table
M.treesitter: table
M.tty: table
M.ui: table
M.version: table
M.provider: table