Back to Blog

Lua for Neovim: The Neovim Lua API — vim.api, vim.opt, vim.keymap.set & Autocommands | Episode 31

Sandy LaneSandy Lane

Video: Lua for Neovim: The Neovim Lua API — vim.api, vim.opt, vim.keymap.set & Autocommands | Episode 31 by Taught by Celeste AI - AI Coding Coach

Watch full page →

Lua for Neovim: The Neovim Lua API — vim.api, vim.opt, vim.keymap.set & Autocommands

This guide covers essential parts of the Neovim Lua API, showing how to interact with Neovim’s core features using Lua. You’ll learn to use vim.api for core functions, call Vimscript with vim.fn, configure options via vim.opt, create keymaps with vim.keymap.set, and set up user commands and autocommands—all directly from Lua.

Code

-- Access buffer API and call Vimscript function
local bufname = vim.api.nvim_buf_get_name(0)  -- get current buffer name
local lines = vim.fn.getline(1, 5)            -- get first 5 lines using Vimscript function

-- Set options using vim.opt
vim.opt.number = true        -- show line numbers
vim.opt.tabstop = 4          -- set tab width to 4 spaces

-- Reload this Lua config file instantly with :luafile %
-- (Run this command inside Neovim to apply changes without restarting)

-- Create a user command :Hello that prints a message
vim.api.nvim_create_user_command('Hello', function()
  print("Hello from Lua user command!")
end, {})

-- Map h to print a greeting message
vim.keymap.set('n', 'h', function()
  print("Hello, Neovim Lua keymap!")
end, { noremap = true, silent = true })

-- Set up an autocommand to echo a message after saving a buffer
vim.api.nvim_create_autocmd('BufWritePost', {
  pattern = '*',
  callback = function()
    print("Buffer saved!")
  end,
})

Key Points

  • vim.api provides direct access to Neovim’s core functions for buffer, window, and editor manipulation.
  • vim.fn allows calling any Vimscript function seamlessly from Lua.
  • vim.opt is the recommended way to set editor options like line numbers and tab width.
  • vim.keymap.set offers a clean, Lua-native method to define key mappings with options like noremap and silent.
  • Using :luafile % reloads your Lua config instantly, speeding up development and testing.
  • User commands and autocommands can be created entirely in Lua, enabling powerful customization triggered by events.