Nvim :help
pages, generated
from source
using the tree-sitter-vimdoc parser.
vim.*
not mentioned already; see lua-stdlib.nil
); and Vim API functions can use 0-based indexing even if Lua
arrays are 1-indexed by default.:lua print("Hello!")
:lua local foo = 1
:lua print(foo)
" prints "nil" instead of "1"
:lua=
, which is equivalent to :lua vim.print(...)
, to
conveniently check the value of a variable or a table:
: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
or init.lua
as the configuration file, but
not both at the same time. This should be placed in your config directory,
which is typically ~/.config/nvim
for Linux, BSD, or macOS, and
~/AppData/Local/nvim/
for Windows. Note that you can use Lua in init.vim
and Vimscript in init.lua
, which will be covered below.plugin/
in your 'runtimepath'.lua/
directory in your 'runtimepath' and load them with require
. (This is the
Lua equivalent of Vimscript's autoload mechanism.)~/.config/nvim |-- after/ |-- ftplugin/ |-- lua/ | |-- myluamodule.lua | |-- other_modules/ | |-- anothermodule.lua | |-- init.lua |-- plugin/ |-- syntax/ |-- init.vim
myluamodule.lua
:
require("myluamodule")
.lua
extension.other_modules/anothermodule.lua
is done via
require('other_modules/anothermodule')
-- or
require('other_modules.anothermodule')
.
is equivalent to the
path separator /
(even on Windows).require('other_modules') -- loads other_modules/init.lua
pcall()
may be used to catch such errors. The
following example tries to load the module_with_error
and only calls one of
its functions if this succeeds and prints an error message otherwise:
local ok, mymod = pcall(require, 'module_with_error')
if not ok then
print("Module had an error")
else
mymod.function()
end
lua/
directories
under 'runtimepath', it also caches the module on first use. Calling
require()
a second time will therefore _not_ execute the script again and
instead return the cached file. To rerun the file, you need to remove it from
the cache manually first:
package.loaded['myluamodule'] = nil
require('myluamodule') -- read and execute the module again from disk
vim.cmd("colorscheme habamax")
vim.cmd("%s/\\Vfoo/bar/g")
[[ ]]
as in
vim.cmd([[%s/\Vfoo/bar/g]])
vim.cmd([[
highlight Error guibg=red
highlight link Warning Error
]])
init.lua
.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 })
#
) are not valid characters for identifiers in Lua, so,
e.g., autoload functions have to be called with this syntax:
vim.fn['my#autoload#function']()
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
,
is through vim.opt
and friends: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
and friends, similarly to how you can get and set options via :echo &number
and :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
{mode}
is a string or a table of strings containing the mode
prefix for which the mapping will take effect. The prefixes are the ones
listed in :map-modes, or "!" for :map!, or empty string for :map.
{lhs}
is a string with the key sequences that should trigger the mapping.
{rhs}
is either a string with a Vim command or a Lua function that should
be executed when the {lhs}
is entered.
An empty string is equivalent to <Nop>, which disables a key.
-- 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
: If given, only set the mapping for the buffer with the specified
number; 0
or true
means the current buffer.-- 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
: If set to true
, suppress output such as error messages.
vim.keymap.set('n', '<Leader>pl1', require('plugin').action, { silent = true })
expr
: If set to true
, do not execute the {rhs}
but use the return value
as input. Special keycodes are converted automatically. For example, the following
mapping replaces <down>
with <c-n>
in the popupmenu only:vim.keymap.set('c', '<down>', function()
if vim.fn.pumvisible() == 1 then return '<c-n>' end
return '<down>'
end, { expr = true })
desc
: A string that is shown when listing mappings with, e.g., :map.
This is useful since Lua functions as {rhs}
are otherwise only listed as
Lua: <number> <source file>:<line>
. Plugins should therefore always use this
for mappings they create.vim.keymap.set('n', '<Leader>pl1', require('plugin').action,
{ desc = 'Execute action from plugin' })
remap
: By default, all mappings are nonrecursive (i.e., vim.keymap.set()
behaves like :noremap). If the {rhs}
is itself a mapping that should be
executed, set 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
:vim.keymap.set('n', '[%', '<Plug>(MatchitNormalMultiBackward)')
vim.keymap.del('n', '<Leader>ex1')
vim.keymap.del({'n', 'c'}, '<Leader>ex2', {buffer = true})
vim.api.
nvim_get_keymap(): return all global mapping
vim.api.
nvim_buf_get_keymap(): return all mappings for buffer
vim.api.
nvim_create_autocmd(), which takes
two mandatory arguments:
{event}
: a string or table of strings containing the event(s) which should
trigger the command or function.
{opts}
: a table with keys that control what should happen when the event(s)
are triggered.
pattern
: A string or table of strings containing the autocmd-pattern.
Note: Environment variable like $HOME
and ~
are not automatically
expanded; you need to explicitly use vim.fn.
expand() for this.
command
: A string containing a Vim command.
callback
: A Lua function.
command
and callback
. If pattern
is
omitted, it defaults to pattern = '*'
.
Examples:
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
: the number of the buffer the event was triggered in (see <abuf>)
file
: the file name of the buffer the event was triggered in (see <afile>)
data
: a table with other relevant data that is passed for some events
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
to avoid an error:
vim.api.nvim_create_autocmd('TextYankPost', {
callback = function() vim.highlight.on_yank() end
})
function(args) ... end
.)buffer
; in this case, pattern
cannot be used:
-- 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.highlight.on_yank() end,
desc = "Briefly highlight yanked text"
})
group
key; this will be
covered in detail in the next section.vim.api.
nvim_create_augroup(). This function
takes two mandatory arguments: a string with the name of a group and a table
determining whether the group should be cleared (i.e., all grouped
autocommands removed) if it already exists. The function returns a number that
is the internal identifier of the group. Groups can be specified either by
this identifier or by the name (but only if the group has been created first).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() to remove autocommands. This
function takes a single mandatory argument that is a table of keys describing
the autocommands that are to be removed:
-- 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
key is
specified, even if another option matches it.desc
(a string describing the command); force
(set to false
to avoid
replacing an already existing command with the same name), and preview
(a
Lua function that is used for :command-preview).
vim.api.nvim_create_user_command('Test', 'echo "It works!"', {})
vim.cmd.Test()
--> It works!
name
: a string with the command name
fargs
: a table containing the command arguments split by whitespace (see <f-args>)
line1
: the starting line number of the command range (see <line1>)
line2
: the final line number of the command range (see <line2>)
range
: the number of items in the command range: 0, 1, or 2 (see <range>)
count
: any count supplied (see <count>)
smods
: a table containing the command modifiers (see <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
attribute can take a Lua function in addition to the
attributes listed in :command-complete.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().
Here the first argument is the buffer number (0
being the current buffer);
the remaining arguments are the same as for 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_del_user_command(). The only
argument is the name of the command:
vim.api.nvim_del_user_command('Upper')
vim.api.
nvim_buf_del_user_command().
Here the first argument is the buffer number (0
being the current buffer),
and second is command name:
vim.api.nvim_buf_del_user_command(4, 'Upper')