Chuyển đến nội dung

Bài 29 · Neovim and Lua

Writing init.lua

Configure Neovim in Lua: vim.o, vim.opt and vim.g, vim.keymap.set, autocommands with vim.api, user commands, calling Vim script, and a clean multi-file layout.

Neovim exposes its whole editor through a global table named vim. Options, keymaps, autocommands, diagnostics and the file system are all reachable from it. In this lesson you translate the vimrc you wrote earlier into a modular init.lua.

The Lua snippets are read-only (the site has no Neovim), but the stand-in at the end is a runnable JavaScript model of the vim table so you can see how a config file "talks" to the editor.

Options

Three ways to set options:

LUA
vim.o.number = true            -- like :set (global value)
vim.opt.number = true          -- friendly wrapper, supports lists and sets
vim.wo.cursorline = true       -- window-local
vim.bo.shiftwidth = 2          -- buffer-local
vim.g.mapleader = " "          -- global variable (g:mapleader)

vim.opt is the one you will use most. For options that hold lists or flags, it has real methods:

LUA
local opt = vim.opt
opt.number = true
opt.relativenumber = true
opt.tabstop = 4
opt.shiftwidth = 4
opt.expandtab = true
opt.ignorecase = true
opt.smartcase = true
opt.scrolloff = 8
opt.signcolumn = "yes"
opt.undofile = true
opt.termguicolors = true
opt.clipboard = "unnamedplus"
opt.listchars = { tab = ">-", trail = "~" }
opt.wildignore:append({ "*.o", "*.pyc" })
opt.shortmess:append("c")

:append, :prepend and :remove take the place of +=, ^= and -=. Read a value back with vim.opt.tabstop:get() or simply vim.o.tabstop. Set vim.g.mapleader before any keymap that uses <leader>.

Keymaps

vim.keymap.set(mode, lhs, rhs, opts) replaces the whole nnoremap family:

LUA
vim.keymap.set("n", "<leader>w", "<cmd>write<cr>", { desc = "Save file" })
vim.keymap.set("n", "<leader>h", "<cmd>nohlsearch<cr>", { desc = "Clear highlights" })
vim.keymap.set({ "n", "v" }, "<leader>y", '"+y', { desc = "Yank to system clipboard" })
vim.keymap.set("x", "<", "<gv")
vim.keymap.set("n", "<C-h>", "<C-w>h")
vim.keymap.set("n", "j", "v:count == 0 ? 'gj' : 'j'", { expr = true })
vim.keymap.set("n", "<leader>x", function()
  print("a Lua function as the right-hand side")
end, { desc = "Demo" })

Differences from Vim script:

  • The mode can be a string or a list of modes.
  • Mappings are non-recursive by default (remap = false), so you never need a noremap variant.
  • The right-hand side can be a Lua function.
  • Options go in one table: desc, silent, buffer = true (or a buffer number), expr, remap, nowait. Writing desc makes the map appear helpfully in :map and in key-hint plugins.
  • Key notation stays the same: <cmd>, <cr>, <leader>, <C-w>.

Remove a mapping with vim.keymap.del("n", "<leader>x").

Autocommands

LUA
local group = vim.api.nvim_create_augroup("my_config", { clear = true })

vim.api.nvim_create_autocmd("TextYankPost", {
  group = group,
  callback = function() vim.highlight.on_yank() end,
})

vim.api.nvim_create_autocmd("BufWritePre", {
  group = group,
  pattern = "*.py",
  command = [[%s/\s\+$//e]],
})

vim.api.nvim_create_autocmd("FileType", {
  group = group,
  pattern = { "yaml", "lua" },
  callback = function() vim.opt_local.shiftwidth = 2 end,
})

clear = true plays the role of autocmd! so sourcing again does not duplicate. Use callback for a Lua function or command for an Ex command string. vim.opt_local sets an option for the current buffer or window only, which is what you want inside a FileType handler. (In recent Neovim, vim.hl.on_yank() is the new name of vim.highlight.on_yank(); check :help vim.hl on your version.)

User commands, Vim script and functions

LUA
vim.api.nvim_create_user_command("Trim", function()
  vim.cmd([[keeppatterns %s/\s\+$//e]])
end, { desc = "Trim trailing whitespace" })

vim.cmd("colorscheme habamax")            -- run any Ex command
local has_clip = vim.fn.has("clipboard")   -- call a Vim function
local cwd = vim.fn.getcwd()
local name = vim.fn.expand("%:t")          -- current file name only
vim.notify("loaded " .. name, vim.log.levels.INFO)

vim.cmd runs Ex commands (a multi-line [[ ... ]] string works). vim.fn.name(args) calls any Vim function. vim.api.nvim_* functions are Neovim's real API: nvim_buf_get_lines, nvim_get_current_buf, nvim_win_set_cursor, and so on, documented under :help api.

Structure the config

A single 500-line init.lua becomes hard to read. A common layout:

TEXT
~/.config/nvim/
├── init.lua
└── lua/
    ├── config/
    │   ├── options.lua
    │   ├── keymaps.lua
    │   └── autocmds.lua
    └── plugins/
        └── init.lua
LUA
-- init.lua
vim.g.mapleader = " "
vim.g.maplocalleader = ","
require("config.options")
require("config.keymaps")
require("config.autocmds")

Each file just runs its statements; since require caches, they execute once. Keep vim.g.mapleader at the very top. Add plugins in the next lesson.

JS Stand-in: a mini vim table that a config can talk to

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS Stand-in: check a config for a missing leader

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. Which call sets a Neovim option and supports :append for list options?

    vim.opt wraps options and gives list/set options :append, :prepend and :remove.
  2. 2. How is vim.keymap.set different from nmap?

    vim.keymap.set(mode, lhs, rhs, opts) maps non-recursively unless remap = true.
  3. 3. What is the purpose of { clear = true } in nvim_create_augroup?

    Clearing the group prevents duplicates when the config is sourced again.
  4. 4. Where must vim.g.mapleader be set?

    The leader is substituted when the keymap is created.

Summary

  • Configure the editor through the vim table: vim.opt, vim.g, vim.keymap.set, vim.api, vim.cmd and vim.fn.
  • vim.keymap.set takes mode(s), lhs, rhs (string or function) and an options table with desc.
  • Autocommands use nvim_create_augroup with clear = true and nvim_create_autocmd.
  • Split configuration into lua/config/*.lua files loaded by require.

Next: LSP, Tree-sitter and Plugin Managers

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.