Nvim 的 :help 页面,从 生成 于 源代码,使用 tree-sitter-vimdoc 解析器。
vim.* 访问的函数,这些函数尚未提及;参见 lua-stdlib。nil 传递);而 Vim API 函数可以使用基于 0 的索引,即使 Lua 数组默认情况下是基于 1 的。: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.lualua << EOF
local tbl = {1, 2, 3}
for k, v in ipairs(tbl) do
print(v)
end
EOFinit.vim 或 init.lua 作为配置文件,但不能同时使用两者。这应该放在你的 配置 目录中,通常是 Linux、BSD 或 macOS 的 ~/.config/nvim,以及 Windows 的 ~/AppData/Local/nvim/。请注意,你可以在 init.vim 中使用 Lua,在 init.lua 中使用 Vimscript,这将在下面介绍。~/.config/nvim |-- after/ |-- ftplugin/ |-- lua/ | |-- myluamodule.lua | |-- other_modules/ | |-- anothermodule.lua | |-- init.lua |-- plugin/ |-- syntax/ |-- init.vim
myluamodule.luarequire("myluamodule").lua 扩展名。other_modules/anothermodule.lua 通过以下方式完成require('other_modules/anothermodule')
-- or
require('other_modules.anothermodule'). 等同于路径分隔符 /(即使在 Windows 上)。require('other_modules') -- loads other_modules/init.luapcall() 可用于捕获此类错误。以下示例尝试加载 module_with_error,只有在成功加载时才调用其函数之一,否则打印错误消息local ok, mymod = pcall(require, 'module_with_error')
if not ok then
print("Module had an error")
else
mymod.function()
endlua/ 目录,它还会在第一次使用时缓存模块。因此,第二次调用 require() _不会_再次执行脚本,而是返回缓存的文件。要重新运行该文件,你需要先手动从缓存中删除它package.loaded['myluamodule'] = nil
require('myluamodule') -- read and execute the module again from diskvim.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 1005vim.g['my#variable'] = 1vim.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 }nilvim.g.myvar = nilinit.lua 中)是通过 vim.opt 及其朋友set smarttab
set nosmarttabvim.opt.smarttab = true
vim.opt.smarttab = falseset wildignore=*.o,*.a,__pycache__
set listchars=space:_,tab:>~
set formatoptions=njtvim.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)
--> 4vim.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 = truevim.keymap.set('n', '<Leader>ex1', '<cmd>echo "Example 1"<cr>')
-- add a shorter mapping
vim.keymap.set('n', 'e', '<Leader>ex1', { remap = true })
remap = falsevim.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}:一个包含控制事件被触发时发生什么的键的表格。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 ENDlocal 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')
--> FOOcomplete 属性除了 :command-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')