Nvim 的 :help
頁面,從 原始碼 使用 tree-sitter-vimdoc 解析器 產生。
:lua vim.print(package.loaded)
Nvim 為 Lua 包含一個「標準函式庫」lua-stdlib。它補充了「編輯器標準函式庫」(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 區塊 {區塊}
。如果 {區塊}
以「=」開頭,則會將區塊的其餘部分評估為運算式並印出。:lua =expr
和 :=expr
等效於 :lua vim.print(expr)
。:lua vim.api.nvim_command('echo "Hello, Nvim!"')
:lua print(_VERSION)
:lua =jit.version
{範圍}
中的緩衝區行當作 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
{file}
執行 {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
值,又稱 "洞") 整數鍵 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 的 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
的第二個引數會從 Vimscript 轉換 ("marshal") 為 Lua,因此變更 Lua 容器不會影響 Vimscript 中的值。傳回值也始終會轉換。轉換時,會特別處理 msgpack-special-dict。v:lua
來呼叫 Lua 函式,這些函式是全域的或可從全域表格存取。表達式call v:lua.func(arg1, arg2)
等效於 Lua 程式碼片段return func(...)
其中 args 會轉換為 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
回呼中呼叫 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.inspect
vim.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 語意 Token 醒目標示diagnostics
:150
,用於程式碼分析,例如診斷user
:200
,用於使用者觸發的醒目標示,例如 LSP 文件符號或 on_yank
自動指令{bufnr}
(integer
) 要套用高亮的緩衝區編號{ns}
(integer
) 要加入高亮的命名空間{higroup}
(string
) 用於高亮顯示的高亮群組{opts}
(table?
) 包含以下欄位的表格{inclusive}
(boolean
, 預設值: false
) 指示範圍是否包含結束位置{priority}
(integer
, 預設值: 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}
發送請求,以透過 RPC 調用 {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[]
){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
){time}
, {callback}
, {interval}
, {fast_only}
) vim.wait(){time}
(以毫秒為單位),直到 {callback}
返回 true
。{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?
){time}
期間 {callback}
返回 true
:true, nil
{time}
期間 {callback}
從未返回 true
:false, -1
{time}
期間 {callback}
被中斷: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 讀取和修改全域 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 = true
set wildignore=*.o,*.a,__pycache__
Lua:vim.o.wildignore = '*.o,*.a,__pycache__'
set wildignore=*.o,*.a,__pycache__
vim.o
vim.o.wildignore = '*.o,*.a,__pycache__'
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.listchars = 'space:_,tab:>~'
vim.opt
vim.opt.listchars = { space = '_', tab = '>~' }
echo wildignore
vim.o
print(vim.o.wildignore)
vim.opt
vim.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}
或鍵會產生錯誤。{bufnr}
的值為 0
(視窗中的目前緩衝區)。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(){fn}
與命名空間 ID {ns_id}
新增為每個 (是的,每個) 輸入鍵的接聽程式。{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
,則會開啟一個到標準輸入的管道,並可透過 SystemObj 的 write()
方法寫入。如果為 string 或 string[],則會寫入到標準輸入並關閉。預設為 false
。fun(err: string, data: string)
的簽名。預設為 true
fun(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) 包含 extmark。當為 all
時,也會包含沒有 hl_group
的 extmark。{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) 包含 extmark。當為 all
時,也會包含沒有 hl_group
的 extmark。{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}
) vim.defaulttable(){createfn}
提供 (類似 Python 的 "defaultdict")。{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 的最終索引。預設為 #src
table
) 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
的前綴,則為 true
vim.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])
驗證具有值 {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)
(已棄用) 其中 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.dev.org.tw/")
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。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
是 item
在 items
中的從 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}
不為 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}
為字串或表格時,不支援路徑和 glob 模式。如果 {names}
是一個函式,則會針對每個遍歷的項目呼叫該函式,並帶有參數true
。{opts}
(table
) 可選的關鍵字參數{upward}
(boolean
, 預設值: false
) 向上搜尋父目錄。否則,搜尋子目錄(遞迴)。{stop}
(string
) 當到達此目錄時停止搜尋。不會搜尋該目錄本身。{type}
(string
) 僅尋找給定類型的項目。如果省略,則會包含所有符合 {names}
的項目。{limit}
(number
, 預設值: 1
) 在找到這麼多個符合的項目後停止搜尋。使用 math.huge
對符合的項目數量不設限制。{...}
) vim.fs.joinpath()"foo/"
和 "bar"
會被連接成 "foo/bar"
){...}
(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
) 原始 glob 模式vim.lpeg
包含 (https://www.inf.puc-rio.br/~roberto/lpeg/)。{subject}
, {init}
, {...}
) Pattern:match()subject
字串比對給定的 pattern
。如果比對成功,則會返回 subject 中比對後第一個字元的索引,或返回擷取的值(如果模式擷取了任何值)。可選的數值引數 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
返回的所有值分組到單一捕獲中。群組可以是匿名的(如果沒有給定名稱),或使用給定的名稱命名(該名稱可以是任何非 nil 的 Lua 值)。{patt}
(vim.lpeg.Pattern|string|integer|boolean|table|function
){name}
(string?
)vim.lpeg.Capture
){patt}
, {fn}
) vim.lpeg.Cmt()function
。給定的函式會收到整個主題、目前位置(在 patt
匹配之後),以及 patt
產生的任何捕獲值作為參數。函式返回的第一個值定義了匹配如何發生。如果呼叫返回一個數字,則匹配成功,且返回的數字會成為新的目前位置。(假設主題為 s 且目前位置為 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()subject
字串比對給定的 pattern
。如果比對成功,則會返回 subject 中比對後第一個字元的索引,或返回擷取的值(如果模式擷取了任何值)。可選的數值引數 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
。由於任何整數都是「真值」,因此 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
) 如果操作成功則為 true (string
) 如果操作成功則為完整路徑,否則為錯誤訊息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
) 如果 v1 < v2
則為 -1,如果 v1 == v2
則為 0,如果 v1 > v2
則為 1。{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
){depth}
) Iter:flatten(){depth}
取消巢狀值。如果嘗試將類似字典的值平面化,則會產生錯誤。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
是負數,則會從 list-iterator 的結尾偏移。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[]
)