Neovim in Cheatsheet
Quick reference for smart people — part of our dev cheatsheets collection.
Neovim is a hyperextensible text editor that keeps Vim's modal editing and Vimscript, and adds a Lua configuration API, a built-in LSP client, and treesitter.
New to modal editing? :Tutor is an interactive lesson that takes about half an hour.
Examples below assume Neovim 0.11 or newer. To find your config directory, run
:echo stdpath("config"): it is usually~/.config/nvimon Linux and macOS, and~/AppData/Local/nvimon Windows.
Basic example: init.lua
~/.config/nvim
├── init.lua
└── lua
├── config
│ └── lazy.lua
└── plugins
└── comment.lua
-- ~/.config/nvim/init.lua
vim.g.mapleader = " " -- <leader>; must be set before plugins load
vim.g.maplocalleader = "\\"
vim.opt.number = true -- absolute line numbers
vim.opt.relativenumber = true -- distances from the cursor line
vim.opt.expandtab = true -- Tab inserts spaces
vim.opt.shiftwidth = 2 -- one indent step
vim.opt.ignorecase = true -- search is case-insensitive ...
vim.opt.smartcase = true -- ... unless the pattern has capitals
vim.opt.scrolloff = 4 -- keep 4 lines above and below the cursor
vim.keymap.set("n", "<leader>w", "<cmd>w<cr>", { desc = "Save file" })
require("config.lazy") -- plugin manager, see #Plugins
A config does four things: set options, map keys, define autocommands, and load plugins.
Modes
| Mode | Enter with | Purpose |
|---|---|---|
| Normal | Esc |
move around, run operators and commands |
| Insert | i a I A o O |
type at the cursor, after it, at line start, at line end, in a new line below, in a new line above |
| Visual | v V Ctrl-v |
select by character, by line, by block |
| Replace | R |
overwrite characters |
| Command-line | : / ? |
Ex commands, search |
| Terminal | :terminal |
run a shell; i to type, Ctrl-\ Ctrl-n back to Normal
|
Operators, motions, text objects
A Normal-mode command reads as [count] operator motion: d2w deletes two words. A text object replaces the motion when prefixed with i (inner) or a (around).
| Operator | Effect |
|---|---|
d |
delete (cut) |
c |
change: delete, then Insert mode |
y |
yank (copy) |
p P |
paste after / before |
> < |
indent / dedent |
gu gU g~ |
lowercase, uppercase, toggle case |
gq |
format: rewrap text, or format through the LSP client |
= |
reindent |
| Motion | Moves |
|---|---|
w b e |
word forward, back, to its end (W B E: whitespace-delimited)
|
0 ^ $ |
column 0, first non-blank, end of line |
gg G |
first line, last line (42G: line 42)
|
f{c} t{c} |
to / until the next {c} on the line; F T backward, ; repeats
|
% |
the matching bracket |
{ } |
previous / next paragraph |
n N |
next / previous search match |
| Text object | Selects |
|---|---|
iw aw |
a word / a word and its whitespace |
i" a" |
inside / around quotes (' and ` too)
|
i( a( |
inside / around parentheses (ib; also [ { <)
|
it at |
inside / around an HTML or XML tag |
ip ap |
inside / around a paragraph |
ciw change the word under the cursor
di" delete everything inside the double quotes
da( delete the parentheses and their contents
yap copy the paragraph
>i{ indent the inside of the braces
gUiw uppercase the word
dG delete to the end of the file
Everyday edits
u undo; Ctrl-r redo
. repeat the last change
x delete the character under the cursor
J join the line below onto this one
yyp duplicate the current line
gg=G reindent the whole file
Registers and macros
"+y yank to the system clipboard
"ayy yank the line into register a
"ap paste register a
qa start recording a macro into register a
q stop recording
@a run macro a; @@ repeats it; 3@a runs it three times
Search and replace
/pattern search forward; n and N jump to the next and previous match
?pattern search backward
* search the word under the cursor
:nohlsearch clear the highlight until the next search
:s/old/new/ replace on the current line
:%s/old/new/g replace in the whole file
:%s/old/new/gc ... asking for confirmation each time
In Visual mode press
:to get the range for free: select lines, then:'<,'>s/old/new/greplaces inside the selection only.
Files, buffers, windows, tabs
:e file edit a file
:w / :wq write / write and quit
:q / :q! quit / quit and discard changes
:x write if changed, then quit
:e! reload the file, discarding changes
:bn / :bp next / previous buffer
:bd close the buffer
:ls list open buffers
:sp file split the window horizontally
:vs file split the window vertically
Ctrl-w h/j/k/l move to the window left, below, above, right
Ctrl-w q close the window
:tabnew / gt new tab / next tab (gT: previous)
:terminal terminal in a buffer
A buffer is not a window.
:qcloses a window and leaves the buffer loaded in memory;:bdunloads the buffer.Ctrl-oandCtrl-iwalk the jump list backwards and forwards.
Configuring in Lua
Options
| Form | Reaches |
|---|---|
vim.opt.number = true |
any option, converting Lua values to Vim types |
vim.o vim.bo vim.wo |
global, buffer-local, window-local raw access |
vim.g.mapleader = " " |
a global variable, here g:mapleader
|
vim.opt.listchars:append({ space = "·" }) |
add one entry to a comma-separated option |
vim.opt.colorcolumn = "80"
vim.opt.wrap = false
vim.o.scrolloff = 4 -- same as :set scrolloff=4
vim.wo.number = true -- window-local
vim.bo.commentstring = "// %s" -- buffer-local
Keymaps
vim.keymap.set("n", "<leader>w", "<cmd>w<cr>", { desc = "Save file" })
vim.keymap.set({ "n", "v" }, "<leader>y", '"+y', { desc = "Yank to clipboard" })
vim.keymap.set("i", "jk", "<Esc>", { desc = "Leave insert mode" })
vim.keymap.set("n", "]d", function() vim.diagnostic.jump({ count = 1 }) end,
{ desc = "Next diagnostic" })
vim.keymap.set("n", "<leader>f", vim.lsp.buf.format, { desc = "Format buffer" })
Modes are "n" normal, "i" insert, "v" visual and select, "x" visual only, "t" terminal, "" all of them.
vim.keymap.setdiffers from Vim's:mapin two ways: the mapping is silent by default, and{ remap = true }is needed for the right-hand side to expand other mappings. Prefer<cmd>...<cr>over:...<cr>: it does not switch modes and keeps the cursor put.
Autocommands and user commands
vim.api.nvim_create_autocmd("BufWritePre", {
group = vim.api.nvim_create_augroup("trim_whitespace", { clear = true }),
pattern = "*",
desc = "Strip trailing whitespace on save",
callback = function()
local view = vim.fn.winsaveview()
vim.cmd([[%s/\s\+$//e]])
vim.fn.winrestview(view) -- put the cursor back
end,
})
vim.api.nvim_create_user_command("Reload", function()
vim.cmd.source(vim.fn.stdpath("config") .. "/init.lua")
end, { desc = "Re-run init.lua" })
Plugins
lazy.nvim installs plugins, lazy-loads them by event, command or keymap, and keeps a lockfile of installed revisions.
-- ~/.config/nvim/lua/config/lazy.lua
local lazypath = vim.fn.stdpath("data") .. "/lazy/lazy.nvim"
if not (vim.uv or vim.loop).fs_stat(lazypath) then
vim.fn.system({ "git", "clone", "--filter=blob:none", "--branch=stable",
"https://github.com/folke/lazy.nvim.git", lazypath })
end
vim.opt.rtp:prepend(lazypath)
require("lazy").setup({ { import = "plugins" } }) -- every file under lua/plugins/
One file per plugin, each returning a spec:
-- ~/.config/nvim/lua/plugins/comment.lua
return {
"numToStr/Comment.nvim",
event = "VeryLazy", -- load after startup
opts = {}, -- runs require("Comment").setup({})
}
| Spec field | Effect |
|---|---|
opts = {} |
passed to the plugin's setup(); the module name is guessed from the repository name
|
config = function() ... end |
full control over setup; use instead of opts
|
cmd = "Mason" |
load when the command is first run |
keys = { ... } |
load when one of these mappings is first pressed |
event = "BufReadPre" |
load on an autocommand event, or on "VeryLazy"
|
ft = "python" |
load for a filetype |
dependencies = { ... } |
plugins to load with it |
enabled = false |
keep the spec, install nothing |
version branch tag |
pin a revision |
| Command | Effect |
|---|---|
:Lazy |
the UI: status, install, update, clean, log |
:Lazy update |
update every plugin |
:Lazy sync |
update, install missing plugins, clean removed ones |
:Lazy restore |
go back to the revisions recorded in the lockfile |
:Lazy profile |
startup time per plugin |
:checkhealth lazy |
diagnose the setup |
lazy-lock.jsonrecords the installed revision of every plugin: commit it to make your setup reproducible. Plugins land instdpath("data")/lazy, which is why the bootstrap builds the path withvim.fn.stdpath("data")instead of typing~/.local/share/nvim: the tilde is shell shorthand, not something Lua expands.
With that spec installed, Comment.nvim toggles comments:
| Key | Effect |
|---|---|
gcc |
toggle the current line |
gc{motion} |
toggle a motion: gcap, gcw, gc5j, gci{
|
gc (Visual) |
toggle the selection |
gco gcO |
add a comment below / above and enter Insert mode |
gcA |
add a comment at the end of the line |
gbc gb{motion} |
the same with block comments |
Built-in LSP
Neovim ships the LSP client; the servers themselves (lua-language-server, pyright, clangd, ...) are installed separately and must be on $PATH.
-- ~/.config/nvim/lua/config/lsp.lua
vim.lsp.config("luals", {
cmd = { "lua-language-server" },
filetypes = { "lua" },
root_markers = { ".luarc.json", ".luarc.jsonc", ".git" },
})
vim.lsp.enable("luals") -- start it for matching buffers
| Key | Effect |
|---|---|
K |
hover for the symbol under the cursor |
grn |
rename the symbol |
gra |
code action (Normal and Visual) |
grr |
references |
gri |
implementations |
gO |
document symbols |
Ctrl-s (Insert) |
signature help |
Ctrl-x Ctrl-o (Insert) |
LSP completion |
:checkhealth vim.lsp is a client attached to this buffer?
:lua =vim.lsp.get_clients() list the active clients
These mappings are bound even when no server is attached: pressing
grnin a buffer without a client reports that no matching language server was found. Diagnostics, on the other hand, have no default keys; bindvim.diagnostic.open_floatandvim.diagnostic.jumpyourself, as in Configuring in Lua.
Built-in commands worth knowing
:Tutor interactive Vim lesson
:help topic e.g. :help lua-guide, :help vim.keymap.set
:checkhealth diagnose config, plugins, LSP, treesitter
:Inspect highlight group and treesitter node under the cursor
:source $MYVIMRC re-run init.lua
:luafile % run the Lua file in the current buffer
:lua =vim.o.shiftwidth print a value
:set shiftwidth? print an option
:verbose set shiftwidth? ... and which file set it
:messages read past messages
:scriptnames files loaded at startup
For more
:help: the authoritative manual, available offline- Neovim user manual: the same text online
- Lua guide: porting a vimrc to init.lua
- LSP documentation: configs, attach handlers, diagnostics
- kickstart.nvim: a small, commented starting config to read
- lazy.nvim documentation: specs, lazy-loading, debugging
- Comment.nvim: the comment plugin used above