This guide introduces the basics of everyday Lua usage for configuring and
controlling Nvim. It assumes some familiarity with the (non-Lua) basics of
Nvim (commands, options, mappings, autocommands), which are covered in the
user-manual.
This is not a comprehensive encyclopedia of all available features. Think of
it as a survival kit: the bare minimum needed to comfortably get started on
using Lua in Nvim.
See lua-plugin for guidance on developing Lua plugins.
See luaref and lua-concepts for details on the Lua programming language.
The purpose of this guide is to introduce the different ways of interacting
with Nvim through Lua (the "API"). This API consists of three different
layers:
The "Nvim API" written in C for use in remote plugins and GUIs; see api.
These functions are accessed through vim.api.
The "Lua API" written in and specifically for Lua. These are any other
functions accessible through vim.* not mentioned already; see
lua-stdlib.
This distinction is important, as API functions inherit behavior from their
original layer: For example, Nvim API functions always need all arguments to
be specified even if Lua itself allows omitting arguments (which are then
passed as nil); and Vim API functions can use 0-based indexing even if Lua
arrays are 1-indexed by default.
Through this, any possible interaction can be done through Lua without writing
a complete new API from scratch. For this reason, functions are usually not
duplicated between layers unless there is a significant benefit in
functionality or performance (e.g., you can map Lua functions directly through
nvim_create_autocmd() but not through :autocmd). In case there are multiple
ways of achieving the same thing, this guide will only cover what is most
convenient to use from Lua.
To run Lua code from the Nvim command line, use the :lua command:
:lua print("Hello!")
Note: each :lua command has its own scope and variables declared with the
local keyword are not accessible outside of the command. This won't work:
:lua local foo = 1
:lua print(foo)
" prints "nil" instead of "1"
You can also use :lua=, which is equivalent to :lua vim.print(...), to
conveniently check the value of a variable or a table:
:lua =package
To run a Lua script in an external file, you can use the :source command
exactly like for a Vimscript file:
:source ~/programs/baz/myluafile.lua
Finally, you can include Lua code in a Vimscript file by putting it inside a
:lua-heredoc block:
lua << EOF
local tbl = {1, 2, 3}
for k, v in ipairs(tbl) do
print(v)
end
EOF
lua-guide-interrupt
Lua cannot normally be interrupted by CTRL-C (Lua does not implicitly
"yield" to Nvim). To allow the user to interrupt potentially slow loops,
periodically call vim.wait(). Passing interval=0 skips the dummy timer
setup, minimizing per-call overhead in a tight loop:
while true do
-- ...work...
local _, code = vim.wait(0, nil, 0)
if code == -2 then -- CTRL-C.
break
end
end
Nvim supports using init.vim or init.lua as the configuration file, but
not both at the same time. This should be placed in your config directory
(run :echo stdpath('config') to see where it is). Note that you can also use
Lua in init.vim and Vimscript in init.lua, which will be covered below.
If you'd like to run any other Lua script on startup automatically, then you
can simply put it in plugin/ in your 'runtimepath'.
If you want to load Lua files on demand, you can place them in the lua/
directory in your 'runtimepath' and load them with require. (This is the
Lua equivalent of Vimscript's autoload mechanism.)
Let's assume you have the following directory structure:
Requiring a nonexistent module or a module which contains syntax errors aborts
the currently executing script. 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.func()
end
In contrast to :source, require() not only searches through all 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
For this reason, there exists a more direct variable-like access using vim.o
and friends, similarly to how you can get and set options via :echo &number
and :let &listchars='space:_,tab:>~':
Just like variables, you can specify a buffer number or window-ID for buffer
and window options, respectively. If no number is given, the current buffer or
window is used:
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
Mappings can be created using vim.keymap.set(). This function takes three
mandatory arguments:
{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 , which disables a key.
Examples:
-- Normal mode mapping for Vim command
vim.keymap.set('n', 'ex1', 'echo "Example 1"')
-- Normal and Command-line mode mapping for Vim command
vim.keymap.set({'n', 'c'}, 'ex2', 'echo "Example 2"')
-- Normal mode mapping for Lua function
vim.keymap.set('n', 'ex3', vim.treesitter.start)
-- Normal mode mapping for Lua function with arguments
vim.keymap.set('n', 'ex4', function() print('Example 4') end)
Note that this loads the plugin at the time the mapping is defined. If you
want to defer the loading to the time when the mapping is executed (as for
autoload functions), wrap it in function() end:
The fourth, optional, argument is a table with keys that modify the behavior
of the mapping such as those from :map-arguments. The following are the most
useful options:
buf: 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', 'pl1', require('plugin').action, { buf = 0 })
-- set mapping for the buffer number 4
vim.keymap.set('n', 'pl1', require('plugin').action, { buf = 4 })
silent: If set to true, suppress output such as error messages.
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 with in the popupmenu only:
vim.keymap.set('c', '', function()
if vim.fn.pumvisible() == 1 then return '' end
return ''
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: :. Plugins should therefore always use this
for mappings they create.
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:
An autocommand is a Vim command or a Lua function that is automatically
executed whenever one or more events are triggered, e.g., when a file is
read or written, or when a window is created. These are accessible from Lua
through the Nvim API.
Autocommands are created using 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.
The most important options are:
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.
You must specify one and only one of 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,
})
Nvim will always call a Lua function with a single table containing information
about the triggered autocommand. The most useful keys are
match: a string that matched the pattern (see )
buf: the number of the buffer the event was triggered in (see )
file: the file name of the buffer the event was triggered in (see )
data: a table with other relevant data that is passed for some events
For example, this allows you to set buffer-local mappings for some filetypes:
Autocommand groups can be used to group related autocommands together; see
autocmd-groups. This is useful for organizing autocommands and especially
for preventing autocommands to be set multiple times.
Groups can be created with 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).
For example, a common Vimscript pattern for autocommands defined in files that
may be reloaded is
augroup vimrc
" Remove all vimrc autocommands
autocmd!
au BufNewFile,BufRead *.html set shiftwidth=4
au BufNewFile,BufRead *.html set expandtab
augroup END
You can use 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 })
Note: Autocommands in groups will only be removed if the group key is
specified, even if another option matches it.
user-commands are custom Vim commands that call a Vimscript or Lua function.
Just like built-in commands, they can have arguments, act on ranges, or have
custom completion of arguments. As these are most useful for plugins, we will
cover only the basics of this advanced topic.
User commands can be created via nvim_create_user_command(). This function
takes three mandatory arguments:
a string that is the name of the command (which must start with an uppercase
letter to distinguish it from builtin commands);
a string containing Vim commands or a Lua function that is executed when the
command is invoked;
a table with command-attributes; in addition, it can contain the keys
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).
Example:
vim.api.nvim_create_user_command('Test', 'echo "It works!"')
vim.cmd.Test()
--> It works!
(Note that the third argument is mandatory even if no attributes are given.)
Lua functions are called with a single table argument containing arguments and
modifiers. The most important are:
name: a string with the command name
fargs: a table containing the command arguments split by whitespace (see )
bang: true if the command was executed with a ! modifier (see )
line1: the starting line number of the command range (see )
line2: the final line number of the command range (see )
range: the number of items in the command range: 0, 1, or 2 (see )
count: any count supplied (see )
smods: a table containing the command modifiers (see )
Buffer-local user commands are created with 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():
User commands can be deleted with vim.api.nvim_del_user_command(). The only
argument is the name of the command:
vim.api.nvim_del_user_command('Upper')
To delete buffer-local user commands use 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: