Vim cheat sheet
The Vim keys and Ex commands you need on a server and at your desk, from getting out of the editor to macros, splits and search and replace, checked on Vim 9.1 with notes where Neovim differs.
171 entries12 sectionsChecked on Vim 9.1, Neovim 0.11Reviewed
Keys are written as Vim's own help writes them: <C-w> is Ctrl+W, <Esc> is Escape and <CR> is Enter. A line that starts with : is an Ex command: type it in Normal mode and press Enter. Most Normal mode commands take a count in front, so 3dd deletes three lines. Names such as file.txt and old are examples. Everything here works the same in Neovim unless a note says otherwise.
Modes and getting out
Enter Insert and Visual mode, get back to Normal, save and quit.
Vim opens in Normal mode, where keys are commands. You type text in Insert mode, select in Visual mode, and
<Esc>always takes you back to Normal.<Esc>Go back to Normal mode from Insert, Visual or a half-typed command.
Tip:
<C-[>sends the same key, and is easier to reach on many keyboards.iInsert before the cursor.
aAppend after the cursor.
IInsert at the first non-blank character of the line.
AAppend at the end of the line.
o OOpen a new line below the cursor, or above it, and start Insert mode there.
s SDelete the character under the cursor, or the whole line's text, and start Insert mode.
v V <C-v>Start Visual mode, selecting by character, by line or by block. The Visual mode section has what to do next.
:wWrite the file, keeping it open.
:qQuit the window. Vim refuses with
E37while the buffer has unsaved changes.:wqWrite the file and quit.
:xWrite the file only if it changed, then quit: the file's modification time stays as it was when nothing changed.
Tip:
ZZin Normal mode does the same.:q!Quit and throw away every unsaved change.
Tip:
ZQin Normal mode does the same.:qaQuit every window.
:qa!quits even with unsaved changes,:wqawrites them all first.
Moving around
Move by character, word, line, screen and file without the arrow keys.
h j k lMove left, down, up and right by one character or line. A count moves further:
5jgoes five lines down.w b eMove to the start of the next word, back to the start of a word, or to the end of a word. A word stops at punctuation.
W B EThe same moves by WORD: anything between spaces, so
Wcrossesuser@host:/pathin one go.0 ^ $Go to the first column of the line, its first non-blank character, or its end.
gg GGo to the first line or the last line of the file.
42GGo to line 42.
:42does the same.fx txJump to the next
xon the line, or to just before it.FandTsearch backwards.Tip:
;repeats the lastf,t,ForT, and,repeats it the other way.%Jump to the bracket that matches the one under the cursor:
(),[]or{}.{ }Move to the previous or the next blank line: back or on by a paragraph.
<C-d> <C-u>Scroll half a screen down or up, taking the cursor with it.
<C-f> <C-b>Scroll a whole screen forward or back.
H M LMove the cursor to the top, the middle or the bottom line of the screen.
zz zt zbScroll so the cursor's line is in the middle, at the top or at the bottom of the screen, leaving the cursor where it is.
gj gkMove down or up by a line as it is shown on the screen, when a long line wraps.
Editing
Delete, change, copy, paste, undo and repeat, with an operator and a motion.
An operator takes a motion:
ddeletes,cchanges andyyanks (copies) whatever the motion covers, sodwdeletes to the next word andy$copies to the end of the line.xDelete the character under the cursor.
rxReplace the character under the cursor with
x, staying in Normal mode.RStart Replace mode: what you type overwrites the text until
<Esc>.ddDelete the whole line.
3dddeletes three lines.DDelete from the cursor to the end of the line, the same as
d$.ccChange the whole line: delete its text, keep its indent, and start Insert mode.
CChange from the cursor to the end of the line, the same as
c$.cwChange to the end of the word and start Insert mode.
yyYank (copy) the whole line.
5yycopies five lines.p PPut (paste) what was deleted or yanked after the cursor, or before it. A whole line goes below or above the current one.
uUndo the last change.
3uundoes three.<C-r>Redo what was undone.
.Repeat the last change, at the cursor:
dwthen.deletes the next word as well.JJoin the line below onto this one, with a space between.
gJjoins without adding the space.~Switch the case of the character under the cursor and move on.
guiw gUiwMake the word under the cursor lower case or upper case.
guandgUtake any motion.>> <<Indent the line or take one level of indent off, by
shiftwidth.<C-a> <C-x>Add one to the number under or after the cursor, or take one off.
10<C-a>adds ten.xpSwap the character under the cursor with the next one, to fix a typo such as
teh.ddpSwap the line with the one below it.
Text objects
Act on a word, a sentence, a quoted string or a bracketed block wherever the cursor is in it.
After an operator or in Visual mode,
itakes the inside of an object andatakes it with its surroundings:ci"changes inside the quotes,da"deletes the quotes too.ciwChange the word under the cursor, wherever the cursor is in it.
dawDelete the word under the cursor and the space after it.
ci"Change the text inside the double quotes on the line.
ci'and `ci`` do the same for other quotes.Tip: The cursor need not be inside the quotes: Vim takes the next quoted string on the line.
ci(Change everything inside the parentheses around the cursor.
ci)andcibare the same.da[Delete the square brackets around the cursor and what is in them.
di{Delete what is inside the braces around the cursor, such as a function's body.
diBis the same.citChange the text inside the HTML or XML tag around the cursor.
datdeletes the tag as well.yipYank the paragraph around the cursor: the lines up to a blank line on each side.
dasDelete the sentence around the cursor and the space after it.
vi{Select the inside of a block in Visual mode. Pressing
i{again widens it to the block around that one.
Visual mode
Select characters, lines or a block, then act on the selection.
vSelect by character. Move to widen the selection, then press an operator such as
d,y,cor>.VSelect whole lines.
<C-v>Select a rectangular block of columns.
Tip: In a terminal where
<C-v>pastes, as Windows Terminal does by default,<C-q>starts block selection instead.oMove the cursor to the other end of the selection, to widen it from that side.
gvSelect again what was selected last.
<C-v>jjjI# <Esc>Put
#at the start of four lines at once: select a column, insert withI, and the text appears on every line after<Esc>.Tip:
Ainstead ofIappends after the block;$Aappends at the end of each line, however long.Vjj>Indent three lines. Then
.indents them again, orgv>reselects and indents.:'<,'>What Vim types when you press
:with a selection: the command that follows runs on the selected lines only, such as:'<,'>s/a/b/g.VyCopy the current line in Visual line mode, the same text as
yy.vU vuMake the selection upper case or lower case.
~switches its case.
Search and replace
Find text, substitute across a file and run a command on every matching line.
/patternSearch forward for a pattern.
?patternsearches backward.n NGo to the next match, or to the previous one, in the direction of the last search.
* #Search forward or backward for the whole word under the cursor.
:nohClear the highlighting of the last search until the next one. It does not turn
hlsearchoff.:s/old/new/Replace the first
oldon the current line withnew. Addgto replace every one on the line.:%s/old/new/gReplace every
oldin the file withnew.%is every line.:%s/old/new/gcReplace every
oldin the file, asking before each one:yto replace,nto skip,afor all the rest,qto stop.:5,20s/old/new/gReplace on lines 5 to 20 only.
.,$is from the current line to the end.:%s#/usr/local#/opt#gUse another delimiter than
/when the text has slashes in it, such as a path.:%s/\v(\w+) (\w+)/\2 \1/Swap two words on each line:
\vmakes(,)and+special without a backslash, and\1and\2are the groups.:%s/\s\+$//eRemove spaces and tabs at the end of every line.
ekeeps quiet when there are none.:%s//new/gReplace the last pattern you searched for: an empty pattern is the last search, so
*then this replaces the word under the cursor.:g/pattern/dDelete every line that matches the pattern.
:gruns any Ex command on each matching line.:v/pattern/dDelete every line that does not match the pattern, keeping only the matches.
:g!is the same.:set ignorecase smartcaseSearch without case, unless the pattern has a capital letter in it.
/\<word\>Search for
wordas a whole word only, not insidepassword.&Repeat the last
:son the current line.g&repeats it on every line.
Registers and macros
Named places to copy into, the system clipboard, and keystrokes recorded to replay.
A register is named by
"and a letter before a command:"ayyyanks intoa,"apputs from it. Without one, Vim uses the unnamed register"."ayyYank the line into register
a."AyyAppend the line to register
a, keeping what was there: a capital letter appends."apPut the contents of register
aafter the cursor."+yYank into the system clipboard, in Visual mode or with a motion.
"+ppastes from it.Warning: Needs a Vim built with
+clipboard: check:echo has('clipboard'). Neovim needs a clipboard tool such aswl-copy,xcliporpbcopy."0pPut the last thing you yanked, even after a delete has replaced the unnamed register.
"_dDelete into the black hole register, so what you yanked before stays in the unnamed register.
:regList the registers and what is in each.
:reg ashows onlya.<C-r>aIn Insert mode or on the command line, insert the contents of register
a.<C-r>"inserts the last yank or delete.qaStart recording keystrokes into register
a.qagain stops the recording.@aReplay the macro in register
a.@@replays the last one played.10@aReplay the macro ten times. It stops early at the first command that fails, such as a search with no match.
:%norm @aRun the macro once on every line of the file.
:'<,'>norm @aruns it on the selected lines.:%norm A;Run Normal mode keys on every line: here, append
;to each one.
Marks and jumps
Remember a place in a file and get back to where you were.
maSet mark
aat the cursor. A lower-case mark belongs to its file; a capital one, such asmA, works across files.`aJump to mark
a, at its line and column.'aJump to the first non-blank character of mark
a's line.d'aDelete from the current line to the line of mark
a. Any operator takes a mark as its motion.:marksList the marks, with each one's line, column and text.
<C-o> <C-i>Go back to where the cursor was before a jump, such as
G, a search or%, and forward again.``Jump back to where the cursor was before the last jump, and again to return.
`.Jump to where the last change was made.
giGo to where you last left Insert mode and start Insert mode there.
g; g,Go back and forward through the places where changes were made.
:jumpsList the jump list that
<C-o>and<C-i>move through.
Buffers, windows and tabs
Several files open at once, side by side or one at a time.
A buffer is a file loaded in memory, a window is a view of a buffer, and a tab page holds a layout of windows. Several windows can show one buffer.
:e file.txtOpen a file in the current window.
:ealone reloads the file from disk;:e!throws away the changes first.:lsList the open buffers with their numbers.
%marks the current one and#the one before it.:b 3Switch to buffer 3.
:b partswitches to the one whose name matches, and Tab completes it.:bn :bpSwitch to the next or the previous buffer.
<C-^>Switch to the buffer you were in before, and back.
:bdUnload the current buffer and close its window.
:sp file.txtSplit the window in two, one above the other, with a file in the new one.
<C-w>ssplits on the same file.:vs file.txtSplit the window side by side.
<C-w>vsplits on the same file.<C-w>h <C-w>j <C-w>k <C-w>lMove to the window to the left, below, above or to the right.
<C-w>wgoes to the next one.<C-w>=Make every window the same size.
<C-w>_ <C-w>|Make the window as tall, or as wide, as it can be.
<C-w>oClose every window but this one.
:onlyis the same.<C-w>qClose the current window.
<C-w>ccloses it unless it is the last.:tabnew file.txtOpen a file in a new tab page.
gt gTGo to the next or the previous tab page.
3gtgoes to the third.:tabcloseClose the current tab page and its windows.
:bufdo %s/old/new/ge | updateReplace in every open buffer and write each one that changed.
:windoand:tabdodo the same for windows and tabs.
Files and the shell
Open, read and write files, and send text through shell commands.
vim +42 file.txtOpen a file at line 42.
vim +/pattern file.txtopens it at the first match.vim -R file.txtOpen a file read-only.
view file.txtdoes the same.vim -d old.conf new.confShow two files side by side with their differences marked.
vimdiffis the same.Tip:
]cand[cjump to the next and previous change;dotakes the other side's version,dpgives yours to it.command | vim -Read a command's output into a new buffer, to read or edit it.
vimtutorStart the built-in lesson, about half an hour, on a copy of its file. In Neovim it is
:Tutor.:w other.txtWrite the buffer to another file, staying on the one you have open.
:sav other.txtwrites and switches to it.:10,20w part.txtWrite lines 10 to 20 to a file of their own.
:r file.txtRead a file in below the cursor's line.
:r !dateRead a shell command's output in below the cursor's line.
:!lsRun a shell command and show its output, then press Enter to return.
%stands for the file's name, as in:!python3 %.:%!jq .Send the whole buffer through a command and replace it with the output: here, format JSON with
jq.uundoes it.!ipsortSend the paragraph through
sortand replace it with the result.!takes a motion and fills in:.,.+N!for you.:w !sudo tee % > /dev/nullWrite a file you opened without the rights to, through
sudo, then answerLto load it again.Warning: Fails in Neovim, which gives
sudono terminal to ask for a password. Save elsewhere with:w /tmp/fileand move it withsudo mv.gfOpen the file whose path is under the cursor.
<C-w>fopens it in a new window.:ExBrowse the current file's directory with netrw: Enter opens,
-goes up,%makes a file,da directory.:e %:h/other.txtOpen a file in the same directory as the current one:
%:his the current file's directory.:set ff=unixChange the line endings to Unix ones on the next write, to remove the
^Mof a file made on Windows.
Settings and vimrc
Options for the session, and the file that sets them every time.
:set number relativenumberShow line numbers: the current line's own number, and the distance to every other line, for counts such as
5j.:set nonumberTurn a setting off with
noin front.:set number!switches it.:set expandtab tabstop=4 shiftwidth=4Indent with four spaces: Tab types spaces, a tab shows as four columns and
>>moves by four.:retabTurn the file's tabs into spaces, or the other way, to match
expandtabandtabstop.:set listShow tabs and the end of each line, to find stray whitespace.
:set listchars=tab:>-,trail:.picks the marks.:set wrap!Switch the wrapping of long lines on or off.
:set pasteTurn off auto-indent and mappings while you paste into a terminal Vim, then
:set nopaste.Tip: Rarely needed now: Vim 8 and later understand bracketed paste from most terminals. Neovim handles pastes itself and marks the option as deprecated.
:set filetype?Show a setting's value: a
?after its name.:set filetype=yamlchanges how the buffer is highlighted and indented.:syntax onTurn syntax highlighting on, which most distributions' default vimrc already does.
:help :sOpen Vim's help on a command.
:help i_<C-r>is a key in Insert mode,:help 'tabstop'an option.:source ~/.vimrcRead the vimrc again without restarting Vim.
:so %reads the file you are editing.~/.vimrc
set nocompatible filetype plugin indent on syntax on set number relativenumber set expandtab tabstop=4 shiftwidth=4 softtabstop=4 set ignorecase smartcase incsearch hlsearch set backspace=indent,eol,start set cursorline scrolloff=5 set undofile undodir=~/.vim/undo// let mapleader = " " nnoremap <leader>h :nohlsearch<CR> autocmd FileType yaml setlocal tabstop=2 shiftwidth=2 softtabstop=2A small vimrc for working on servers: numbers, spaces for indent, case-aware search and a visible cursor line.
Tip: Neovim reads
~/.config/nvim/init.vimorinit.luainstead, and already setsnocompatible,hlsearch,incsearchandbackspacelike this.Warning: Make
~/.vim/undofirst, withmkdir -p ~/.vim/undo: Vim does not create it.
Pitfalls
What goes wrong, what it looks like, and how to get out of it.
The terminal stops answering: keys do nothing and the screen does not change.
Fix:
<C-s>froze the terminal's output, an old flow control the shell kept. Press<C-q>to let it go on.stty -ixonin your shell's rc file turns it off for good.The screen shows
Entering Ex mode. Type "visual" to go to Normal mode.and every key waits for Enter.Fix:
QorgQstarted Ex mode. Typevisualand press Enter to get back to Normal mode.Opening a file shows
E325: ATTENTIONandFound a swap file by the name ".file.txt.swp".Fix: Another Vim has the file open, or one ended without closing it. If none is running, press
rto recover, write, then delete the.swpfile; oreto edit anyway,qto give up.Pasted text ends up indented further on each line, like a staircase, or comment marks repeat down the block.
Fix: Auto-indent acted on every pasted line. Paste with
"+pfrom the clipboard instead of the terminal, or:set pastebefore and:set nopasteafter.:wanswersE45: 'readonly' option is set (add ! to override)orE212: Can't open file for writing.Fix:
E45is a file opened read-only::w!writes it if you own it.E212is a file you have no right to write::w !sudo tee % > /dev/nullin Vim, or write it to/tmpand move it withsudo.recording @qshows at the bottom of the screen, and keys seem to be stored somewhere.Fix:
qfollowed by a letter started recording a macro. Pressqagain to stop. Nothing changed in the file because of it.:qanswersE37: No write since last change (add ! to override).Fix: The buffer has changes you have not saved.
:wqkeeps them,:q!throws them away.:qaanswersE162for the same reason in another buffer.A search or
:sfor a path or an address matches the wrong text, or none:/1.2.3.4matches1a2b3c4.Fix:
.,*,[and~mean something in a pattern, and/ends it. Escape them with a backslash,/1\.2\.3\.4, or start the pattern with\Vfor very nomagic:/\V1.2.3.4.A Makefile answers
missing separator, or YAML refuses a file that looks indented right.Fix:
expandtabturned the Makefile's tab into spaces, or a tab got into YAML.:set listshows them. A Makefile needs:setlocal noexpandtaband:retab!; YAML needs spaces only.Backspace does not delete past the point where Insert mode started, or across the start of a line.
Fix:
backspaceis empty, as in Vim's old default. Addset backspace=indent,eol,startto your vimrc; Neovim and Vim'sdefaults.vimalready set it.A file made on Windows shows
^Mat the end of each line.Fix: Vim read it as Unix with carriage returns left in.
:e ++ff=dosreads it again as DOS, then:set ff=unixand:wwrite it with Unix endings.