Nvim :help
pages, generated
from source
using the tree-sitter-vimdoc parser.
Nvim :help
pages,使用 tree-sitter-vimdoc 解析器从源生成。
: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 -l foo.lua [args...]
goto
that some Lua 5.1 interpreters like LuaJIT may support.
goto
一些 Lua 5.1 解释器(如 LuaJIT)可能支持。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:ffi
、lua-profile 和增强的标准库函数;这些不能假设是可用的,init.lua 或插件中的 Lua 代码应该在使用它们之前检查 jit
全局变量:if jit then
-- code for luajit
else
-- code for plain lua 5.1
end
bit
extension, which is always available: when
built with PUC Lua, Nvim includes a fallback implementation which provides
require("bit")
.
位
扩展,它始终可用:当
Nvim 使用 PUC Lua 构建,包括一个回退实现,它提供
require(“bit”)
的-- 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:p.lua
源::lua vim.cmd.edit(package.searchpath('jit.p', package.path))
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).
一个 do
块 (lua-do) 是一个闭包——它们的工作原理都是一样的。Lua 模块实际上只是在 “path” 上发现的一个大闭包(你的模块所在的位置:package.cpath)。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.
assert()
the
"result-or-message" result:assert()
“result-or-message” 结果是惯用的:local value = assert(fn())
Guidance: use the "result-or-message" pattern for...
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:nil
传递,额外的参数将被静默丢弃。例:foo(1)
-- ==== Result ====
-- A: 1
-- B: nil
"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" }
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
, 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
.
foo.bar
,每个目录都会搜索 lua/foo/bar.lua
,然后搜索 lua/foo/bar/init.lua
。 如果未找到文件,则
将再次搜索目录以查找名称匹配的共享库
lua/foo/bar.?
,其中 ?
是从 package.cpath 的初始值派生的后缀(例如 so
或 dll
)列表。如果仍然没有找到文件,Nvim 会失败
回到 Lua 的默认搜索机制。找到的第一个脚本是 run 和
require()
返回脚本返回的值(如果有),否则为 true
。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()。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"):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
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
).
package.path
可以通过简单地附加 /lua/?来调整。lua
和
/lua/?/init.lua
到 'runtimepath' 的每个目录(/
实际上是 package.config
的第一个字符)。/lua/?.lua
and
/lua/?/init.lua
to each runtimepath, all unique ?
-containing suffixes of
the existing package.cpath are used. Example:
/lua/?。lua
和
/lua/?/init.lua
添加到每个运行时路径,都是唯一的 ?
-包含现有 package.cpath 的后缀。例:$LUA_CPATH
/ $LUA_INIT
) contains ./?.so;/def/ghi/a?d/j/g.elf;/def/?.so
.
$LUA_CPATH
/ $LUA_INIT)
包含 ./?.so;/def/ghi/a?d/j/g.elf;/def/?.so
.?
-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.
?
-包含后缀 /?。所以
,/a?d/j/g.elf
和 /?.因此
,按顺序:从包含问号和前面的路径分隔符的第一个路径组件开始的路径部分。/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.
/def/?的后缀。所以
,即 /?。so
不是唯一的,因为它与 package.path 中第一个路径的后缀相同(即 ./?.所以
)。剩下 /?.so
和 /a?d/j/g.elf
,按此顺序。/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.
/foo/bar
、/xxx;yyy/baz
和 /abc
。第二个包含分号,它是一个路径分隔符,因此它被省略,只留下 /foo/bar
和 /abc
按顺序排列。/lua
path segment is inserted
between path and suffix, leaving:
/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
/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/?.soNote:
let &runtimepath = &runtimepath
{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)
.
{chunk}
执行 Lua chunk {chunk}
。如果 {chunk}
以 “=” 开头,则 chunk 的其余部分将作为表达式计算并打印。:lua =expr
和 :=expr
等价于 :lua vim.print(expr)。
:lua vim.api.nvim_command('echo "Hello, Nvim!"')
:lua print(_VERSION)
:lua =jit.version
{range}
as Lua code. Unlike :source, this
always treats the lines as Lua code.
{range}
中的缓冲区行作为 Lua 代码执行。与 :source 不同,它总是将这些行视为 Lua 代码。print(string.format(
'unix time: %s', os.time()))
{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.
{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
variables will disappear when the block finishes.
But not globals.
局部
变量将消失。但不是 globals。{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,$".
{body}
为每个缓冲区执行 Lua 块 “function(line, linenr) {body}
end”
line in [range],其中 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
{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.
{文件}
在 {file}
中执行 Lua 脚本。
整个参数用作文件名(如 :edit),空格则不
需要被转义。或者,你可以 :source Lua 文件。: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
values, aka "holes") integer keys 1…N is
a list. See also list-iterator.
nil
值,又名“holes”)整数键 1...N 是
一个列表。另请参见 list-iterator。lua-dict lua-dict 命令vim.type_idx
key may be a dictionary, a list or floating-point
value:
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 步序列的整数键,以及所有非整数键都将被忽略。: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
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 会被特殊处理。v:lua
prefix can be used to call Lua functions
which are global or accessible from global tables. The expressionv:lua
前缀可用于调用全局或可从全局表访问的 Lua 函数。表达式call v:lua.func(arg1, arg2)
is equivalent to the Lua chunkreturn func(...)
where the args are converted to Lua values. The expressioncall v:lua.somemod.func(args)
is equivalent to the Lua chunkreturn somemod.func(...)
In addition, functions of packages can be accessed likecall 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 返回一个有用的
值)。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)
v:lua
in "func" options like 'tagfunc', 'omnifunc', etc.
For example consider the following Lua omnifunc handler: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.
v:lua
without a call is not allowed in a Vimscript expression:
Funcrefs cannot represent Lua functions. The following are errors: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
module, which exposes
various functions and sub-modules. It is always loaded, thus require("vim")
is unnecessary.
vim
模块,它暴露了各种函数和子模块。它总是被加载的,因此 require(“vim”)
是不必要的。: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:
:help vim.deepcopy()
Note that underscore-prefixed functions (e.g. "_os_proc_children") are
internal/private and must not be used by plugins.
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 交互。vim.api
functions (except api-fast) in
vim.uv
callbacks. For example, this is an error:
vim.uv
回调。例如,这是一个错误: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
watches
and queued events as the default limit can be too low. To increase the limit,
run:inotify
监视和排队事件的最大数量,因为默认限制可能太低。要提高限制,请运行:sysctl fs.inotify.max_user_watches=494462
/etc/sysctl.conf
to make the changes persistent.
/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
. 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.
vim.uv.new_thread
。每个线程都有自己单独的 Lua 解释器状态,无法访问主线程上的 Lua 全局变量。编辑器状态(缓冲区、窗口等)也不能直接从线程访问。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.mpack
和 vim.json
(用于在线程之间序列化消息)require
in threads can use Lua packages from the global package.pathrequire
在线程中可以使用来自全局 package.path 的 Lua 包
print()
and vim.inspect
print()
和 vim.inspect
vim.diff
vim.diff 中
vim.*
that work with pure Lua values, like
vim.split
, vim.tbl_*
, vim.list_*
, etc.
vim.*
中大多数使用纯 Lua 值的实用函数,例如
vim.split
、vim.tbl_*
、vim.list_*
等。vim.is_thread()
returns true from a non-main thread.
vim.is_thread()
从非主线程返回 true。{opts}
) {opts}
)vim.hl.on_yank() vim.hl.on_yank()init.vim
:init.vim
中:autocmd TextYankPost * silent! lua vim.hl.on_yank {higroup='Visual', timeout=300}
{opts}
(table?
) Optional parameters
{opts}
(表格?
可选参数syntax
: 50
, used for standard syntax highlighting
语法
:50
,用于标准语法高亮显示treesitter
: 100
, used for treesitter-based highlighting
treesitter
:100
,用于基于 treesitter 的突出显示semantic_tokens
: 125
, used for LSP semantic token highlighting
semantic_tokens
:125
,用于 LSP 语义标记突出显示diagnostics
: 150
, used for code analysis such as diagnostics
diagnostics
: 150
,用于代码分析,例如诊断user
: 200
, used for user-triggered highlights such as LSP document
symbols or on_yank
autocommands
user
:200
,用于用户触发的高亮,例如 LSP 文档符号或 on_yank
自动命令{bufnr}
, {ns}
, {higroup}
, {start}
, {finish}
, {opts}
)
Apply highlight group to range of text.
{bufnr}
, {ns}
, {higroup}
, {start}
, {finish}
, {opts}
)
将高亮组应用于文本范围。{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) 清除高亮显示之前的时间(以毫秒为单位){a}
, {b}
, {opts}
) {a}
, {b}
, {opts}
)vim.diff() vim.diff() 文件{a}
and {b}
. Any indices returned by this function,
either directly or via callback arguments, are 1-based.
{a}
和 {b}
运行 diff。此函数返回的任何索引
直接或通过 callback 参数,都是从 1 开始的。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
) 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 库使用缩进启发式方法。string|integer[][]?
) See {opts.result_type}
. nil
if
{opts.on_hunk}
is given.
字符串|整数[][]?
)参见 {opts.result_type}
。如果 nil
{opts.on_hunk}
给出。{str}
) {str}
)vim.mpack.decode() vim.mpack.decode(){str}
to a Lua object.
{str}
解码(或“解包”)为 Lua 对象。{str}
(string
)
{str}
(字符串
)any
)
(任意
){obj}
) {obj}
)vim.mpack.encode() vim.mpack.encode(){obj}
as msgpack in a Lua string.
{obj}
编码(或“打包”)为 Lua 字符串中的 msgpack。{obj}
(any
)
{obj}
(任意
)string
)
(字符串
){str}
, {opts}
) {str}
, {opts}
)vim.json.decode() vim.json.decode(){str}
to a Lua object.
{str}
解码(或“解包”)为 Lua 对象。{opts}
, see below).
{opts}
控制,见下文)。{}
(empty Lua table).
{}
(空 Lua 表)。vim.print(vim.json.decode('{"bar":[],"foo":{},"zub":null}'))
-- { bar = {}, foo = vim.empty_dict(), zub = vim.NIL }
{str}
(string
) Stringified JSON data.
{str}
(string
) 字符串化的 JSON 数据。{opts}
(table<string,any>?
) Options table with keys:
{opts}
(表<string,any>?
)包含键的选项表:any
)
(任意
){obj}
, {opts}
) {obj}
, {opts}
)vim.json.encode() vim.json.encode(){obj}
as JSON in a Lua string.
{obj}
编码(或“打包”)为 Lua 字符串中的 JSON。{obj}
(any
)
{obj}
(任意
){opts}
(table<string,any>?
) Options table with keys:
{opts}
(表<string,any>?
)包含键的选项表:string
)
(字符串
){str}
) {str}
)vim.base64.decode() vim.base64.decode(){str}
(string
) Base64 encoded string
{str}
(string
) Base64 编码字符串string
) Decoded string
字符串
)解码字符串{str}
) {str}
)vim.base64.encode() vim.base64.encode(){str}
using Base64.
{str}
进行编码。{str}
(string
) String to encode
{str}
(string
) 要编码的字符串string
) Encoded string
字符串
)编码字符串{str}
) {str}
)vim.spell.check() vim.spell.check(){str}
for spelling errors. Similar to the Vimscript function
spellbadword().
{str}
是否有拼写错误。与 Vimscript 函数类似
spellbadword() 的vim.spell.check("the quik brown fox")
-- =>
-- {
-- {'quik', 'bad', 5}
-- }
{str}
(string
)
{str}
(字符串
)[string, 'bad'|'rare'|'local'|'caps', integer][]
) List of tuples
with three items:
[string, 'bad'|'rare'|'local'|'caps', integer][]
) 元组列表
包含三项:{str}
where the word begins.
单词在 {str}
中开始的位置。{...}
) {...}
)vim.api{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.NILnil
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"}
.
nil
不能用作 Lua 的一部分
table 表示 Dictionary 或 Array,因为它被视为
missing: {“foo”, nil}
与 {“foo”}
相同。{
[vim.type_idx] = vim.types.float,
[vim.val_idx] = 1.0,
}
float
, array
and
dictionary
types.
float
、array
和
dictionary
类型。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.array
和 vim.types.dictionary
仅属于以下两个假设:1. Value 在表中既可以用作键,也可以用作 value。考虑到 Lua 表的属性,这基本上意味着 “value is not nil
”。2. 对于 vim.types
表中的每个值,vim.types[vim.types[value]]
与 value
相同。对类型没有其他限制,并且不能保证对应于 vim.types.float
、vim.types.array
和
vim.types.dictionary
不会改变,或者 vim.types
表将只包含这三种类型的值。vim.log.levels
:
vim.log.levels
中定义的值之一:{}
without this
metatable to an list/array.
{}
,而不需要这个
metatable 转换为列表/数组。table
)
(表
){str}
, {from}
, {to}
) {str}
, {from}
, {to}
)vim.iconv() vim.iconv(){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".
{str}
{from}
进行编码 {to}
。转换失败时,将返回 nil
。什么时候
有些字符无法转换,它们被替换为 “?”。这
编码名称是 iconv() 库函数可以接受的任何名称,请参阅
“:Man 3 iconv”.{str}
(string
) Text to convert
{str}
(string
) 要转换的文本{from}
(string
) Encoding of {str}
{from}
(string
) {str}
的编码
{to}
(string
) Target encoding
{to}
(string
) 目标编码string?
) Converted string if conversion succeeds, nil
otherwise.
字符串?
如果转换成功,则转换字符串,否则为 nil
。false
most API functions are callable (but may be subject
to other restrictions such as textlock).
false
时,大多数 API 函数都是可调用的(但可能会受制于
更改为其他限制,例如 Textlock)。{channel}
, {method}
, {...}
) {channel}
, {method}
, {...}
)vim.rpcnotify() vim.rpcnotify(){event}
to {channel}
via RPC and returns immediately. If {channel}
is 0, the event is broadcast to all channels.
{event}
发送到 {channel}
并立即返回。如果 {channel}
为 0,则事件将广播到所有频道。{channel}
(integer
)
{channel}
(整数
){method}
(string
)
{method}
(字符串
){...}
(any?
)
{...}
(任何?
{channel}
, {method}
, {...}
) {channel}
, {method}
, {...}
)vim.rpcrequest() vim.rpcrequest(){channel}
to invoke {method}
via RPC and blocks until
a response is received.
{channel}
发送请求,通过 RPC 调用 {method}
并阻塞,直到
收到响应。{channel}
(integer
)
{channel}
(整数
){method}
(string
)
{method}
(字符串
){...}
(any?
)
{...}
(任何?
{fn}
) {fn}
)vim.schedule() vim.schedule(){fn}
to be invoked soon by the main event-loop. Useful to avoid
textlock or other temporary restrictions.
{fn}
很快由主事件循环调用。有助于避免
textlock 或其他临时限制。{fn}
(fun()
)
{fn}
(fun()
){str}
, {index}
) {str}
, {index}
)vim.str_utf_end() vim.str_utf_end(){index}
points to.
index}
指向的 (字符) 的 intent 的-- 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
)
{str}
(字符串
){index}
(integer
)
{index}
(整数
)integer
)
(整数
){str}
) {str}
)vim.str_utf_pos() vim.str_utf_pos(){str}
(string
)
{str}
(字符串
)integer[]
)
(整数[]
){str}
, {index}
) {str}
, {index}
)vim.str_utf_start() vim.str_utf_start(){index}
points to.
index}
指向的 (字符) 的 intent 的{index}
to get the starting byte of a
character.
{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
)
{str}
(字符串
){index}
(integer
)
{index}
(整数
)integer
)
(整数
){a}
, {b}
) {a}
, {b}
)vim.stricmp() vim.stricmp(){a}
(string
)
{a}
(字符串
){b}
(string
)
{b}
(字符串
)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}
。{ns}
, {options}
, {callback}
) {ns}
, {options}
, {callback}
)vim.ui_attach() vim.ui_attach(){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菜单和以下部分,了解相应事件的事件格式。msg_show
events are executed in api-fast context;
showing the message should be scheduled.
msg_show
事件的回调在 api-fast 上下文中执行;应安排显示消息。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).
ext_messages
行为可能会进一步更改和可用性改进。当将 'cmdheight' 设为 0 时,这应该被用来处理消息(这同样是实验性的)。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
)
{ns}
(整数
){options}
(table<string, any>
)
{options}
(表<字符串, any>
){callback}
(fun()
)
{回调}
(fun()
){ns}
) {ns}
)vim.ui_detach() vim.ui_detach(){ns}
.
{ns}
中。{ns}
(integer
)
{ns}
(整数
){time}
, {callback}
, {interval}
, {fast_only}
) {时间}
, {回调}
, {间隔}
, {fast_only}
)vim.wait() vim.wait(){time}
in milliseconds until {callback}
returns true
.
{time}
(以毫秒为单位),直到 {callback}
返回 true
。{callback}
immediately and at approximately {interval}
milliseconds (default 200). Nvim still processes other events during this
time.
{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
) 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}
(整数?
轮询之间等待的 (近似) 毫秒数boolean
)
(-1|-2?
)
布尔
值)
(-1|-2?
){callback}
returns true
during the {time}
: true, nil
{callback}
在 {time}
: true 期间返回 true
,则为 nil
{callback}
never returns true
during the {time}
: false, -1
{callback}
在 {time}
期间从未返回 true
: false,则为 -1
{callback}
is interrupted during the {time}
: false, -2
{time}
期间 {callback}
被中断: false,则为 -2
{callback}
errors, the error is raised.
{callback}
错误,则会引发错误。vim.fn.remove()
on a
Lua list copies the list object to Vimscript and does NOT modify the Lua list:vim.fn.remove()
会将列表对象复制到 Vimscript,并且不会修改 Lua 列表:local list = { 1, 2, 3 }
vim.fn.remove(list, 0)
vim.print(list) --> "{ 1, 2, 3 }"
{func}
, {...}
) {func}
, {...}
)vim.call() vim.call(){func}
with arguments {...}
.
See also vim.fn.
Equivalent to:{...}
的 vim-function 或 user-function{func}
。
另请参见 vim.fn。
相当于:vim.fn[func]({...})
{...}
) {...}
)vim.fn{func}
with arguments {...}
.
To call autoload functions, use the syntax:{...}
的 vim-function 或 user-function{func}
。
要调用 autoload 函数,请使用以下语法:vim.fn['some#function']({...})
pairs(vim.fn)
only
enumerates functions that were called at least once.
pairs(vim.fn)
只枚举至少被调用过一次的函数。vim.*
Lua tables
described below. In this way you can easily read and modify global Vimscript
variables from Lua.
vim.*
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
.
nil
。nil
. Can be indexed with
an integer to access variables for a specific buffer.
nil
。可以使用
一个整数,用于访问特定缓冲区的变量。nil
. Can be indexed with
an integer to access variables for a specific window.
nil
。可以使用
一个整数,用于访问特定窗口的变量。nil
. Can be indexed with
an integer to access variables for a specific tabpage.
nil
。可以使用
一个整数,用于访问特定标签页的变量。set number
Lua: vim.o.number = true
set number
Lua: vim.o.number = true
set wildignore=*.o,*.a,__pycache__
Lua: vim.o.wildignore = '*.o,*.a,__pycache__'
set wildignore=*.o,*.a,__pycache__
Lua: vim.o.wildignore = '*.o,*.a,__pycache__'
set wildignore=*.o,*.a,__pycache__
vim.o
:vim.o
:vim.o.wildignore = '*.o,*.a,__pycache__'
vim.opt
:vim.opt
:vim.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.o
:vim.o
:vim.o.listchars = 'space:_,tab:>~'
vim.opt
:vim.opt
:vim.opt.listchars = { space = '_', tab = '>~' }
Option
object, not the value of the option,
which is accessed through vim.opt:get():
Option
对象,而不是 option 的值,可通过 vim.opt:get() 访问:echo wildignore
vim.o
:vim.o
:print(vim.o.wildignore)
vim.opt
:vim.opt
:vim.print(vim.opt.wildignore:get())
vim.opt_local
. Additionally, to replicate the behavior of :setglobal, use
vim.opt_global
.
vim.opt_local
。此外,要复制 :setglobal 的行为,请使用
vim.opt_global
。{value}
) {value}
)vim.opt:append() vim.opt:append()vim.opt.formatoptions:append('j')
vim.opt.formatoptions = vim.opt.formatoptions + 'j'
{value}
(string
) Value to append
{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
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
string|integer|boolean?
) value of option
字符串|整数|布尔值?
)期权价值{value}
) {value}
)vim.opt:prepend() vim.opt:prepend()vim.opt.wildignore:prepend('*.o')
vim.opt.wildignore = vim.opt.wildignore ^ '*.o'
{value}
(string
) Value to prepend
{value}
(string
) 要预置的值{value}
) {value}
)vim.opt:remove() vim.opt:remove()vim.opt.wildignore:remove('*.pyc')
vim.opt.wildignore = vim.opt.wildignore - '*.pyc'
{value}
(string
) Value to remove
{value}
(string
) 要删除的值{bufnr}
] vim.bo{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 是错误。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
nil
.
nil
。vim.env.FOO = 'bar'
print(vim.env.TERM)
:setglobal
. Invalid key is an error.
:setglobal
一样。无效的密钥是错误的。vim.go.cmdheight = 4
print(vim.go.columns)
print(vim.go.bar) -- error: invalid key
:set
, so buffer/window-scoped options
target the current buffer/window. Invalid key is an error.
:set
,因此 buffer/window 范围的选项
以当前缓冲区/窗口为目标。无效的密钥是错误的。vim.o.cmdheight = 4
print(vim.o.columns)
print(vim.o.foo) -- error: invalid key
{winid}
][{bufnr}
] vim.wo{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}
或密钥
是一个错误。{bufnr}
with value 0
(the current buffer in the window) is
supported.
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'
{command}
) {command}
)vim.cmd() vim.cmd()vim.cmd
can be indexed with a command name to return a
callable function to the command.
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
) 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
为空。{fn}
, {timeout}
) {fn}
, {timeout}
)vim.defer_fn() vim.defer_fn(){fn}
until {timeout}
ms passes.
{fn}
,直到 {timeout}
毫秒过去。{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 函数。{fn}
(function
) Callback to call once timeout
expires
{fn}
(function
) 超时
到期后要调用的回调{timeout}
(integer
) Number of milliseconds to wait before calling
fn
{timeout}
(integer
) 调用前要等待的毫秒数
fn
table
) timer luv timer object
表
) 计时器 LUV 计时器对象{name}
, {alternative}
, {version}
, {plugin}
, {backtrace}
)
Shows a deprecation message to the user.
{名称}
, {alternative}
, {版本}
, {plugin}
, {backtrace}
)
向用户显示弃用消息。{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。string?
) Deprecated message, or nil if no message was shown.
字符串?
已弃用的消息,如果未显示任何消息,则为 nil。string
)
(字符串
)local k = vim.keycode
vim.g.mapleader = k'<bs>'
{str}
(string
) String to be converted.
{str}
(string
) 要转换的字符串。string
)
(字符串
){find_start}
) {find_start}
)vim.lua_omnifunc() vim.lua_omnifunc():lua
command.
:lua
命令的内置补全。set omnifunc=v:lua.vim.lua_omnifunc
in a Lua buffer.
set omnifunc=v:lua.vim.lua_omnifunc
。{find_start}
(1|0
)
{find_start}
(1|0
){msg}
, {level}
, {opts}
) {msg}
, {level}
, {opts}
)vim.notify() vim.notify(){msg}
(string
) Content of the notification to show to the user.
{msg}
(string
) 要向用户显示的通知内容。{opts}
(table?
) Optional parameters. Unused by default.
{opts}
(表格?
可选参数。默认未使用。{msg}
, {level}
, {opts}
) {msg}
, {level}
, {opts}
)vim.notify_once() vim.notify_once(){msg}
(string
) Content of the notification to show to the user.
{msg}
(string
) 要向用户显示的通知内容。{opts}
(table?
) Optional parameters. Unused by default.
{opts}
(表格?
可选参数。默认未使用。boolean
) true if message was displayed, else false
布尔
值)如果显示消息,则为 true,否则为 false{fn}
, {ns_id}
, {opts}
) {fn}
, {ns_id}
, {opts}
)vim.on_key() vim.on_key(){fn}
with namespace id {ns_id}
as a listener to every,
yes every, input key.
为 {ns_id}
的 Lua 函数 {fn}
添加为每个
是的,每个,输入键。{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}
(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}
(表格?
可选参数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() 被调用时不带参数)。{lines}
, {phase}
) {行}
, {phase}
)vim.paste() vim.paste()vim.paste
.
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)
{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
指示流状态:boolean
) result false if client should cancel the paste.
boolean
) 结果 如果客户端应取消粘贴,则为 false。{...}
) {...}
)vim.print() vim.print()local hl_normal = vim.print(vim.api.nvim_get_hl(0, { name = 'Normal' }))
{...}
(any
)
{...}
(任意
)any
) given arguments.
any
) 给定的参数。{fn}
) {fn}
)vim.schedule_wrap() vim.schedule_wrap(){fn}
via vim.schedule().
{fn}
的函数。{fn}
.
{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
)
{fn}
(函数
)function
)
(功能
){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.
{s}
, {encoding}
, {index}
, {strict_indexing}
)
将 UTF-32、UTF-16 或 UTF-8 {index}
转换为字节索引。如果
{strict_indexing}
为 false,则超出范围的索引将返回
字节长度,而不是引发错误。{index}
in the middle of a UTF-16 sequence is rounded upwards to the end of that
sequence.
{index}
向上舍入到该序列的末尾。{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?
) 默认值:trueinteger
)
(整数
){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.
{s}
, {encoding}
, {index}
, {strict_indexing}
)
将字节索引转换为 UTF-32、UTF-16 或 UTF-8 索引。如果 {index}
不是
提供字符串的长度。所有索引都从零开始。{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}
向上舍入到该序列的末尾。{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?
) 默认值:trueinteger
)
(整数
){cmd}
, {opts}
, {on_exit}
) {cmd}
, {opts}
, {on_exit}
)vim.system() vim.system(){cmd}
cannot be run.
{cmd}
无法运行,则引发错误。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 = '' }
{cmd}
cannot be run.
{cmd}
无法运行,vim.system 会抛出错误。{cmd}
(string[]
) Command to execute
{cmd}
(string[]
) 要执行的命令{opts}
(vim.SystemOpts?
) Options:
{opts}
(vim.SystemOpts?
)选项:NVIM
set to v:servername.
NVIM
设置为 v:servername。env
defines the job environment
exactly, instead of merging current environment.
env
精确定义作业环境,而不是合并当前环境。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
.
为 true
,则管道
to stdin 已打开,并且可以通过
write()
方法添加到 SystemObj 中。如果 string 或 string[] 则将被写入 stdin 并关闭。默认为 false
。fun(err: string, data: string)
. Defaults to true
fun(err: string, data: string)
。默认为 true
fun(err: string, data: string)
. Defaults to true
.
fun(err: string, data: string)
。默认为 true
。\r\n
with \n
.
\r\n
替换为 \n
。{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() 的返回。vim.SystemObj
) Object with the fields:
vim.SystemObj
)Object 的字段:stdin=true
. Pass nil
to
close the stream.
stdin=true
。传递 nil
以关闭流。{bufnr}
, {row}
, {col}
, {filter}
) {bufnr}
, {row}
, {col}
, {filter}
)vim.inspect_pos() vim.inspect_pos(){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) 包括语义标记高亮。table
) a table with the following key-value pairs. Items are in
"traversal order":
table
) 一个包含以下键值对的表。项目在
“遍历顺序”:{bufnr}
, {row}
, {col}
, {filter}
) {bufnr}
, {row}
, {col}
, {filter}
)vim.show_pos() vim.show_pos()zS
in
Normal mode:zS
正常模式:vim.keymap.set('n', 'zS', vim.show_pos)
{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) 包括语义标记高亮。any?
)
(任何?
any?
)
(任何?
{item}
) {item}
)Ringbuf:push() ringbuf:push(){item}
(any
)
{item}
(任意
){a}
, {b}
) {a}
, {b}
)vim.deep_equal() vim.deep_equal()eq
metamethod. All other types are compared using the equality ==
operator.
eq
元方法。使用相等 ==
运算符比较所有其他类型。{a}
(any
) First value
{a}
(any
) 第一个值{b}
(any
) Second value
{b}
(任意
) 第二个值boolean
) true
if values are equals, else false
布尔
值)如果值等于,则为 true
,否则为 false
{orig}
, {noref}
) {orig}
, {noref}
)vim.deepcopy() vim.deepcopy()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
在重用表字段的表上性能更高。{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()
失败。table
) Table of copied keys and (nested) values.
表
)复制的键和(嵌套)值的表。{createfn}
) {createfn}
)vim.defaulttable() vim.defaulttable(){createfn}
(like
Python's "defaultdict").
{createfn}
提供(如
Python 的 “defaultdict” 的 “defaultdict” 的{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
{createfn}
(fun(key:any):any?
) Provides the value for a missing
key
.
{createfn}
(fun(key:any):any?
)提供缺失
键
。table
) Empty table with __index
metamethod.
表
)带有 __index
metamethod 的空表。{s}
, {suffix}
) {s}
, {后缀}
)vim.endswith() vim.endswith()s
ends with suffix
.
s
是否以 suffix
结尾。{s}
(string
) String
{s}
(string
) 字符串{suffix}
(string
) Suffix to match
{suffix}
(string
) 要匹配的后缀boolean
) true
if suffix
is a suffix of s
布尔
值)如果 suffix
是 s
的后缀,则为 true
{s}
, {sep}
, {opts}
) {s}
, {sep}
, {opts}
)vim.gsplit() 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
) String to split
{s}
(string
) 要拆分的字符串{sep}
(string
) Separator or pattern
{sep}
(string
) 分隔符或模式{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
) 丢弃序列开头和结尾的空段。fun():string?
) Iterator over the split components
fun():string?
)拆分组件上的 Iterator{f}
) {f}
)vim.is_callable() vim.is_callable()f
can be called as a function.
f
可以作为函数调用,则返回 true。{f}
(any
) Any object
{f}
(any
) 任何对象boolean
) true
if f
is callable, else false
布尔
值)如果 f
是可调用的,则为 true
,否则为 false
{t}
) {t}
)vim.isarray() vim.isarray()t
is an "array": a table indexed only by integers (potentially
non-contiguous).
t
是否为“数组”:仅由整数索引的表(可能
non-contiguous) 的 Package。{}
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 的{t}
(table?
)
{t}
(表格?
boolean
) true
if array-like table, else false
.
布尔
值)如果是类似数组的表,则为 true
,否则为 false
。{t}
) vim.islist({t}
)vim.islist() vim.islist()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 称为 “常规数组”)。{}
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 的{t}
(table?
)
{t}
(表格?
boolean
) true
if list-like table, else false
.
布尔
值)如果是类似列表的表,则为 true
,否则为 false
。{t}
, {value}
) {t}
, {value}
)vim.list_contains() vim.list_contains()value
.
value
。{t}
(table
) Table to check (must be list-like, not validated)
{t}
(table
) 要检查的表 (必须是类似列表的,未经验证){value}
(any
) Value to compare
{value}
(any
) 要比较的值boolean
) true
if t
contains value
布尔
值)如果 t
包含值
,则为 true
{dst}
, {src}
, {start}
, {finish}
) {dst}
, {src}
, {start}
, {finish}
)vim.list_extend() vim.list_extend(){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
table
) dst
(表
) DST{list}
, {start}
, {finish}
) {list}
, {start}
, {finish}
)vim.list_slice() vim.list_slice(){list}
(any[]
) Table
{list}
(any[]
) 表{start}
(integer?
) Start range of slice
{start}
(整数?
切片的起始范围{finish}
(integer?
) End range of slice
{finish}
(整数?
切片的结束范围any[]
) Copy of table sliced from start to finish (inclusive)
任何[]
)从头到尾(含)切片的表副本{s}
) vim.pesc({s}
)vim.pesc() vim.pesc(){s}
(string
) String to escape
{s}
(string
) 要转义的字符串string
) %-escaped pattern string
string
) % 转义的模式字符串{size}
) {大小}
)vim.ringbuf() 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
)
{size}
(整数
){t}
) vim.spairs({t}
)vim.spairs() vim.spairs(){t}
(table
) Dict-like table
{t}
(table
) 类似 Dict 的表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, V
) for-in 迭代器 over
排序的 Key 及其值
(表
){s}
, {sep}
, {opts}
) {s}
, {sep}
, {opts}
)vim.split() vim.split()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
) String to split
{s}
(string
) 要拆分的字符串{sep}
(string
) Separator or pattern
{sep}
(string
) 分隔符或模式{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
) 丢弃序列开头和结尾的空段。string[]
) List of split components
字符串[]
)拆分组件列表{s}
, {prefix}
) {s}
, {prefix}
)vim.startswith() vim.startswith()s
starts with prefix
.
s
是否以 prefix
开头。{s}
(string
) String
{s}
(string
) 字符串{prefix}
(string
) Prefix to match
{prefix}
(string
) 要匹配的前缀boolean
) true
if prefix
is a prefix of s
布尔
值)如果 prefix
是 s
的前缀,则为 true
{t}
, {value}
, {opts}
) {t}
, {value}
, {opts}
)vim.tbl_contains() vim.tbl_contains()vim.tbl_contains({ 'a', { 'b', 'c' } }, function(v)
return vim.deep_equal(v, { 'b', 'c' })
end, { predicate = true })
-- true
{t}
(table
) Table to check
{t}
(table
) 要检查的表{value}
(any
) Value to compare or predicate function reference
{value}
(any
) 要比较或谓词函数引用的值{predicate}
(boolean
) value
is a function reference to
be checked (default false)
{predicate}
(boolean
) 值
是要检查的函数引用(默认为 false)boolean
) true
if t
contains value
布尔
值)如果 t
包含值
,则为 true
{t}
) {t}
)vim.tbl_count() vim.tbl_count()t
.t
中非 nil 值的个数。vim.tbl_count({ a=1, b=2 }) --> 2
vim.tbl_count({ 1, 2 }) --> 2
{t}
(table
) Table
{t}
(table
) 表integer
) Number of non-nil values in table
整数
)表中非 nil 值的数量{behavior}
, {...}
) {行为}
, {...}
)vim.tbl_deep_extend() vim.tbl_deep_extend(){behavior}
('error'|'keep'|'force'
) Decides what to do if a key is
found in more than one map:
{behavior}
('错误'|'保持'|'force'
) 决定在多个 map 中找到一个键时该怎么做:{...}
(table
) Two or more tables
{...}
(表
)两个或多个表table
) Merged table
表
)合并表{behavior}
, {...}
) {行为}
, {...}
)vim.tbl_extend() vim.tbl_extend(){behavior}
('error'|'keep'|'force'
) Decides what to do if a key is
found in more than one map:
{behavior}
('错误'|'保持'|'force'
) 决定在多个 map 中找到一个键时该怎么做:{...}
(table
) Two or more tables
{...}
(表
)两个或多个表table
) Merged table
表
)合并表{func}
, {t}
) {func}
, {t}
)vim.tbl_filter() vim.tbl_filter(){func}
(function
) Function
{func}
(function
) 函数{t}
(table
) Table
{t}
(table
) 表any[]
) Table of filtered values
任何[]
)筛选值表{o}
, {...}
) {o}
, {...}
)vim.tbl_get() vim.tbl_get()nil
if the key does not exist.
nil
。vim.tbl_get({ key = { nested_key = true }}, 'key', 'nested_key') == true
vim.tbl_get({ key = {}}, 'key', 'nested_key') == nil
{o}
(table
) Table to index
{o}
(table
) 要索引的表{...}
(any
) Optional keys (0 or more, variadic) via which to index
the table
{...}
(任意
)用于为表编制索引的可选键(0 或更多,可变)any
) Nested value indexed by key (if it exists), else nil
任意
)按 key 索引的嵌套值(如果存在),否则为 nil{t}
) {t}
)vim.tbl_isempty() vim.tbl_isempty(){t}
(table
) Table to check
{t}
(table
) 要检查的表boolean
) true
if t
is empty
布尔
值)如果 t
为空,则为 true
{t}
) {t}
)vim.tbl_keys() vim.tbl_keys(){t}
(table
) Table
{t}
(table
) 表any[]
) List of keys
任何[]
)键列表{func}
, {t}
) {func}
, {t}
)vim.tbl_map() vim.tbl_map(){func}
(fun(value: T): any
) Function
{func}
(fun(value: T): any
) 函数{t}
(table<any, T>
) Table
{t}
(table<any, T>
) 表table
) Table of transformed values
表
)转换值表{t}
) {t}
)vim.tbl_values() vim.tbl_values(){t}
(table
) Table
{t}
(table
) 表any[]
) List of values
任何[]
)值列表{s}
) vim.trim({s}
)vim.trim() vim.trim(){s}
(string
) String to trim
{s}
(string
) 要修剪的字符串string
) String with whitespace removed from its beginning and end
字符串
)从开头和结尾删除空格的字符串{name}
, {value}
, {validator}
, {optional}
, {message}
)
Validate function arguments.
{名称}
, {值}
, {验证器}
, {可选}
, {消息}
)
验证函数参数。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: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
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: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
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
set to a value returned by lua-type() provides the best
performance.
验证器
设置为 lua-type() 返回的值可提供最佳性能。{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?
) 消息{enable}
) {启用}
)vim.loader.enable() vim.loader.enable()enable=true
):
enable=true
):enable=false
):
enable=false
):{enable}
(boolean?
) true/nil to enable, false to disable
{enable}
(boolean?
) true/nil 启用,false 禁用{modname}
, {opts}
) {modname}
, {opts}
)vim.loader.find() vim.loader.find(){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
) 搜索所有匹配项。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=“*”
返回
{path}
) {路径}
)vim.loader.reset() vim.loader.reset(){path}
(string?
) path to reset
{path}
(string?
) 路径{str}
) {str}
)vim.uri_decode() vim.uri_decode(){str}
(string
) string to decode
{str}
(string
) 要解码的字符串string
) decoded string
string
) 解码字符串{str}
, {rfc}
) {str}
, {rfc}
)vim.uri_encode() vim.uri_encode(){str}
(string
) string to encode
{str}
(string
) 字符串进行编码{rfc}
("rfc2396"|"rfc2732"|"rfc3986"?
)
{RFC}
( "rfc2396"|"rfc2732"|"rfc3986"?
)string
) encoded string
string
) 编码的字符串{bufnr}
) {bufnr}
)vim.uri_from_bufnr() vim.uri_from_bufnr(){bufnr}
(integer
)
{bufnr}
(整数
)string
) URI
(字符串
)URI{path}
) {path}
)vim.uri_from_fname() vim.uri_from_fname(){path}
(string
) Path to file
{path}
(string
) 文件路径string
) URI
(字符串
)URI{uri}
) {uri}
)vim.uri_to_bufnr() vim.uri_to_bufnr(){uri}
(string
)
{uri}
(字符串
)integer
) bufnr
(整数
) bufnr{uri}
) {uri}
)vim.uri_to_fname() vim.uri_to_fname(){uri}
(string
)
{uri}
(字符串
)string
) filename or unchanged URI for non-file URIs
string
) 文件名或非文件 URI 的未更改 URI{opts}
, {on_confirm}
) {opts}
, {on_confirm}
)vim.ui.input() vim.ui.input()on_confirm
.
on_confirm
。vim.ui.input({ prompt = 'Enter value for shiftwidth: ' }, function(input)
vim.o.shiftwidth = tonumber(input)
end)
{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
。{path}
, {opt}
) {路径}
, {opt}
)vim.ui.open() vim.ui.open()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.
打开
、Windows 打开)打开路径
explorer.exe
、Linux xdg-open
、...) 或返回(但不显示)一个
失败时出现错误消息。-- 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
{path}
(string
) Path or URL to open
{path}
(string
) 要打开的路径或 URL{opt}
({ cmd?: string[] }?
) Options
{opt}
({ cmd?: string[] }?
)选项vim.SystemObj?
) Command object, or nil if not found.
(string?
) Error message on failure, or nil on success.
vim.SystemObj?
Command 对象,如果未找到,则为 nil。
(字符串?
失败时出现错误消息,或成功时出现 nil。{items}
, {opts}
, {on_choice}
) {items}
, {opts}
, {on_choice}
)vim.ui.select() vim.ui.select()on_choice
.
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[]
) Arbitrary items
{items}
(any[]
) 任意项{opts}
(table
) Additional options
{opts}
(table
) 其他选项Select one of:
选择以下选项之一:
items
. Defaults to
tostring
.
项目中
格式化单个项目的函数。默认为
tostring
的vim.ui.select
may
wish to use this to infer the structure or semantics of
items
, or the context in which select() was called.
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?)
)在用户做出选择后调用。idx
是 item
的从 1 开始的索引
在项目
内。nil
如果用户中止了对话。{filetypes}
) {文件类型}
)vim.filetype.add() vim.filetype.add()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
) 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
){filetype}
, {option}
)
Get the default option value for a {filetype}
.
{filetype}
, {option}
)
获取 {filetype}
的默认选项值。vim.filetype.get_option('vim', 'commentstring')
{filetype}
(string
) Filetype
{filetype}
(string
) 文件类型{option}
(string
) Option name
{option}
(string
) 选项名称string|boolean|integer
) Option value
字符串|布尔值|整数
)选项值{args}
) {args}
)vim.filetype.match() vim.filetype.match()-- 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
) 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}
互斥。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,设置一些特定于文件类型的缓冲区变量)。函数
接受缓冲区编号作为其唯一参数。{modes}
, {lhs}
, {opts}
) {modes}
, {lhs}
, {opts}
)vim.keymap.del() vim.keymap.del()vim.keymap.del('n', 'lhs')
vim.keymap.del({'n', 'i', 'v'}, '<leader>w', { buffer = 5 })
{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
) 从给定的缓冲区中删除映射。当 0
或 true
时,使用当前缓冲区。{mode}
, {lhs}
, {rhs}
, {opts}
) {mode}
, {lhs}
, {rhs}
, {opts}
)vim.keymap.set() vim.keymap.set()-- 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)')
{mode}
(string|string[]
) Mode "short-name" (see
nvim_set_keymap()), or a list thereof.
{mode}
(string|string[]
) 模式 “short-name” (参见
nvim_set_keymap()) 或其列表。{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
.
true
,则 {replace_keycodes}
默认为 true
。{buffer}
(integer|boolean
) Creates buffer-local mapping,
0
or true
for current buffer.
{buffer}
(integer|boolean
) 创建缓冲区本地映射,
0
或 true
表示当前缓冲区。{remap}
(boolean
, default: false
) Make the mapping
recursive. Inverse of {noremap}
.
{remap}
(boolean
, default: false
) 使映射递归。{noremap}
的逆值。if vim.uv.fs_stat(file) then
vim.print("file exists")
end
{path}
) {路径}
)vim.fs.abspath() vim.fs.abspath().
and ..
), or expand environment variables. If the path is
already absolute, it is returned unchanged. Also converts \
path
separators to /
.
.
和 ..
),或展开环境变量。如果路径为
already absolute,则返回原封不动。还将 \
path
separators 设置为 /
。{path}
(string
) Path
{path}
(string
) 路径string
) Absolute path
字符串
)绝对路径{file}
) {文件}
)vim.fs.basename() vim.fs.basename(){file}
(string?
) Path
{file}
(字符串?
路径string?
) Basename of {file}
字符串?
{file}
的基名称
{path}
, {opts}
) {路径}
, {opts}
)vim.fs.dir() vim.fs.dir(){path}
{path}
中的项目的迭代器
{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}
(表格?
可选关键字参数: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”。{file}
) {文件}
)vim.fs.dirname() vim.fs.dirname(){file}
(string?
) Path
{file}
(字符串?
路径string?
) Parent directory of {file}
字符串?
{file}
的父目录
{names}
, {opts}
) {names}
, {opts}
)vim.fs.find() vim.fs.find()opts.type
) in
the given path.
给定的路径。{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” 来缩小搜索范围,只找到该类型。-- 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 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 为每个遍历的项目调用它: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
) 关注符号链接。string[]
) Normalized paths vim.fs.normalize() of all matching
items
字符串[]
)所有匹配项的规范化路径 vim.fs.normalize()
项目{...}
) {...}
)vim.fs.joinpath() vim.fs.joinpath(){...}
(string
)
{...}
(字符串
)string
)
(字符串
){path}
, {opts}
) {路径}
, {opts}
)vim.fs.normalize() 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
) 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 路径。string
) Normalized path
字符串
)规范化路径{start}
) {start}
)vim.fs.parents() vim.fs.parents()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
) Initial path.
{start}
(string
) 初始路径。fun(_, dir: string): string?
) Iterator
(nil
)
(string?
)
fun(_, dir: string): 字符串?
迭 代
(无
)
(字符串?
{base}
, {target}
, {opts}
) {base}
, {target}
, {opts}
)vim.fs.relpath() vim.fs.relpath()target
path relative to base
, or nil
if base
is not an
ancestor.
base
的目标
路径,如果
base
不是
祖先。vim.fs.relpath('/var', '/var/lib') -- 'lib'
vim.fs.relpath('/var', '/usr/bin') -- nil
{base}
(string
)
{base}
(字符串
){target}
(string
)
{target}
(字符串
){opts}
(table?
) Reserved for future use
{opts}
(表格?
保留供将来使用string?
)
(字符串?
{path}
, {opts}
) {path}
, {opts}
)vim.fs.rm() vim.fs.rm(){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}
(布尔
值) 忽略不存在的文件和参数{source}
, {marker}
) {源}
, {标记}
)vim.fs.root() vim.fs.root()-- 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