Skip to content

Neovim: the same keys, a config in Lua

NinjaLesson 57 of 669 min

What Neovim adds to Vim, and your first init.lua: options with vim.opt, a leader key and a keymap with vim.keymap.set, in a practice Neovim in your browser.

Neovim (nvim) started in 2014 as a fork of Vim. Everything you've learned so far works in it unchanged: the modes, motions, operators, registers, macros and windows. What's different is around the edges.

What Neovim adds

  • Config in Lua. ~/.config/nvim/init.lua instead of ~/.vimrc. Lua is a small, real programming language, so a config can have functions, loops and modules.
  • Better defaults. Search highlighting, autoindent, hidden buffers, a shorter Y (to the end of the line, like D and C) and more are on from the start.
  • A built-in language client (LSP). With a language server installed, you get go to definition, rename and errors as you type, as in an IDE.
  • Tree-sitter. Syntax highlighting from a real parser of the language, not patterns.
  • A big plugin world written in Lua, usually installed with a plugin manager such as lazy.nvim.

Your first init.lua

vim.opt.number = true               -- line numbers
vim.opt.relativenumber = true       -- count lines from the cursor, for 5j and 3dd
vim.g.mapleader = ' '               -- the leader key: space
vim.keymap.set('n', '<leader>w', ':w<CR>')   -- space then w saves

vim.opt sets options (the same ones :set does). vim.g.mapleader picks the leader, a key you press before your own shortcuts, so they don't clash with Vim's. vim.keymap.set(mode, keys, what) makes a mapping: 'n' for normal mode, 'i' for insert mode. Lines starting with -- are comments.

The folder doesn't exist yet, so make it first. You can write the file in nvim itself, or one line at a time from the shell:

mkdir -p ~/.config/nvim
echo "vim.opt.number = true" >> ~/.config/nvim/init.lua

Neovim reads init.lua when it starts. After editing it inside nvim, :source % applies it without restarting.

What this practice Neovim does

It's the practice Vim with Neovim's defaults, and it reads a small part of Lua: vim.opt.x = …, vim.o, vim.g, vim.keymap.set with keys as the right-hand side, vim.cmd('…') and local opt = vim.opt. When it opens it says what it set. Anything else (plugins, require, mappings to Lua functions, LSP, Tree-sitter, :terminal) isn't here, and it tells you so instead of failing quietly. On your own computer, install Neovim and the same init.lua works there.

Your turn

Write ~/.config/nvim/init.lua that turns on line numbers, makes space the leader and maps <leader>w to save. Then open todo.txt in nvim, add a line, and save it with space then w.

Next