这是用户在 2025-1-26 11:45 为 https://neovim.io/doc/user/lua.html 保存的双语快照页面,由 沉浸式翻译 提供双语支持。了解如何保存?

Lua

Nvim :help pages, generated from source using the tree-sitter-vimdoc parser.
Nvim :help pages,使用 tree-sitter-vimdoc 解析器从生成


Lua engine Lua

INTRODUCTION  介绍 lua-intro

The Lua 5.1 script engine is builtin and always available. Try this command to get an idea of what lurks beneath:
Lua 5.1 脚本引擎是内置的,并且始终可用。尝试此命令 了解下面潜伏着什么:
:lua vim.print(package.loaded)
Nvim includes a "standard library" lua-stdlib for Lua. It complements the "editor stdlib" (vimscript-functions + Ex-commands) and the API, all of which can be used from Lua code (lua-vimscript vim.api). These three namespaces form the Nvim programming interface.
Nvim 包括一个用于 Lua 的 “标准库” lua-stdlib。 它补充了 “editor stdlib” (vimscript-functions + Ex-commands) 和 API,所有这些都可以从 Lua 代码 (lua-vimscriptvim.api) 中使用。这三个 命名空间构成了 Nvim 编程接口。
Lua plugins and user config are automatically discovered and loaded, just like Vimscript. See lua-guide for practical guidance.
Lua 插件和用户配置会自动发现和加载,就像 Vimscript 一样。有关实用指南,请参阅 lua-guide
You can also run Lua scripts from your shell using the -l argument:
您还可以使用 -l 参数从 shell 运行 Lua 脚本:
nvim -l foo.lua [args...]
lua-compat  lua-compat 公司
Lua 5.1 is the permanent interface for Nvim Lua. Plugins should target Lua 5.1 as specified in luaref; later versions (which are essentially different, incompatible, dialects) are not supported. This includes extensions such as goto that some Lua 5.1 interpreters like LuaJIT may support.
Lua 5.1 是 Nvim Lua 的永久接口。插件应以 Lua 5.1 为目标 如 luaref 中指定;更高版本(本质上不同, 不兼容、方言)的 S 的 Quinect S S 的 Dialect 的这包括 goto 一些 Lua 5.1 解释器(如 LuaJIT)可能支持。
lua-luajit
While Nvim officially only requires Lua 5.1 support, it should be built with LuaJIT or a compatible fork on supported platforms for performance reasons. LuaJIT also comes with useful extensions such as ffi, lua-profile, and enhanced standard library functions; these cannot be assumed to be available, and Lua code in init.lua or plugins should check the jit global variable before using them:
虽然 Nvim 官方只需要 Lua 5.1 支持,但它应该使用 LuaJIT 或受支持平台上的兼容 fork。 LuaJIT 还附带了有用的扩展,例如 ffilua-profile 和增强的标准库函数;这些不能假设是可用的,init.lua 或插件中的 Lua 代码应该在使用它们之前检查 jit 全局变量:
if jit then
  -- code for luajit
else
  -- code for plain lua 5.1
end
lua-bit
One exception is the LuaJIT bit extension, which is always available: when built with PUC Lua, Nvim includes a fallback implementation which provides require("bit").
一个例外是 LuaJIT 扩展,它始终可用:当 Nvim 使用 PUC Lua 构建,包括一个回退实现,它提供 require(“bit”)
lua-profile  lua-配置文件
If Nvim is built with LuaJIT, Lua code can be profiled via
如果 Nvim 是使用 LuaJIT 构建的,则可以通过以下方式分析 Lua 代码
-- Start a profiling session:
require('jit.p').start('ri1', '/tmp/profile')
-- Perform arbitrary tasks (use plugins, scripts, etc.) ...
-- Stop the session. Profile is written to /tmp/profile.
require('jit.p').stop()
See https://luajit.org/ext_profiler.html or the p.lua source for details:
有关详细信息,请参阅 https://luajit.org/ext_profiler.htmlp.lua 源:
:lua vim.cmd.edit(package.searchpath('jit.p', package.path))

LUA CONCEPTS AND IDIOMS  LUA 概念和习语 lua-concepts

Lua is very simple, and _consistent_: while there are some quirks, once you internalize those quirks, everything works the same everywhere. Scopes (closures) in particular are very consistent, unlike JavaScript or most other languages.
Lua 非常简单,而且 _consistent_: 虽然有一些怪癖,但一旦你内化了这些怪癖,一切都在任何地方都是一样的。特别是 scopes(闭包)非常一致,这与 JavaScript 或大多数其他语言不同。
Lua has three fundamental mechanisms—one for "each major aspect of programming": tables, closures, and coroutines. https://www.lua.org/doc/cacm2018.pdf
Lua 有三个基本机制 — 一个用于“每个主要方面 programming“:表、闭包和协程。 https://www.lua.org/doc/cacm2018.pdf
Tables are the "object" or container datastructure: they represent both lists and maps, you can extend them to represent your own datatypes and change their behavior using metatables (like Python's "datamodel").
表是 “对象” 或容器数据结构:它们同时表示列表和映射,您可以扩展它们以表示您自己的数据类型,并使用元表(如 Python 的 “datamodel”)更改它们的行为。
EVERY scope in Lua is a closure: a function is a closure, a module is a closure, a do block (lua-do) is a closure--and they all work the same. A Lua module is literally just a big closure discovered on the "path" (where your modules are found: package.cpath).
Lua 中的每个作用域都是一个闭包:一个函数是一个闭包,一个模块是一个闭包,一个 do 块 (lua-do) 是一个闭包——它们的工作原理都是一样的。Lua 模块实际上只是在 “path” 上发现的一个大闭包(你的模块所在的位置:package.cpath)。
Stackful coroutines enable cooperative multithreading, generators, and versatile control for both Lua and its host (Nvim).
Stackful 协程支持 Lua 及其主机 (Nvim) 的协作式多线程、生成器和多功能控制。
lua-error-handling  lua-错误处理
Lua functions may throw lua-errors for exceptional (unexpected) failures, which you can handle with pcall().
Lua 函数可能会因异常(意外)故障而引发 lua-errors,您可以使用 pcall() 处理。
lua-result-or-message
When failure is normal and expected, it's idiomatic to return nil which signals to the caller that failure is not "exceptional" and must be handled. This "result-or-message" pattern is expressed as the multi-value return type any|nil,nil|string, or in LuaLS notation:
当失败是正常且预期的时,惯用的返回 nil 是惯用的,它 向调用者发出信号,表明失败不是 “异常” 的,必须进行处理。 这种 “result-or-message” 模式表示为多值返回类型 any|nil,nil|string,或者以 LuaLS 表示法表示:
---@return any|nil    # result on success, nil on failure.
---@return nil|string # nil on success, error message on failure.
Examples of the "result-or-message" pattern:
“result-or-message” 模式的示例:
When a caller can't proceed on failure, it's idiomatic to assert() the "result-or-message" result:
当调用者在失败时无法继续时,惯用的 assert() “result-or-message” 结果是惯用的:
local value = assert(fn())
Guidance: use the "result-or-message" pattern for...
指导:将 “result-or-message” 模式用于...
Functions where failure is expected, especially when communicating with the external world. E.g. HTTP requests or LSP requests often fail because of server problems, even if the caller did everything right.
预期会失败的函数,尤其是在与外部世界通信时。例如,HTTP 请求或 LSP 请求经常因为服务器问题而失败,即使调用方做对了一切。
Functions that return a value, e.g. Foo:new().
返回值的函数,例如 Foo:new()。
When there is a list of known error codes which can be returned as a third value (like luv-error-handling).
当存在可以作为第三个值返回的已知错误代码列表(如 luv-error-handling)时。
iterator  迭 代
An iterator is just a function that can be called repeatedly to get the "next" value of a collection (or any other iterable). This interface is expected by for-in loops, produced by pairs(), supported by vim.iter, etc. https://www.lua.org/pil/7.1.html
迭代器只是一个可以重复调用以获得“下一个”的函数 值(或任何其他可迭代对象)。此接口由 for-in 循环,由 pairs() 生成,由 vim.iter 支持,等等。 https://www.lua.org/pil/7.1.html
iterable  可迭代
An "iterable" is anything that vim.iter() can consume: tables, dicts, lists, iterator functions, tables implementing the __call() metamethod, and vim.iter() objects.
“可迭代对象” 是 vim.iter() 可以使用的任何东西:表、字典、列表、迭代器函数、实现 __call() 元方法的表,以及 vim.iter() 对象。
list-iterator  列表迭代器
Iterators on lua-list tables have a "middle" and "end", whereas iterators in general may be logically infinite. Therefore some vim.iter operations (e.g. Iter:rev()) make sense only on list-like tables (which are finite by definition).
lua-list 表上的迭代器有 “middle” 和 “end”,而迭代器通常在逻辑上可能是无限的。因此,一些 vim.iter 操作(例如 iter:rev())仅在类似列表的表(其有限 定义)。
lua-function-call  lua 函数调用
Lua functions can be called in multiple ways. Consider the function:
可以通过多种方式调用 Lua 函数。考虑函数:
local foo = function(a, b)
    print("A: ", a)
    print("B: ", b)
end
The first way to call this function is:
调用此函数的第一种方法是:
foo(1, 2)
-- ==== Result ====
-- A: 1
-- B: 2
This way of calling a function is familiar from most scripting languages. In Lua, any missing arguments are passed as nil, and extra parameters are silently discarded. Example:
这种调用函数的方式在大多数脚本语言中都很常见。在 Lua,则任何缺失的参数都将作为 nil 传递,额外的参数将被静默丢弃。例:
foo(1)
-- ==== Result ====
-- A: 1
-- B: nil
kwargs  夸格斯
When calling a function, you can omit the parentheses if the function takes exactly one string literal ("foo") or table literal ({1,2,3}). The latter is often used to mimic "named parameters" ("kwargs" or "keyword args") as in languages like Python and C#. Example:
调用函数时,如果函数采用 恰好是一个字符串文本 (“foo”) 或表文本 ({1,2,3})。后者通常用于模拟 Python 和 C# 等语言中的“命名参数”(“kwargs”或“keyword args”)。例:
local func_with_opts = function(opts)
    local will_do_foo = opts.foo
    local filename = opts.filename
    -- ...
end
func_with_opts { foo = true, filename = "hello.world" }
There's nothing special going on here except that parentheses are implicitly added. But visually, this small bit of sugar gets reasonably close to a "keyword args" interface.
除了隐式添加括号外,这里没有什么特别之处。但从视觉上看,这小点糖相当接近 “keyword args” 界面。
lua-regex  lua-正则表达式
Lua intentionally does not support regular expressions, instead it has limited lua-patterns which avoid the performance pitfalls of extended regex. Lua scripts can also use Vim regex via vim.regex().
Lua 故意不支持正则表达式,而是将 lua-patterns 避免了扩展正则表达式的性能陷阱。Lua 脚本也可以通过 vim.regex() 使用 Vim 正则表达式。
Examples:  例子:
print(string.match("foo123bar123", "%d+"))
-- 123
print(string.match("foo123bar123", "[^%d]+"))
-- foo
print(string.match("foo123bar123", "[abc]+"))
-- ba
print(string.match("foo.bar", "%.bar"))
-- .bar

IMPORTING LUA MODULES  导入 LUA 模块 lua-module-load  lua-module-load 模块

Modules are searched for under the directories specified in 'runtimepath', in the order they appear. Any "." in the module name is treated as a directory separator when searching. For a module foo.bar, each directory is searched for lua/foo/bar.lua, then lua/foo/bar/init.lua. If no files are found, the directories are searched again for a shared library with a name matching lua/foo/bar.?, where ? is a list of suffixes (such as so or dll) derived from the initial value of package.cpath. If still no files are found, Nvim falls back to Lua's default search mechanism. The first script found is run and require() returns the value returned by the script if any, else true.
按照模块出现的顺序在 'runtimepath' 中指定的目录下搜索模块。搜索时,模块名称中的任何 “.” 都被视为目录分隔符。对于模块 foo.bar,每个目录都会搜索 lua/foo/bar.lua,然后搜索 lua/foo/bar/init.lua。 如果未找到文件,则 将再次搜索目录以查找名称匹配的共享库 lua/foo/bar.?,其中 是从 package.cpath 的初始值派生的后缀(例如 sodll)列表。如果仍然没有找到文件,Nvim 会失败 回到 Lua 的默认搜索机制。找到的第一个脚本是 run 和 require() 返回脚本返回的值(如果有),否则为 true
The return value is cached after the first call to require() for each module, with subsequent calls returning the cached value without searching for, or executing any script. For further details see require().
返回值在每个模块第一次调用 require() 后缓存,后续调用返回缓存的值,而不搜索或执行任何脚本。有关更多详细信息,请参阅 require()。
For example, if 'runtimepath' is foo,bar and package.cpath was ./?.so;./?.dll at startup, require('mod') searches these paths in order and loads the first module found ("first wins"):
例如,如果 'runtimepath'foo,bar 并且 package.cpath./?.所以;。/?.dll 启动时,require('mod') 按顺序搜索这些路径并加载找到的第一个模块 (“first wins”):
foo/lua/mod.lua
foo/lua/mod/init.lua
bar/lua/mod.lua
bar/lua/mod/init.lua
foo/lua/mod.so
foo/lua/mod.dll
bar/lua/mod.so
bar/lua/mod.dll
lua-package-path
Nvim automatically adjusts package.path and package.cpath according to the effective 'runtimepath' value. Adjustment happens whenever 'runtimepath' is changed. package.path is adjusted by simply appending /lua/?.lua and /lua/?/init.lua to each directory from 'runtimepath' (/ is actually the first character of package.config).
Nvim 根据有效的 'runtimepath' 值自动调整 package.pathpackage.cpath。每当 'runtimepath' 发生更改时,都会进行调整。package.path 可以通过简单地附加 /lua/?来调整。lua/lua/?/init.lua'runtimepath' 的每个目录(/ 实际上是 package.config 的第一个字符)。
Similarly to package.path, modified directories from 'runtimepath' are also added to package.cpath. In this case, instead of appending /lua/?.lua and /lua/?/init.lua to each runtimepath, all unique ?-containing suffixes of the existing package.cpath are used. Example:
package.path 类似,从 'runtimepath' 修改的目录也会添加到 package.cpath 中。在这种情况下,而不是附加 /lua/?。lua/lua/?/init.lua 添加到每个运行时路径,都是唯一的 -包含现有 package.cpath 的后缀。例:
1. Given that   1. 鉴于
'runtimepath' contains /foo/bar,/xxx;yyy/baz,/abc;
'runtimepath' 包含 /foo/bar,/xxx;yyy/baz,/abc;
initial package.cpath (defined at compile-time or derived from $LUA_CPATH / $LUA_INIT) contains ./?.so;/def/ghi/a?d/j/g.elf;/def/?.so.
初始 package.cpath(在编译时定义或从 $LUA_CPATH / $LUA_INIT) 包含 ./?.so;/def/ghi/a?d/j/g.elf;/def/?.so .
2. It finds ?-containing suffixes /?.so, /a?d/j/g.elf and /?.so, in order: parts of the path starting from the first path component containing question mark and preceding path separator.
2. 它发现 -包含后缀 /?。所以/a?d/j/g.elf/?.因此,按顺序:从包含问号和前面的路径分隔符的第一个路径组件开始的路径部分。
3. The suffix of /def/?.so, namely /?.so is not unique, as it’s the same as the suffix of the first path from package.path (i.e. ./?.so). Which leaves /?.so and /a?d/j/g.elf, in this order.
3. /def/?的后缀。所以,即 /?。so 不是唯一的,因为它与 package.path 中第一个路径的后缀相同(即 ./?.所以)。剩下 /?.so/a?d/j/g.elf,按此顺序。
4. 'runtimepath' has three paths: /foo/bar, /xxx;yyy/baz and /abc. The second one contains a semicolon which is a paths separator so it is out, leaving only /foo/bar and /abc, in order.
4. 'runtimepath' 有三个路径:/foo/bar/xxx;yyy/baz/abc。第二个包含分号,它是一个路径分隔符,因此它被省略,只留下 /foo/bar/abc 按顺序排列。
5. The cartesian product of paths from 4. and suffixes from 3. is taken, giving four variants. In each variant a /lua path segment is inserted between path and suffix, leaving:
5. 路径的笛卡尔积 4.和 3 的后缀。被采用,给出四种变体。在每个变体中,在 path 和 suffix 之间插入一个 /lua 路径段,留下:
/foo/bar/lua/?.so
/foo/bar/lua/?中。所以
/foo/bar/lua/a?d/j/g.elf
/foo/bar/lua/a?d/j/g.elf
/abc/lua/?.so  /abc/lua/?中。所以
/abc/lua/a?d/j/g.elf
/abc/lua/a?d/j/g.elf
6. New paths are prepended to the original package.cpath.
6. 新路径将添加到原始 package.cpath 之前。
The result will look like this:
/foo/bar,/xxx;yyy/baz,/abc ('runtimepath')
× ./?.so;/def/ghi/a?d/j/g.elf;/def/?.so (package.cpath)
= /foo/bar/lua/?.so;/foo/bar/lua/a?d/j/g.elf;/abc/lua/?.so;/abc/lua/a?d/j/g.elf;./?.so;/def/ghi/a?d/j/g.elf;/def/?.so
Note:
结果将如下所示:注意:
To track 'runtimepath' updates, paths added at previous update are remembered and removed at the next update, while all paths derived from the new 'runtimepath' are prepended as described above. This allows removing paths when path is removed from 'runtimepath', adding paths when they are added and reordering package.path/|package.cpath| content if 'runtimepath' was reordered.
要跟踪 'runtimepath' 更新,在上一次更新时添加的路径将被记住并在下次更新时删除,而从新 'runtimepath' 派生的所有路径都会如前所述在前面添加。这允许在 path 从 'runtimepath' 中删除时删除路径,在添加路径时添加路径,并重新排序 package.path/package.cpath|content 如果 'runtimepath' 已重新排序。
Although adjustments happen automatically, Nvim does not track current values of package.path or package.cpath. If you happen to delete some paths from there you can set 'runtimepath' to trigger an update:
尽管调整是自动进行的,但 Nvim 不会跟踪当前 package.pathpackage.cpath 的值。如果你碰巧删除了一些 paths 从那里你可以设置 'runtimepath' 来触发更新:
let &runtimepath = &runtimepath
Skipping paths from 'runtimepath' which contain semicolons applies both to package.path and package.cpath. Given that there are some badly written plugins using shell, which will not work with paths containing semicolons, it is better to not have them in 'runtimepath' at all.
跳过 'runtimepath' 中包含分号的路径适用于 package.pathpackage.cpath 的 package.cpath 中。鉴于有一些使用 shell 编写的插件,它们不适用于包含分号的路径,因此最好不要将它们放在 'runtimepath' 中。

COMMANDS  命令 lua-commands  lua 命令

These commands execute a Lua chunk from either the command line (:lua, :luado) or a file (:luafile) on the given line [range]. As always in Lua, each chunk has its own scope (closure), so only global variables are shared between command calls. The lua-stdlib modules, user modules, and anything else on package.path are available.
这些命令从命令行 (:lua, :luado) 或给定行 [range] 上的文件 (:luafile) 执行 Lua 块。与 Lua 一样,每个 chunk 都有自己的范围(闭包),因此在命令调用之间只有全局变量共享。lua-stdlib 模块、用户模块以及 package.path 可用。
The Lua print() function redirects its output to the Nvim message area, with arguments separated by " " (space) instead of "\t" (tab).
Lua print() 函数将其输出重定向到 Nvim 消息区域,参数用“ ”(空格)而不是 “\t” (制表符)分隔。
:lua= :lua :lua {chunk} Executes Lua chunk {chunk}. If {chunk} starts with "=" the rest of the chunk is evaluated as an expression and printed. :lua =expr and :=expr are equivalent to :lua vim.print(expr).
:lua=:lua :lua {chunk} 执行 Lua chunk {chunk}。如果 {chunk} 以 “=” 开头,则 chunk 的其余部分将作为表达式计算并打印。:lua =expr:=expr 等价于 :lua vim.print(expr)。
Examples:  例子:
:lua vim.api.nvim_command('echo "Hello, Nvim!"')
To see the Lua version:
要查看 Lua 版本:
:lua print(_VERSION)
To see the LuaJIT version:
要查看 LuaJIT 版本:
:lua =jit.version
:{range}lua Executes buffer lines in {range} as Lua code. Unlike :source, this always treats the lines as Lua code.
:{range}lua 将 {range} 中的缓冲区行作为 Lua 代码执行。与 :source 不同,它总是将这些行视为 Lua 代码。
Example: select the following code and type ":lua<Enter>" to execute it:
示例:选择以下代码并键入 “:lua<Enter>” 来执行它:
print(string.format(
    'unix time: %s', os.time()))
:lua-heredoc  :lua-heredoc
:lua << [trim] [{endmarker}] {script} {endmarker} Executes Lua script {script} from within Vimscript. You can omit [endmarker] after the "<<" and use a dot "." after {script} (similar to :append, :insert). Refer to :let-heredoc for more information.
:lua << [修剪] [{endmarker}] {script}{endmarker} 从 Vimscript 中执行 Lua 脚本 {script}。您可以省略 [endmarker],并在 {script} 后使用点 “.”(类似于 :append:insert) 的有关更多信息,请参阅 :let-heredoc
Example:  例:
function! CurrentLineInfo()
lua << EOF
local linenr = vim.api.nvim_win_get_cursor(0)[1]
local curline = vim.api.nvim_buf_get_lines(0, linenr - 1, linenr, false)[1]
print(string.format('Line [%d] has %d bytes', linenr, #curline))
EOF
endfunction
Note that the local variables will disappear when the block finishes. But not globals.
请注意,当模块完成时,局部变量将消失。但不是 globals。
:luado  :卢阿多
:[range]luado {body} Executes Lua chunk "function(line, linenr) {body} end" for each buffer line in [range], where line is the current line text (without <EOL>), and linenr is the current line number. If the function returns a string that becomes the text of the corresponding buffer line. Default [range] is the whole file: "1,$".
:[range]luado {body} 为每个缓冲区执行 Lua 块 “function(line, linenr) {body} end” line in [range],其中 line 是当前行文本(不含 <EOL>), linenr 是当前行号。如果函数返回字符串 这将成为相应缓冲区行的文本。默认值 [range] 为 整个文件:“1,$”。
Examples:  例子:
:luado return string.format("%s\t%d", line:reverse(), #line)
:lua require"lpeg"
:lua -- balanced parenthesis grammar:
:lua bp = lpeg.P{ "(" * ((1 - lpeg.S"()") + lpeg.V(1))^0 * ")" }
:luado if bp:match(line) then return "=>\t" .. line end
:luafile  :lua文件
:luafile {file} Execute Lua script in {file}. The whole argument is used as the filename (like :edit), spaces do not need to be escaped. Alternatively you can :source Lua files.
:luafile {文件}{file} 中执行 Lua 脚本。 整个参数用作文件名(如 :edit),空格则不 需要被转义。或者,你可以 :source Lua 文件。
Examples:  例子:
:luafile script.lua
:luafile %

luaeval()  卢阿瓦尔() lua-eval

The (dual) equivalent of "vim.eval" for passing Lua values to Nvim is "luaeval". "luaeval" takes an expression string and an optional argument used for _A inside expression and returns the result of the expression. It is semantically equivalent in Lua to:
将 Lua 值传递给 Nvim 的 “vim.eval” 的(双重)等价物是 “卢阿瓦尔”。“luaeval” 接受一个表达式字符串和一个使用的可选参数 for _A 表达式中,并返回表达式的结果。是的 在 Lua 中语义上等同于:
local chunkheader = "local _A = select(1, ...) return "
function luaeval (expstr, arg)
    local chunk = assert(loadstring(chunkheader .. expstr, "luaeval"))
    return chunk(arg) -- return typval
end
Lua nils, numbers, strings, tables and booleans are converted to their respective Vimscript types. If a Lua string contains a NUL byte, it will be converted to a Blob. Conversion of other Lua types is an error.
Lua nils、数字、字符串、表格和布尔值被转换为它们各自的 Vimscript 类型。如果 Lua 字符串包含 NUL 字节,它将被转换为 Blob。其他 Lua 类型的转换是一个错误。
The magic global "_A" contains the second argument to luaeval().
魔术全局 “_A” 包含 luaeval() 的第二个参数。
Example:  例:
:echo luaeval('_A[1] + _A[2]', [40, 2])
" 42
:echo luaeval('string.match(_A, "[a-z]+")', 'XYXfoo123')
" foo
lua-table-ambiguous
Lua tables are used as both dictionaries and lists, so it is impossible to decide whether empty table is a list or a dict. Also Lua does not have integer numbers. To disambiguate these cases, we define:
Lua 表既用作字典又用作列表,因此不可能 确定 Empty Table 是 List 还是 Dict。此外,Lua 没有整数 数字。为了消除这些情况的歧义,我们定义了:
lua-list
0. Empty table is a list. Use vim.empty_dict() to represent empty dict. 1. Table with N consecutive (no nil values, aka "holes") integer keys 1…N is a list. See also list-iterator.
0. 空表是一个列表。使用 vim.empty_dict() 表示空字典。具有 N 个连续(无 nil 值,又名“holes”)整数键 1...N 是 一个列表。另请参见 list-iterator
lua-dict  lua-dict 命令
2. Table with string keys, none of which contains NUL byte, is a dict. 3. Table with string keys, at least one of which contains NUL byte, is also considered to be a dictionary, but this time it is converted to a msgpack-special-map.
2. 带有字符串键的表,其中不包含 NUL 字节,是一个字典。 3. 带有字符串键的表,其中至少有一个包含 NUL 字节,也是 被认为是一个字典,但这次它被转换为 一个 msgpack-special-map 的 map。
lua-special-tbl
4. Table with vim.type_idx key may be a dictionary, a list or floating-point value:
4. 带vim.type_idx键的表格可以是字典、列表或浮点 价值:
{[vim.type_idx]=vim.types.float, [vim.val_idx]=1} is converted to a floating-point 1.0. Note that by default integral Lua numbers are converted to Numbers, non-integral are converted to Floats. This variant allows integral Floats.
{[vim.type_idx]=vim.types.float, [vim.val_idx]=1} 转换为浮点 1.0。请注意,默认情况下,整型 Lua 数字将转换为数字s,非整型数字将转换为 Floats。此变体允许整数 Floats。
{[vim.type_idx]=vim.types.dictionary} is converted to an empty dictionary, {[vim.type_idx]=vim.types.dictionary, [42]=1, a=2} is converted to a dictionary {'a': 42}: non-string keys are ignored. Without vim.type_idx key tables with keys not fitting in 1., 2. or 3. are errors.
{[vim.type_idx]=vim.types.dictionary} 转换为空字典, {[vim.type_idx]=vim.types.dictionary, [42]=1, a=2} 转换为字典 {'a': 42}:忽略非字符串键。没有 vim.type_idx 键表的键不适合 1., 2.或 3.是错误的。
{[vim.type_idx]=vim.types.array} is converted to an empty list. As well as {[vim.type_idx]=vim.types.array, [42]=1}: integral keys that do not form a 1-step sequence from 1 to N are ignored, as well as all non-integral keys.
{[vim.type_idx]=vim.types.array} 将转换为空列表。以及 {[vim.type_idx]=vim.types.array, [42]=1} : 不形成从 1 到 N 的 1 步序列的整数键,以及所有非整数键都将被忽略。
Examples:  例子:
:echo luaeval('math.pi')
:function Rand(x,y) " random uniform between x and y
:  return luaeval('(_A.y-_A.x)*math.random()+_A.x', {'x':a:x,'y':a:y})
:  endfunction
:echo Rand(1,10)
Note: Second argument to luaeval is converted ("marshalled") from Vimscript to Lua, so changes to Lua containers do not affect values in Vimscript. Return value is also always converted. When converting, msgpack-special-dicts are treated specially.
注意:luaeval 的第二个参数从 Vimscript 转换(“编组”)为 Lua,因此对 Lua 容器的更改不会影响 Vimscript 中的值。返回值也始终进行转换。在转换时,msgpack-special-dicts 会被特殊处理。

Vimscript v:lua interface  Vimscript v:lua 接口 v:lua-call  v:lua-call

From Vimscript the special v:lua prefix can be used to call Lua functions which are global or accessible from global tables. The expression
在 Vimscript 中,特殊的 v:lua 前缀可用于调用全局或可从全局表访问的 Lua 函数。表达式
call v:lua.func(arg1, arg2)
is equivalent to the Lua chunk
等同于 Lua 块
return func(...)
where the args are converted to Lua values. The expression
其中 args 转换为 Lua 值。表达式
call v:lua.somemod.func(args)
is equivalent to the Lua chunk
等同于 Lua 块
return somemod.func(...)
In addition, functions of packages can be accessed like
此外,还可以访问包的功能,例如
call v:lua.require'mypack'.func(arg1, arg2)
call v:lua.require'mypack.submod'.func(arg1, arg2)
Note: Only single quote form without parens is allowed. Using require"mypack" or require('mypack') as prefixes do NOT work (the latter is still valid as a function call of itself, in case require returns a useful value).
注意:只允许没有括号的单引号格式。用 require“mypack”require('mypack') 作为前缀不起作用(后者 仍然有效,以防 require 返回一个有用的 值)。
The v:lua prefix may be used to call Lua functions as methods. For example:
v:lua 前缀可用于将 Lua 函数作为方法s 调用。例如:
:eval arg1->v:lua.somemod.func(arg2)
You can use v:lua in "func" options like 'tagfunc', 'omnifunc', etc. For example consider the following Lua omnifunc handler:
你可以在 'tagfunc''omnifunc' 等 “func” 选项中使用 v:lua。例如,考虑以下 Lua omnifunc 处理程序:
function mymod.omnifunc(findstart, base)
  if findstart == 1 then
    return 0
  else
    return {'stuff', 'steam', 'strange things'}
  end
end
vim.bo[buf].omnifunc = 'v:lua.mymod.omnifunc'
Note: The module ("mymod" in the above example) must either be a Lua global, or use require() as shown above to access it from a package.
注意:模块(上面例子中的“mymod”)必须是 Lua 全局变量, 或者使用上面所示的 require() 从包中访问它。
Note: v:lua without a call is not allowed in a Vimscript expression: Funcrefs cannot represent Lua functions. The following are errors:
注意:在 Vimscript 表达式中不允许不带调用的 v:luaFuncref不能表示 Lua 函数。以下是错误:
let g:Myvar = v:lua.myfunc        " Error
call SomeFunc(v:lua.mycallback)   " Error
let g:foo = v:lua                 " Error
let g:foo = v:['lua']             " Error

Lua standard modules  Lua 标准模块 lua-stdlib

The Nvim Lua "standard library" (stdlib) is the vim module, which exposes various functions and sub-modules. It is always loaded, thus require("vim") is unnecessary.
Nvim Lua“标准库”(stdlib)是 vim 模块,它暴露了各种函数和子模块。它总是被加载的,因此 require(“vim”) 是不必要的。
You can peek at the module properties:
您可以查看模块属性:
:lua vim.print(vim)
Result is something like this:
{
  _os_proc_children = <function 1>,
  _os_proc_info = <function 2>,
  ...
  api = {
    nvim__id = <function 5>,
    nvim__id_array = <function 6>,
    ...
  },
  deepcopy = <function 106>,
  gsplit = <function 107>,
  ...
}
To find documentation on e.g. the "deepcopy" function:
Result 是这样的: 要查找有关 “deepcopy” 函数的文档:
:help vim.deepcopy()
Note that underscore-prefixed functions (e.g. "_os_proc_children") are internal/private and must not be used by plugins.
请注意,以下划线为前缀的函数(例如“_os_proc_children”)是 internal/private 的,并且不得件使用。

VIM.UV lua-loop vim.uv

vim.uv exposes the "luv" Lua bindings for the libUV library that Nvim uses for networking, filesystem, and process management, see luvref.txt. In particular, it allows interacting with the main Nvim luv-event-loop.
vim.uv 公开了 nvim 用于网络、文件系统和进程管理的 libUV 库的 “luv” Lua 绑定,请参见luvref.txt。特别是,它允许与主 Nvim luv-event-loop 交互。
E5560 lua-loop-callbacks It is an error to directly invoke vim.api functions (except api-fast) in vim.uv callbacks. For example, this is an error:
E5560lua-loop-callbacks vim.uv 回调。例如,这是一个错误:
local timer = vim.uv.new_timer()
timer:start(1000, 0, function()
  vim.api.nvim_command('echomsg "test"')
end)
To avoid the error use vim.schedule_wrap() to defer the callback:
为避免此错误,请使用 vim.schedule_wrap() 延迟回调:
local timer = vim.uv.new_timer()
timer:start(1000, 0, vim.schedule_wrap(function()
  vim.api.nvim_command('echomsg "test"')
end))
(For one-shot timers, see vim.defer_fn(), which automatically adds the wrapping.)
(对于一次性计时器,请参阅 vim.defer_fn(),它会自动添加换行。
Example: repeating timer 1. Save this code to a file. 2. Execute it with ":luafile %".
示例:重复计时器 1. 将此代码保存到文件中。 2. 用 “:luafile %” 执行它。
-- Create a timer handle (implementation detail: uv_timer_t).
local timer = vim.uv.new_timer()
local i = 0
-- Waits 1000ms, then repeats every 750ms until timer:close().
timer:start(1000, 750, function()
  print('timer invoked! i='..tostring(i))
  if i > 4 then
    timer:close()  -- Always close handles to avoid leaks.
  end
  i = i + 1
end)
print('sleeping');
Example: File-change detection
示例:文件更改检测
watch-file  监视文件
1. Save this code to a file. 2. Execute it with ":luafile %". 3. Use ":Watch %" to watch any file. 4. Try editing the file from another text editor. 5. Observe that the file reloads in Nvim (because on_change() calls :checktime).
1. 将此代码保存到文件中。 2. 用 “:luafile %” 执行它。 3. 使用 “:watch %” 来监视任何文件。 4. 尝试从其他文本编辑器编辑文件。 5. 观察文件在 Nvim 中重新加载(因为 on_change() 调用 :checktime 的 S T
local w = vim.uv.new_fs_event()
local function on_change(err, fname, status)
  -- Do work...
  vim.api.nvim_command('checktime')
  -- Debounce: stop/start.
  w:stop()
  watch_file(fname)
end
function watch_file(fname)
  local fullpath = vim.api.nvim_call_function(
    'fnamemodify', {fname, ':p'})
  w:start(fullpath, {}, vim.schedule_wrap(function(...)
    on_change(...) end))
end
vim.api.nvim_command(
  "command! -nargs=1 Watch call luaeval('watch_file(_A)', expand('<args>'))")
inotify-limitations  inotify-限制
When on Linux you may need to increase the maximum number of inotify watches and queued events as the default limit can be too low. To increase the limit, run:
在 Linux 上时,您可能需要增加 inotify 监视和排队事件的最大数量,因为默认限制可能太低。要提高限制,请运行:
sysctl fs.inotify.max_user_watches=494462
This will increase the limit to 494462 watches and queued events. These lines can be added to /etc/sysctl.conf to make the changes persistent.
这将增加对 494462 个监视和排队事件的限制。可以将这些行添加到 /etc/sysctl.conf 中,以使更改持久化。
Note that each watch is a structure in the Kernel, thus available memory is also a bottleneck for using inotify. In fact, a watch can take up to 1KB of space. This means a million watches could result in 1GB of extra RAM usage.
请注意,每个 watch 都是 Kernel 中的一个结构,因此可用内存也是使用 inotify 的瓶颈。事实上,一只手表最多可以占用 1KB 的空间。这意味着 100 万只手表可能会导致 1GB 的额外 RAM 使用量。
Example: TCP echo-server   示例:TCP echo-servertcp-server  tcp 服务器
1. Save this code to a file. 2. Execute it with ":luafile %". 3. Note the port number. 4. Connect from any TCP client (e.g. "nc 0.0.0.0 36795"):
1. 将此代码保存到文件中。 2. 用 “:luafile %” 执行它。 3. 记下端口号。 4. 从任何 TCP 客户端连接(例如“nc 0.0.0.0 36795”):
local function create_server(host, port, on_connect)
  local server = vim.uv.new_tcp()
  server:bind(host, port)
  server:listen(128, function(err)
    assert(not err, err)  -- Check for errors.
    local sock = vim.uv.new_tcp()
    server:accept(sock)  -- Accept client connection.
    on_connect(sock)  -- Start reading messages.
  end)
  return server
end
local server = create_server('0.0.0.0', 0, function(sock)
  sock:read_start(function(err, chunk)
    assert(not err, err)  -- Check for errors.
    if chunk then
      sock:write(chunk)  -- Echo received messages to the channel.
    else  -- EOF (stream closed).
      sock:close()  -- Always close handles to avoid leaks.
    end
  end)
end)
print('TCP echo-server listening on port: '..server:getsockname().port)
Multithreading   多线程lua-loop-threading
Plugins can perform work in separate (os-level) threads using the threading APIs in luv, for instance vim.uv.new_thread. Each thread has its own separate Lua interpreter state, with no access to Lua globals on the main thread. Neither can the editor state (buffers, windows, etc) be directly accessed from threads.
插件可以使用 luv 中的线程 API 在单独的(操作系统级)线程中执行工作,例如 vim.uv.new_thread。每个线程都有自己单独的 Lua 解释器状态,无法访问主线程上的 Lua 全局变量。编辑器状态(缓冲区、窗口等)也不能直接从线程访问。
A subset of the vim.* stdlib is available in threads, including:
vim.* stdlib 的子集在线程中可用,包括:
vim.uv with a separate event loop per thread.
vim.uv 中,每个线程有一个单独的事件循环。
vim.mpack and vim.json (useful for serializing messages between threads)
vim.mpackvim.json (用于在线程之间序列化消息)
require in threads can use Lua packages from the global package.path
require 在线程中可以使用来自全局 package.path 的 Lua 包
print() and vim.inspect
print()vim.inspect
vim.diff  vim.diff 中
Most utility functions in vim.* that work with pure Lua values, like vim.split, vim.tbl_*, vim.list_*, etc.
vim.* 中大多数使用纯 Lua 值的实用函数,例如 vim.splitvim.tbl_*vim.list_* 等。
vim.is_thread() returns true from a non-main thread.
vim.is_thread() 从非主线程返回 true。

VIM.HL vim.hl

vim.hl.on_yank({opts})
vim.hl.on_yank({opts}
vim.hl.on_yank()  vim.hl.on_yank()
Highlight the yanked text during a TextYankPost event.
TextYankPost 事件期间突出显示被拉取的文本。
Add the following to your init.vim:
将以下内容添加到您的 init.vim 中:
autocmd TextYankPost * silent! lua vim.hl.on_yank {higroup='Visual', timeout=300}
Parameters:  参数:
{opts} (table?) Optional parameters
{opts}表格?可选参数
higroup highlight group for yanked region (default "IncSearch")
被拉扯区域的 higroup 高亮组(默认为 “IncSearch”)
timeout time in ms before highlight is cleared (default 150)
清除高亮显示前的超时时间(以毫秒为单位)(默认为 150)
on_macro highlight when executing macro (default false)
on_macro执行宏时高亮显示 (默认为 false)
on_visual highlight when yanking visual selection (default true)
on_visual 在拉动视觉选择时突出显示(默认为 true)
event event structure (default vim.v.event)
事件事件结构(默认为 vim.v.event)
priority integer priority (default vim.hl.priorities.user)
整数优先级 (默认) vim.hl.priorities.user
vim.hl.priorities   vim.hl.priorities 的vim.hl.priorities  vim.hl.priorities 的
Table with default priorities used for highlighting:
用于突出显示的默认优先级的表:
syntax: 50, used for standard syntax highlighting
语法50,用于标准语法高亮显示
treesitter: 100, used for treesitter-based highlighting
treesitter100,用于基于 treesitter 的突出显示
semantic_tokens: 125, used for LSP semantic token highlighting
semantic_tokens125,用于 LSP 语义标记突出显示
diagnostics: 150, used for code analysis such as diagnostics
diagnostics150,用于代码分析,例如诊断
user: 200, used for user-triggered highlights such as LSP document symbols or on_yank autocommands
user200,用于用户触发的高亮,例如 LSP 文档符号或 on_yank 自动命令
vim.hl.range()  vim.hl.range()
vim.hl.range({bufnr}, {ns}, {higroup}, {start}, {finish}, {opts}) Apply highlight group to range of text.
vim.hl.range({bufnr}{ns}{higroup}{start}{finish}{opts}) 将高亮组应用于文本范围。
Parameters:  参数:
{bufnr} (integer) Buffer number to apply highlighting to
{bufnr}integer) 要应用高亮显示的缓冲区编号
{ns} (integer) Namespace to add highlight to
{ns}integer) 要向其添加高亮显示的命名空间
{higroup} (string) Highlight group to use for highlighting
{higroup}string) 用于高亮显示的高亮组
{start} (integer[]|string) Start of region as a (line, column) tuple or string accepted by getpos()
{start}integer[]|string) 以 getpos() 接受的 (行、列) 元组或字符串形式的区域开始
{finish} (integer[]|string) End of region as a (line, column) tuple or string accepted by getpos()
{finish}integer[]|string) 以 getpos() 接受的 (行、列) 元组或字符串形式的区域结尾
{opts} (table?) A table with the following fields:
{opts}表格?包含以下字段的表:
{regtype} (string, default: 'v' i.e. charwise) Type of range. See getregtype()
{regtype}string, default: 'v' i.e. charwise) 范围的类型。请参阅 getregtype()
{inclusive} (boolean, default: false) Indicates whether the range is end-inclusive
{inclusive}boolean, default: false) 指示范围是否为包含结尾
{priority} (integer, default: vim.hl.priorities.user) Highlight priority
{priority}整数,默认值: vim.hl.priorities.user) 突出显示优先级
{timeout} (integer, default: -1 no timeout) Time in ms before highlight is cleared
{timeout}整数,默认值: -1 no timeout) 清除高亮显示之前的时间(以毫秒为单位)

VIM.DIFF  VIM.DIFF (英文) vim.diff  vim.diff 中

vim.diff({a}, {b}, {opts})
vim.diff({a}{b}{opts}
vim.diff()  vim.diff() 文件
Run diff on strings {a} and {b}. Any indices returned by this function, either directly or via callback arguments, are 1-based.
对字符串 {a}{b} 运行 diff。此函数返回的任何索引 直接或通过 callback 参数,都是从 1 开始的。
Examples:  例子:
vim.diff('a\n', 'b\nc\n')
-- =>
-- @@ -1 +1,2 @@
-- -a
-- +b
-- +c
vim.diff('a\n', 'b\nc\n', {result_type = 'indices'})
-- =>
-- {
--   {1, 1, 1, 2}
-- }
Parameters:  参数:
{a} (string) First string to compare
{a}string) 要比较的第一个字符串
{b} (string) Second string to compare
{b}string) 要比较的第二个字符串
{opts} (table?) Optional parameters:
{opts}表格?可选参数:
{on_hunk} (fun(start_a: integer, count_a: integer, start_b: integer, count_b: integer): integer?) Invoked for each hunk in the diff. Return a negative number to cancel the callback for any remaining hunks. Arguments:
{on_hunk}fun(start_a: integer, count_a: integer, start_b: integer, count_b: integer): integer? ) 为 diff 中的每个块调用。返回负数以取消任何剩余块的回调。参数:
start_a (integer): Start line of hunk in {a}.
start_a整数):{a} 中块的起始行。
count_a (integer): Hunk size in {a}.
count_a整数):以 {a} 为单位的块大小。
start_b (integer): Start line of hunk in {b}.
start_b整数):{b} 中块的起始行。
count_b (integer): Hunk size in {b}.
count_b整数):以 {b} 为单位的块大小。
{result_type} ('unified'|'indices', default: 'unified') Form of the returned diff:
{result_type}'统一'|'indices',默认值:'unified')返回的 diff 的形式:
unified: String in unified format.
unified:统一格式的字符串。
indices: Array of hunk locations. Note: This option is ignored if on_hunk is used.
indices:块位置数组。 注意:如果使用 on_hunk,则会忽略此选项。
{linematch} (boolean|integer) Run linematch on the resulting hunks from xdiff. When integer, only hunks upto this size in lines are run through linematch. Requires result_type = indices, ignored otherwise.
{linematch}boolean|integer) 在 来自 xdiff 的 unks 块。当为 integer 时,只有 hunks 最多 此大小(以行为单位)通过 LineMatch 运行。需要 result_type = indices ,否则忽略。
{algorithm} ('myers'|'minimal'|'patience'|'histogram', default: 'myers') Diff algorithm to use. Values:
{algorithm}'myers'|'minimal'|'patience'|'histogram' , default: 'myers') 要使用的 Diff 算法。值:
myers: the default algorithm
Myers:默认算法
minimal: spend extra time to generate the smallest possible diff
minimal:花费额外的时间来生成尽可能小的差异
patience: patience diff algorithm
patience:patience diff 算法
histogram: histogram diff algorithm
histogram:直方图差异算法
{ctxlen} (integer) Context length
{ctxlen}integer) 上下文长度
{interhunkctxlen} (integer) Inter hunk context length
{interhunkctxlen}integer) Inter hunk 上下文长度
{ignore_whitespace} (boolean) Ignore whitespace
{ignore_whitespace}boolean) 忽略空格
{ignore_whitespace_change} (boolean) Ignore whitespace change
{ignore_whitespace_change}boolean) 忽略空格更改
{ignore_whitespace_change_at_eol} (boolean) Ignore whitespace change at end-of-line.
{ignore_whitespace_change_at_eol}布尔值)忽略行尾的空格更改。
{ignore_cr_at_eol} (boolean) Ignore carriage return at end-of-line
{ignore_cr_at_eol}boolean) 忽略行尾的回车符
{ignore_blank_lines} (boolean) Ignore blank lines
{ignore_blank_lines}boolean) 忽略空行
{indent_heuristic} (boolean) Use the indent heuristic for the internal diff library.
{indent_heuristic}boolean) 对内部 diff 库使用缩进启发式方法。
Return:  返回:
(string|integer[][]?) See {opts.result_type}. nil if {opts.on_hunk} is given.
字符串|整数[][]?)参见 {opts.result_type}如果 nil {opts.on_hunk} 给出。

VIM.MPACK  维姆.MPACK vim.mpack

This module provides encoding and decoding of Lua objects to and from msgpack-encoded strings. Supports vim.NIL and vim.empty_dict().
该模块提供 Lua 对象与 msgpack 编码字符串之间的编码和解码。支持 vim.NILvim.empty_dict()。
vim.mpack.decode({str})
vim.mpack.decode({str}
vim.mpack.decode()  vim.mpack.decode()
Decodes (or "unpacks") the msgpack-encoded {str} to a Lua object.
将 msgpack 编码的 {str} 解码(或“解包”)为 Lua 对象。
Parameters:  参数:
{str} (string)
{str}字符串
Return:  返回:
(any)   任意
vim.mpack.encode({obj})
vim.mpack.encode({obj}
vim.mpack.encode()  vim.mpack.encode()
Encodes (or "packs") Lua object {obj} as msgpack in a Lua string.
将 Lua 对象 {obj} 编码(或“打包”)为 Lua 字符串中的 msgpack。
Parameters:  参数:
{obj} (any)
{obj}任意
Return:  返回:
(string)   字符串

VIM.JSON vim.json

This module provides encoding and decoding of Lua objects to and from JSON-encoded strings. Supports vim.NIL and vim.empty_dict().
此模块提供 Lua 对象与 JSON 编码字符串之间的编码和解码。支持 vim.NILvim.empty_dict()。
vim.json.decode({str}, {opts})
vim.json.decode({str}{opts}
vim.json.decode()  vim.json.decode()
Decodes (or "unpacks") the JSON-encoded {str} to a Lua object.
将 JSON 编码的 {str} 解码(或“解包”)为 Lua 对象。
Decodes JSON "null" as vim.NIL (controllable by {opts}, see below).
将 JSON “null” 解码为 vim.NIL (可通过 {opts} 控制,见下文)。
Decodes empty object as vim.empty_dict().
将空对象解码为 vim.empty_dict()。
Decodes empty array as {} (empty Lua table).
将空数组解码为 {}(空 Lua 表)。
Example:  例:
vim.print(vim.json.decode('{"bar":[],"foo":{},"zub":null}'))
-- { bar = {}, foo = vim.empty_dict(), zub = vim.NIL }
Parameters:  参数:
{str} (string) Stringified JSON data.
{str}string) 字符串化的 JSON 数据。
{opts} (table<string,any>?) Options table with keys:
{opts}表<string,any>?)包含键的选项表:
luanil: (table) Table with keys:
luanil: (table) 带键的表:
object: (boolean) When true, converts null in JSON objects to Lua nil instead of vim.NIL.
object: (boolean) 如果为 true,则将 JSON 对象中的 null 转换为 Lua nil 而不是 vim.NIL
array: (boolean) When true, converts null in JSON arrays to Lua nil instead of vim.NIL.
array: (boolean) 如果为 true,则将 JSON 数组中的 null 转换为 Lua nil 而不是 vim.NIL
Return:  返回:
(any)   任意
vim.json.encode({obj}, {opts})
vim.json.encode({obj}{opts}
vim.json.encode()  vim.json.encode()
Encodes (or "packs") Lua object {obj} as JSON in a Lua string.
将 Lua 对象 {obj} 编码(或“打包”)为 Lua 字符串中的 JSON。
Parameters:  参数:
{obj} (any)
{obj}任意
{opts} (table<string,any>?) Options table with keys:
{opts}表<string,any>?)包含键的选项表:
escape_slash: (boolean) (default false) Escape slash characters "/" in string values.
escape_slash:(布尔值)(默认为 false)对字符串值中的斜杠字符 “/” 进行转义。
Return:  返回:
(string)   字符串
vim.base64.decode({str})
vim.base64.decode({str}
vim.base64.decode()  vim.base64.decode()
Decode a Base64 encoded string.
解码 Base64 编码的字符串。
Parameters:  参数:
{str} (string) Base64 encoded string
{str}string) Base64 编码字符串
Return:  返回:
(string) Decoded string
字符串)解码字符串
vim.base64.encode({str})
vim.base64.encode({str}
vim.base64.encode()  vim.base64.encode()
Encode {str} using Base64.
使用 Base64 对 {str} 进行编码。
Parameters:  参数:
{str} (string) String to encode
{str}string) 要编码的字符串
Return:  返回:
(string) Encoded string
字符串)编码字符串
vim.spell.check({str})
vim.spell.check({str}
vim.spell.check()  vim.spell.check()
Check {str} for spelling errors. Similar to the Vimscript function spellbadword().
检查 {str} 是否有拼写错误。与 Vimscript 函数类似 spellbadword()
Note: The behaviour of this function is dependent on: 'spelllang', 'spellfile', 'spellcapcheck' and 'spelloptions' which can all be local to the buffer. Consider calling this with nvim_buf_call().
注意:这个函数的行为取决于: 'spelllang''spellfile''spellcapcheck''spelloptions' 都可以是缓冲区的本地。考虑使用 nvim_buf_call() 调用此函数。
Example:  例:
vim.spell.check("the quik brown fox")
-- =>
-- {
--     {'quik', 'bad', 5}
-- }
Parameters:  参数:
{str} (string)
{str}字符串
Return:  返回:
([string, 'bad'|'rare'|'local'|'caps', integer][]) List of tuples with three items:
[string, 'bad'|'rare'|'local'|'caps', integer][] ) 元组列表 包含三项:
The badly spelled word.   拼写错误的单词。
The type of the spelling error: "bad" spelling mistake "rare" rare word "local" word only valid in another region "caps" word should start with Capital
拼写错误的类型: “bad” 拼写错误 “rare” 稀有词 “local” 词仅在另一个地区有效 “caps” 词应以 Capital 开头
The position in {str} where the word begins.
单词在 {str} 中开始的位置。
vim.api.{func}({...})
vim.api 的 API 中。{func}({...}
vim.api
Invokes Nvim API function {func} with arguments {...}. Example: call the "nvim_get_current_line()" API function:
使用参数 {...} 调用 Nvim API 函数 {func}。 示例:调用 nvim_get_current_line()) API 函数:
print(tostring(vim.api.nvim_get_current_line()))
vim.NIL vim.NIL
Special value representing NIL in RPC and v:null in Vimscript conversion, and similar cases. Lua nil cannot be used as part of a Lua table representing a Dictionary or Array, because it is treated as missing: {"foo", nil} is the same as {"foo"}.
RPC 中表示 NIL 和 Vimscript 中表示 v:null 的特殊值 conversion 和类似情况。Lua nil 不能用作 Lua 的一部分 table 表示 Dictionary 或 Array,因为它被视为 missing: {“foo”, nil}{“foo”} 相同。
vim.type_idx vim.type_idx
Type index for use in lua-special-tbl. Specifying one of the values from vim.types allows typing the empty table (it is unclear whether empty Lua table represents empty list or empty array) and forcing integral numbers to be Float. See lua-special-tbl for more details.
键入 index 以在 lua-special-tbl 中使用。从 vim.types 允许输入空表(目前尚不清楚空 Lua table 表示空列表或空数组)并强制整数 设置为 Float。有关更多详细信息,请参阅 lua-special-tbl
vim.val_idx vim.val_idx
Value index for tables representing Floats. A table representing floating-point value 1.0 looks like this:
表示 Float的表的值索引。表示 浮点值 1.0 如下所示:
{
  [vim.type_idx] = vim.types.float,
  [vim.val_idx] = 1.0,
}
See also vim.type_idx and lua-special-tbl.
另请参见 vim.type_idxlua-special-tbl
vim.types vim.types
Table with possible values for vim.type_idx. Contains two sets of key-value pairs: first maps possible values for vim.type_idx to human-readable strings, second maps human-readable type names to values for vim.type_idx. Currently contains pairs for float, array and dictionary types.
包含vim.type_idx的可能值的表。包含两组 键值对:首先将 vim.type_idx 的可能值映射到 人类可读的字符串,第二个将人类可读的类型名称映射到值 vim.type_idx。当前包含 floatarraydictionary 类型。
Note: One must expect that values corresponding to vim.types.float, vim.types.array and vim.types.dictionary fall under only two following assumptions: 1. Value may serve both as a key and as a value in a table. Given the properties of Lua tables this basically means “value is not nil”. 2. For each value in vim.types table vim.types[vim.types[value]] is the same as value. No other restrictions are put on types, and it is not guaranteed that values corresponding to vim.types.float, vim.types.array and vim.types.dictionary will not change or that vim.types table will only contain values for these three types.
注意:必须期望对应于 vim.types.float 的值, vim.types.arrayvim.types.dictionary 仅属于以下两个假设:1. Value 在表中既可以用作键,也可以用作 value。考虑到 Lua 表的属性,这基本上意味着 “value is not nil”。2. 对于 vim.types 表中的每个值,vim.types[vim.types[value]]value 相同。对类型没有其他限制,并且不能保证对应于 vim.types.floatvim.types.arrayvim.types.dictionary 不会改变,或者 vim.types 表将只包含这三种类型的值。
log_levels vim.log.levels Log levels are one of the values defined in vim.log.levels:
log_levelsvim.log.levels 日志级别是 vim.log.levels 中定义的值之一:
vim.log.levels.DEBUG vim.log.levels.ERROR vim.log.levels.INFO vim.log.levels.TRACE vim.log.levels.WARN vim.log.levels.OFF
vim.empty_dict()   vim.empty_dict()vim.empty_dict()  vim.empty_dict()
Creates a special empty table (marked with a metatable), which Nvim converts to an empty dictionary when translating Lua values to Vimscript or API types. Nvim by default converts an empty table {} without this metatable to an list/array.
创建一个特殊的空表(用元表标记),该 Nvim 将 Lua 值转换为 Vimscript 时转换为空字典 或 API 类型。默认情况下,Nvim 会转换一个空表 {},而不需要这个 metatable 转换为列表/数组。
Note: If numeric keys are present in the table, Nvim ignores the metatable marker and converts the dict to a list/array anyway.
注意:如果表中存在数字键,Nvim 会忽略元表标记并将 dict 转换为列表/数组。
Return:  返回:
(table)   
vim.iconv({str}, {from}, {to})
vim.iconv({str}{from}{to}
vim.iconv()  vim.iconv()
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".
结果是一个 String,它是从编码转换而来的文本 {str} {from} 进行编码 {to}。转换失败时,将返回 nil。什么时候 有些字符无法转换,它们被替换为 “?”。这 编码名称是 iconv() 库函数可以接受的任何名称,请参阅 “:Man 3 iconv”.
Parameters:  参数:
{str} (string) Text to convert
{str}string) 要转换的文本
{from} (string) Encoding of {str}
{from}string{str} 的编码
{to} (string) Target encoding
{to}string) 目标编码
Return:  返回:
(string?) Converted string if conversion succeeds, nil otherwise.
字符串?如果转换成功,则转换字符串,否则为 nil
vim.in_fast_event()   vim.in_fast_event()vim.in_fast_event()  vim.in_fast_event()
Returns true if the code is executing as part of a "fast" event handler, where most of the API is disabled. These are low-level events (e.g. lua-loop-callbacks) which can be invoked whenever Nvim polls for input. When this is false most API functions are callable (but may be subject to other restrictions such as textlock).
如果代码作为 “fast” 事件处理程序的一部分执行,则返回 true, 其中大多数 API 被禁用。这些是低级事件(例如 lua-loop-callbacks)每当 Nvim 轮询输入时都可以调用它。 当此值为 false 时,大多数 API 函数都是可调用的(但可能会受制于 更改为其他限制,例如 Textlock)。
vim.rpcnotify({channel}, {method}, {...})
vim.rpcnotify({channel}{method}{...}
vim.rpcnotify()  vim.rpcnotify()
Sends {event} to {channel} via RPC and returns immediately. If {channel} is 0, the event is broadcast to all channels.
通过 RPC{event} 发送到 {channel} 并立即返回。如果 {channel} 为 0,则事件将广播到所有频道。
This function also works in a fast callback lua-loop-callbacks.
此函数也适用于快速回调 lua-loop-callbacks
Parameters:  参数:
{channel} (integer)
{channel}整数
{method} (string)
{method}字符串
{...} (any?)
{...}任何?
vim.rpcrequest({channel}, {method}, {...})
vim.rpcrequest({channel}{method}{...}
vim.rpcrequest()  vim.rpcrequest()
Sends a request to {channel} to invoke {method} via RPC and blocks until a response is received.
{channel} 发送请求,通过 RPC 调用 {method} 并阻塞,直到 收到响应。
Note: NIL values as part of the return value is represented as vim.NIL special value
注意:作为返回值一部分的 NIL 值表示为 vim.NIL 特殊值
Parameters:  参数:
{channel} (integer)
{channel}整数
{method} (string)
{method}字符串
{...} (any?)
{...}任何?
vim.schedule({fn})
vim.schedule({fn}
vim.schedule()  vim.schedule()
Schedules {fn} to be invoked soon by the main event-loop. Useful to avoid textlock or other temporary restrictions.
安排 {fn} 很快由主事件循环调用。有助于避免 textlock 或其他临时限制。
Parameters:  参数:
{fn} (fun())
{fn}fun()
vim.str_utf_end({str}, {index})
vim.str_utf_end({str}{index}
vim.str_utf_end()  vim.str_utf_end()
Gets the distance (in bytes) from the last byte of the codepoint (character) that {index} points to.
获取距代码点最后一个字节的距离(以字节为单位) {index} 指向的 (字符) 的 intent 的
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)
Parameters:  参数:
{str} (string)
{str}字符串
{index} (integer)
{index}整数
Return:  返回:
(integer)   整数
vim.str_utf_pos({str})
vim.str_utf_pos({str}
vim.str_utf_pos()  vim.str_utf_pos()
Gets a list of the starting byte positions of each UTF-8 codepoint in the given string.
获取 given 字符串。
Embedded NUL bytes are treated as terminating the string.
嵌入的 NUL 字节被视为终止字符串。
Parameters:  参数:
{str} (string)
{str}字符串
Return:  返回:
(integer[])   整数[]
vim.str_utf_start({str}, {index})
vim.str_utf_start({str}{index}
vim.str_utf_start()  vim.str_utf_start()
Gets the distance (in bytes) from the starting byte of the codepoint (character) that {index} points to.
获取距代码点起始字节的距离(以字节为单位) {index} 指向的 (字符) 的 intent 的
The result can be added to {index} to get the starting byte of a character.
可以将结果添加到 {index} 以获取字符的起始字节。
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)
Parameters:  参数:
{str} (string)
{str}字符串
{index} (integer)
{index}整数
Return:  返回:
(integer)   整数
vim.stricmp({a}, {b})
vim.stricmp({a}{b}
vim.stricmp()  vim.stricmp()
Compares strings case-insensitively.
比较不区分大小写的字符串。
Parameters:  参数:
{a} (string)
{a}字符串
{b} (string)
{b}字符串
Return:  返回:
(0|1|-1) if strings are equal, {a} is greater than {b} or {a} is lesser than {b}, respectively.
0|1|-1) 如果字符串相等,则 {a} 大于 {b}{a} 为 小于 {b}
vim.ui_attach({ns}, {options}, {callback})
vim.ui_attach({ns}{options}{callback}
vim.ui_attach()  vim.ui_attach()
WARNING: This feature is experimental/unstable.
警告:此功能是实验性的/不稳定的。
Attach to ui-events, similar to nvim_ui_attach() but receive events as Lua callback. Can be used to implement screen elements like popupmenu or message handling in Lua.
附加到 ui-events,类似于 nvim_ui_attach(),但作为 Lua 回调接收事件。可用于在 Lua 中实现 popupmenu 或消息处理等屏幕元素。
{options} should be a dictionary-like table, where ext_... options should be set to true to receive events for the respective external element.
{options} 应该是一个类似字典的表格,其中 ext_... options 应该设置为 true 来接收相应 external 元素的事件。
{callback} receives event name plus additional parameters. See ui-popupmenu and the sections below for event format for respective events.
{callback} 接收事件名称和其他参数。看 ui-popup菜单和以下部分,了解相应事件的事件格式。
Callbacks for msg_show events are executed in api-fast context; showing the message should be scheduled.
msg_show 事件的回调在 api-fast 上下文中执行;应安排显示消息。
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).
警告:此 api 被视为实验性 API。可用性会因不同的屏幕元素而异。特别是ext_messages行为可能会进一步更改和可用性改进。当将 'cmdheight' 设为 0 时,这应该被用来处理消息(这同样是实验性的)。
Example (stub for a ui-popupmenu implementation):
示例(ui-popupmenu 实现的存根):
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:  参数:
{ns} (integer)
{ns}整数
{options} (table<string, any>)
{options}表<字符串, any>
{callback} (fun())
{回调}fun()
vim.ui_detach({ns})
vim.ui_detach({ns}
vim.ui_detach()  vim.ui_detach()
Detach a callback previously attached with vim.ui_attach() for the given namespace {ns}.
分离之前使用 vim.ui_attach() 为给定 命名空间 {ns} 中。
Parameters:  参数:
{ns} (integer)
{ns}整数
vim.wait({time}, {callback}, {interval}, {fast_only})
vim.wait({时间}{回调}{间隔}{fast_only}
vim.wait()  vim.wait()
Wait for {time} in milliseconds until {callback} returns true.
等待 {time} (以毫秒为单位),直到 {callback} 返回 true
Executes {callback} immediately and at approximately {interval} milliseconds (default 200). Nvim still processes other events during this time.
立即执行 {callback},大约每 {interval} 毫秒(默认为 200)。在此期间,Nvim 仍会处理其他事件。
Cannot be called while in an api-fast event.
api-fast 事件中无法调用。
Examples:  例子:
---
-- Wait for 100 ms, allowing other events to process
vim.wait(100, function() end)
---
-- Wait for 100 ms or until global variable set.
vim.wait(100, function() return vim.g.waiting_for_var end)
---
-- Wait for 1 second or until global variable set, checking every ~500 ms
vim.wait(1000, function() return vim.g.waiting_for_var end, 500)
---
-- Schedule a function to set a value in 100ms
vim.defer_fn(function() vim.g.timer_result = true end, 100)
-- Would wait ten seconds if results blocked. Actually only waits  100 ms
if vim.wait(10000, function() return vim.g.timer_result end) then
  print('Only waiting a little bit of time!')
end
Parameters:  参数:
{time} (integer) Number of milliseconds to wait
{time}整数) 等待的毫秒数
{callback} (fun(): boolean?) Optional callback. Waits until {callback} returns true
{callback}fun(): 布尔值?可选回调。等到 {callback} 返回 true
{interval} (integer?) (Approximate) number of milliseconds to wait between polls
{interval}整数?轮询之间等待的 (近似) 毫秒数
{fast_only} (boolean?) If true, only api-fast events will be processed.
{fast_only}布尔值?如果为 true,则仅处理 api-fast 事件。
Return (multiple):  返回 (多个):
(boolean) (-1|-2?)
布尔值) (-1|-2?
If {callback} returns true during the {time}: true, nil
如果 {callback}{time}: true 期间返回 true,则为 nil
If {callback} never returns true during the {time}: false, -1
如果 {callback}{time} 期间从未返回 truefalse,则为 -1
If {callback} is interrupted during the {time}: false, -2
如果在 {time} 期间 {callback} 被中断: false,则为 -2
If {callback} errors, the error is raised.
如果 {callback} 错误,则会引发错误。

LUA-VIMSCRIPT BRIDGE  LUA-VIMSCRIPT 桥 lua-vimscript  lua-vimscript 文件

Nvim Lua provides an interface or "bridge" to Vimscript variables and functions, and editor commands and options.
Nvim Lua 为 Vimscript 变量和函数以及编辑器命令和选项提供了一个接口或“桥梁”。
Objects passed over this bridge are COPIED (marshalled): there are no "references". lua-guide-variables For example, using vim.fn.remove() on a Lua list copies the list object to Vimscript and does NOT modify the Lua list:
通过此网桥传递的对象将 COPYED(编组):没有 “参考资料”。lua-guide-变量例如,在 Lua 列表上使用 vim.fn.remove() 会将列表对象复制到 Vimscript,并且不会修改 Lua 列表:
local list = { 1, 2, 3 }
vim.fn.remove(list, 0)
vim.print(list)  --> "{ 1, 2, 3 }"
vim.call({func}, {...})
vim.call({func}{...}
vim.call()  vim.call()
Invokes vim-function or user-function {func} with arguments {...}. See also vim.fn. Equivalent to:
调用带有参数 {...}vim-functionuser-function{func}。 另请参见 vim.fn。 相当于:
vim.fn[func]({...})
vim.cmd({command}) See vim.cmd().
vim.cmd({command}) 参见 vim.cmd()。
vim.fn.{func}({...})
vim.fn 的{func}({...}
vim.fn
Invokes vim-function or user-function {func} with arguments {...}. To call autoload functions, use the syntax:
调用带有参数 {...}vim-functionuser-function{func}。 要调用 autoload 函数,请使用以下语法:
vim.fn['some#function']({...})
Unlike vim.api.|nvim_call_function()| this converts directly between Vim objects and Lua objects. If the Vim function returns a float, it will be represented directly as a Lua number. Empty lists and dictionaries both are represented by an empty table.
与 vim.api.|nvim_call_function()|这会直接在 Vim 对象和 Lua 对象之间转换。如果 Vim 函数返回一个浮点数,它将直接表示为 Lua 数字。空列表和字典都由空表表示。
Note: v:null values as part of the return value is represented as vim.NIL special value
注意:v:null 值作为返回值的一部分表示为 vim.NIL 特殊值
Note: vim.fn keys are generated lazily, thus pairs(vim.fn) only enumerates functions that were called at least once.
注意: vim.fn 键是懒惰生成的,因此 pairs(vim.fn) 只枚举至少被调用过一次的函数。
Note: The majority of functions cannot run in api-fast callbacks with some undocumented exceptions which are allowed.
注意:大多数函数无法在 api-fast 回调中运行,但允许一些未记录的异常。
lua-vim-variables  lua-vim-变量
The Vim editor global dictionaries g: w: b: t: v: can be accessed from Lua conveniently and idiomatically by referencing the vim.* Lua tables described below. In this way you can easily read and modify global Vimscript variables from Lua.
Vim 编辑器全局词典 g:w:b:t:v: 可以通过引用 vim.* Lua 表格,方便、地道地从 Lua 访问 如下所述。通过这种方式,您可以轻松读取和修改全局 Vimscript 变量。
Example:  例:
vim.g.foo = 5     -- Set the g:foo Vimscript variable.
print(vim.g.foo)  -- Get and print the g:foo Vimscript variable.
vim.g.foo = nil   -- Delete (:unlet) the Vimscript variable.
vim.b[2].foo = 6  -- Set b:foo for buffer 2
Note that setting dictionary fields directly will not write them back into Nvim. This is because the index into the namespace simply returns a copy. Instead the whole dictionary must be written as one. This can be achieved by creating a short-lived temporary.
请注意,直接设置字典字段不会将它们写回 Nvim。这是因为命名空间的索引只返回一个副本。相反,整个词典必须写成一个。这可以通过创建一个短期临时变量来实现。
Example:  例:
vim.g.my_dict.field1 = 'value'  -- Does not work
local my_dict = vim.g.my_dict   --
my_dict.field1 = 'value'        -- Instead do
vim.g.my_dict = my_dict         --
vim.g vim.g
Global (g:) editor variables. Key with no value returns nil.
全局 (g:) 编辑器变量。 没有值的 Key 返回 nil
vim.b vim.b
Buffer-scoped (b:) variables for the current buffer. Invalid or unset key returns nil. Can be indexed with an integer to access variables for a specific buffer.
当前缓冲区的缓冲区范围 (b:) 变量。 无效或未设置的键返回 nil。可以使用 一个整数,用于访问特定缓冲区的变量。
vim.w vim.w
Window-scoped (w:) variables for the current window. Invalid or unset key returns nil. Can be indexed with an integer to access variables for a specific window.
当前窗口的窗口范围 (w:) 变量。 无效或未设置的键返回 nil。可以使用 一个整数,用于访问特定窗口的变量。
vim.t vim.t
Tabpage-scoped (t:) variables for the current tabpage. Invalid or unset key returns nil. Can be indexed with an integer to access variables for a specific tabpage.
当前标签页的 Tabpage 范围 (t:) 变量。 无效或未设置的键返回 nil。可以使用 一个整数,用于访问特定标签页的变量。
vim.v vim.v
v: variables. Invalid or unset key returns nil.
v:变量。 无效或未设置的键返回 nil
Vim options can be accessed through vim.o, which behaves like Vimscript :set.
Vim 选项可以通过 vim.o 访问,它的行为类似于 Vimscript :set
Examples:  例子:
To set a boolean toggle: Vimscript: set number Lua: vim.o.number = true
设置布尔值切换: Vimscript: set number Lua: vim.o.number = true
To set a string value: Vimscript: set wildignore=*.o,*.a,__pycache__ Lua: vim.o.wildignore = '*.o,*.a,__pycache__'
设置字符串值: Vimscript: set wildignore=*.o,*.a,__pycache__ Lua: vim.o.wildignore = '*.o,*.a,__pycache__'
Similarly, there is vim.bo and vim.wo for setting buffer-scoped and window-scoped options. Note that this must NOT be confused with local-options and :setlocal. There is also vim.go that only accesses the global value of a global-local option, see :setglobal.
同样,有 vim.bovim.wo 用于设置 buffer-scoped 和 窗口范围的选项。请注意,这不能与 local-options:setlocal 的还有 vim.go 只访问 global-local 选项的 global 值,参见 :setglobal
A special interface vim.opt exists for conveniently interacting with list- and map-style options from Lua: It allows accessing them as Lua tables and offers object-oriented method for adding and removing entries.
存在一个特殊的接口 vim.opt,可以方便地与 Lua 中的列表和映射样式选项进行交互:它允许以 Lua 表格的形式访问它们,并提供面向对象的方法来添加和删除条目。
Examples:  例子:
The following methods of setting a list-style option are equivalent: In Vimscript:
以下设置 list-style 选项的方法等效: 在 Vimscript 中:
set wildignore=*.o,*.a,__pycache__
In Lua using vim.o:
在 Lua 中使用 vim.o
vim.o.wildignore = '*.o,*.a,__pycache__'
In Lua using vim.opt:
在 Lua 中使用 vim.opt
vim.opt.wildignore = { '*.o', '*.a', '__pycache__' }
To replicate the behavior of :set+=, use:
要复制 :set+= 的行为,请使用:
vim.opt.wildignore:append { "*.pyc", "node_modules" }
To replicate the behavior of :set^=, use:
要复制 :set^= 的行为,请使用:
vim.opt.wildignore:prepend { "new_first_value" }
To replicate the behavior of :set-=, use:
要复制 :set-= 的行为,请使用:
vim.opt.wildignore:remove { "node_modules" }
The following methods of setting a map-style option are equivalent: In Vimscript:
以下设置地图样式选项的方法等效: 在 Vimscript 中:
set listchars=space:_,tab:>~
In Lua using vim.o:
在 Lua 中使用 vim.o
vim.o.listchars = 'space:_,tab:>~'
In Lua using vim.opt:
在 Lua 中使用 vim.opt
vim.opt.listchars = { space = '_', tab = '>~' }
Note that vim.opt returns an Option object, not the value of the option, which is accessed through vim.opt:get():
请注意,vim.opt 返回一个 Option 对象,而不是 option 的值,可通过 vim.opt:get() 访问:
Examples:  例子:
The following methods of getting a list-style option are equivalent: In Vimscript:
以下获取列表样式选项的方法等效: 在 Vimscript 中:
echo wildignore
In Lua using vim.o:
在 Lua 中使用 vim.o
print(vim.o.wildignore)
In Lua using vim.opt:
在 Lua 中使用 vim.opt
vim.print(vim.opt.wildignore:get())
In any of the above examples, to replicate the behavior :setlocal, use vim.opt_local. Additionally, to replicate the behavior of :setglobal, use vim.opt_global.
在上述任何示例中,要复制行为 :setlocal,请使用 vim.opt_local。此外,要复制 :setglobal 的行为,请使用 vim.opt_global
Option:append({value})
选项:append({value}
vim.opt:append()  vim.opt:append()
Append a value to string-style options. See :set+=
将值附加到字符串样式选项。参见 :set+=
These are equivalent:  这些是等效的:
vim.opt.formatoptions:append('j')
vim.opt.formatoptions = vim.opt.formatoptions + 'j'
Parameters:  参数:
{value} (string) Value to append
{value}string) 要附加的值
Option:get()   选项:get()vim.opt:get()  vim.opt:get()
Returns a Lua-representation of the option. Boolean, number and string values will be returned in exactly the same fashion.
返回选项的 Lua 表示形式。布尔值、数字和字符串 值将以完全相同的方式返回。
For values that are comma-separated lists, an array will be returned with the values as entries in the array:
对于逗号分隔列表的值,将返回一个数组,其中包含 值作为数组中的条目:
vim.cmd [[set wildignore=*.pyc,*.o]]
vim.print(vim.opt.wildignore:get())
-- { "*.pyc", "*.o", }
for _, ignore_pattern in ipairs(vim.opt.wildignore:get()) do
    print("Will ignore:", ignore_pattern)
end
-- Will ignore: *.pyc
-- Will ignore: *.o
For values that are comma-separated maps, a table will be returned with the names as keys and the values as entries:
对于逗号分隔的映射值,将返回一个表格,其中包含 名称作为键,值作为条目:
vim.cmd [[set listchars=space:_,tab:>~]]
vim.print(vim.opt.listchars:get())
--  { space = "_", tab = ">~", }
for char, representation in pairs(vim.opt.listchars:get()) do
    print(char, "=>", representation)
end
For values that are lists of flags, a set will be returned with the flags as keys and true as entries.
对于作为标志列表的值,将返回一个包含标志的集合 作为键,true 作为条目。
vim.cmd [[set formatoptions=njtcroql]]
vim.print(vim.opt.formatoptions:get())
-- { n = true, j = true, c = true, ... }
local format_opts = vim.opt.formatoptions:get()
if format_opts.j then
    print("J is enabled!")
end
Return:  返回:
(string|integer|boolean?) value of option
字符串|整数|布尔值?)期权价值
Option:prepend({value})
Option:prepend({value}
vim.opt:prepend()  vim.opt:prepend()
Prepend a value to string-style options. See :set^=
在字符串样式选项前面加上一个值。参见 :set^=
These are equivalent:  这些是等效的:
vim.opt.wildignore:prepend('*.o')
vim.opt.wildignore = vim.opt.wildignore ^ '*.o'
Parameters:  参数:
{value} (string) Value to prepend
{value}string) 要预置的值
Option:remove({value})
选项:remove({value}
vim.opt:remove()  vim.opt:remove()
Remove a value from string-style options. See :set-=
从 string-style 选项中删除值。参见 :set-=
These are equivalent:  这些是等效的:
vim.opt.wildignore:remove('*.pyc')
vim.opt.wildignore = vim.opt.wildignore - '*.pyc'
Parameters:  参数:
{value} (string) Value to remove
{value}string) 要删除的值
vim.bo[{bufnr}] vim.bo
Get or set buffer-scoped options for the buffer with number {bufnr}. Like :setlocal. If {bufnr} is omitted then the current buffer is used. Invalid {bufnr} or key is an error.
为编号为 {bufnr} 的缓冲区获取或设置缓冲区范围的选项。 就像 :setlocal 一样。如果省略 {bufnr},则使用当前缓冲区。 无效的 {bufnr} 或 key 是错误。
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.env   vim.env 中vim.env  vim.env 中
Environment variables defined in the editor session. See expand-env and :let-environment for the Vimscript behavior. Invalid or unset key returns nil.
在 Editor 会话中定义的环境变量。请参阅 expand-env:let-environment 的 Vimscript 行为。键无效或未设置 返回 nil
Example:  例:
vim.env.FOO = 'bar'
print(vim.env.TERM)
vim.go vim.go
Get or set global options. Like :setglobal. Invalid key is an error.
获取或设置全局选项。就像 :setglobal 一样。无效的密钥是错误的。
Note: this is different from vim.o because this accesses the global option value and thus is mostly useful for use with global-local options.
注意:这与 vim.o 不同,因为它会访问全局选项值,因此在与 global-local 一起使用时非常有用 选项。
Example:  例:
vim.go.cmdheight = 4
print(vim.go.columns)
print(vim.go.bar)     -- error: invalid key
vim.o vim.o
Get or set options. Works like :set, so buffer/window-scoped options target the current buffer/window. Invalid key is an error.
获取或设置选项。工作方式类似于 :set,因此 buffer/window 范围的选项 以当前缓冲区/窗口为目标。无效的密钥是错误的。
Example:  例:
vim.o.cmdheight = 4
print(vim.o.columns)
print(vim.o.foo)     -- error: invalid key
vim.wo[{winid}][{bufnr}] vim.wo
Get or set window-scoped options for the window with handle {winid} and buffer with number {bufnr}. Like :setlocal if setting a global-local option or if {bufnr} is provided, like :set otherwise. If {winid} is omitted then the current window is used. Invalid {winid}, {bufnr} or key is an error.
获取或设置具有句柄 {winid} 编号为 {bufnr} 的缓冲区。就像 :setlocal 如果设置 global-local 选项,或者如果提供了 {bufnr},则否则为 :set。如果 {winid} 为 省略,则使用当前窗口。无效的 {winid}{bufnr} 或密钥 是一个错误。
Note: only {bufnr} with value 0 (the current buffer in the window) is supported.
注意:仅支持值为 0 (窗口中的当前缓冲区) 的 {bufnr}
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'

Lua module: vim  Lua 模块:vim lua-vim

vim.cmd({command})
vim.cmd({command}
vim.cmd()  vim.cmd()
Executes Vimscript (Ex-commands).
执行 Vimscript (Ex-commands)。
Note that vim.cmd can be indexed with a command name to return a callable function to the command.
请注意,可以使用命令名称对 vim.cmd 进行索引,以将可调用函数返回给命令。
Example:  例:
vim.cmd('echo 42')
vim.cmd([[
  augroup My_group
    autocmd!
    autocmd FileType c setlocal cindent
  augroup END
]])
-- Ex command :echo "foo"
-- Note string literals need to be double quoted.
vim.cmd('echo "foo"')
vim.cmd { cmd = 'echo', args = { '"foo"' } }
vim.cmd.echo({ args = { '"foo"' } })
vim.cmd.echo('"foo"')
-- Ex command :write! myfile.txt
vim.cmd('write! myfile.txt')
vim.cmd { cmd = 'write', args = { "myfile.txt" }, bang = true }
vim.cmd.write { args = { "myfile.txt" }, bang = true }
vim.cmd.write { "myfile.txt", bang = true }
-- Ex command :colorscheme blue
vim.cmd('colorscheme blue')
vim.cmd.colorscheme('blue')
Parameters:  参数:
{command} (string|table) Command(s) to execute. If a string, executes multiple lines of Vimscript at once. In this case, it is an alias to nvim_exec2(), where opts.output is set to false. Thus it works identical to :source. If a table, executes a single command. In this case, it is an alias to nvim_cmd() where opts is empty.
{command}string|table) 要执行的命令。如果是字符串,则一次执行多行 Vimscript。在这种情况下,它是 nvim_exec2() 的别名,其中 opts.output 设置为 false。因此,它的工作方式与 :source 相同。如果是表,则执行单个命令。在这种情况下,它是 nvim_cmd() 的别名,其中 opts 为空。
See also:  另请参阅:
vim.defer_fn({fn}, {timeout})
vim.defer_fn({fn}{timeout}
vim.defer_fn()  vim.defer_fn()
Defers calling {fn} until {timeout} ms passes.
推迟调用 {fn},直到 {timeout} 毫秒过去。
Use to do a one-shot timer that calls {fn} Note: The {fn} is vim.schedule_wrap()ped automatically, so API functions are safe to call.
用于执行调用 {fn} 的一次性计时器 注意:{fn}vim.schedule_wrap()ped 的 API 函数,因此可以安全地调用 API 函数。
Parameters:  参数:
{fn} (function) Callback to call once timeout expires
{fn}function超时到期后要调用的回调
{timeout} (integer) Number of milliseconds to wait before calling fn
{timeout}integer) 调用前要等待的毫秒数 fn
Return:  返回:
(table) timer luv timer object
) 计时器 LUV 计时器对象
vim.deprecate()  vim.deprecate()
vim.deprecate({name}, {alternative}, {version}, {plugin}, {backtrace}) Shows a deprecation message to the user.
vim.deprecate({名称}{alternative}{版本}{plugin}{backtrace}) 向用户显示弃用消息。
Parameters:  参数:
{name} (string) Deprecated feature (function, API, etc.).
{name}string 已弃用的功能(函数、API 等)。
{alternative} (string?) Suggested alternative feature.
{alternative}字符串?建议的替代功能。
{version} (string) Version when the deprecated function will be removed.
{version}string) 已弃用函数将被删除的版本。
{plugin} (string?) Name of the plugin that owns the deprecated feature. Defaults to "Nvim".
{plugin}字符串?拥有已弃用功能的插件的名称。默认为 “Nvim”。
{backtrace} (boolean?) Prints backtrace. Defaults to true.
{backtrace}布尔值?打印回溯。默认为 true。
Return:  返回:
(string?) Deprecated message, or nil if no message was shown.
字符串? 已弃用的消息,如果未显示任何消息,则为 nil。
vim.inspect()   vim.inspect()vim.inspect()  vim.inspect()
Gets a human-readable representation of the given object.
获取给定对象的人类可读表示形式。
Return:  返回:
(string)   字符串
vim.keycode({str})
vim.keycode({str}
vim.keycode()  vim.keycode()
Translates keycodes.   翻译键码。
Example:  例:
local k = vim.keycode
vim.g.mapleader = k'<bs>'
Parameters:  参数:
{str} (string) String to be converted.
{str}string) 要转换的字符串。
Return:  返回:
(string)   字符串
vim.lua_omnifunc({find_start})
vim.lua_omnifunc({find_start}
vim.lua_omnifunc()  vim.lua_omnifunc()
Omnifunc for completing Lua values from the runtime Lua interpreter, similar to the builtin completion for the :lua command.
Omnifunc 用于从运行时 Lua 解释器完成 Lua 值, 类似于 :lua 命令的内置补全。
Activate using set omnifunc=v:lua.vim.lua_omnifunc in a Lua buffer.
在 Lua 缓冲区中激活 using set omnifunc=v:lua.vim.lua_omnifunc
Parameters:  参数:
{find_start} (1|0)
{find_start}1|0
vim.notify({msg}, {level}, {opts})
vim.notify({msg}{level}{opts}
vim.notify()  vim.notify()
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.
插件可以覆盖此函数,以使用自定义提供程序(例如系统通知提供程序)显示通知。默认情况下,写入 :messages
Parameters:  参数:
{msg} (string) Content of the notification to show to the user.
{msg}string) 要向用户显示的通知内容。
{level} (integer?) One of the values from vim.log.levels.
{level}整数?来自 vim.log.levels 的值之一。
{opts} (table?) Optional parameters. Unused by default.
{opts}表格?可选参数。默认未使用。
vim.notify_once({msg}, {level}, {opts})
vim.notify_once({msg}{level}{opts}
vim.notify_once()  vim.notify_once()
Displays a notification only one time.
通知仅显示一次。
Like vim.notify(), but subsequent calls with the same message will not display a notification.
vim.notify() 类似,但具有相同消息的后续调用不会显示通知。
Parameters:  参数:
{msg} (string) Content of the notification to show to the user.
{msg}string) 要向用户显示的通知内容。
{level} (integer?) One of the values from vim.log.levels.
{level}整数?来自 vim.log.levels 的值之一。
{opts} (table?) Optional parameters. Unused by default.
{opts}表格?可选参数。默认未使用。
Return:  返回:
(boolean) true if message was displayed, else false
布尔值)如果显示消息,则为 true,否则为 false
vim.on_key({fn}, {ns_id}, {opts})
vim.on_key({fn}{ns_id}{opts}
vim.on_key()  vim.on_key()
Adds Lua function {fn} with namespace id {ns_id} as a listener to every, yes every, input key.
将命名空间 ID 为 {ns_id} 的 Lua 函数 {fn} 添加为每个 是的,每个,输入键。
The Nvim command-line option -w is related but does not support callbacks and cannot be toggled dynamically.
Nvim 命令行选项 -w 是相关的,但不支持回调,也无法动态切换。
Note:  注意:
{fn} will be removed on error.
{fn} 将在出错时被删除。
{fn} won't be invoked recursively, i.e. if {fn} itself consumes input, it won't be invoked for those keys.
{fn} 不会被递归调用,即如果 {fn} 本身消耗 input,则不会为这些键调用它。
{fn} will not be cleared by nvim_buf_clear_namespace()
{fn} 不会被 nvim_buf_clear_namespace() 清除
Parameters:  参数:
{fn} (fun(key: string, typed: string): string??) Function invoked for every input key, after mappings have been applied but before further processing. Arguments {key} and {typed} are raw keycodes, where {key} is the key after mappings are applied, and {typed} is the key(s) before mappings are applied. {typed} may be empty if {key} is produced by non-typed key(s) or by the same typed key(s) that produced a previous {key}. If {fn} returns an empty string, {key} is discarded/ignored. When {fn} is nil, the callback associated with namespace {ns_id} is removed.
{fn}fun(key: string, typed: string): string?? ) 在应用映射之后但在进一步处理之前为每个输入键调用的函数。参数 {key}{typed} 是原始键码,其中 {key} 是应用映射后的键,{typed} 是应用映射之前的键。如果 {key} 由非类型化 key(s) 或由生成前一个 {key} 的相同类型化 key(s) 生成,则 {typed} 可能为空。如果 {fn} 返回空字符串,则丢弃/忽略 {key}。当 {fn}nil 时,将删除与命名空间 {ns_id} 关联的回调。
{ns_id} (integer?) Namespace ID. If nil or 0, generates and returns a new nvim_create_namespace() id.
{ns_id}整数?命名空间 ID。如果为 nil 或 0,则生成并返回新的 nvim_create_namespace() id。
{opts} (table?) Optional parameters
{opts}表格?可选参数
Return:  返回:
(integer) Namespace id associated with {fn}. Or count of all callbacks if on_key() is called without arguments.
整数)与 {fn} 关联的命名空间 ID。或 count of all callbacks (如果 on_key() 被调用时不带参数)。
See also:  另请参阅:
vim.paste({lines}, {phase})
vim.paste({行}{phase}
vim.paste()  vim.paste()
Paste handler, invoked by nvim_paste().
Paste 处理程序,由 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.
注意:这仅作为 “钩子” 提供,不要直接调用它;叫 nvim_paste() 来代替它,它安排重做(点重复)并调用 vim.paste 中。
Example: To remove ANSI color codes when pasting:
示例:要在粘贴时删除 ANSI 颜色代码:
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:  参数:
{lines} (string[]) readfile()-style list of lines to paste. channel-lines
{lines}string[]readfile()样式的要粘贴的行列表。 通道线
{phase} (-1|1|2|3) -1: "non-streaming" paste: the call contains all lines. If paste is "streamed", phase indicates the stream state:
{phase}-1|1|2|3) -1: “非流式” paste: 调用包含所有行。如果 paste 为 “streamed”,则 phase 指示流状态:
1: starts the paste (exactly once)
1:开始粘贴(恰好一次)
2: continues the paste (zero or more times)
2:继续粘贴(零次或多次)
3: ends the paste (exactly once)
3:结束粘贴(恰好一次)
Return:  返回:
(boolean) result false if client should cancel the paste.
boolean) 结果 如果客户端应取消粘贴,则为 false。
See also:  另请参阅:
vim.print({...})
vim.print({...}
vim.print()  vim.print()
"Pretty prints" the given arguments and returns them unmodified.
“Pretty 打印” 给定的参数并返回它们。
Example:  例:
local hl_normal = vim.print(vim.api.nvim_get_hl(0, { name = 'Normal' }))
Parameters:  参数:
{...} (any)
{...}任意
Return:  返回:
(any) given arguments.
any) 给定的参数。
See also:  另请参阅:
:=
vim.schedule_wrap({fn})
vim.schedule_wrap({fn}
vim.schedule_wrap()  vim.schedule_wrap()
Returns a function which calls {fn} via vim.schedule().
返回一个通过 vim.schedule() 调用 {fn} 的函数。
The returned function passes all arguments to {fn}.
返回的函数将所有参数传递给 {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))
Parameters:  参数:
{fn} (function)
{fn}函数
Return:  返回:
(function)   功能
vim.str_byteindex()  vim.str_byteindex()
vim.str_byteindex({s}, {encoding}, {index}, {strict_indexing}) Convert UTF-32, UTF-16 or UTF-8 {index} to byte index. If {strict_indexing} is false then then an out of range index will return byte length instead of throwing an error.
vim.str_byteindex({s}{encoding}{index}{strict_indexing}) 将 UTF-32、UTF-16 或 UTF-8 {index} 转换为字节索引。如果 {strict_indexing} 为 false,则超出范围的索引将返回 字节长度,而不是引发错误。
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.
无效的 UTF-8 和 NUL 的处理方式与 vim.str_utfindex() 中的处理方式相同。UTF-16 序列中间的 {index} 向上舍入到该序列的末尾。
Parameters:  参数:
{s} (string)
{s}字符串
{encoding} ("utf-8"|"utf-16"|"utf-32")
{编码}“utf-8”|”UTF-16“|”UTF-32 英寸
{index} (integer)
{index}整数
{strict_indexing} (boolean?) default: true
{strict_indexing}boolean?) 默认值:true
Return:  返回:
(integer)   整数
vim.str_utfindex()  vim.str_utfindex()
vim.str_utfindex({s}, {encoding}, {index}, {strict_indexing}) 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.
vim.str_utfindex({s}{encoding}{index}{strict_indexing}) 将字节索引转换为 UTF-32、UTF-16 或 UTF-8 索引。如果 {index} 不是 提供字符串的长度。所有索引都从零开始。
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.
如果 {strict_indexing} 为 false,则超出范围的索引将返回字符串长度,而不是引发错误。无效的 UTF-8 字节和嵌入的代理项各计为 1 个码位。UTF-8 序列中间的 {index} 向上舍入到该序列的末尾。
Parameters:  参数:
{s} (string)
{s}字符串
{encoding} ("utf-8"|"utf-16"|"utf-32")
{编码}“utf-8”|”UTF-16“|”UTF-32 英寸
{index} (integer?)
{index}整数?
{strict_indexing} (boolean?) default: true
{strict_indexing}boolean?) 默认值:true
Return:  返回:
(integer)   整数
vim.system({cmd}, {opts}, {on_exit})
vim.system({cmd}{opts}{on_exit}
vim.system()  vim.system()
Runs a system command or throws an error if {cmd} cannot be run.
运行系统命令,如果 {cmd} 无法运行,则引发错误。
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.
有关更多详细信息,请参阅 uv.spawn() 注意:uv.spawn() 不同,如果 {cmd} 无法运行,vim.system 会抛出错误。
Parameters:  参数:
{cmd} (string[]) Command to execute
{cmd}string[]) 要执行的命令
{opts} (vim.SystemOpts?) Options:
{opts}vim.SystemOpts?)选项:
cwd: (string) Set the current working directory for the sub-process.
cwd: (string) 设置子进程的当前工作目录。
env: table<string,string> Set environment variables for the new process. Inherits the current environment with NVIM set to v:servername.
env: table 设置环境变量 新流程。继承当前环境 NVIM 设置为 v:servername
clear_env: (boolean) env defines the job environment exactly, instead of merging current environment.
clear_env:(布尔值)env 精确定义作业环境,而不是合并当前环境。
stdin: (string|string[]|boolean) If true, then a pipe to stdin is opened and can be written to via the write() method to SystemObj. If string or string[] then will be written to stdin and closed. Defaults to false.
stdin: (string|string[]|boolean) 如果为 true,则管道 to stdin 已打开,并且可以通过 write() 方法添加到 SystemObj 中。如果 string 或 string[] 则将被写入 stdin 并关闭。默认为 false
stdout: (boolean|function) Handle output from stdout. When passed as a function must have the signature fun(err: string, data: string). Defaults to true
stdout: (boolean|function) 处理 stdout 的输出。 作为函数传递时,必须具有签名 fun(err: string, data: string) 。默认为 true
stderr: (boolean|function) Handle output from stderr. When passed as a function must have the signature fun(err: string, data: string). Defaults to true.
stderr: (boolean|function) 处理 stderr 的输出。 作为函数传递时,必须具有签名 fun(err: string, data: string) 。默认为 true
text: (boolean) Handle stdout and stderr as text. Replaces \r\n with \n.
text: (boolean) 将 stdout 和 stderr 作为文本处理。将 \r\n 替换为 \n
timeout: (integer) Run the command with a time limit. Upon timeout the process is sent the TERM signal (15) and the exit code is set to 124.
timeout: (integer) 运行有时间限制的命令。超时时,进程将发送 TERM 信号 (15),并将退出代码设置为 124。
detach: (boolean) If true, spawn the child process in a detached state - this will make it a process group leader, and will effectively enable the child to keep running after the parent exits. Note that the child process will still keep the parent's event loop alive unless the parent process calls uv.unref() on the child's process handle.
detach: (boolean) 如果为 true,则生成处于 detached 状态的子进程 - 这将使其成为进程组领导者,并有效地使子进程在父进程退出后继续运行。请注意,除非父进程在子进程的句柄上调用 uv.unref(),否则子进程仍将保持父进程的事件循环处于活动状态。
{on_exit} (fun(out: vim.SystemCompleted)?) Called when subprocess exits. When provided, the command runs asynchronously. Receives SystemCompleted object, see return of SystemObj:wait().
{on_exit}fun(out: vim.SystemCompleted)? ) 在子进程退出时调用。提供后,该命令将异步运行。接收 SystemCompleted 对象,请参见 SystemObj:wait() 的返回。
Return:  返回:
(vim.SystemObj) Object with the fields:
vim.SystemObj)Object 的字段:
cmd (string[]) Command name and args
cmd (string[]) 命令名称和参数
pid (integer) Process ID   pid (整数) 进程 ID
wait (fun(timeout: integer|nil): SystemCompleted) Wait for the process to complete. Upon timeout the process is sent the KILL signal (9) and the exit code is set to 124. Cannot be called in api-fast.
wait (fun(timeout: integer|nil): SystemCompleted) 等待 要完成的流程。超时时,进程将发送 KILL signal (9) 的 Exit Code 设置为 124。无法调用 api-fast 的 API 快速。
SystemCompleted is an object with the fields:
SystemCompleted 是一个包含以下字段的对象:
code: (integer)   code: (整数)
signal: (integer)   signal:(整数)
stdout: (string), nil if stdout argument is passed
stdout: (string),如果传递 stdout 参数,则为 nil
stderr: (string), nil if stderr argument is passed
stderr: (string),如果传递 stderr 参数,则为 nil
kill (fun(signal: integer|string))
kill (fun(signal: integer|string))
write (fun(data: string|nil)) Requires stdin=true. Pass nil to close the stream.
write (fun(data: string|nil)) 需要 stdin=true。传递 nil 以关闭流。
is_closing (fun(): boolean)
is_closing (fun(): boolean)

Lua module: vim.inspector  Lua 模块:vim.inspector vim.inspector  vim.inspector 命令

vim.inspect_pos({bufnr}, {row}, {col}, {filter})
vim.inspect_pos({bufnr}{row}{col}{filter}
vim.inspect_pos()  vim.inspect_pos()
Get all the items at a given buffer position.
获取给定缓冲区位置的所有项目。
Can also be pretty-printed with :Inspect!.
也可以使用 :Inspect! 进行漂亮打印。
:Inspect!  :检查!
Attributes:  属性:
Since: 0.9.0   从:0.9.0 开始
Parameters:  参数:
{bufnr} (integer?) defaults to the current buffer
{bufnr}integer?) 默认为当前缓冲区
{row} (integer?) row to inspect, 0-based. Defaults to the row of the current cursor
{row}integer?) 行,从 0 开始。默认为当前游标的行
{col} (integer?) col to inspect, 0-based. Defaults to the col of the current cursor
{col}integer?) col 进行检查,从 0 开始。默认为当前游标的 col
{filter} (table?) Table with key-value pairs to filter the items
{filter}表格?)具有键值对的表,用于筛选项目
{syntax} (boolean, default: true) Include syntax based highlight groups.
{syntax}boolean, default: true) 包括基于语法的高亮组。
{treesitter} (boolean, default: true) Include treesitter based highlight groups.
{treesitter}boolean, default: true) 包括基于 treesitter 的高亮组。
{extmarks} (boolean|"all", default: true) Include extmarks. When all, then extmarks without a hl_group will also be included.
{extmarks}布尔值|”all“,默认值:true)包括 extmarks。when all, then extmarks without a hl_group 也将包括在内。
{semantic_tokens} (boolean, default: true) Include semantic token highlights.
{semantic_tokens}boolean, default: true) 包括语义标记高亮。
Return:  返回:
(table) a table with the following key-value pairs. Items are in "traversal order":
table) 一个包含以下键值对的表。项目在 “遍历顺序”:
treesitter: a list of treesitter captures
treesitter:Treesitter 捕获的列表
syntax: a list of syntax groups
syntax:语法组列表
semantic_tokens: a list of semantic tokens
semantic_tokens:语义标记列表
extmarks: a list of extmarks
extmarks:extmark 列表
buffer: the buffer used to get the items
buffer:用于获取项目的缓冲区
row: the row used to get the items
row:用于获取项目的行
col: the col used to get the items
col:用于获取项目的 col
vim.show_pos({bufnr}, {row}, {col}, {filter})
vim.show_pos({bufnr}{row}{col}{filter}
vim.show_pos()  vim.show_pos()
Show all the items at a given buffer position.
显示给定缓冲区位置的所有项目。
Can also be shown with :Inspect.
也可以用 :Inspect 显示。
:Inspect  :检查
Example: To bind this function to the vim-scriptease inspired zS in Normal mode:
示例:若要将此函数绑定到 vim-scriptease 启发的 zS 正常模式:
vim.keymap.set('n', 'zS', vim.show_pos)
Attributes:  属性:
Since: 0.9.0   从:0.9.0 开始
Parameters:  参数:
{bufnr} (integer?) defaults to the current buffer
{bufnr}integer?) 默认为当前缓冲区
{row} (integer?) row to inspect, 0-based. Defaults to the row of the current cursor
{row}integer?) 行,从 0 开始。默认为当前游标的行
{col} (integer?) col to inspect, 0-based. Defaults to the col of the current cursor
{col}integer?) col 进行检查,从 0 开始。默认为当前游标的 col
{filter} (table?) A table with the following fields:
{filter}表格?)包含以下字段的表:
{syntax} (boolean, default: true) Include syntax based highlight groups.
{syntax}boolean, default: true) 包括基于语法的高亮组。
{treesitter} (boolean, default: true) Include treesitter based highlight groups.
{treesitter}boolean, default: true) 包括基于 treesitter 的高亮组。
{extmarks} (boolean|"all", default: true) Include extmarks. When all, then extmarks without a hl_group will also be included.
{extmarks}布尔值|”all“,默认值:true)包括 extmarks。when all, then extmarks without a hl_group 也将包括在内。
{semantic_tokens} (boolean, default: true) Include semantic token highlights.
{semantic_tokens}boolean, default: true) 包括语义标记高亮。
Fields:  领域:
{clear} (fun()) See Ringbuf:clear().
{clear}fun()) 参见 ringbuf:clear()。
{push} (fun(item: T)) See Ringbuf:push().
{push}fun(item: T)) 参见 ringbuf:push()。
{pop} (fun(): T?) See Ringbuf:pop().
{pop}fun(): T?)参见 ringbuf:pop()。
{peek} (fun(): T?) See Ringbuf:peek().
{peek}fun(): T?)参见 ringbuf:peek()。
Ringbuf:clear()   Ringbuf:clear()Ringbuf:clear()  Ringbuf:clear()
Clear all items   清除所有项目
Ringbuf:peek()   Ringbuf:peek()Ringbuf:peek()  Ringbuf:peek()
Returns the first unread item without removing it
返回第一个未读项目,而不将其删除
Return:  返回:
(any?)   任何?
Ringbuf:pop()   ringbuf:pop()Ringbuf:pop()  ringbuf:pop()
Removes and returns the first unread item
删除并返回第一个未读项目
Return:  返回:
(any?)   任何?
Ringbuf:push({item})
Ringbuf:push({item}
Ringbuf:push()  ringbuf:push()
Adds an item, overriding the oldest item if the buffer is full.
添加一个项,如果缓冲区已满,则覆盖最早的项。
Parameters:  参数:
{item} (any)
{item}任意
vim.deep_equal({a}, {b})
vim.deep_equal({a}{b}
vim.deep_equal()  vim.deep_equal()
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.
表以递归方式进行比较,除非它们都提供 eq 元方法。使用相等 == 运算符比较所有其他类型。
Parameters:  参数:
{a} (any) First value
{a}any) 第一个值
{b} (any) Second value
{b}任意) 第二个值
Return:  返回:
(boolean) true if values are equals, else false
布尔值)如果值等于,则为 true,否则为 false
vim.deepcopy({orig}, {noref})
vim.deepcopy({orig}{noref}
vim.deepcopy()  vim.deepcopy()
Returns a deep copy of the given object. Non-table objects are copied as in a typical Lua assignment, whereas table objects are copied recursively. Functions are naively copied, so functions in the copied table point to the same functions as those in the input table. Userdata and threads are not copied and will throw an error.
返回给定对象的深层副本。非表对象将复制为 在典型的 Lua 赋值中,而 table 对象是递归复制的。 函数是天真地复制的,因此复制的表中的函数指向 与 Input Table 中的功能相同。Userdata 和 threads 是 未复制,将引发错误。
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.
注意:noref=true 在具有唯一表字段的表上性能要高得多,而 noref=false 在重用表字段的表上性能更高。
Parameters:  参数:
{orig} (table) Table to copy
{orig}table) 要复制的表
{noref} (boolean?) When false (default) a contained table is only copied once and all references point to this single copy. When true every occurrence of a table results in a new copy. This also means that a cyclic reference can cause deepcopy() to fail.
{noref}布尔值?false (默认) 时,包含的 table 仅复制一次,并且所有引用都指向此单个副本。如果为 true,则表的每次出现都会生成一个新的 复制。这也意味着循环引用可能会导致 deepcopy() 失败。
Return:  返回:
(table) Table of copied keys and (nested) values.
)复制的键和(嵌套)值的表。
vim.defaulttable({createfn})
vim.defaulttable({createfn}
vim.defaulttable()  vim.defaulttable()
Creates a table whose missing keys are provided by {createfn} (like Python's "defaultdict").
创建一个表,其缺失的键由 {createfn} 提供(如 Python 的 “defaultdict” 的 “defaultdict” 的
If {createfn} is nil it defaults to defaulttable() itself, so accessing nested keys creates nested tables:
如果 {createfn}nil,则默认为 defaulttable() 本身,因此访问 嵌套键创建嵌套表:
local a = vim.defaulttable()
a.b.c = 1
Parameters:  参数:
{createfn} (fun(key:any):any?) Provides the value for a missing key.
{createfn}fun(key:any):any?)提供缺失
Return:  返回:
(table) Empty table with __index metamethod.
)带有 __index metamethod 的空表。
vim.endswith({s}, {suffix})
vim.endswith({s}{后缀}
vim.endswith()  vim.endswith()
Tests if s ends with suffix.
测试 s 是否以 suffix 结尾。
Parameters:  参数:
{s} (string) String
{s}string) 字符串
{suffix} (string) Suffix to match
{suffix}string) 要匹配的后缀
Return:  返回:
(boolean) true if suffix is a suffix of s
布尔值)如果 suffixs 的后缀,则为 true
vim.gsplit({s}, {sep}, {opts})
vim.gsplit({s}{sep}{opts}
vim.gsplit()  vim.gsplit()
Gets an iterator that splits a string at each instance of a separator, in "lazy" fashion (as opposed to vim.split() which is "eager").
获取一个迭代器,该迭代器在分隔符的每个实例处拆分字符串, 以 “懒惰” 的方式(而不是 “eager” 的 vim.split() )。
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:
如果您还想检查分隔符本身(而不是丢弃 it),请使用 string.gmatch()。例:
for word, num in ('foo111bar222'):gmatch('([^0-9]*)(%d*)') do
  print(('word: %s num: %s'):format(word, num))
end
Parameters:  参数:
{s} (string) String to split
{s}string) 要拆分的字符串
{sep} (string) Separator or pattern
{sep}string) 分隔符或模式
{opts} (table?) Keyword arguments kwargs:
{opts}表格?关键字参数 kwargs
{plain} (boolean) Use sep literally (as in string.find).
{plain}布尔值) 按字面意思使用 sep(如 string.find)。
{trimempty} (boolean) Discard empty segments at start and end of the sequence.
{trimempty}boolean) 丢弃序列开头和结尾的空段。
Return:  返回:
(fun():string?) Iterator over the split components
fun():string?)拆分组件上的 Iterator
vim.is_callable({f})
vim.is_callable({f}
vim.is_callable()  vim.is_callable()
Returns true if object f can be called as a function.
如果对象 f 可以作为函数调用,则返回 true。
Parameters:  参数:
{f} (any) Any object
{f}any) 任何对象
Return:  返回:
(boolean) true if f is callable, else false
布尔值)如果 f 是可调用的,则为 true,否则为 false
vim.isarray({t})
vim.isarray({t}
vim.isarray()  vim.isarray()
Tests if t is an "array": a table indexed only by integers (potentially non-contiguous).
测试 t 是否为“数组”:仅由整数索引的表(可能 non-contiguous) 的 Package。
If the indexes start from 1 and are contiguous then the array is also a list. vim.islist()
如果索引从 1 开始并且是连续的,则数组也是一个列表。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.
空表 {} 是一个数组,除非它是由 vim.empty_dict() 创建的或作为类似 dict 的 API 或 Vimscript 结果返回的,例如从 rpcrequest()vim.fn
Parameters:  参数:
{t} (table?)
{t}表格?
Return:  返回:
(boolean) true if array-like table, else false.
布尔值)如果是类似数组的表,则为 true,否则为 false
vim.islist({t})   vim.islist({t}vim.islist()  vim.islist()
Tests if t is a "list": a table indexed only by contiguous integers starting from 1 (what lua-length calls a "regular array").
测试 t 是否为 “list”:仅由连续整数索引的表 从 1 开始(Lua-Length 称为 “常规数组”)。
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.
空表 {} 是一个列表,除非它是由 vim.empty_dict() 创建的或作为类似 dict 的 API 或 Vimscript 结果返回的,例如 rpcrequest()vim.fn
Parameters:  参数:
{t} (table?)
{t}表格?
Return:  返回:
(boolean) true if list-like table, else false.
布尔值)如果是类似列表的表,则为 true,否则为 false
See also:  另请参阅:
vim.list_contains({t}, {value})
vim.list_contains({t}{value}
vim.list_contains()  vim.list_contains()
Checks if a list-like table (integer keys without gaps) contains value.
检查列表状表(无间隙的整数键)是否包含 value
Parameters:  参数:
{t} (table) Table to check (must be list-like, not validated)
{t}table) 要检查的表 (必须是类似列表的,未经验证)
{value} (any) Value to compare
{value}any) 要比较的值
Return:  返回:
(boolean) true if t contains value
布尔值)如果 t 包含则为 true
See also:  另请参阅:
vim.tbl_contains() for checking values in general tables
vim.tbl_contains() 用于检查常规表中的值
vim.list_extend({dst}, {src}, {start}, {finish})
vim.list_extend({dst}{src}{start}{finish}
vim.list_extend()  vim.list_extend()
Extends a list-like table with the values of another list-like table.
使用另一个类似列表的表的值扩展一个类似列表的表。
NOTE: This mutates dst!
注意:这会改变 dst!
Parameters:  参数:
{dst} (table) List which will be modified and appended to
{dst}table) 列表,该列表将被修改并附加到
{src} (table) List from which values will be inserted
{src}table) 将从中插入值的列表
{start} (integer?) Start index on src. Defaults to 1
{start}整数?在 src 上启动索引。默认为 1
{finish} (integer?) Final index on src. Defaults to #src
{finish}整数?src 上的 Final 索引。默认为 #src
Return:  返回:
(table) dst   ) DST
See also:  另请参阅:
vim.list_slice({list}, {start}, {finish})
vim.list_slice({list}{start}{finish}
vim.list_slice()  vim.list_slice()
Creates a copy of a table containing only elements from start to end (inclusive)
创建仅包含从头到尾元素的表的副本 (含)
Parameters:  参数:
{list} (any[]) Table
{list}any[]) 表
{start} (integer?) Start range of slice
{start}整数?切片的起始范围
{finish} (integer?) End range of slice
{finish}整数?切片的结束范围
Return:  返回:
(any[]) Copy of table sliced from start to finish (inclusive)
任何[])从头到尾(含)切片的表副本
vim.pesc({s})   vim.pesc({s}vim.pesc()  vim.pesc()
Escapes magic chars in lua-patterns.
转义 lua 模式中的 magic chars。
Parameters:  参数:
{s} (string) String to escape
{s}string) 要转义的字符串
Return:  返回:
(string) %-escaped pattern string
string) % 转义的模式字符串
See also:  另请参阅:
vim.ringbuf({size})
vim.ringbuf({大小}
vim.ringbuf()  vim.ringbuf()
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 实例,方法如下:
Parameters:  参数:
{size} (integer)
{size}整数
Return:  返回:
(vim.Ringbuf) ringbuf See vim.Ringbuf.
vim.Ringbuf) ringbuf 参见 vim.Ringbuf.
vim.spairs({t})   vim.spairs({t}vim.spairs()  vim.spairs()
Enumerates key-value pairs of a table, ordered by key.
枚举表的键值对,按键排序。
Parameters:  参数:
{t} (table) Dict-like table
{t}table) 类似 Dict 的表
Return (multiple):  返回 (多个):
(fun(table: table<K, V>, index?: K):K, V) for-in iterator over sorted keys and their values (table)
fun(table: table<K, V>, index?: K):K, Vfor-in 迭代器 over 排序的 Key 及其值 (
vim.split({s}, {sep}, {opts})
vim.split({s}{sep}{opts}
vim.split()  vim.split()
Splits a string at each instance of a separator and returns the result as a table (unlike vim.gsplit()).
在分隔符的每个实例处拆分字符串,并将结果返回为 一个表(与 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:  参数:
{s} (string) String to split
{s}string) 要拆分的字符串
{sep} (string) Separator or pattern
{sep}string) 分隔符或模式
{opts} (table?) Keyword arguments kwargs:
{opts}表格?关键字参数 kwargs
{plain} (boolean) Use sep literally (as in string.find).
{plain}布尔值) 按字面意思使用 sep(如 string.find)。
{trimempty} (boolean) Discard empty segments at start and end of the sequence.
{trimempty}boolean) 丢弃序列开头和结尾的空段。
Return:  返回:
(string[]) List of split components
字符串[])拆分组件列表
vim.startswith({s}, {prefix})
vim.startswith({s}{prefix}
vim.startswith()  vim.startswith()
Tests if s starts with prefix.
测试 s 是否以 prefix 开头。
Parameters:  参数:
{s} (string) String
{s}string) 字符串
{prefix} (string) Prefix to match
{prefix}string) 要匹配的前缀
Return:  返回:
(boolean) true if prefix is a prefix of s
布尔值)如果 prefixs 的前缀,则为 true
vim.tbl_contains({t}, {value}, {opts})
vim.tbl_contains({t}{value}{opts}
vim.tbl_contains()  vim.tbl_contains()
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:  参数:
{t} (table) Table to check
{t}table) 要检查的表
{value} (any) Value to compare or predicate function reference
{value}any) 要比较或谓词函数引用的值
{opts} (table?) Keyword arguments kwargs:
{opts}表格?关键字参数 kwargs
{predicate} (boolean) value is a function reference to be checked (default false)
{predicate}boolean是要检查的函数引用(默认为 false)
Return:  返回:
(boolean) true if t contains value
布尔值)如果 t 包含则为 true
See also:  另请参阅:
vim.list_contains() for checking values in list-like tables
vim.list_contains() 用于检查类似列表的表中的值
vim.tbl_count({t})
vim.tbl_count({t}
vim.tbl_count()  vim.tbl_count()
Counts the number of non-nil values in table t.
计算表 t 中非 nil 值的个数。
vim.tbl_count({ a=1, b=2 })  --> 2
vim.tbl_count({ 1, 2 })      --> 2
Parameters:  参数:
{t} (table) Table
{t}table) 表
Return:  返回:
(integer) Number of non-nil values in table
整数)表中非 nil 值的数量
vim.tbl_deep_extend({behavior}, {...})
vim.tbl_deep_extend({行为}{...}
vim.tbl_deep_extend()  vim.tbl_deep_extend()
Merges recursively two or more tables.
以递归方式合并两个或多个表。
Only values that are empty tables or tables that are not lua-lists (indexed by consecutive integers starting from 1) are merged recursively. This is useful for merging nested tables like default and user configurations where lists should be treated as literals (i.e., are overwritten instead of merged).
只有空表或非 lua-lists(由从 1 开始的连续整数索引)的值才会递归合并。这对于合并嵌套表(如 default 和 user configuration)非常有用,其中列表应被视为 Literals(即,被覆盖而不是合并)。
Parameters:  参数:
{behavior} ('error'|'keep'|'force') Decides what to do if a key is found in more than one map:
{behavior}'错误'|'保持'|'force') 决定在多个 map 中找到一个键时该怎么做:
"error": raise an error   “error”: 引发错误
"keep": use value from the leftmost map
“keep”:使用最左侧地图中的值
"force": use value from the rightmost map
“force”:使用最右侧映射中的值
{...} (table) Two or more tables
{...})两个或多个表
Return:  返回:
(table) Merged table
)合并表
See also:  另请参阅:
vim.tbl_extend({behavior}, {...})
vim.tbl_extend({行为}{...}
vim.tbl_extend()  vim.tbl_extend()
Merges two or more tables.
合并两个或多个表。
Parameters:  参数:
{behavior} ('error'|'keep'|'force') Decides what to do if a key is found in more than one map:
{behavior}'错误'|'保持'|'force') 决定在多个 map 中找到一个键时该怎么做:
"error": raise an error   “error”: 引发错误
"keep": use value from the leftmost map
“keep”:使用最左侧地图中的值
"force": use value from the rightmost map
“force”:使用最右侧映射中的值
{...} (table) Two or more tables
{...})两个或多个表
Return:  返回:
(table) Merged table
)合并表
See also:  另请参阅:
vim.tbl_filter({func}, {t})
vim.tbl_filter({func}{t}
vim.tbl_filter()  vim.tbl_filter()
Filter a table using a predicate function
使用 predicate 函数筛选表
Parameters:  参数:
{func} (function) Function
{func}function) 函数
{t} (table) Table
{t}table) 表
Return:  返回:
(any[]) Table of filtered values
任何[])筛选值表
vim.tbl_get({o}, {...})
vim.tbl_get({o}{...}
vim.tbl_get()  vim.tbl_get()
Index into a table (first argument) via string keys passed as subsequent arguments. Return nil if the key does not exist.
通过作为后续传递的字符串键对表(第一个参数)进行索引 参数。如果键不存在,则返回 nil
Examples:  例子:
vim.tbl_get({ key = { nested_key = true }}, 'key', 'nested_key') == true
vim.tbl_get({ key = {}}, 'key', 'nested_key') == nil
Parameters:  参数:
{o} (table) Table to index
{o}table) 要索引的表
{...} (any) Optional keys (0 or more, variadic) via which to index the table
{...}任意)用于为表编制索引的可选键(0 或更多,可变)
Return:  返回:
(any) Nested value indexed by key (if it exists), else nil
任意)按 key 索引的嵌套值(如果存在),否则为 nil
vim.tbl_isempty({t})
vim.tbl_isempty({t}
vim.tbl_isempty()  vim.tbl_isempty()
Checks if a table is empty.
检查表是否为空。
Parameters:  参数:
{t} (table) Table to check
{t}table) 要检查的表
Return:  返回:
(boolean) true if t is empty
布尔值)如果 t 为空,则为 true
vim.tbl_keys({t})
vim.tbl_keys({t}
vim.tbl_keys()  vim.tbl_keys()
Return a list of all keys used in a table. However, the order of the return table of keys is not guaranteed.
返回表中使用的所有键的列表。但是, 不保证 return table of keys。
Parameters:  参数:
{t} (table) Table
{t}table) 表
Return:  返回:
(any[]) List of keys
任何[])键列表
vim.tbl_map({func}, {t})
vim.tbl_map({func}{t}
vim.tbl_map()  vim.tbl_map()
Apply a function to all values of a table.
将函数应用于表的所有值。
Parameters:  参数:
{func} (fun(value: T): any) Function
{func}fun(value: T): any) 函数
{t} (table<any, T>) Table
{t}table<any, T>) 表
Return:  返回:
(table) Table of transformed values
)转换值表
vim.tbl_values({t})
vim.tbl_values({t}
vim.tbl_values()  vim.tbl_values()
Return a list of all values used in a table. However, the order of the return table of values is not guaranteed.
返回表中使用的所有值的列表。但是, 不保证 return table of values。
Parameters:  参数:
{t} (table) Table
{t}table) 表
Return:  返回:
(any[]) List of values
任何[])值列表
vim.trim({s})   vim.trim({s}vim.trim()  vim.trim()
Trim whitespace (Lua pattern "%s") from both sides of a string.
从字符串的两侧修剪空格 (Lua 模式 “%s”)。
Parameters:  参数:
{s} (string) String to trim
{s}string) 要修剪的字符串
Return:  返回:
(string) String with whitespace removed from its beginning and end
字符串)从开头和结尾删除空格的字符串
vim.validate()  vim.validate()
vim.validate({name}, {value}, {validator}, {optional}, {message}) Validate function arguments.
vim.validate({名称}{值}{验证器}{可选}{消息}) 验证函数参数。
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:
此函数有两种有效形式: 1. vim.validate(name, value, validator[, optional][, message]) 验证值为 {value} 的参数 {name} 是否满足 {validator} 的如果给出了 {optional} 并且为 true,则 {value} 可能是 nil。如果给出了 {message},则将其用作 错误消息。 例:
 function vim.startswith(s, prefix)
  vim.validate('s', s, 'string')
  vim.validate('prefix', prefix, 'string')
  -- ...
end
2. vim.validate(spec) (deprecated) where spec is 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. Example:
2. vim.validate(spec) (已弃用),其中 spec 的类型为 table<string,[value:any, validator: vim.validate.Validator, optional_or_msg? : boolean|string]>) 验证参数规范。规范以字母数字进行评估 order 的 URL 中,直到第一次失败。 例:
 function user.new(name, age, hobbies)
  vim.validate{
    name={name, 'string'},
    age={age, 'number'},
    hobbies={hobbies, 'table'},
  }
  -- ...
end
Examples with explicit argument values (can be run directly):
具有显式参数值的示例(可以直接运行):
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')
Note:  注意:
validator set to a value returned by lua-type() provides the best performance.
验证器设置为 lua-type() 返回的值可提供最佳性能。
Parameters:  参数:
{name} (string) Argument name
{name}string) 参数名称
{value} (any) Argument value
{value}any) 参数值
{validator} (vim.validate.Validator)
{验证器}vim.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'.
string|string[]):除了 'callable' 之外,还可以从 lua-type() 返回的任何值: '布尔值''可调用''函数''零''数字''字符串''表''线程''userdata'
(fun(val:any): boolean, string?) A function that returns a boolean and an optional string message.
fun(val:any): boolean, string? ) 返回布尔值和可选字符串消息的函数。
{optional} (boolean?) Argument is optional (may be omitted)
{optional}布尔值?)参数是可选的(可以省略)
{message} (string?) message when validation fails
验证失败时 {message}string?) 消息

Lua module: vim.loader  Lua 模块:vim.loader vim.loader  vim.loader 中

vim.loader.enable({enable})
vim.loader.enable({启用}
vim.loader.enable()  vim.loader.enable()
WARNING: This feature is experimental/unstable.
警告:此功能是实验性的/不稳定的。
Enables or disables the experimental Lua module loader:
启用或禁用实验性 Lua 模块加载器:
Enable (enable=true):
启用 (enable=true):
overrides loadfile()
覆盖 loadFile()
adds the Lua loader using the byte-compilation cache
使用字节编译缓存添加 Lua 加载程序
adds the libs loader   添加 libs 加载程序
removes the default Nvim loader
删除默认的 Nvim 加载程序
Disable (enable=false):
禁用 (enable=false):
removes the loaders   移除加载器
adds the default Nvim loader
添加默认的 Nvim 加载程序
Parameters:  参数:
{enable} (boolean?) true/nil to enable, false to disable
{enable}boolean?) true/nil 启用,false 禁用
vim.loader.find({modname}, {opts})
vim.loader.find({modname}{opts}
vim.loader.find()  vim.loader.find()
WARNING: This feature is experimental/unstable.
警告:此功能是实验性的/不稳定的。
Finds Lua modules for the given module name.
查找给定模块名称的 Lua 模块。
Parameters:  参数:
{modname} (string) Module name, or "*" to find the top-level modules instead
{modname}string) 模块名称,或 “*” 来查找顶级模块
{opts} (table?) Options for finding a module:
{opts}表格?查找模块的选项:
{rtp} (boolean, default: true) Search for modname in the runtime path.
{rtp}boolean, default: true) 在运行时路径中搜索 modname。
{paths} (string[], default: {}) Extra paths to search for modname
{paths}string[], default: {}) 搜索 modname 的额外路径
{patterns} (string[], default: {"/init.lua", ".lua"}) List of patterns to use when searching for modules. A pattern is a string added to the basename of the Lua module being searched.
{patterns}string[],默认: {“/init.lua”, “.lua”})搜索模块时要使用的模式列表。模式是添加到正在搜索的 Lua 模块的基本名称中的字符串。
{all} (boolean, default: false) Search for all matches.
{all}boolean, default: false) 搜索所有匹配项。
Return:  返回:
(table[]) A list of objects with the following fields:
表[])具有以下字段的对象列表:
{modpath} (string) Path of the module
{modpath}string) 模块的路径
{modname} (string) Name of the module
{modname}string) 模块的名称
{stat} (uv.fs_stat.result) The fs_stat of the module path. Won't be returned for modname="*"
{stat}uv.fs_stat.result) 模块路径的fs_stat。不会为 modname=“*” 返回
vim.loader.reset({path})
vim.loader.reset({路径}
vim.loader.reset()  vim.loader.reset()
WARNING: This feature is experimental/unstable.
警告:此功能是实验性的/不稳定的。
Resets the cache for the path, or all the paths if path is nil.
重置路径的缓存,如果 path 为 nil,则重置所有路径的缓存。
Parameters:  参数:
{path} (string?) path to reset
要重置的 {path}string?) 路径

Lua module: vim.uri  Lua 模块:vim.uri vim.uri

vim.uri_decode({str})
vim.uri_decode({str}
vim.uri_decode()  vim.uri_decode()
URI-decodes a string containing percent escapes.
URI 对包含百分号转义的字符串进行解码。
Parameters:  参数:
{str} (string) string to decode
{str}string) 要解码的字符串
Return:  返回:
(string) decoded string
string) 解码字符串
vim.uri_encode({str}, {rfc})
vim.uri_encode({str}{rfc}
vim.uri_encode()  vim.uri_encode()
URI-encodes a string using percent escapes.
URI 使用百分号转义符对字符串进行编码。
Parameters:  参数:
{str} (string) string to encode
{str}string) 字符串进行编码
{rfc} ("rfc2396"|"rfc2732"|"rfc3986"?)
{RFC}"rfc2396"|"rfc2732"|"rfc3986"?
Return:  返回:
(string) encoded string
string) 编码的字符串
vim.uri_from_bufnr({bufnr})
vim.uri_from_bufnr({bufnr}
vim.uri_from_bufnr()  vim.uri_from_bufnr()
Gets a URI from a bufnr.
从 bufnr 获取 URI。
Parameters:  参数:
{bufnr} (integer)
{bufnr}整数
Return:  返回:
(string) URI   字符串)URI
vim.uri_from_fname({path})
vim.uri_from_fname({path}
vim.uri_from_fname()  vim.uri_from_fname()
Gets a URI from a file path.
从文件路径获取 URI。
Parameters:  参数:
{path} (string) Path to file
{path}string) 文件路径
Return:  返回:
(string) URI   字符串)URI
vim.uri_to_bufnr({uri})
vim.uri_to_bufnr({uri}
vim.uri_to_bufnr()  vim.uri_to_bufnr()
Gets the buffer for a uri. Creates a new unloaded buffer if no buffer for the uri already exists.
获取 URI 的缓冲区。如果没有 的缓冲区,则创建新的卸载缓冲区 URI 已存在。
Parameters:  参数:
{uri} (string)
{uri}字符串
Return:  返回:
(integer) bufnr   整数) bufnr
vim.uri_to_fname({uri})
vim.uri_to_fname({uri}
vim.uri_to_fname()  vim.uri_to_fname()
Gets a filename from a URI.
从 URI 获取文件名。
Parameters:  参数:
{uri} (string)
{uri}字符串
Return:  返回:
(string) filename or unchanged URI for non-file URIs
string) 文件名或非文件 URI 的未更改 URI

Lua module: vim.ui  Lua 模块:vim.ui vim.ui

vim.ui.input({opts}, {on_confirm})
vim.ui.input({opts}{on_confirm}
vim.ui.input()  vim.ui.input()
Prompts the user for input, allowing arbitrary (potentially asynchronous) work until on_confirm.
提示用户输入,允许任意(可能是异步的) 工作到 on_confirm
Example:  例:
vim.ui.input({ prompt = 'Enter value for shiftwidth: ' }, function(input)
    vim.o.shiftwidth = tonumber(input)
end)
Parameters:  参数:
{opts} (table?) Additional options. See input()
{opts}表格?其他选项。请参阅 input()
prompt (string|nil) Text of the prompt
prompt (string|nil) 提示的文本
default (string|nil) Default reply to the input
default (string|nil) 对输入的默认回复
completion (string|nil) Specifies type of completion supported for input. Supported types are the same that can be supplied to a user-defined command using the "-complete=" argument. See :command-completion
completion (string|nil) 指定输入支持的完成类型。支持的类型与可以使用 “-complete=” 参数提供给用户定义命令的类型相同。参见 :command-completion
highlight (function) Function that will be used for highlighting user inputs.
highlight (function) 将用于高亮显示用户输入的函数。
{on_confirm} (function) ((input|nil) -> ()) Called once the user confirms or abort the input. input is what the user typed (it might be an empty string if nothing was entered), or nil if the user aborted the dialog.
{on_confirm}function) ((input|nil) -> ()) 在用户确认或中止输入后调用。input 是用户键入的内容(如果未输入任何内容,则可能是空字符串),如果用户中止了对话框,则为 nil
vim.ui.open({path}, {opt})
vim.ui.open({路径}{opt}
vim.ui.open()  vim.ui.open()
Opens path with the system default handler (macOS open, Windows explorer.exe, Linux xdg-open, …), or returns (but does not show) an error message on failure.
使用系统默认处理程序(macOS 打开、Windows 打开)打开路径 explorer.exe、Linux xdg-open、...) 或返回(但不显示)一个 失败时出现错误消息。
Expands "~/" and environment variables in filesystem paths.
扩展文件系统路径中的 “~/” 和环境变量。
Examples:  例子:
-- Asynchronous.
vim.ui.open("https://neovim.io/")
vim.ui.open("~/path/to/file")
-- Use the "osurl" command to handle the path or URL.
vim.ui.open("gh#neovim/neovim!29490", { cmd = { 'osurl' } })
-- Synchronous (wait until the process exits).
local cmd, err = vim.ui.open("$VIMRUNTIME")
if cmd then
  cmd:wait()
end
Parameters:  参数:
{path} (string) Path or URL to open
{path}string) 要打开的路径或 URL
{opt} ({ cmd?: string[] }?) Options
{opt}{ cmd?: string[] }?)选项
cmd string[]|nil Command used to open the path or URL.
cmd string[]|nil 用于打开路径或 URL 的命令。
Return (multiple):  返回 (多个):
(vim.SystemObj?) Command object, or nil if not found. (string?) Error message on failure, or nil on success.
vim.SystemObj?Command 对象,如果未找到,则为 nil。 (字符串?失败时出现错误消息,或成功时出现 nil。
See also:  另请参阅:
vim.ui.select({items}, {opts}, {on_choice})
vim.ui.select({items}{opts}{on_choice}
vim.ui.select()  vim.ui.select()
Prompts the user to pick from a list of items, allowing arbitrary (potentially asynchronous) work until on_choice.
提示用户从项目列表中选取,允许任意 (可能是异步的)工作到 on_choice
Example:  例:
vim.ui.select({ 'tabs', 'spaces' }, {
    prompt = 'Select tabs or spaces:',
    format_item = function(item)
        return "I'd like to choose " .. item
    end,
}, function(choice)
    if choice == 'spaces' then
        vim.o.expandtab = true
    else
        vim.o.expandtab = false
    end
end)
Parameters:  参数:
{items} (any[]) Arbitrary items
{items}any[]) 任意项
{opts} (table) Additional options
{opts}table) 其他选项
prompt (string|nil) Text of the prompt. Defaults to Select one of:
prompt (string|nil) 提示的文本。默认为 选择以下选项之一:
format_item (function item -> text) Function to format an individual item from items. Defaults to tostring.
format_item (function item -> text) 用于从项目中格式化单个项目的函数。默认为 tostring
kind (string|nil) Arbitrary hint string indicating the item shape. Plugins reimplementing vim.ui.select may wish to use this to infer the structure or semantics of items, or the context in which select() was called.
kind (string|nil) 指示项形状的任意提示字符串。重新实现 vim.ui.select 的插件可能会 希望使用它来推断 items 或调用 select() 的上下文。
{on_choice} (fun(item: T?, idx: integer?)) Called once the user made a choice. idx is the 1-based index of item within items. nil if the user aborted the dialog.
{on_choice}fun(item: T?, idx: integer?))在用户做出选择后调用。idxitem 的从 1 开始的索引 在项目内。nil 如果用户中止了对话。

Lua module: vim.filetype  Lua 模块:vim.filetype vim.filetype  vim.file类型

vim.filetype.add({filetypes})
vim.filetype.add({文件类型}
vim.filetype.add()  vim.filetype.add()
Add new filetype mappings.
添加新的文件类型映射。
Filetype mappings can be added either by extension or by filename (either the "tail" or the full file path). The full file path is checked first, followed by the file name. If a match is not found using the filename, then the filename is matched against the list of lua-patterns (sorted by priority) until a match is found. Lastly, if pattern matching does not find a filetype, then the file extension is used.
文件类型映射可以按扩展名或文件名(“tail”或完整文件路径)添加。首先检查完整的文件路径,然后检查文件名。如果使用文件名未找到匹配项,则将文件名与 lua 模式列表(按优先级排序)进行匹配,直到找到匹配项。最后,如果模式匹配找不到文件类型,则使用文件扩展名。
The filetype can be either a string (in which case it is used as the filetype directly) or a function. If a function, it takes the full path and buffer number of the file as arguments (along with captures from the matched pattern, if any) and should return a string that will be used as the buffer's filetype. Optionally, the function can return a second function value which, when called, modifies the state of the buffer. This can be used to, for example, set filetype-specific buffer variables. This function will be called by Nvim before setting the buffer's filetype.
文件类型可以是字符串(在这种情况下,它直接用作文件类型)或函数。如果是一个函数,它将文件的完整路径和缓冲区编号作为参数(以及从匹配模式中捕获的内容,如果有),并且应该返回一个字符串,该字符串将用作缓冲区的文件类型。(可选)该函数可以返回第二个函数值,该值在调用时会修改缓冲区的状态。例如,这可用于设置特定于文件类型的缓冲区变量。在设置缓冲区的文件类型之前,Nvim 将调用此函数。
Filename patterns can specify an optional priority to resolve cases when a file path matches multiple patterns. Higher priorities are matched first. When omitted, the priority defaults to 0. A pattern can contain environment variables of the form "${SOME_VAR}" that will be automatically expanded. If the environment variable is not set, the pattern won't be matched.
文件名模式可以指定可选的优先级,以解决文件路径与多个模式匹配的情况。优先级越高,优先级越高。省略时,优先级默认为 0。模式可以包含将自动扩展的 “${SOME_VAR}” 形式的环境变量。如果未设置环境变量,则不会匹配模式。
See $VIMRUNTIME/lua/vim/filetype.lua for more examples.
有关更多示例,请参见 $VIMRUNTIME/lua/vim/filetype.lua。
Example:  例:
vim.filetype.add({
  extension = {
    foo = 'fooscript',
    bar = function(path, bufnr)
      if some_condition() then
        return 'barscript', function(bufnr)
          -- Set a buffer variable
          vim.b[bufnr].barscript_version = 2
        end
      end
      return 'bar'
    end,
  },
  filename = {
    ['.foorc'] = 'toml',
    ['/etc/foo/config'] = 'toml',
  },
  pattern = {
    ['.*/etc/foo/.*'] = 'fooscript',
    -- Using an optional priority
    ['.*/etc/foo/.*%.conf'] = { 'dosini', { priority = 10 } },
    -- A pattern containing an environment variable
    ['${XDG_CONFIG_HOME}/foo/git'] = 'git',
    ['.*README.(%a+)'] = function(path, bufnr, ext)
      if ext == 'md' then
        return 'markdown'
      elseif ext == 'rst' then
        return 'rst'
      end
    end,
  },
})
To add a fallback match on contents, use
要在内容上添加回退匹配,请使用
vim.filetype.add {
  pattern = {
    ['.*'] = {
      function(path, bufnr)
        local content = vim.api.nvim_buf_get_lines(bufnr, 0, 1, false)[1] or ''
        if vim.regex([[^#!.*\\<mine\\>]]):match_str(content) ~= nil then
          return 'mine'
        elseif vim.regex([[\\<drawing\\>]]):match_str(content) ~= nil then
          return 'drawing'
        end
      end,
      { priority = -math.huge },
    },
  },
}
Parameters:  参数:
{filetypes} (table) A table containing new filetype maps (see example).
{filetypes}table) 包含新文件类型映射的表(参见示例)。
{pattern} (vim.filetype.mapping)
{pattern}vim.filetype.mapping
{extension} (vim.filetype.mapping)
{extension}vim.filetype.mapping
{filename} (vim.filetype.mapping)
{filename}vim.filetype.mapping
vim.filetype.get_option()
vim.filetype.get_option()

vim.filetype.get_option({filetype}, {option}) Get the default option value for a {filetype}.
vim.filetype.get_option({filetype}{option}) 获取 {filetype} 的默认选项值。
The returned value is what would be set in a new buffer after 'filetype' is set, meaning it should respect all FileType autocmds and ftplugin files.
返回的值是在设置 'filetype' 后在新缓冲区中设置的值,这意味着它应该尊重所有 FileType autocmd 和 ftplugin 文件。
Example:  例:
vim.filetype.get_option('vim', 'commentstring')
Note: this uses nvim_get_option_value() but caches the result. This means ftplugin and FileType autocommands are only triggered once and may not reflect later changes.
注意:这会使用 nvim_get_option_value() 但会缓存结果。这意味着 ftpluginFileType 自动命令只触发一次,可能不会反映以后的更改。
Attributes:  属性:
Since: 0.9.0   从:0.9.0 开始
Parameters:  参数:
{filetype} (string) Filetype
{filetype}string) 文件类型
{option} (string) Option name
{option}string) 选项名称
Return:  返回:
(string|boolean|integer) Option value
字符串|布尔值|整数)选项值
vim.filetype.match({args})
vim.filetype.match({args}
vim.filetype.match()  vim.filetype.match()
Perform filetype detection.
执行文件类型检测。
The filetype can be detected using one of three methods: 1. Using an existing buffer 2. Using only a file name 3. Using only file contents
可以使用以下三种方法之一来检测文件类型: 1. 使用现有缓冲区 2.仅使用文件名 3.仅使用文件内容
Of these, option 1 provides the most accurate result as it uses both the buffer's filename and (optionally) the buffer contents. Options 2 and 3 can be used without an existing buffer, but may not always provide a match in cases where the filename (or contents) cannot unambiguously determine the filetype.
其中,选项 1 提供了最准确的结果,因为它同时使用缓冲区的文件名和(可选)缓冲区内容。选项 2 和 3 可以在没有现有缓冲区的情况下使用,但在文件名(或内容)无法明确确定文件类型的情况下,可能并不总是提供匹配项。
Each of the three options is specified using a key to the single argument of this function. Example:
这三个选项中的每一个都是使用单个参数的键指定的 此功能。例:
-- Using a buffer number
vim.filetype.match({ buf = 42 })
-- Override the filename of the given buffer
vim.filetype.match({ buf = 42, filename = 'foo.c' })
-- Using a filename without a buffer
vim.filetype.match({ filename = 'main.lua' })
-- Using file contents
vim.filetype.match({ contents = {'#!/usr/bin/env bash'} })
Parameters:  参数:
{args} (table) Table specifying which matching strategy to use. Accepted keys are:
{args}table) 指定要使用的匹配策略的表。接受的密钥包括:
{buf} (integer) Buffer number to use for matching. Mutually exclusive with {contents}
{buf}integer) 用于匹配的缓冲区编号。与 {contents} 互斥
{filename} (string) Filename to use for matching. When {buf} is given, defaults to the filename of the given buffer number. The file need not actually exist in the filesystem. When used without {buf} only the name of the file is used for filetype matching. This may result in failure to detect the filetype in cases where the filename alone is not enough to disambiguate the filetype.
{filename}string) 用于匹配的文件名。什么时候 {buf} 时,默认为给定缓冲区编号的文件名。该文件实际上不需要存在于文件系统中。在没有 {buf} 的情况下使用时,仅使用文件名进行文件类型匹配。这可能会导致在仅凭文件名不足以消除文件类型歧义的情况下无法检测到文件类型。
{contents} (string[]) An array of lines representing file contents to use for matching. Can be used with {filename}. Mutually exclusive with {buf}.
{contents}string[]) 表示用于匹配的文件内容的行数组。可以与 {filename} 一起使用。与 {buf} 互斥。
Return (multiple):  返回 (多个):
(string?) If a match was found, the matched filetype. (function?) A function that modifies buffer state when called (for example, to set some filetype specific buffer variables). The function accepts a buffer number as its only argument.
字符串?如果找到匹配项,则为匹配的文件类型。 (功能?一个函数,在调用时修改缓冲区状态(对于 example,设置一些特定于文件类型的缓冲区变量)。函数 接受缓冲区编号作为其唯一参数。

Lua module: vim.keymap  Lua 模块:vim.keymap vim.keymap

vim.keymap.del({modes}, {lhs}, {opts})
vim.keymap.del({modes}{lhs}{opts}
vim.keymap.del()  vim.keymap.del()
Remove an existing mapping. Examples:
删除现有映射。例子:
vim.keymap.del('n', 'lhs')
vim.keymap.del({'n', 'i', 'v'}, '<leader>w', { buffer = 5 })
Parameters:  参数:
{modes} (string|string[])
{modes}字符串|string[]
{lhs} (string)
{lhs}字符串
{opts} (table?) A table with the following fields:
{opts}表格?包含以下字段的表:
{buffer} (integer|boolean) Remove a mapping from the given buffer. When 0 or true, use the current buffer.
{buffer}integer|boolean) 从给定的缓冲区中删除映射。当 0true 时,使用当前缓冲区。
See also:  另请参阅:
vim.keymap.set({mode}, {lhs}, {rhs}, {opts})
vim.keymap.set({mode}{lhs}{rhs}{opts}
vim.keymap.set()  vim.keymap.set()
Defines a mapping of keycodes to a function or keycodes.
定义键码到函数或键码的映射
Examples:  例子:
-- Map "x" to a Lua function:
vim.keymap.set('n', 'x', function() print("real lua function") end)
-- Map "<leader>x" to multiple modes for the current buffer:
vim.keymap.set({'n', 'v'}, '<leader>x', vim.lsp.buf.references, { buffer = true })
-- Map <Tab> to an expression (|:map-<expr>|):
vim.keymap.set('i', '<Tab>', function()
  return vim.fn.pumvisible() == 1 and "<C-n>" or "<Tab>"
end, { expr = true })
-- Map "[%%" to a <Plug> mapping:
vim.keymap.set('n', '[%%', '<Plug>(MatchitNormalMultiBackward)')
Parameters:  参数:
{mode} (string|string[]) Mode "short-name" (see nvim_set_keymap()), or a list thereof.
{mode}string|string[]) 模式 “short-name” (参见 nvim_set_keymap()) 或其列表。
{lhs} (string) Left-hand side {lhs} of the mapping.
{lhs}string) 映射的左侧 {lhs}
{rhs} (string|function) Right-hand side {rhs} of the mapping, can be a Lua function.
{rhs}string|function) 映射的右侧 {rhs} 可以是 Lua 函数。
{opts} (table?) Table of :map-arguments. Same as nvim_set_keymap() {opts}, except:
{opts}表格?:map-arguments 的表。等同 nvim_set_keymap(){opts},除了:
{replace_keycodes} defaults to true if "expr" is true.
如果 “expr” 为 true则 {replace_keycodes} 默认为 true
Also accepts:   也接受:
{buffer} (integer|boolean) Creates buffer-local mapping, 0 or true for current buffer.
{buffer}integer|boolean) 创建缓冲区本地映射, 0true 表示当前缓冲区。
{remap} (boolean, default: false) Make the mapping recursive. Inverse of {noremap}.
{remap}boolean, default: false) 使映射递归。{noremap} 的逆值。

Lua module: vim.fs  Lua 模块:vim.fs vim.fs  vim.fs 文件

vim.fs.exists()  vim.fs.exists()
Use uv.fs_stat() to check a file's type, and whether it exists.
使用 uv.fs_stat() 检查文件类型以及它是否存在。
Example:  例:
if vim.uv.fs_stat(file) then
  vim.print("file exists")
end
vim.fs.abspath({path})
vim.fs.abspath({路径}
vim.fs.abspath()  vim.fs.abspath()
Convert path to an absolute path. A tilde (~) character at the beginning of the path is expanded to the user's home directory. Does not check if the path exists, normalize the path, resolve symlinks or hardlinks (including . and ..), or expand environment variables. If the path is already absolute, it is returned unchanged. Also converts \ path separators to /.
将 path 转换为绝对路径。开头的波形符 (~) 的路径将扩展到用户的主目录。不检查 路径存在,规范化路径,解析符号链接或硬链接 (包括 ...),或展开环境变量。如果路径为 already absolute,则返回原封不动。还将 \ path separators 设置为 /
Parameters:  参数:
{path} (string) Path
{path}string) 路径
Return:  返回:
(string) Absolute path
字符串)绝对路径
vim.fs.basename({file})
vim.fs.basename({文件}
vim.fs.basename()  vim.fs.basename()
Return the basename of the given path
返回给定路径的 basename
Attributes:  属性:
Since: 0.8.0   从:0.8.0 开始
Parameters:  参数:
{file} (string?) Path
{file}字符串?路径
Return:  返回:
(string?) Basename of {file}
字符串?{file} 的基名称
vim.fs.dir({path}, {opts})
vim.fs.dir({路径}{opts}
vim.fs.dir()  vim.fs.dir()
Return an iterator over the items located in {path}
返回位于 {path} 中的项目的迭代器
Attributes:  属性:
Since: 0.8.0   从:0.8.0 开始
Parameters:  参数:
{path} (string) An absolute or relative path to the directory to iterate over. The path is first normalized vim.fs.normalize().
{path}string) 要目录的绝对或相对路径 遍历。首先对路径进行规范化 vim.fs.normalize()
{opts} (table?) Optional keyword arguments:
{opts}表格?可选关键字参数:
depth: integer|nil How deep the traverse (default 1)
depth: integer|nil 遍历的深度(默认为 1)
skip: (fun(dir_name: string): boolean)|nil Predicate to control traversal. Return false to stop searching the current directory. Only useful when depth > 1
skip: (fun(dir_name: string): boolean)|nil 谓词来控制遍历。返回 false 以停止搜索当前目录。仅在深度 > 1 时有用
follow: boolean|nil Follow symbolic links. (default: true)
follow: boolean|nil 关注符号链接。(默认值:true)
Return:  返回:
(Iterator) over items in {path}. Each iteration yields two values: "name" and "type". "name" is the basename of the item relative to {path}. "type" is one of the following: "file", "directory", "link", "fifo", "socket", "char", "block", "unknown".
Iterator) 对 {path} 中的项进行迭代。每次迭代都会产生两个值: “name” 和 “type” 来获取。“name” 是项相对于 的 basename {path} 的“type” 是以下之一: “file”, “directory”, “link”, “fifo”, “socket”, “char”, “block”, “unknown”。
vim.fs.dirname({file})
vim.fs.dirname({文件}
vim.fs.dirname()  vim.fs.dirname()
Return the parent directory of the given path
返回给定路径的父目录
Attributes:  属性:
Since: 0.8.0   从:0.8.0 开始
Parameters:  参数:
{file} (string?) Path
{file}字符串?路径
Return:  返回:
(string?) Parent directory of {file}
字符串?{file} 的父目录
vim.fs.find({names}, {opts})
vim.fs.find({names}{opts}
vim.fs.find()  vim.fs.find()
Find files or directories (or other items as specified by opts.type) in the given path.
给定的路径。
Finds items given in {names} starting from {path}. If {upward} is "true" then the search traverses upward through parent directories; otherwise, the search traverses downward. Note that downward searches are recursive and may search through many directories! If {stop} is non-nil, then the search stops when the directory given in {stop} is reached. The search terminates when {limit} (default 1) matches are found. You can set {type} to "file", "directory", "link", "socket", "char", "block", or "fifo" to narrow the search to find only that type.
查找 {names} 中从 {path} 开始的项。如果 {upward} 为 “true”,则搜索将向上遍历父目录;否则,搜索将向下遍历。请注意,向下搜索是递归的,可能会搜索许多目录!如果 {stop} 为非 nil,则当到达 {stop} 中给定的目录时,搜索将停止。当找到 {limit}(默认值为 1)匹配项时,搜索将终止。你可以将 {type} 设置为 “file”、“directory”、“link”、“socket”、“char”、“block” 或 “fifo” 来缩小搜索范围,只找到该类型。
Examples:  例子:
-- list all test directories under the runtime directory
local test_dirs = vim.fs.find(
  {'test', 'tst', 'testdir'},
  {limit = math.huge, type = 'directory', path = './runtime/'}
)
-- get all files ending with .cpp or .hpp inside lib/
local cpp_hpp = vim.fs.find(function(name, path)
  return name:match('.*%.[ch]pp$') and path:match('[/\\]lib$')
end, {limit = math.huge, type = 'file'})
Attributes:  属性:
Since: 0.8.0   从:0.8.0 开始
Parameters:  参数:
{names} (string|string[]|fun(name: string, path: string): boolean) Names of the items to find. Must be base names, paths and globs are not supported when {names} is a string or a table. If {names} is a function, it is called for each traversed item with args:
{names}string|string[]|fun(name: string, path: string): boolean ) 要查找的项目的名称。必须是基名称,当 {names} 是字符串或表时,不支持 paths 和 globs。如果 {names} 是一个函数,则使用 args 为每个遍历的项目调用它:
name: base name of the current item
name:当前项目的基名称
path: full path of the current item
path:当前项的完整路径
The function should return true if the given item is considered a match.
如果给定的项为 被认为是匹配项。
{opts} (table) Optional keyword arguments:
{opts}table) 可选关键字参数:
{path} (string) Path to begin searching from. If omitted, the current-directory is used.
{path}string) 开始搜索的路径。如果省略,则使用 current-directory
{upward} (boolean, default: false) Search upward through parent directories. Otherwise, search through child directories (recursively).
{upward}boolean, default: false) 向上搜索父目录。否则,请搜索子目录 (递归) 。
{stop} (string) Stop searching when this directory is reached. The directory itself is not searched.
{stop}string) 到达此目录时停止搜索。不搜索目录本身。
{type} (string) Find only items of the given type. If omitted, all items that match {names} are included.
{type}string) 仅查找给定类型的项目。如果省略,则包括与 {names} 匹配的所有项。
{limit} (number, default: 1) Stop the search after finding this many matches. Use math.huge to place no limit on the number of matches.
{limit}number, default: 1) 找到这么多匹配项后停止搜索。使用 math.huge 对匹配项的数量没有限制。
{follow} (boolean, default: true) Follow symbolic links.
{follow}boolean, default: true) 关注符号链接。
Return:  返回:
(string[]) Normalized paths vim.fs.normalize() of all matching items
字符串[])所有匹配项的规范化路径 vim.fs.normalize() 项目
vim.fs.joinpath({...})
vim.fs.joinpath({...}
vim.fs.joinpath()  vim.fs.joinpath()
Concatenates partial paths (one absolute or relative path followed by zero or more relative paths). Slashes are normalized: redundant slashes are removed, and (on Windows) backslashes are replaced with forward-slashes.
连接部分路径(一个绝对或相对路径后跟零 或更多相对路径)。斜杠是规范化的:多余的斜杠是 removed,并且 (在 Windows 上) 反斜杠将替换为正斜杠。
Examples:   例子:
"foo/", "/bar" => "foo/bar"
“foo/”, “/bar” => “foo/bar”
Windows: "a\foo\", "\bar" => "a/foo/bar"
Windows: “a\foo\”, “\bar” => “a/foo/bar”
Attributes:  属性:
Since: 0.10.0   从:0.10.0 开始
Parameters:  参数:
{...} (string)
{...}字符串
Return:  返回:
(string)   字符串
vim.fs.normalize({path}, {opts})
vim.fs.normalize({路径}{opts}
vim.fs.normalize()  vim.fs.normalize()
Normalize a path to a standard format. A tilde (~) character at the beginning of the path is expanded to the user's home directory and environment variables are also expanded. "." and ".." components are also resolved, except when the path is relative and trying to resolve it would result in an absolute path.
将路径标准化为标准格式。波形符 (~) 位于 路径的开头将扩展到用户的主目录, 环境变量也会展开。“.” 和 “..” 组件也是 resolved,除非路径是相对的,并且尝试解析它会 结果为绝对路径。
"." as the only part in a relative path:
“.” 作为相对路径中的唯一部分:
"." => "."   “.” => “.”
"././" => "."   “././” => “.”
".." when it leads outside the current directory
“..” 当它指向当前目录之外时
"foo/../../bar" => "../bar"
“foo/../../bar“ => ”../bar”
"../../foo" => "../../foo"
"../../foo“ => ”../../foo”
".." in the root directory returns the root directory.
根目录中的 “..” 返回根目录。
"/../../" => "/"   "/../../“ => ”/”
On Windows, backslash (\) characters are converted to forward slashes (/).
在 Windows 上,反斜杠 (\) 字符将转换为正斜杠 (/)。
Examples:  例子:
[[C:\Users\jdoe]]                         => "C:/Users/jdoe"
"~/src/neovim"                            => "/home/jdoe/src/neovim"
"$XDG_CONFIG_HOME/nvim/init.vim"          => "/Users/jdoe/.config/nvim/init.vim"
"~/src/nvim/api/../tui/./tui.c"           => "/home/jdoe/src/nvim/tui/tui.c"
"./foo/bar"                               => "foo/bar"
"foo/../../../bar"                        => "../../bar"
"/home/jdoe/../../../bar"                 => "/bar"
"C:foo/../../baz"                         => "C:../baz"
"C:/foo/../../baz"                        => "C:/baz"
[[\\?\UNC\server\share\foo\..\..\..\bar]] => "//?/UNC/server/share/bar"
Attributes:  属性:
Since: 0.8.0   从:0.8.0 开始
Parameters:  参数:
{path} (string) Path to normalize
{path}string) 要归一化的路径
{opts} (table?) A table with the following fields:
{opts}表格?包含以下字段的表:
{expand_env} (boolean, default: true) Expand environment variables.
{expand_env}boolean, default: true) 展开环境变量。
{win} (boolean, default: true in Windows, false otherwise) Path is a Windows path.
{win}布尔值,默认值:在 Windows 中为 true为 false 否则)Path 是 Windows 路径。
Return:  返回:
(string) Normalized path
字符串)规范化路径
vim.fs.parents({start})
vim.fs.parents({start}
vim.fs.parents()  vim.fs.parents()
Iterate over all the parents of the given path.
迭代给定路径的所有父级。
Example:  例:
local root_dir
for dir in vim.fs.parents(vim.api.nvim_buf_get_name(0)) do
  if vim.fn.isdirectory(dir .. "/.git") == 1 then
    root_dir = dir
    break
  end
end
if root_dir then
  print("Found git repository at", root_dir)
end
Attributes:  属性:
Since: 0.8.0   从:0.8.0 开始
Parameters:  参数:
{start} (string) Initial path.
{start}string) 初始路径。
Return (multiple):  返回 (多个):
(fun(_, dir: string): string?) Iterator (nil) (string?)
fun(_, dir: string): 字符串?迭 代 () (字符串?
vim.fs.relpath({base}, {target}, {opts})
vim.fs.relpath({base}{target}{opts}
vim.fs.relpath()  vim.fs.relpath()
Gets target path relative to base, or nil if base is not an ancestor.
获取相对于 base 的目标路径,如果 base 不是 祖先。
Example:  例:
vim.fs.relpath('/var', '/var/lib') -- 'lib'
vim.fs.relpath('/var', '/usr/bin') -- nil
Parameters:  参数:
{base} (string)
{base}字符串
{target} (string)
{target}字符串
{opts} (table?) Reserved for future use
{opts}表格?保留供将来使用
Return:  返回:
(string?)   字符串?
vim.fs.rm({path}, {opts})
vim.fs.rm({path}{opts}
vim.fs.rm()  vim.fs.rm()
WARNING: This feature is experimental/unstable.
警告:此功能是实验性的/不稳定的。
Remove files or directories
删除文件或目录
Parameters:  参数:
{path} (string) Path to remove
{path}string) 要删除的路径
{opts} (table?) A table with the following fields:
{opts}表格?包含以下字段的表:
{recursive} (boolean) Remove directories and their contents recursively
{recursive}boolean) 递归删除目录及其内容
{force} (boolean) Ignore nonexistent files and arguments
{force}布尔值) 忽略不存在的文件和参数
vim.fs.root({source}, {marker})
vim.fs.root({源}{标记}
vim.fs.root()  vim.fs.root()
Find the first parent directory containing a specific "marker", relative to a file path or buffer.
查找包含特定 “marker” 的第一个父目录,相对 添加到文件路径或缓冲区中。
If the buffer is unnamed (has no backing file) or has a non-empty 'buftype' then the search begins from Nvim's current-directory.
如果缓冲区未命名(没有后备文件)或具有非空 'buftype' 则从 Nvim 的当前目录开始搜索。
Example:  例:
-- Find the root of a Python project, starting from file 'main.py'
vim.fs.root(vim.fs.joinpath(vim.env.PWD, 'main.py'), {'pyproject.toml', 'setup.py' })
-- Find the root of a git repository
vim.fs.root(0, '.git')
-- Find the parent directory containing any file with a .csproj extension
vim.fs.root(0, function(name, path)
  return name:match('%.csproj$') ~= nil