Nvim 的 :help
頁面,從 原始碼 使用 tree-sitter-vimdoc 解析器 產生。
vim.*
存取的任何其他未提及的函式;請參閱 lua-stdlib。nil
傳遞),Nvim API 函式始終需要指定所有參數;而即使 Lua 陣列預設從 1 開始索引,Vim API 函式也可以使用從 0 開始的索引。:lua print("Hello!")
:lua local foo = 1
:lua print(foo)
" prints "nil" instead of "1"
:lua=
,它等效於 :lua vim.print(...)
,以方便地檢查變數或表格的值:lua =package
:source ~/programs/baz/myluafile.lua
lua << EOF
local tbl = {1, 2, 3}
for k, v in ipairs(tbl) do
print(v)
end
EOF
init.vim
或 init.lua
作為組態檔案,但不能同時使用兩者。這應放置在您的 組態 目錄中,該目錄在 Linux、BSD 或 macOS 中通常是 ~/.config/nvim
,在 Windows 中是 ~/AppData/Local/nvim/
。請注意,您可以在 init.vim
中使用 Lua,並在 init.lua
中使用 Vimscript,這將在下面介紹。lua/
目錄中,並使用 require
載入。(這是 Lua 中等效於 Vimscript 的 autoload 機制。)~/.config/nvim |-- after/ |-- ftplugin/ |-- lua/ | |-- myluamodule.lua | |-- other_modules/ | |-- anothermodule.lua | |-- init.lua |-- plugin/ |-- syntax/ |-- init.vim
myluamodule.lua
require("myluamodule")
.lua
副檔名。other_modules/anothermodule.lua
是通過以下方式完成的require('other_modules/anothermodule')
-- or
require('other_modules.anothermodule')
.
等效於路徑分隔符 /
(即使在 Windows 上也是如此)。require('other_modules') -- loads other_modules/init.lua
pcall()
來捕獲此類錯誤。以下範例嘗試載入 module_with_error
,並且僅在成功時才呼叫其其中一個函式,否則會列印錯誤訊息local ok, mymod = pcall(require, 'module_with_error')
if not ok then
print("Module had an error")
else
mymod.function()
end
lua/
目錄中搜尋,還會在第一次使用時快取模組。因此,第二次呼叫 require()
_不會_ 再次執行腳本,而是傳回快取的檔案。若要重新執行檔案,您需要先手動從快取中刪除它package.loaded['myluamodule'] = nil
require('myluamodule') -- read and execute the module again from disk
vim.cmd("colorscheme habamax")
vim.cmd("%s/\\Vfoo/bar/g")
vim.cmd([[
highlight Error guibg=red
highlight link Warning Error
]])
init.lua
中包含 Vimscript 程式碼。vim.cmd.colorscheme("habamax")
vim.cmd.highlight({ "Error", "guibg=red" })
vim.cmd.highlight({ "link", "Warning", "Error" })
print(vim.fn.printf('Hello from %s', 'Lua'))
local reversed_list = vim.fn.reverse({ 'a', 'b', 'c' })
vim.print(reversed_list) -- { "c", "b", "a" }
local function print_stdout(chan_id, data, name)
print(data[1])
end
vim.fn.jobstart('ls', { on_stdout = print_stdout })
require()
搜尋的所有路徑列表vim.g.some_global_variable = {
key1 = "value",
key2 = 300
}
vim.print(vim.g.some_global_variable)
--> { key1 = "value", key2 = 300 }
vim.b[2].myvar = 1 -- set myvar for buffer number 2
vim.w[1005].myothervar = true -- set myothervar for window ID 1005
vim.g['my#variable'] = 1
vim.g.some_global_variable.key2 = 400
vim.print(vim.g.some_global_variable)
--> { key1 = "value", key2 = 300 }
local temp_table = vim.g.some_global_variable
temp_table.key2 = 400
vim.g.some_global_variable = temp_table
vim.print(vim.g.some_global_variable)
--> { key1 = "value", key2 = 400 }
nil
vim.g.myvar = nil
init.lua
中設定全域和本機選項最方便的方式是通過 vim.opt
及其相關函式set smarttab
set nosmarttab
vim.opt.smarttab = true
vim.opt.smarttab = false
set wildignore=*.o,*.a,__pycache__
set listchars=space:_,tab:>~
set formatoptions=njt
vim.opt.wildignore = { '*.o', '*.a', '__pycache__' }
vim.opt.listchars = { space = '_', tab = '>~' }
vim.opt.formatoptions = { n = true, j = true, t = true }
vim.opt.shortmess:append({ I = true })
vim.opt.wildignore:prepend('*.o')
vim.opt.whichwrap:remove({ 'b', 's' })
print(vim.opt.smarttab)
--> {...} (big table)
print(vim.opt.smarttab:get())
--> false
vim.print(vim.opt.listchars:get())
--> { space = '_', tab = '>~' }
vim.o
及其相關函式進行更直接的類似變數存取的方式,類似於您如何通過 :echo &number
和 :let &listchars='space:_,tab:>~'
來取得和設定選項vim.o.smarttab = false -- :set nosmarttab
print(vim.o.smarttab)
--> false
vim.o.listchars = 'space:_,tab:>~' -- :set listchars='space:_,tab:>~'
print(vim.o.listchars)
--> 'space:_,tab:>~'
vim.o.isfname = vim.o.isfname .. ',@-@' -- :set isfname+=@-@
print(vim.o.isfname)
--> '@,48-57,/,.,-,_,+,,,#,$,%,~,=,@-@'
vim.bo.shiftwidth = 4 -- :setlocal shiftwidth=4
print(vim.bo.shiftwidth)
--> 4
vim.bo[4].expandtab = true -- sets expandtab to true in buffer 4
vim.wo.number = true -- sets number to true in current window
vim.wo[0].number = true -- same as above
vim.wo[0][0].number = true -- sets number to true in current buffer
-- in current window only
print(vim.wo[0].number) --> true
{lhs}
是一個字串,其中包含應觸發映射的按鍵序列。-- Normal mode mapping for Vim command
vim.keymap.set('n', '<Leader>ex1', '<cmd>echo "Example 1"<cr>')
-- Normal and Command-line mode mapping for Vim command
vim.keymap.set({'n', 'c'}, '<Leader>ex2', '<cmd>echo "Example 2"<cr>')
-- Normal mode mapping for Lua function
vim.keymap.set('n', '<Leader>ex3', vim.treesitter.start)
-- Normal mode mapping for Lua function with arguments
vim.keymap.set('n', '<Leader>ex4', function() print('Example 4') end)
vim.keymap.set('n', '<Leader>pl1', require('plugin').action)
function() end
中。vim.keymap.set('n', '<Leader>pl2', function() require('plugin').action() end)
buffer
:如果指定,則僅為具有指定編號的緩衝區設定映射;0
或 true
表示目前的緩衝區。-- set mapping for the current buffer
vim.keymap.set('n', '<Leader>pl1', require('plugin').action, { buffer = true })
-- set mapping for the buffer number 4
vim.keymap.set('n', '<Leader>pl1', require('plugin').action, { buffer = 4 })
silent
:如果設定為 true
,則會抑制輸出,例如錯誤訊息。vim.keymap.set('n', '<Leader>pl1', require('plugin').action, { silent = true })
expr
:如果設定為 true
,則不會執行 {rhs}
,而是使用傳回值作為輸入。特殊的 按鍵代碼 會自動轉換。例如,以下映射僅在彈出式選單中將 <down>
替換為 <c-n>
vim.keymap.set('c', '<down>', function()
if vim.fn.pumvisible() == 1 then return '<c-n>' end
return '<down>'
end, { expr = true })
desc
:一個字串,當使用例如 :map 列出映射時顯示。這很有用,因為 Lua 函數作為 {rhs}
否則只會列為 Lua: <number> <source file>:<line>
。因此,外掛程式應該始終將此用於它們建立的映射。vim.keymap.set('n', '<Leader>pl1', require('plugin').action,
{ desc = 'Execute action from plugin' })
remap
:預設情況下,所有映射都是非遞迴的(即 vim.keymap.set() 的行為類似於 :noremap)。如果 {rhs}
本身是一個應執行的映射,請設定 remap = true
。vim.keymap.set('n', '<Leader>ex1', '<cmd>echo "Example 1"<cr>')
-- add a shorter mapping
vim.keymap.set('n', 'e', '<Leader>ex1', { remap = true })
remap = false
,<Plug> 映射也始終會展開。vim.keymap.set('n', '[%', '<Plug>(MatchitNormalMultiBackward)')
vim.keymap.del('n', '<Leader>ex1')
vim.keymap.del({'n', 'c'}, '<Leader>ex2', {buffer = true})
vim.api.
nvim_create_autocmd() 建立的,它接受兩個強制參數{event}
:一個字串或字串表格,其中包含應觸發命令或函數的事件。{opts}
:一個表格,其中包含控制觸發事件時應發生情況的鍵。pattern
:一個字串或字串表格,其中包含 autocmd-pattern。 注意: 像是 $HOME
和 ~
的環境變數不會自動展開;您需要明確使用 vim.fn.
expand() 來做到這一點。command
:一個包含 Vim 命令的字串。callback
:一個 Lua 函數。command
和 callback
其中一個,且只能指定一個。如果省略 pattern
,則預設為 pattern = '*'
。範例vim.api.nvim_create_autocmd({"BufEnter", "BufWinEnter"}, {
pattern = {"*.c", "*.h"},
command = "echo 'Entering a C or C++ file'",
})
-- Same autocommand written with a Lua function instead
vim.api.nvim_create_autocmd({"BufEnter", "BufWinEnter"}, {
pattern = {"*.c", "*.h"},
callback = function() print("Entering a C or C++ file") end,
})
-- User event triggered by MyPlugin
vim.api.nvim_create_autocmd("User", {
pattern = "MyPlugin",
callback = function() print("My Plugin Works!") end,
})
buf
:觸發事件的緩衝區編號(請參閱 <abuf>)file
:觸發事件的緩衝區的檔案名稱(請參閱 <afile>)data
:一個包含某些事件傳遞的其他相關資料的表格vim.api.nvim_create_autocmd("FileType", {
pattern = "lua",
callback = function(args)
vim.keymap.set('n', 'K', vim.lsp.buf.hover, { buffer = args.buf })
end
})
function() end
中以避免錯誤vim.api.nvim_create_autocmd('TextYankPost', {
callback = function() vim.hl.on_yank() end
})
function(args) ... end
。)buffer
而不是使用模式來建立緩衝區本機的自動指令(請參閱 autocmd-buflocal);在這種情況下,無法使用 pattern
。-- set autocommand for current buffer
vim.api.nvim_create_autocmd("CursorHold", {
buffer = 0,
callback = function() print("hold") end,
})
-- set autocommand for buffer number 33
vim.api.nvim_create_autocmd("CursorHold", {
buffer = 33,
callback = function() print("hold") end,
})
desc
來新增說明(而且應該新增)。vim.api.nvim_create_autocmd('TextYankPost', {
callback = function() vim.hl.on_yank() end,
desc = "Briefly highlight yanked text"
})
group
鍵來群組自動指令;這將在下一節中詳細介紹。vim.api.
nvim_create_augroup() 建立群組。此函數接受兩個強制參數:一個包含群組名稱的字串和一個表格,用於判斷如果群組已存在,是否應清除該群組(即移除所有已分組的自動指令)。該函數會傳回一個數字,它是群組的內部識別碼。群組可以透過此識別碼或名稱指定(但前提是必須先建立群組)。augroup vimrc
" Remove all vimrc autocommands
autocmd!
au BufNewFile,BufRead *.html set shiftwidth=4
au BufNewFile,BufRead *.html set expandtab
augroup END
local mygroup = vim.api.nvim_create_augroup('vimrc', { clear = true })
vim.api.nvim_create_autocmd({ 'BufNewFile', 'BufRead' }, {
pattern = '*.html',
group = mygroup,
command = 'set shiftwidth=4',
})
vim.api.nvim_create_autocmd({ 'BufNewFile', 'BufRead' }, {
pattern = '*.html',
group = 'vimrc', -- equivalent to group=mygroup
command = 'set expandtab',
})
local mygroup = vim.api.nvim_create_augroup('vimrc', { clear = false })
vim.api.nvim_create_autocmd({ 'BufNewFile', 'BufRead' }, {
pattern = '*.c',
group = mygroup,
command = 'set noexpandtab',
})
vim.api.
nvim_clear_autocmds() 來移除自動指令。此函數接受單一強制參數,它是描述要移除的自動指令的鍵的表格-- Delete all BufEnter and InsertLeave autocommands
vim.api.nvim_clear_autocmds({event = {"BufEnter", "InsertLeave"}})
-- Delete all autocommands that uses "*.py" pattern
vim.api.nvim_clear_autocmds({pattern = "*.py"})
-- Delete all autocommands in group "scala"
vim.api.nvim_clear_autocmds({group = "scala"})
-- Delete all ColorScheme autocommands in current buffer
vim.api.nvim_clear_autocmds({event = "ColorScheme", buffer = 0 })
group
鍵的情況下,才會移除群組中的自動指令,即使另一個選項符合它也是如此。desc
(描述命令的字串);force
(設定為 false
以避免替換同名的現有命令)和 preview
(用於 :command-preview 的 Lua 函數)。vim.api.nvim_create_user_command('Test', 'echo "It works!"', {})
vim.cmd.Test()
--> It works!
name
:一個包含命令名稱的字串fargs
:一個表格,其中包含以空白分隔的命令參數(請參閱 <f-args>)line1
:命令範圍的起始行號(請參閱 <line1>)line2
:命令範圍的結束行號(請參閱 <line2>)range
:命令範圍中的項目數:0、1 或 2(請參閱 <range>)count
:任何提供的計數(請參閱 <count>)smods
:一個包含命令修飾符的表格(請參閱 <mods>)vim.api.nvim_create_user_command('Upper',
function(opts)
print(string.upper(opts.fargs[1]))
end,
{ nargs = 1 })
vim.cmd.Upper('foo')
--> FOO
complete
屬性還可以採用 Lua 函數。vim.api.nvim_create_user_command('Upper',
function(opts)
print(string.upper(opts.fargs[1]))
end,
{ nargs = 1,
complete = function(ArgLead, CmdLine, CursorPos)
-- return completion candidates as a list-like table
return { "foo", "bar", "baz" }
end,
})
vim.api.
nvim_buf_create_user_command() 建立緩衝區本機的使用者命令。此處第一個參數是緩衝區編號(0
表示目前的緩衝區);其餘參數與 nvim_create_user_command() 的參數相同。vim.api.nvim_buf_create_user_command(0, 'Upper',
function(opts)
print(string.upper(opts.fargs[1]))
end,
{ nargs = 1 })
vim.api.
nvim_buf_del_user_command()。此處第一個參數是緩衝區編號(0
表示目前的緩衝區),第二個參數是命令名稱vim.api.nvim_buf_del_user_command(4, 'Upper')