Nvim 的 :help 页面,从 这里 生成,源自 这里,使用 tree-sitter-vimdoc 解析器。
:lua vim.print(package.loaded)Nvim 包含一个“标准库” lua-stdlib 用于 Lua。它补充了“编辑器标准库”(builtin-functions 和 Ex-commands)和 API,所有这些都可以在 Lua 代码中使用 (lua-vimscript vim.api)。这些“命名空间”共同构成了 Nvim 编程接口。nvim -l foo.lua [args...]
goto。ffi、lua-profile 和增强的标准库函数;这些不能被认为是可用的,在 init.lua 或插件中的 Lua 代码应在使用它们之前检查 jit 全局变量。if jit then
-- code for luajit
else
-- code for plain lua 5.1
end
-- 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()请参阅 https://luajit.org/ext_profiler.html 或 p.lua 源代码以获取详细信息。:lua vim.cmd.edit(package.searchpath('jit.p', package.path))
do 块 (lua-do) 是一个闭包——它们都以相同的方式工作。Lua 模块实际上只是一个在“路径”上发现的大型闭包(模块所在的位置:package.cpath)。nil,它向调用者发出信号表明故障不是“异常的”,必须进行处理。这种“结果或消息”模式表示为多值返回类型 any|nil,nil|string,或在 LuaLS 符号中表示为---@return any|nil # result on success, nil on failure. ---@return nil|string # nil on success, error message on failure.
assert()。local value = assert(fn())指南:在以下情况下使用“结果或消息”模式...local foo = function(a, b)
print("A: ", a)
print("B: ", b)
end调用此函数的第一种方式是foo(1, 2)
-- ==== Result ====
-- A: 1
-- B: 2这种调用函数的方式在大多数脚本语言中都很熟悉。在 Lua 中,任何缺失的参数都作为 nil 传递,额外的参数会被静默丢弃。示例foo(1)
-- ==== Result ====
-- A: 1
-- B: nil
"foo") 或表字面量 ({1,2,3}),则可以省略括号。后者经常用于模拟“命名参数”(“kwargs”或“关键字参数”),就像 Python 和 C# 等语言一样。示例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" }
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
foo.bar,每个目录都将搜索 lua/foo/bar.lua,然后搜索 lua/foo/bar/init.lua。如果未找到任何文件,则再次搜索这些目录以查找与 lua/foo/bar.? 匹配的共享库,其中 ? 是从 package.cpath 的初始值派生的后缀列表(例如 so 或 dll)。如果仍然找不到任何文件,Nvim 将回退到 Lua 的默认搜索机制。找到的第一个脚本将被运行,require() 将返回脚本返回的值(如果有),否则返回 true。require() 调用后,返回值将被缓存,后续的调用将返回缓存的值,而无需搜索或执行任何脚本。有关更多详细信息,请参阅 require()。foo,bar 并且 package.cpath 在启动时是 ./?.so;./?.dll,则 require('mod') 会按顺序搜索这些路径并加载找到的第一个模块(“先找到的优先”)。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
package.path 通过简单地将 /lua/?.lua 和 /lua/?/init.lua 附加到 'runtimepath' 中的每个目录来进行调整(/ 实际上是 package.config 的第一个字符)。/lua/?.lua 和 /lua/?/init.lua 附加到每个 runtimepath,而是使用现有 package.cpath 中所有唯一的包含 ? 的后缀。示例/foo/bar,/xxx;yyy/baz,/abc;? 的后缀 /?.so、/a?d/j/g.elf 和 /?.so:从第一个包含问号且在路径分隔符之前的路径组件开始的路径部分。/def/?.so 的后缀,即 /?.so 不是唯一的,因为它与 package.path 中的第一个路径的后缀相同(即 ./?.so)。这留下了 /?.so 和 /a?d/j/g.elf,按此顺序排列。/foo/bar、/xxx;yyy/baz 和 /abc。第二个包含一个分号,它是一个路径分隔符,所以它被排除在外,只留下 /foo/bar 和 /abc,按此顺序排列。/lua 路径段,留下/foo/bar/lua/?.so
/foo/bar/lua/a?d/j/g.elf
/abc/lua/?.so
/abc/lua/a?d/j/g.elf
/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
注意
let &runtimepath = &runtimepath
:lua、:luado) 或给定行 [范围] 的文件中执行 Lua 代码块。和 Lua 中一样,每个代码块都有自己的作用域(闭包),因此只有全局变量在命令调用之间共享。 lua-stdlib 模块、用户模块以及 package.path 上的任何其他内容都可用。print() 函数将它的输出重定向到 Nvim 的消息区域,参数使用“ ”(空格)而不是“\t”(制表符)分隔。{chunk} 执行 Lua 代码块 {chunk}。如果 {chunk} 以 "=" 开头,则代码块的其余部分将被评估为表达式并打印。:lua =expr 和 :=expr 等同于 :lua vim.print(expr)。:lua vim.api.nvim_command('echo "Hello, Nvim!"')
:lua print(_VERSION)
:lua =jit.version
{range} 行范围内的代码作为 Lua 代码执行。与 :source 不同,此命令始终将这些行视为 Lua 代码。print(string.format(
'unix time: %s', os.time()))
{endmarker}] {script} {endmarker} 在 Vimscript 中执行 Lua 脚本 {script}。您可以在 "<<" 后省略 [endmarker] 并使用 {script} 后面的点 "."(类似于 :append,:insert)。有关更多信息,请参阅 :let-heredoc。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
local 变量在代码块结束时将消失,但全局变量不会消失。{body} 对于缓冲区中 [range] 行范围内的每一行,执行 Lua 代码块 "function(line, linenr) {body} end",其中 line 是当前行文本(不包含 <EOL>),linenr 是当前行号。如果函数返回字符串,该字符串将成为对应缓冲区行的文本。默认 [range] 是整个文件:"1,$"。: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 script.lua
:luafile %
local chunkheader = "local _A = select(1, ...) return "
function luaeval (expstr, arg)
local chunk = assert(loadstring(chunkheader .. expstr, "luaeval"))
return chunk(arg) -- return typval
end
:echo luaeval('_A[1] + _A[2]', [40, 2])
" 42
:echo luaeval('string.match(_A, "[a-z]+")', 'XYXfoo123')
" foo
nil 值,即“空洞”)整数键 1…N 的表是列表。另请参阅 list-iterator。 lua-dictvim.type_idx 键的表可能是字典、列表或浮点数{[vim.type_idx]=vim.types.float, [vim.val_idx]=1} 被转换为浮点数 1.0。请注意,默认情况下,整数 Lua 数字被转换为 Number,非整数被转换为 Float。此变体允许整数 Float。{[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} 被转换为一个空列表。以及 {[vim.type_idx]=vim.types.array, [42]=1}:不构成从 1 到 N 的一步序列的整数键将被忽略,所有非整数键也将被忽略。: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)
luaeval 的第二个参数将从 Vimscript 转换为 Lua,因此对 Lua 容器的更改不会影响 Vimscript 中的值。返回值也总是被转换。转换时,msgpack-special-dict 将被特殊处理。v:lua 前缀调用 Lua 函数,这些函数是全局的或可以通过全局表访问。表达式call v:lua.func(arg1, arg2)等同于 Lua 代码块return func(...)其中参数被转换为 Lua 值。表达式call v:lua.somemod.func(args)等同于 Lua 代码块return somemod.func(...)此外,可以像这样访问包的函数call v:lua.require'mypack'.func(arg1, arg2)
call v:lua.require'mypack.submod'.func(arg1, arg2)
注意:只允许单引号形式,没有括号。使用 require"mypack" 或 require('mypack') 作为前缀不起作用(后者仍然有效,因为它本身的函数调用,以防 require 返回有用的值)。v:lua,例如 'tagfunc','omnifunc' 等。例如,考虑以下 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'
注意:该模块(在上面的示例中为 "mymod")必须是 Lua 全局变量,或者使用 require()(如上所示)从包中访问它。v:lua:Funcref 无法表示 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
vim 模块,它公开各种函数和子模块。它始终被加载,因此 require("vim") 是不必要的。:lua vim.print(vim)结果类似于以下内容{
_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>,
...
}要查找有关例如 "deepcopy" 函数的文档:help vim.deepcopy()请注意,以下划线开头的函数(例如 "_os_proc_children")是内部的/私有的,插件不得使用它们。vim.uv 公开用于 Nvim 使用的 libUV 库的 "luv" Lua 绑定,用于网络、文件系统和进程管理,请参阅 luvref.txt。特别是,它允许与主 Nvim luv-event-loop 交互。vim.uv 回调中直接调用 vim.api 函数(除了 api-fast)会导致错误。例如,以下操作会导致错误local timer = vim.uv.new_timer()
timer:start(1000, 0, function()
vim.api.nvim_command('echomsg "test"')
end)
local timer = vim.uv.new_timer()
timer:start(1000, 0, vim.schedule_wrap(function()
vim.api.nvim_command('echomsg "test"')
end))
-- 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');
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 监视和排队事件的最大数量,因为默认限制可能过低。要增加限制,请运行sysctl fs.inotify.max_user_watches=494462
/etc/sysctl.conf 中以使更改持久化。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)
vim.uv.new_thread)在单独的(操作系统级别)线程中执行工作。请注意,每个线程都获得它自己的单独 Lua 解释器状态,无法访问主线程中的 Lua 全局变量。编辑器状态(缓冲区、窗口等)也不能直接从线程中访问。vim.* API 的一个子集在线程中可用。这包括vim.uv,每个线程都有一个单独的事件循环。vim.mpack 和 vim.json(用于在线程之间序列化消息)require 可以使用全局 package.path 中的 Lua 包print() 和 vim.inspectvim.diff
vim.* 中的大多数实用程序函数,用于处理纯 Lua 值,例如 vim.split、vim.tbl_*、vim.list_* 等等。vim.is_thread() 从非主线程返回 true。init.vim 中autocmd TextYankPost * silent! lua vim.hl.on_yank {higroup='Visual', timeout=300}
{opts} (table?) 可选参数.user)syntax: 50,用于标准语法突出显示treesitter: 100,用于基于 treesitter 的突出显示semantic_tokens: 125,用于 LSP 语义标记突出显示diagnostics: 150,用于代码分析,例如诊断user: 200,用于用户触发的突出显示,例如 LSP 文档符号或 on_yank 自动命令{bufnr} (integer) 要应用突出显示的缓冲区编号{ns} (integer) 要添加突出显示的命名空间{higroup} (string) 用于突出显示的突出显示组{opts} (table?) 包含以下字段的表{inclusive} (boolean, default: false) 指示范围是否为端点包含{priority} (integer, default: vim.hl.priorities.user) 突出显示优先级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}
-- }
{a} (string) 要比较的第一个字符串{b} (string) 要比较的第二个字符串{opts} (table?) 可选参数{on_hunk} (fun(start_a: integer, count_a: integer, start_b: integer, count_b: integer): integer?) 针对 diff 中的每个 hunk 调用。返回一个负数来取消对任何剩余 hunk 的回调。参数start_a (integer): {a} 中 hunk 的起始行。count_a (integer): {a} 中 hunk 的大小。start_b (integer): {b} 中 hunk 的起始行。count_b (integer): {b} 中 hunk 的大小。{result_type} ('unified'|'indices', 默认: 'unified') 返回的 diff 的形式unified: 统一格式的字符串。indices: hunk 位置的数组。 注意: 如果使用 on_hunk,则会忽略此选项。{linematch} (boolean|integer) 对来自 xdiff 的结果 hunk 运行 linematch。如果为整数,则只对行数不超过此大小的 hunk 运行 linematch。需要 result_type = indices,否则会忽略。{algorithm} ('myers'|'minimal'|'patience'|'histogram', 默认: 'myers') 要使用的 diff 算法。值myers: 默认算法minimal: 花费额外时间生成尽可能小的 diffpatience: patience diff 算法histogram: histogram diff 算法{ctxlen} (integer) 上下文长度{interhunkctxlen} (integer) hunk 间上下文长度{ignore_whitespace} (boolean) 忽略空白{ignore_whitespace_change} (boolean) 忽略空白变化{ignore_whitespace_change_at_eol} (boolean) 忽略行尾的空白变化。{ignore_cr_at_eol} (boolean) 忽略行尾的回车符{ignore_blank_lines} (boolean) 忽略空行{indent_heuristic} (boolean) 对内部 diff 库使用缩进启发式方法。string|integer[][]?) 查看 {opts.result_type}。如果给出了 {opts.on_hunk},则为 nil。{str} (string)any){obj} (any)string){str}, {opts}) vim.json.decode(){str} 解码(或“解包”)为 Lua 对象。{opts} 控制,见下文)。{}(空的 Lua 表)。vim.print(vim.json.decode('{"bar":[],"foo":{},"zub":null}'))
-- { bar = {}, foo = vim.empty_dict(), zub = vim.NIL }
{str} (string) 字符串化的 JSON 数据。{opts} (table<string,any>?) 选项表,包含键any){obj} (any)string){str} (string) Base64 编码的字符串string) 解码后的字符串{str} (string) 要编码的字符串string) 编码后的字符串vim.spell.check("the quik brown fox")
-- =>
-- {
-- {'quik', 'bad', 5}
-- }
{str} (string)[string, 'bad'|'rare'|'local'|'caps', integer][]) 包含三个项目的元组列表{str} 中单词开始的位置。{...}) vim.api{...} 调用 Nvim API 函数 {func}。示例: 调用 "nvim_get_current_line()" API 函数print(tostring(vim.api.nvim_get_current_line()))vim.NIL vim.NILnil 不能用作代表字典或数组的 Lua 表的一部分,因为它被视为缺失: {"foo", nil} 与 {"foo"} 相同。{
[vim.type_idx] = vim.types.float,
[vim.val_idx] = 1.0,
}
float,array 和 dictionary 类型的键值对。vim.types.float,vim.types.array 和 vim.types.dictionary 相对应的值只遵循以下两个假设: 1. 值可以在表中同时用作键和值。考虑到 Lua 表的属性,这基本上意味着“值不是 nil”。 2. 对于 vim.types 表中的每个值 vim.types[vim.types[value]] 与 value 相同。对类型没有其他限制,不能保证与 vim.types.float,vim.types.array 和 vim.types.dictionary 相对应的值不会改变,或者 vim.types 表只会包含这三种类型的值。{} 转换为列表/数组。table){str}, {from}, {to}) vim.iconv(){str} 从编码 {from} 转换为编码 {to} 的结果。如果转换失败,则返回 nil。如果某些字符无法转换,则用 "?" 替换它们。编码名称是 iconv() 库函数可以接受的任何名称,请参阅 ":Man 3 iconv"。{str} (string) 要转换的文本{from} (string) {str} 的编码{to} (string) 目标编码string?) 如果转换成功,则为转换后的字符串,否则为 nil。false 时,大多数 API 函数都可以调用(但可能受到其他限制,例如 textlock)。{channel}, {method}, {...}) vim.rpcnotify(){event} 发送到 {channel},并立即返回。如果 {channel} 为 0,则将事件广播到所有频道。{channel} (integer){method} (string){...} (any?){channel}, {method}, {...}) vim.rpcrequest(){channel} 以调用 {method},并在收到响应之前阻塞。{channel} (integer){method} (string){...} (any?){fn} (fun())-- 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)
{str} (string){index} (integer)integer){str} (string)integer[]){str}, {index}) vim.str_utf_start(){index} 指向的代码点(字符)的起始字节之间的距离(以字节为单位)。{index} 上,得到字符的起始字节。-- 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)
{str} (string){index} (integer)integer){a} (string){b} (string)0|1|-1) 分别表示字符串相等,{a} 大于 {b} 或 {a} 小于 {b}。{options} 应为类似字典的表,其中 ext_... 选项应设置为 true 以接收相应外部元素的事件。{callback} 接收事件名称以及其他参数。请参阅 ui-popupmenu 以及以下部分,了解相应事件的事件格式。ext_messages 的行为可能会发生进一步变化和可用性改进。预计这将用于在将 'cmdheight' 设置为零(同样是实验性的)时处理消息。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)
{ns} (integer){options} (table<string, any>){callback} (fun()){ns} (integer){callback},并在大约 {interval} 毫秒(默认 200)后执行。在此期间,Nvim 仍然处理其他事件。---
-- 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
{time} (integer) 等待的毫秒数{callback} (fun(): boolean?) 可选回调。等待 {callback} 返回 true{interval} (integer?) 轮询之间等待的(近似)毫秒数boolean) (-1|-2?){callback} 在 {time} 内返回 true:true, nil{callback} 在 {time} 内从未返回 true:false, -1{callback} 在 {time} 内被打断:false, -2{callback} 出现错误,则会抛出该错误。vim.fn.remove() 会将列表对象复制到 Vimscript,而不会修改 Lua 列表。local list = { 1, 2, 3 }
vim.fn.remove(list, 0)
vim.print(list) --> "{ 1, 2, 3 }"
{func}, {...}) vim.call(){...} 调用 vim-function 或 user-function {func}。另请参阅 vim.fn。等效于vim.fn[func]({...})
{command}) 请参阅 vim.cmd()。{...}) vim.fn{...} 调用 vim-function 或 user-function {func}。要调用自动加载函数,请使用语法vim.fn['some#function']({...})
pairs(vim.fn) 仅枚举至少调用过一次的函数。vim.* Lua 表从 Lua 方便地和惯用地访问。这样,您可以轻松地从 Lua 读取和修改全局 Vimscript 变量。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
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.gnil。set number Lua:vim.o.number = trueset wildignore=*.o,*.a,__pycache__ Lua:vim.o.wildignore = '*.o,*.a,__pycache__'set wildignore=*.o,*.a,__pycache__
vim.ovim.o.wildignore = '*.o,*.a,__pycache__'
vim.optvim.opt.wildignore = { '*.o', '*.a', '__pycache__' }
vim.opt.wildignore:append { "*.pyc", "node_modules" }
vim.opt.wildignore:prepend { "new_first_value" }
vim.opt.wildignore:remove { "node_modules" }
set listchars=space:_,tab:>~
vim.ovim.o.listchars = 'space:_,tab:>~'
vim.optvim.opt.listchars = { space = '_', tab = '>~' }
echo wildignore
vim.oprint(vim.o.wildignore)
vim.optvim.print(vim.opt.wildignore:get())
vim.opt.formatoptions:append('j')
vim.opt.formatoptions = vim.opt.formatoptions + 'j'
{value} (string) 要追加的值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
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
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
string|integer|boolean?) 选项的值vim.opt.wildignore:prepend('*.o')
vim.opt.wildignore = vim.opt.wildignore ^ '*.o'
{value} (string) 要前置的值vim.opt.wildignore:remove('*.pyc')
vim.opt.wildignore = vim.opt.wildignore - '*.pyc'
{value} (string) 要删除的值{bufnr}] vim.bo{bufnr} 的缓冲区的缓冲区范围 选项。类似于 :setlocal。如果省略 {bufnr},则使用当前缓冲区。无效的 {bufnr} 或键是错误。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.FOO = 'bar'
print(vim.env.TERM)
vim.go.cmdheight = 4
print(vim.go.columns)
print(vim.go.bar) -- error: invalid key
vim.o.cmdheight = 4
print(vim.o.columns)
print(vim.o.foo) -- error: invalid key
{winid}][{bufnr}] vim.wo{winid} 的窗口和编号为 {bufnr} 的缓冲区的窗口范围 选项。如果设置 全局局部 选项或提供 {bufnr},则类似于 :setlocal,否则类似于 :set。如果省略 {winid},则使用当前窗口。无效的 {winid}、{bufnr} 或键是错误。0 的 {bufnr}(窗口中的当前缓冲区)。local winid = vim.api.nvim_get_current_win()
vim.wo[winid].number = true -- same as vim.wo.number = true
print(vim.wo.foldmarker)
print(vim.wo.quux) -- error: invalid key
vim.wo[winid][0].spell = false -- like ':setlocal nospell'
vim.cmd 可以使用命令名称索引,返回该命令的可调用函数。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')
{command} (string|table) 要执行的命令。如果为字符串,则一次执行多行 Vim 脚本。在这种情况下,它等效于 nvim_exec2(),其中 opts.output 设置为 false。因此,它与 :source 的工作方式相同。如果为表,则执行单个命令。在这种情况下,它等效于 nvim_cmd(),其中 opts 为空。{fn} (function) 当 timeout 到期时要调用的回调函数{timeout} (integer) 在调用 fn 之前等待的毫秒数table) 计时器 luv 计时器对象{name} (string) 已弃用 特性(函数、API 等)。{alternative} (string?) 建议的替代特性。{version} (string) 将删除弃用函数的版本。{plugin} (string?) 拥有弃用特性的插件名称。默认为“Nvim”。{backtrace} (boolean?) 打印堆栈跟踪。默认为 true。string?) 已弃用 消息,如果未显示消息则为 nil。string)local k = vim.keycode
vim.g.mapleader = k'<bs>'
{str} (string) 要转换的字符串。string)set omnifunc=v:lua.vim.lua_omnifunc 激活。{find_start} (1|0){msg} (string) 要向用户显示的通知内容。{opts} (table?) 可选参数。默认情况下未被使用。{msg} (string) 要向用户显示的通知内容。{opts} (table?) 可选参数。默认情况下未被使用。boolean) 如果消息已显示,则为 true,否则为 false{fn}, {ns_id}, {opts}) vim.on_key(){ns_id} 的 Lua 函数 {fn} 添加为每个输入键的监听器,没错,是每个输入键。{fn} 将在发生错误时被移除。{fn} 不会递归调用,即如果 {fn} 本身消耗输入,则不会针对那些键调用它。{fn} 不会被 nvim_buf_clear_namespace() 清理。{fn} (fun(key: string, typed: string): string??) 针对每个输入键调用的函数,在应用映射后但进行进一步处理之前调用。参数 {key} 和 {typed} 是原始键码,其中 {key} 是应用映射后的键,而 {typed} 是应用映射之前的键。如果 {key} 由非类型键或与产生先前 {key} 的相同类型键产生,则 {typed} 可能为空。如果 {fn} 返回空字符串,则 {key} 将被丢弃/忽略。当 {fn} 为 nil 时,将移除与命名空间 {ns_id} 关联的回调。{opts} (table?) 可选参数integer) 与 {fn} 关联的命名空间 ID。或者,如果 on_key() 在没有参数的情况下调用,则为所有回调的计数。vim.paste。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)
{phase} (-1|1|2|3) -1:“非流式”粘贴:调用包含所有行。如果粘贴是“流式”的,则 phase 表示流状态boolean) 如果客户端应取消粘贴,则结果为 false。local hl_normal = vim.print(vim.api.nvim_get_hl(0, { name = 'Normal' }))
{...} (any)any) 给定的参数。{fn}。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))
{fn} (function)function){s}, {encoding}, {index}, {strict_indexing}) 将 UTF-32、UTF-16 或 UTF-8 {index} 转换为字节索引。如果 {strict_indexing} 为 false,则超出范围的索引将返回字节长度,而不是抛出错误。{index} 将向上舍入到该序列的末尾。{s} (string){encoding} ("utf-8"|"utf-16"|"utf-32"){index} (integer){strict_indexing} (boolean?) 默认值:trueinteger){s}, {encoding}, {index}, {strict_indexing}) 将字节索引转换为 UTF-32、UTF-16 或 UTF-8 索引。如果未提供 {index},则使用字符串的长度。所有索引都是从零开始的。{strict_indexing} 为 false,则超出范围的索引将返回字符串长度,而不是抛出错误。无效的 UTF-8 字节和嵌入的代理都计为一个代码点。UTF-8 序列中间的 {index} 将向上舍入到该序列的末尾。{s} (string){encoding} ("utf-8"|"utf-16"|"utf-32"){index} (integer?){strict_indexing} (boolean?) 默认值:trueinteger)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', stderr = '' }
{cmd} (string[]) 要执行的命令{opts} (vim.SystemOpts?) 选项NVIM 设置为 v:servername。env 精确定义作业环境,而不是合并当前环境。true,则会打开一个通向 stdin 的管道,并且可以通过 write() 方法写入 SystemObj。如果为字符串或字符串数组,则会写入 stdin 并关闭。默认为 false。fun(err: string, data: string)。默认为 truefun(err: string, data: string)。默认为 true。\r\n 替换为 \n。{on_exit} (fun(out: vim.SystemCompleted)?) 在子进程退出时调用。当提供时,命令会异步运行。接收 SystemCompleted 对象,请参阅 SystemObj:wait() 的返回值。vim.SystemObj) 具有以下字段的对象stdin=true。传递 nil 以关闭流。{bufnr} (integer?) 默认值为当前缓冲区{row} (integer?) 要检查的行,从 0 开始。默认为当前光标的行{col} (integer?) 要检查的列,从 0 开始。默认为当前光标的列{filter} (table?) 具有键值对的表,用于过滤项{syntax} (boolean,默认值:true) 包含基于语法的突出显示组。{treesitter} (boolean,默认值:true) 包含基于 treesitter 的突出显示组。{extmarks} (boolean|"all",默认值:true) 包含 extmarks。当为 all 时,则还将包含没有 hl_group 的 extmarks。{semantic_tokens} (boolean,默认值:true) 包含语义标记突出显示。table) 具有以下键值对的表。项按“遍历顺序”排列{bufnr} (integer?) 默认值为当前缓冲区{row} (integer?) 要检查的行,从 0 开始。默认为当前光标的行{col} (integer?) 要检查的列,从 0 开始。默认为当前光标的列{filter} (table?) 具有以下字段的表{syntax} (boolean,默认值:true) 包含基于语法的突出显示组。{treesitter} (boolean,默认值:true) 包含基于 treesitter 的突出显示组。{extmarks} (boolean|"all",默认值:true) 包含 extmarks。当为 all 时,则还将包含没有 hl_group 的 extmarks。{semantic_tokens} (boolean,默认值:true) 包含语义标记突出显示。{clear} (fun()) 清理所有项目{push} (fun(item: T)) 添加项目,如果缓冲区已满,则覆盖最旧的项目。{pop} (fun(): T?) 移除并返回第一个未读项目{peek} (fun(): T?) 返回第一个未读项目,但不移除它any?)any?){item} (any)eq元方法,否则递归地比较表。所有其他类型都使用相等运算符==进行比较。{a} (any) 第一个值{b} (any) 第二个值boolean) 如果值相等,则为true,否则为false{orig}, {noref}) vim.deepcopy()noref=true 的性能要高得多,而对于重复使用表字段的表,noref=false 的性能要高得多。{orig} (table) 要复制的表{noref} (boolean?) 当为false(默认值)时,仅复制一次包含的表,所有引用都指向此单个副本。当为true 时,每个表出现都会导致一个新的副本。这也意味着循环引用会导致deepcopy()失败。table) 复制的键和(嵌套)值的表。{createfn}为nil,则默认为defaulttable()本身,因此访问嵌套键会创建嵌套表local a = vim.defaulttable()
a.b.c = 1
{createfn} (fun(key:any):any?) 为缺少的key提供值。table) 带有__index元方法的空表。{s} (string) 字符串{suffix} (string) 要匹配的后缀boolean) 如果suffix是s的后缀,则为true{s}, {sep}, {opts}) vim.gsplit()for s in vim.gsplit(':aa::b:', ':', {plain=true}) do
print(s)
end
for word, num in ('foo111bar222'):gmatch('([^0-9]*)(%d*)') do
print(('word: %s num: %s'):format(word, num))
end
{s} (string) 要分割的字符串{sep} (string) 分隔符或模式{plain} (boolean) 按字面意思使用sep(如 string.find 中)。{trimempty} (boolean) 丢弃序列开头和结尾的空段。fun():string?) 对分割组件的迭代器{f} (any) 任何对象boolean) 如果f是可调用的,则为true,否则为false{t} (table?)boolean) 如果是类似数组的表,则为true,否则为false。{t} (table?)boolean) 如果是类似列表的表,则为true,否则为false。{t} (table) 要检查的表(必须是类似列表的,不会被验证){value} (any) 要比较的值boolean) 如果t包含value,则为true{dst} (table) 将被修改和附加到的列表{src} (table) 将从中插入值的列表{start} (integer?) src 上的起始索引。默认为 1{finish} (integer?) src 上的最终索引。默认为#srctable) dst{list} (any[]) 表{start} (integer?) 切片的起始范围{finish} (integer?) 切片的结束范围any[]) 从开始到结束(含)切片的表的副本{s} (string) 要转义的字符串string) %-转义的模式字符串{size}) vim.ringbuf()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
{size} (integer){t} (table) 类似字典的表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'}
{s} (string) 要分割的字符串{sep} (string) 分隔符或模式{plain} (boolean) 按字面意思使用sep(如 string.find 中)。{trimempty} (boolean) 丢弃序列开头和结尾的空段。string[]) 分割组件列表{s} (string) 字符串{prefix} (string) 要匹配的前缀boolean) 如果prefix是s的前缀,则为truevim.tbl_contains({ 'a', { 'b', 'c' } }, function(v)
return vim.deep_equal(v, { 'b', 'c' })
end, { predicate = true })
-- true
{t} (table) 要检查的表{value} (any) 要比较的值或谓词函数引用{predicate} (boolean) value 是要检查的函数引用(默认为 false)boolean) 如果t包含value,则为true{t}) vim.tbl_count()t中非 nil 值的数量。vim.tbl_count({ a=1, b=2 }) --> 2
vim.tbl_count({ 1, 2 }) --> 2
{t} (table) 表integer) 表中非 nil 值的数量{behavior} ('error'|'keep'|'force') 决定如果在多个映射中找到一个键,该怎么办{...} (table) 两个或多个表table) 合并的表{behavior} ('error'|'keep'|'force') 决定如果在多个映射中找到一个键,该怎么办{...} (table) 两个或多个表table) 合并的表{func} (function) 函数{t} (table) 表any[]) 过滤后的值表vim.tbl_get({ key = { nested_key = true }}, 'key', 'nested_key') == true
vim.tbl_get({ key = {}}, 'key', 'nested_key') == nil
{o} (table) 要索引的表{...} (any) 可选键(0 个或多个,可变),通过这些键对表进行索引any) 由键索引的嵌套值(如果存在),否则为 nil{t} (table) 要检查的表boolean) 如果t为空,则为true{t} (table) 表any[]) 键列表{func} (fun(value: T): any) 函数{t} (table<any, T>) 表格table) 转换后的值表格{t} (table) 表any[]) 值列表{s} (string) 要修剪的字符串string) 从开头和结尾删除空白字符后的字符串vim.validate(name, value, validator[, optional][, message]) 验证参数 {name} 的值 {value} 是否满足 {validator}。如果 {optional} 给定且为 true,则 {value} 可以为 nil。如果给定 {message},则它将用作错误消息中的预期类型。示例 function vim.startswith(s, prefix)
vim.validate('s', s, 'string')
vim.validate('prefix', prefix, 'string')
...
end
vim.validate(spec) (已弃用)其中 spec 的类型为 table<string,[value:any, validator: vim.validate.Validator, optional_or_msg? : boolean|string]>) 验证参数规范。规范按字母数字顺序进行评估,直到第一个失败为止。示例 function user.new(name, age, hobbies)
vim.validate{
name={name, 'string'},
age={age, 'number'},
hobbies={hobbies, 'table'},
}
...
end
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')
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')
validator 设置为 lua-type() 返回的值可以提供最佳性能。{name} (string) 参数名称{value} (string) 参数值{validator} (vim.validate.Validator)string|string[]): 除 'callable' 之外,还可以从 lua-type() 返回的任何值:'boolean', 'callable', 'function', 'nil', 'number', 'string', 'table', 'thread', 'userdata'。fun(val:any): boolean, string?) 返回布尔值和可选字符串消息的函数。{optional} (boolean?) 参数是可选的(可以省略){message} (string?) 验证失败时的消息{modname} (string) 模块名称,或 "*" 用于查找顶级模块{opts} (table?) 查找模块的选项{rtp} (boolean, 默认值:true) 在运行时路径中搜索 modname。{paths} (string[], 默认值:{}) 搜索 modname 的额外路径{patterns} (string[], 默认值:{"/init.lua", ".lua"}) 搜索模块时使用的模式列表。模式是添加到正在搜索的 Lua 模块基本名的字符串。{all} (boolean, 默认值:false) 搜索所有匹配项。table[]) 包含以下字段的对象列表{modpath} (string) 模块的路径{modname} (string) 模块的名称{stat} (uv.fs_stat.result) 模块路径的 fs_stat。不会为 modname="*" 返回{path} (string?) 要重置的路径{str} (string) 要解码的字符串string) 解码后的字符串{str} (string) 要编码的字符串{rfc} ("rfc2396"|"rfc2732"|"rfc3986"?)string) 编码后的字符串{bufnr} (integer)string) URI{path} (string) 文件路径string) URI{uri} (string)integer) bufnr{uri} (string)string) 文件名或非文件 URI 的未更改 URIvim.ui.input({ prompt = 'Enter value for shiftwidth: ' }, function(input)
vim.o.shiftwidth = tonumber(input)
end)
{on_confirm} (function) ((input|nil) -> ()) 用户确认或中止输入后调用。input 是用户输入的内容(如果未输入任何内容,它可能为空字符串),或者如果用户中止了对话框,则为 nil。{path}, {opt}) vim.ui.open()path(macOS open、Windows explorer.exe、Linux xdg-open 等),或者返回(但不会显示)失败时的错误消息。-- Asynchronous.
vim.ui.open("https://neovim.cn/")
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
{path} (string) 要打开的路径或 URL{opt} ({ cmd?: string[] }?) 选项vim.SystemObj?) 命令对象,如果未找到,则为 nil。 (string?) 失败时的错误消息,成功时为 nil。{items}, {opts}, {on_choice}) vim.ui.select()on_choice 为止。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)
{items} (any[]) 任意项目{opts} (table) 额外的选项Select one of:items 中单个项目的函数。默认值为 tostring。vim.ui.select 的插件可能希望使用它来推断 items 的结构或语义,或者调用 select() 的上下文。{on_choice} (fun(item: T?, idx: integer?)) 用户做出选择后调用。idx 是 items 中 item 的 1 索引。如果用户中止了对话框,则为 nil。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,
},
})
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 },
},
},
}
{filetypes} (table) 包含新的文件类型映射的表格(请参阅示例)。{pattern} (vim.filetype.mapping){extension} (vim.filetype.mapping){filename} (vim.filetype.mapping)vim.filetype.get_option('vim', 'commentstring')
{filetype} (string) 文件类型{option} (string) 选项名称string|boolean|integer) 选项值-- 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'} })
{args} (table) 指定使用哪种匹配策略的表。接受的键为{buf} (integer) 用于匹配的缓冲区编号。与 {contents} 互斥{filename} (string) 用于匹配的文件名。当给出 {buf} 时,默认为给定缓冲区编号的文件名。该文件不必实际存在于文件系统中。当不使用 {buf} 时,仅使用文件的名称来进行文件类型匹配。这可能导致在文件名本身不足以区分文件类型的情况下无法检测到文件类型。{contents} (string[]) 表示用于匹配的文件内容的字符串数组。可以与 {filename} 一起使用。与 {buf} 互斥。string?) 如果找到匹配项,则为匹配的文件类型。 (function?) 当调用时修改缓冲区状态的函数(例如,设置一些特定于文件类型的缓冲区变量)。该函数接受缓冲区编号作为其唯一参数。{modes}, {lhs}, {opts}) vim.keymap.del()vim.keymap.del('n', 'lhs')
vim.keymap.del({'n', 'i', 'v'}, '<leader>w', { buffer = 5 })
{modes} (string|string[]){lhs} (string){opts} (table?) 包含以下字段的表{buffer} (integer|boolean) 从给定缓冲区中删除映射。当为 0 或 true 时,使用当前缓冲区。-- 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)')
true,则 {replace_keycodes} 默认为 true。{buffer} (integer|boolean) 创建缓冲区局部映射,0 或 true 用于当前缓冲区。{remap} (boolean, 默认值: false) 使映射递归。是 {noremap} 的反义词。{file} (string?) 路径string?) {file} 的基名{opts} (table?) 可选的关键字参数Iterator) {path} 中的项目。每次迭代都会产生两个值:“name”和“type”。“name”是相对于 {path} 的项目的基名。“type”是以下内容之一:“file”、“directory”、“link”、“fifo”、“socket”、“char”、“block”、“unknown”。{file} (string?) 路径string?) {file} 的父目录{path} 开始查找 {names} 中给出的项目。如果 {upward} 为“true”,则搜索将向上遍历父目录;否则,搜索将向下遍历。请注意,向下搜索是递归的,可能会搜索多个目录!如果 {stop} 非空,则当到达 {stop} 中给出的目录时,搜索停止。当找到 {limit}(默认 1)个匹配项时,搜索终止。可以将 {type} 设置为“file”、“directory”、“link”、“socket”、“char”、“block”或“fifo”以将搜索范围缩小到仅查找该类型。-- 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'})
{names} (string|string[]|fun(name: string, path: string): boolean) 要查找的项目的名称。必须是基名,路径和通配符在 {names} 为字符串或表时不受支持。如果 {names} 是一个函数,则会为每个遍历的项目调用它,并带有参数true。{opts} (table) 可选的关键字参数{upward} (boolean, 默认值: false) 向上搜索父目录。否则,搜索子目录(递归地)。{stop} (string) 当到达此目录时停止搜索。该目录本身不会被搜索。{type} (string) 仅查找给定类型的项目。如果省略,则包括所有与 {names} 匹配的项目。{limit} (number, 默认值: 1) 在找到此数量的匹配项后停止搜索。使用 math.huge 对匹配项数量不设限制。{...} (string)string){path}, {opts}) vim.fs.normalize()[[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"
{path} (string) 要标准化的路径{opts} (table?) 包含以下字段的表{expand_env} (boolean, 默认值: true) 扩展环境变量。{win} (boolean, 默认值: 在 Windows 中为 true,在其他系统中为 false) 路径是 Windows 路径。string) 标准化的路径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
{start} (string) 初始路径。fun(_, dir: string): string?) 迭代器 (nil) (string?){path} (string) 要删除的路径{opts} (table?) 包含以下字段的表{recursive} (boolean) 递归删除目录及其内容{force} (boolean) 忽略不存在的文件和参数-- 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
end)
{marker} (string|string[]|fun(name: string, path: string): boolean) 要搜索的标记或标记列表。如果为函数,则会为每个评估的项目调用该函数,如果 {name} 和 {path} 匹配,则应返回 true。string?) 包含给定标记之一的目录路径,如果没有找到目录,则为 nil。* 匹配路径段中的一个或多个字符? 匹配路径段中的一个字符** 匹配任意数量的路径段,包括零个{} 用于对条件进行分组(例如 *.{ts,js} 匹配 TypeScript 和 JavaScript 文件)[] 用于声明路径段中要匹配的字符范围(例如,example.[0-9] 匹配 example.0、example.1 等)[!...] 用于否定路径段中要匹配的字符范围(例如,example.[!0-9] 匹配 example.a、example.b,但不匹配 example.0){pattern} (string) 原始通配符模式vim.lpeg 中 (https://www.inf.puc-rio.br/~roberto/lpeg/)。{subject}, {init}, {...}) Pattern:match()pattern与subject字符串进行匹配。如果匹配成功,则返回匹配后第一个字符在subject中的索引,或者返回捕获的值(如果pattern捕获了任何值)。可选的数值参数init可以使匹配从subject字符串中的该位置开始。与 Lua 库中的惯例一样,负值从末尾开始计数。与典型的模式匹配函数不同,match仅在锚定模式下工作;也就是说,它尝试将模式与给定subject字符串的前缀(位于位置init处)匹配,而不是与subject的任意子字符串匹配。因此,如果我们想在字符串中的任何位置找到一个模式,我们必须要么在 Lua 中写一个循环,要么写一个在任何位置都匹配的模式。local pattern = lpeg.R('az') ^ 1 * -1
assert(pattern:match('hello') == 6)
assert(lpeg.match(pattern, 'hello') == 6)
assert(pattern:match('1 hello') == nil)
{subject} (string){init} (integer?){...} (any)any) ...{pattern}) vim.lpeg.B()patt时才匹配。模式patt必须仅匹配具有固定长度的字符串,并且不能包含捕获。与and谓词一样,此模式永远不会消耗任何输入,无论成功与否。{pattern} (vim.lpeg.Pattern|string|integer|boolean|table)vim.lpeg.Pattern){patt}) vim.lpeg.C()patt匹配的subject的子字符串。捕获的值是一个字符串。如果patt有其他捕获,则它们的返回值将在此值之后返回。local function split (s, sep)
sep = lpeg.P(sep)
local elem = lpeg.C((1 - sep) ^ 0)
local p = elem * (sep * elem) ^ 0
return lpeg.match(p, s)
end
local a, b, c = split('a,b,c', ',')
assert(a == 'a')
assert(b == 'b')
assert(c == 'c')
{patt} (vim.lpeg.Pattern|string|integer|boolean|table|function)vim.lpeg.Capture){n} (integer)vim.lpeg.Capture){name}) vim.lpeg.Cb()name生成的值(其中name可以是任何 Lua 值)。最近表示具有给定名称的最后一个完整的最外层组捕获。完整捕获意味着与捕获相对应的整个模式已匹配。最外层捕获意味着捕获不在另一个完整捕获内部。与 LPeg 不指定何时评估捕获一样,它也不指定是否重用先前由组生成的值或重新评估它们。{name} (any)vim.lpeg.Capture){...} (any)vim.lpeg.Capture){patt}, {func}) vim.lpeg.Cf()patt生成一个捕获 C1 C2 ... Cn 的列表,此捕获将生成值func(...func(func(C1, C2), C3)...,Cn),也就是说,它将使用函数func折叠(或累积或减少)来自patt的捕获。此捕获假设patt应该至少产生一个具有至少一个值(任何类型)的捕获,这将成为累加器的初始值。(如果您需要一个特定的初始值,您可以在patt前面添加一个常量捕获。)对于每个后续捕获,LPeg 使用此累加器作为第一个参数调用func,并将捕获生成的所有值作为额外参数;此调用中的第一个结果将成为累加器的新的值。累加器的最终值将成为捕获的值。local number = lpeg.R('09') ^ 1 / tonumber
local list = number * (',' * number) ^ 0
local function add(acc, newvalue) return acc + newvalue end
local sum = lpeg.Cf(list, add)
assert(sum:match('10,30,43') == 83)
{patt} (vim.lpeg.Pattern|string|integer|boolean|table|function){func} (fun(acc, newvalue))vim.lpeg.Capture){patt}, {name}) vim.lpeg.Cg()patt返回的所有值分组到单个捕获中。该组可以是匿名的(如果未给出名称)或使用给定名称命名(可以是任何非空 Lua 值)。{patt} (vim.lpeg.Pattern|string|integer|boolean|table|function){name} (string?)vim.lpeg.Capture){patt}, {fn}) vim.lpeg.Cmt()function。给定的函数将整个主题、当前位置(在匹配patt之后)以及由patt产生的任何捕获值作为参数。由function返回的第一个值定义了匹配发生的方式。如果调用返回一个数字,则匹配成功,并且返回的数字将成为新的当前位置。(假设主题和当前位置为i,则返回的数字必须在范围[i, len(s) + 1]内。)如果调用返回true,则匹配成功,但不会消耗任何输入(因此,返回 true 等同于返回i)。如果调用返回false、nil或没有值,则匹配失败。由函数返回的任何额外值将成为捕获产生的值。{patt} (vim.lpeg.Pattern|string|integer|boolean|table|function){fn} (fun(s: string, i: integer, ...: any)) (position: boolean|integer, ...: any)vim.lpeg.Capture)local I = lpeg.Cp()
local function anywhere(p) return lpeg.P({I * p * I + 1 * lpeg.V(1)}) end
local match_start, match_end = anywhere('world'):match('hello world!')
assert(match_start == 7)
assert(match_end == 12)
vim.lpeg.Capture){patt}) vim.lpeg.Cs()patt匹配的主题的子字符串,并进行替换。对于patt内部具有值的任何捕获,与捕获匹配的子字符串将被捕获值(应该是字符串)替换。最终的捕获值是所有替换后得到的字符串。local function gsub (s, patt, repl)
patt = lpeg.P(patt)
patt = lpeg.Cs((patt / repl + 1) ^ 0)
return lpeg.match(patt, s)
end
assert(gsub('Hello, xxx!', 'xxx', 'World') == 'Hello, World!')
{patt} (vim.lpeg.Pattern|string|integer|boolean|table|function)vim.lpeg.Capture){patt}) vim.lpeg.Ct()patt在此表内以连续的整数键(从 1 开始)进行的所有匿名捕获的值。此外,对于由patt创建的每个命名捕获组,该组的第一个值将使用组名称作为其键放入表中。捕获的值仅是该表。{patt} (vim.lpeg.Pattern|string|integer|boolean|table|function)vim.lpeg.Capture){tab}) vim.lpeg.locale()alnum、alpha、cntrl、digit、graph、lower、print、punct、space、upper和xdigit的字段,每个字段都包含一个相应的模式。每个模式都匹配属于其类的任何单个字符。如果调用时带有参数table,则它将在给定的表中创建这些字段,并返回该表。lpeg.locale(lpeg)
local space = lpeg.space ^ 0
local name = lpeg.C(lpeg.alpha ^ 1) * space
local sep = lpeg.S(',;') * space
local pair = lpeg.Cg(name * '=' * space * name) * sep ^ -1
local list = lpeg.Cf(lpeg.Ct('') * pair ^ 0, rawset)
local t = list:match('a=b, c = hi; next = pi')
assert(t.a == 'b')
assert(t.c == 'hi')
assert(t.next == 'pi')
local locale = lpeg.locale()
assert(type(locale.digit) == 'userdata')
{tab} (table?)vim.lpeg.Locale){pattern}, {subject}, {init}, {...}) vim.lpeg.match()pattern与subject字符串进行匹配。如果匹配成功,则返回匹配后第一个字符在subject中的索引,或者返回捕获的值(如果pattern捕获了任何值)。可选的数值参数init可以使匹配从subject字符串中的该位置开始。与 Lua 库中的惯例一样,负值从末尾开始计数。与典型的模式匹配函数不同,match仅在锚定模式下工作;也就是说,它尝试将模式与给定subject字符串的前缀(位于位置init处)匹配,而不是与subject的任意子字符串匹配。因此,如果我们想在字符串中的任何位置找到一个模式,我们必须要么在 Lua 中写一个循环,要么写一个在任何位置都匹配的模式。local pattern = lpeg.R('az') ^ 1 * -1
assert(pattern:match('hello') == 6)
assert(lpeg.match(pattern, 'hello') == 6)
assert(pattern:match('1 hello') == nil)
{pattern} (vim.lpeg.Pattern|string|integer|boolean|table|function){subject} (string){init} (integer?){...} (any)any) ...{value}) vim.lpeg.P()n,则结果是一个匹配恰好n个字符的模式。-n,则结果是一个模式,该模式仅在输入字符串的剩余字符少于n个时才成功:lpeg.P(-n)等效于-lpeg.P(n)(参见一元减运算符)。{value} (vim.lpeg.Pattern|string|integer|boolean|table|function)vim.lpeg.Pattern){...}) vim.lpeg.R()range是一个长度为 2 的字符串xy,表示所有代码介于x和y(包括两者)的代码之间的字符。例如,模式lpeg.R('09')匹配任何数字,而lpeg.R('az', 'AZ')匹配任何 ASCII 字母。local pattern = lpeg.R('az') ^ 1 * -1
assert(pattern:match('hello') == 6)
{...} (string)vim.lpeg.Pattern){string}) vim.lpeg.S()S代表集合)。例如,模式lpeg.S('+-*/')匹配任何算术运算符。请注意,如果s是一个字符(即长度为 1 的字符串),则lpeg.P(s)等效于lpeg.S(s),而lpeg.S(s)等效于lpeg.R(s..s)。还要注意,lpeg.S('')和lpeg.R()都是始终失败的模式。{string} (string)vim.lpeg.Pattern){max}) vim.lpeg.setmaxstack()400。大多数编写良好的模式只需要很少的回溯级别,因此您很少需要更改此限制;在更改它之前,您应该尝试重写您的模式以避免对额外空间的需要。但是,一些有用的模式可能会溢出。此外,对于递归语法,具有深度递归的主题可能也需要更大的限制。{max} (integer){value} (vim.lpeg.Pattern|string|integer|boolean|table|function)"pattern"?)local b = lpeg.P({'(' * ((1 - lpeg.S '()') + lpeg.V(1)) ^ 0 * ')'})
assert(b:match('((string))') == 11)
assert(b:match('(') == nil)
{v} (boolean|string|number|function|table|thread|userdata|lightuserdata)vim.lpeg.Pattern)string){string}, {defs}) vim.re.compile(){string},并返回一个等效的 LPeg 模式。给定的字符串可以定义表达式或语法。可选的{defs}表提供额外的 Lua 值供模式使用。{string} (string){defs} (table?)vim.lpeg.Pattern){subject}, {pattern}, {init}) vim.re.find(){subject}中搜索给定的{pattern}。如果找到匹配项,则返回该匹配项开始的索引和结束的索引。否则返回 nil。{init} 使搜索从主题字符串中的该位置开始。与 Lua 库中通常一样,负值从末尾开始计数。{subject} (string){pattern} (vim.lpeg.Pattern|string){init} (integer?)integer?) 匹配项开始的索引,如果未匹配则为 nil (integer?) 匹配项结束的索引,如果未匹配则为 nil{subject}, {pattern}, {replacement}) vim.re.gsub(){subject}中的所有{pattern} 替换为{replacement}。{subject} (string){pattern} (vim.lpeg.Pattern|string){replacement} (string)string){subject} (string){pattern} (vim.lpeg.Pattern|string){init} (integer?)integer|vim.lpeg.Capture?){bufnr}, {line_idx}, {start}, {end_}) 匹配缓冲区bufnr 中line_idx (基于零) 处的行。如果给定,则匹配限制在字节索引范围start 和end_ 内,否则参见regex:match_str()。如果给定,则返回的字节索引相对于start。{bufnr} (integer){line_idx} (integer){start} (integer?){end_} (integer?)integer?) 匹配开始 (字节索引),相对于start,或如果未匹配则为nil (integer?) 匹配结束 (字节索引),相对于start,或如果未匹配则为nil{str}) regex:match_str()str 与该正则表达式匹配。要精确匹配字符串,请在正则表达式周围加上 "^" 和 "$"。返回匹配项的开始和结束的字节索引,或者如果未匹配则返回nil。因为任何整数都是 "truthy",所以regex:match_str() 可以直接用作 if 语句中的条件。{str} (string)integer?) 匹配开始 (字节索引),或如果未匹配则为nil (integer?) 匹配结束 (字节索引),或如果未匹配则为nil{re}) vim.regex()re 并返回一个正则表达式对象。正则表达式默认情况下是 "magic" 且区分大小写,无论'magic' 和 'ignorecase' 是什么。它们可以用标志控制,参见/magic 和/ignorecase。{re} (string)vim.regex){path}) vim.secure.read(){path} 处的文件,如果需要信任该文件,则提示用户。用户的选择将保存在 $XDG_STATE_HOME/nvim/trust 中的信任数据库中。{path} (string) 要读取的文件的路径。string?) 如果给定文件存在且受信任,则为该文件的内容,否则为 nil。{opts} (table) 包含以下字段的表{action} ('allow'|'deny'|'remove') - 'allow' 将文件添加到信任数据库并信任它,'deny' 将文件添加到信任数据库并拒绝它,'remove' 从信任数据库中删除文件{path} (string) 要更新的文件的路径。与{bufnr} 互斥。当{action} 为 "allow" 时不可使用。{bufnr} (integer) 要更新的缓冲区编号。与{path} 互斥。boolean) 成功 如果操作成功 (string) msg 如果操作成功,则为完整路径,否则为错误消息vim.version 模块提供了用于比较版本和符合 https://semver.org 规范的范围的函数。插件和插件管理器可以使用它来检查当前系统上可用的工具和依赖项。local v = vim.version.parse(vim.fn.system({'tmux', '-V'}), {strict=false})
if vim.version.gt(v, {3, 2, 0}) then
-- ...
end
1.2.3 is 1.2.3 =1.2.3 is 1.2.3 >1.2.3 greater than 1.2.3 <1.2.3 before 1.2.3 >=1.2.3 at least 1.2.3 ~1.2.3 is >=1.2.3 <1.3.0 "reasonably close to 1.2.3" ^1.2.3 is >=1.2.3 <2.0.0 "compatible with 1.2.3" ^0.2.3 is >=0.2.3 <0.3.0 (0.x.x is special) ^0.0.1 is =0.0.1 (0.0.x is special) ^1.2 is >=1.2.0 <2.0.0 (like ^1.2.0) ~1.2 is >=1.2.0 <1.3.0 (like ~1.2.0) ^1 is >=1.0.0 <2.0.0 "compatible with 1" ~1 same "reasonably close to 1" 1.x same 1.* same 1 same * any version x same 1.2.3 - 2.3.4 is >=1.2.3 <=2.3.4 Partial right: missing pieces treated as x (2.3 => 2.3.x). 1.2.3 - 2.3 is >=1.2.3 <2.4.0 1.2.3 - 2 is >=1.2.3 <3.0.0 Partial left: missing pieces treated as 0 (1.2 => 1.2.0). 1.2 - 2.3.0 is 1.2.0 - 2.3.0
{v1}, {v2}) vim.version.cmp(){major, minor, patch} 元组,例如 {1, 0, 3})。if vim.version.cmp({1,0,3}, {0,2,1}) == 0 then
-- ...
end
local v1 = vim.version.parse('1.0.3-pre')
local v2 = vim.version.parse('0.2.1')
if vim.version.cmp(v1, v2) == 0 then
-- ...
end
{v1} (vim.Version|number[]|string) 版本对象。{v2} (vim.Version|number[]|string) 要与v1 比较的版本。integer) -1 如果v1 < v2,0 如果v1 == v2,1 如果v1 > v2。{v1} (vim.Version|number[]|string){v2} (vim.Version|number[]|string)boolean){v1} (vim.Version|number[]|string){v2} (vim.Version|number[]|string)boolean){v1} (vim.Version|number[]|string){v2} (vim.Version|number[]|string)boolean){versions} (vim.Version[])vim.Version?){v1} (vim.Version|number[]|string){v2} (vim.Version|number[]|string)boolean){v1} (vim.Version|number[]|string){v2} (vim.Version|number[]|string)boolean){version}, {opts}) vim.version.parse()vim.version 函数一起使用。例如 "1.0.1-rc1+build.2" 返回{ major = 1, minor = 0, patch = 1, prerelease = "rc1", build = "build.2" }
{version} (string) 要解析的版本字符串。{opts} (table?) 可选的关键字参数true,则不会对不符合 semver v2.0.0 的输入进行强制转换。如果false,parse() 将尝试对 "1.0"、"0-x"、"tmux 3.2a" 等输入进行强制转换,使其成为有效的版本。vim.Version?) parsed_version 版本对象,如果输入无效则为nil。{spec}) vim.version.range(){
from: Version
to: Version
has(v: string|Version)
}
:has() 检查版本是否在范围内(包含from,不包含to)。local r = vim.version.range('1.0.0 - 2.0.0')
print(r:has('1.9.9')) -- true
print(r:has('2.0.0')) -- false
print(r:has(vim.version())) -- check against current Nvim version
.to 和.from 进行比较local r = vim.version.range('1.0.0 - 2.0.0') -- >=1.0, <2.0
print(vim.version.ge({1,0,3}, r.from) and vim.version.lt({1,0,3}, r.to))
{spec} (string) 版本范围 "规范"table?) 包含以下字段的表{from} (vim.Version){to} (vim.Version)vim.iter() 的类型vim.iter(pairs(…))。vim.iter(ipairs(…))。vim.iter() 扫描表输入以确定它是一个列表还是一个字典;为了避免这种成本,可以使用迭代器包装表,例如 vim.iter(ipairs({…})),但这将阻止使用 list-iterator 操作,例如 Iter:rev())。local it = vim.iter({ 1, 2, 3, 4, 5 })
it:map(function(v)
return v * 3
end)
it:rev()
it:skip(2)
it:totable()
-- { 9, 6, 3 }
-- ipairs() is a function iterator which returns both the index (i) and the value (v)
vim.iter(ipairs({ 1, 2, 3, 4, 5 })):map(function(i, v)
if i > 2 then return v end
end):totable()
-- { 3, 4, 5 }
local it = vim.iter(vim.gsplit('1,2,3,4,5', ','))
it:map(function(s) return tonumber(s) end)
for i, d in it:enumerate() do
print(string.format("Column %d is %d", i, d))
end
-- Column 1 is 1
-- Column 2 is 2
-- Column 3 is 3
-- Column 4 is 4
-- Column 5 is 5
vim.iter({ a = 1, b = 2, c = 3, z = 26 }):any(function(k, v)
return k == 'z'
end)
-- true
local rb = vim.ringbuf(3)
rb:push("a")
rb:push("b")
vim.iter(rb):totable()
-- { "a", "b" }
{pred} (fun(...):boolean) 谓词函数。将管道中前一阶段返回的所有值作为参数,如果谓词匹配则返回 true。{pred} (fun(...):boolean) 谓词函数。将管道中前一阶段返回的所有值作为参数,如果谓词匹配则返回 true。{f} (fun(...)) 要对管道中的每个项目执行的函数。将管道中前一阶段返回的所有值作为参数。vim.iter(ipairs(t))
vim.iter(t):enumerate()
local it = vim.iter(vim.gsplit('abc', '')):enumerate()
it:next()
-- 1 'a'
it:next()
-- 2 'b'
it:next()
-- 3 'c'
Iter)local bufs = vim.iter(vim.api.nvim_list_bufs()):filter(vim.api.nvim_buf_is_loaded)
{f} (fun(...):boolean) 获取管道中前一阶段返回的所有值,如果当前迭代器元素应该被移除,则返回 false 或 nil。Iter)local it = vim.iter({ 3, 6, 9, 12 })
it:find(12)
-- 12
local it = vim.iter({ 3, 6, 9, 12 })
it:find(20)
-- nil
local it = vim.iter({ 3, 6, 9, 12 })
it:find(function(v) return v % 4 == 0 end)
-- 12
{f} (any)any)vim.iter({ 1, { 2 }, { { 3 } } }):flatten():totable()
-- { 1, 2, { 3 } }
vim.iter({1, { { a = 2 } }, { 3 } }):flatten():totable()
-- { 1, { a = 2 }, 3 }
vim.iter({ 1, { { a = 2 } }, { 3 } }):flatten(math.huge):totable()
-- error: attempt to flatten a dict-like table
Iter)-- Create a new table with only even values
vim.iter({ a = 1, b = 2, c = 3, d = 4 })
:filter(function(k, v) return v % 2 == 0 end)
:fold({}, function(acc, k, v)
acc[k] = v
return acc
end) --> { b = 2, d = 4 }
-- Get the "maximum" item of an iterable.
vim.iter({ -99, -4, 3, 42, 0, 0, 7 })
:fold({}, function(acc, v)
acc.max = math.max(v, acc.max or v)
return acc
end) --> { max = 42 }
{init} (any) 累加器的初始值。{f} (fun(acc:A, ...):A) 累加函数。any){delim} 分隔。{delim} (string) 分隔符string)local it = vim.iter(vim.gsplit('abcdefg', ''))
it:last()
-- 'g'
local it = vim.iter({ 3, 6, 9, 12, 15 })
it:last()
-- 15
any)local it = vim.iter({ 1, 2, 3, 4 }):map(function(v)
if v % 2 == 0 then
return v * 3
end
end)
it:totable()
-- { 6, 12 }
{f} (fun(...):...:any) 映射函数。将管道中前一阶段返回的所有值作为参数,并返回一个或多个新值,这些值将在管道下一阶段使用。Nil 返回值将从输出中过滤掉。Iter)local it = vim.iter(string.gmatch('1 2 3', '%d+')):map(tonumber)
it:next()
-- 1
it:next()
-- 2
it:next()
-- 3
any)n 为负数,则从 列表迭代器 的末尾偏移。local it = vim.iter({ 3, 6, 9, 12 })
it:nth(2)
-- 6
it:nth(2)
-- 12
local it2 = vim.iter({ 3, 6, 9, 12 })
it2:nth(-2)
-- 9
it2:nth(-2)
-- 3
any)local it = vim.iter({ 3, 6, 9, 12 })
it:peek()
-- 3
it:peek()
-- 3
it:next()
-- 3
any)local it = vim.iter({1, 2, 3, 4})
it:pop()
-- 4
it:pop()
-- 3
any)local it = vim.iter({ 3, 6, 9, 12 }):rev()
it:totable()
-- { 12, 9, 6, 3 }
Iter)local it = vim.iter({ 1, 2, 3, 2, 1 }):enumerate()
it:rfind(1)
-- 5 1
it:rfind(1)
-- 1 1
{f} (any)any)local it = vim.iter({1, 2, 3, 4})
it:rpeek()
-- 4
it:rpeek()
-- 4
it:pop()
-- 4
any)local it = vim.iter({ 1, 2, 3, 4, 5 }):rskip(2)
it:next()
-- 1
it:pop()
-- 3
{n} (number) 要跳过的值的数量。Iter)local it = vim.iter({ 3, 6, 9, 12 }):skip(2)
it:next()
-- 9
{n} (number) 要跳过的值的数量。Iter):skip(first - 1):rskip(len - last + 1)。{first} (number){last} (number)Iter)local it = vim.iter({ 1, 2, 3, 4 }):take(2)
it:next()
-- 1
it:next()
-- 2
it:next()
-- nil
{n} (integer)Iter)vim.iter(string.gmatch('100 20 50', '%d+')):map(tonumber):totable()
-- { 100, 20, 50 }
vim.iter({ 1, 2, 3 }):map(function(v) return v, 2 * v end):totable()
-- { { 1, 2 }, { 2, 4 }, { 3, 6 } }
vim.iter({ a = 1, b = 2, c = 3 }):filter(function(k, v) return v % 2 ~= 0 end):totable()
-- { { 'a', 1 }, { 'c', 3 } }
table){direction} (vim.snippet.Direction) 导航方向。-1 表示上一个,1 表示下一个。vim.keymap.set({ 'i', 's' }, '<Tab>', function()
if vim.snippet.active({ direction = 1 }) then
return '<Cmd>lua vim.snippet.jump(1)<CR>'
else
return '<Tab>'
end
end, { expr = true })
{filter} (vim.snippet.ActiveFilter?) 用于限制搜索的过滤器boolean){input}) vim.snippet.expand(){input} (string)<Tab> 映射到片段处于活动状态时跳转vim.keymap.set({ 'i', 's' }, '<Tab>', function()
if vim.snippet.active({ direction = 1 }) then
return '<Cmd>lua vim.snippet.jump(1)<CR>'
else
return '<Tab>'
end
end, { expr = true })
{direction} (vim.snippet.Direction) 导航方向。-1 表示上一个,1 表示下一个。{enc} (string) 要解码的字符串string?) 解码后的字符串 (string?) 错误消息(如果有){str} (string) 要编码的字符串string) 十六进制编码的字符串{file} :TOhtml{file}。如果没有给出 {file},则使用一个临时文件(由 tempname() 创建)。{winid} (integer?) 要转换的窗口(默认为当前窗口){opt} (table?) 可选参数。{title} (string|false, 默认:缓冲区名称) 在生成的 HTML 代码中设置的标题标签。{number_lines} (boolean, 默认:false) 显示行号。{font} (string[]|string, 默认:guifont) 要使用的字体。{range} (integer[], 默认:整个缓冲区) 要使用的行范围。string[])