Cheat Sheets

Vim Cheat Sheet: Modes, Motions, Macros and .vimrc (Free PDF)

Creating an empty ~/.vimrc makes Vim worse on Ubuntu. That sounds backwards, but the moment the file exists, Vim stops loading defaults.vim. Incremental search and the scroll margin you were used to just disappear. This Vim cheat sheet starts with that kind of thing in mind: the quick reference tables come first, then each group of commands gets a section that shows what actually happens on screen, including the parts that trip people up when they’re new to modal editing.

Original content from computingforgeeks.com - post 194268

You’ll find modes, motions, operators and text objects, search and replace, buffers and split windows, registers, macros and a small tested .vimrc, plus the three error messages almost everyone hits in their first week. I went through every command again on Ubuntu 26.04 with Vim 9.1.2141 and on Rocky Linux 10 with Vim 9.1.083 in November 2026, and they still hold. Where the two builds behave differently, the section says so.

Vim cheat sheet: the quick reference

Use these tables when you already know what you want to do and only need the keys. Everything here is typed in Normal mode unless the row starts with a colon, which means Command-line mode, so press Esc first if you’re not sure where you are. The sections further down show the commands running against a small config file, with the output you should expect. If you want the shell side of file work next to this, the Linux file management commands cheat sheet covers copying, moving and finding the files you’ll open here.

Modes

CommandWhat it does
i / aInsert before / after the cursor
I / AInsert at line start / line end
o / OOpen a new line below / above
vVisual mode, select characters
VVisual line mode, select whole lines
Ctrl+vVisual block mode, select a column
RReplace mode, overtype text
EscBack to Normal mode from anywhere
:Command-line mode for ex commands

Move the cursor

CommandWhat it does
h j k lLeft, down, up, right
w / b / eNext word, previous word, end of word
0 / ^ / $Line start, first non-blank, line end
gg / GFirst line / last line
10G or :10Jump to line 10
5jDown 5 lines (pairs well with relativenumber)
f= / ;Jump to the next = on the line / repeat
%Jump to the matching bracket
{ / }Previous / next blank-line paragraph
Ctrl+d / Ctrl+uHalf a page down / up

Edit with operators and text objects

CommandWhat it does
xDelete the character under the cursor
dd / 3ddDelete the line / three lines
dw / DDelete to next word / to end of line
ciwChange the word under the cursor
ci"Change everything inside the quotes
dapDelete a paragraph and its blank line
yy / yiwYank (copy) the line / the word
p / PPaste after / before the cursor
>> / <<Indent / unindent the line
JJoin the next line onto this one
~Toggle case of the character

Undo, redo and repeat

CommandWhat it does
uUndo the last change
Ctrl+rRedo
.Repeat the last change
:earlier 5mRewind the file to 5 minutes ago
:later 5mMove forward again

Search and replace

CommandWhat it does
/port / ?portSearch forward / backward
n / NNext / previous match
* / #Search the word under the cursor
:nohClear the search highlight
:%s/old/new/gReplace every match in the file
:%s/old/new/gcReplace, asking at each match
:3,9s/old/new/gReplace on lines 3 to 9 only
:g/^#/dDelete every line that matches
:v/port/dDelete every line that does not match
:sort uSort lines and drop duplicates

Buffers, windows and tabs

CommandWhat it does
:e hosts.txtOpen another file in a new buffer
:lsList open buffers
:bn / :bpNext / previous buffer
:b2 / :b#Buffer 2 / the alternate buffer
:bdClose the current buffer
:sp file / :vsp fileSplit horizontally / vertically
Ctrl+w wCycle through windows
Ctrl+w h/j/k/lMove to the window in that direction
:onlyClose every other window
:tabnew file / gtOpen a tab / go to next tab

Registers and clipboard

CommandWhat it does
"ayy / "apYank the line into register a / paste it
"AyyAppend the line to register a
"0pPaste the last yank, not the last delete
"_ddDelete without touching any register
:reg a 0 1Show what registers a, 0 and 1 hold
Ctrl+r aIn Insert mode, insert register a
"+yy / "+pSystem clipboard (needs +clipboard)

Macros and marks

CommandWhat it does
qq / qStart recording into q / stop
@q / @@Replay q / replay the last macro
4@qReplay q four times
:%normal @qRun macro q on every line
:2,4normal I# Insert “# ” (note the space) at the start of lines 2 to 4
ma / 'aSet mark a / jump back to its line
''Jump back to where you were

Save and quit

CommandWhat it does
:w / :w copy.confSave / save a copy under a new name
:wq or ZZSave and quit
:q!Quit and throw away changes
:qa!Quit every window without saving
:e!Reload the file from disk
:w !sudo tee % > /dev/nullSave a root-owned file you opened as a user
vim +10 app.confOpen a file at line 10

Settings you toggle often

CommandWhat it does
:set number relativenumberLine numbers, relative to the cursor
:set hlsearch incsearchHighlight matches, search as you type
:set ignorecase smartcaseCase-insensitive unless you type capitals
:set expandtab shiftwidth=4Spaces instead of tabs, 4 per indent
:set listShow tabs and line ends
:verbose set shiftwidth?Show a value and the file that set it
:help :sOpen the manual on a topic

Check which Vim you have

Before anything else, find out which build you’re running, because two details change how this whole sheet behaves for you: the patch level and whether clipboard support was compiled in. On the Ubuntu box the full vim package was already installed, while on Rocky Linux a minimal install ships vim-minimal, which is what answers when you type vi. Install the full editor if you don’t have it yet.

On Ubuntu or Debian:

sudo apt install -y vim

On Rocky Linux, AlmaLinux or RHEL, the package you want is vim-enhanced:

sudo dnf install -y vim-enhanced

Now ask Vim what it is and which features it has. The second command picks out the handful of feature flags that matter for everyday editing:

vim --version | head -n 4
vim --version | grep -o -E '[+-](clipboard|xterm_clipboard|python3|syntax|terminal|vim9script)'

This is Ubuntu 26.04. The interesting line is -clipboard: the stray +clipboard further down is really +clipboard_provider, which the short pattern cuts off, so don’t let it fool you.

vim --version output on Ubuntu 26.04 showing Vim 9.1 with patches up to 2141 and -clipboard

Rocky Linux 10 reports the same 9.1 release, but look at the patch line: 1 to 83, against 2141 on Ubuntu. That’s roughly two years of upstream fixes Rocky’s build doesn’t carry, which matters if you copy a plugin or a newer option from someone’s dotfiles and it errors out. You’ll also notice /usr/bin/vi is its own binary here, the small vim-minimal build, so vi and vim are not the same editor on this system.

vim --version on Rocky Linux 10 showing patches 1-83, -clipboard and the vim-enhanced, vim-minimal and vim-common packages

Neither build has clipboard support, and that’s normal for terminal Vim from a distro’s base package. Keep it in mind for the registers and .vimrc sections below. And when you’re brand new, run vimtutor once: it ships with Vim on both distros and takes about half an hour.

Switch modes without getting stuck

Vim opens in Normal mode, where every key is a command, and that’s the part that trips people up on day one. You type a sentence, and Vim deletes lines and jumps around instead. Nothing is broken. You only need to know which mode you’re in and how to get back. The last line of the screen shows -- INSERT --, -- VISUAL -- or -- VISUAL LINE --, and nothing at all in Normal mode.

  • You can enter Insert mode with i, a or o.
  • You can leave any mode with Esc, and a second press does no harm.
  • You can select text with v or V, then press d to delete it.
  • You can type an ex command after : and run it with Enter.

Here V plus 2j selected three lines under [server], starting with a timeout = 30 line typed a moment earlier in Insert mode. The 3 in the bottom right corner is Vim counting the selected lines for you, which is handy when you want to check a selection before you delete it.

Vim Visual Line mode with three lines of app.conf selected and the line count shown in the status line

From there, > indents all three lines, d deletes them and y copies them. If you change your mind, Esc drops the selection and leaves the text alone.

Edit faster with operators and motions

Vim’s editing commands are a small grammar rather than a long list to memorise. An operator says what to do (d delete, c change, y yank, > indent), and a motion or text object says how much. So dw deletes to the next word, d$ deletes to the end of the line, ci" changes what’s inside the quotes, and y} copies to the end of the paragraph. Once you know eight operators and a dozen motions, you have a few hundred commands without learning any of them separately.

Counts slot in front: 3dd deletes three lines, 5j moves down five. Relative line numbers make counts easy to read off the screen, because every line shows its distance from the cursor. In this capture a /localhost search left the cursor on line 3, which shows its real number, while every other line shows how far away it is. The bind line reads 2, so 2j lands on it and d2j would delete from here down to it.

Vim with number and relativenumber set and every match of a search highlighted by hlsearch in app.conf

The highlighted matches come from hlsearch, which stays on until you clear it with :noh. The . key is the other half of this grammar: it repeats your last change, so you can fix one line with ciw, jump to the next match with n, and press . to make the same edit there.

Replace text across a whole file

Substitution has the shape :[range]s/pattern/replacement/flags. The range % means the whole file, g replaces every match on a line instead of only the first, and c asks before each change. Every count below comes from the same 17-line app.conf used in the screenshots, so save this into ~/demo/app.conf if you want your numbers to match.

# demo application config
[server]
host = localhost
port = 8080
bind = localhost
debug = true

[database]
host = localhost
port = 5432
name = appdb
debug = true

[cache]
upstream = localhost
port = 8080
debug = true

Open it and run :%s/localhost/127.0.0.1/gc, and Vim stops on each match with this question.

replace with 127.0.0.1 (y/n/a/q/l/^E/^Y)?

Press y or n per match, a to accept the rest, or q to stop. After a, the status line reports the count, which is your quick check that the pattern hit what you expected and nothing more:

Vim status line reporting 4 substitutions on 4 lines after replacing localhost with 127.0.0.1

You can also run ex commands straight from the shell. It’s a nice way to test a pattern on a copy before you touch the real file. -Nu NONE skips every config file and -es runs Vim silently without a screen:

cp app.conf t1.conf; vim -Nu NONE -es -c '%s/localhost/127.0.0.1/g' -c 'wq' t1.conf; grep -c 127.0.0.1 t1.conf; grep -c localhost app.conf

Four lines changed in the copy, matching the four lines that held localhost in the original:

4
4

The global command :g/pattern/command runs a command on every matching line. :g/^#/d strips comment lines, and pairing it with normal lets you run any Normal mode keys on the matches:

cp app.conf t2.conf; vim -Nu NONE -es -c 'g/^#/d' -c 'wq' t2.conf; wc -l app.conf t2.conf
cp app.conf t2b.conf; vim -Nu NONE -es -c 'g/debug/normal dd' -c 'wq' t2b.conf; wc -l t2b.conf; grep -c debug t2b.conf

The comment line went (17 lines down to 16), and the second run removed all three debug lines:

 17 app.conf
 16 t2.conf
 33 total
14 t2b.conf
0

For anything with groups, the very magic flag \v saves you from escaping every bracket. This one swaps the key and value on the database port line only, and diff proves nothing else moved:

cp app.conf t5.conf; vim -Nu NONE -es -c 'g/^port = 5432/s/\v^(\w+) \= (\w+)$/\2 = \1/' -c 'wq' t5.conf; diff app.conf t5.conf

One line changed, exactly as intended:

10c10
< port = 5432
---
> 5432 = port

Notice the = is escaped as \= inside the very magic pattern. In \v mode a bare = means “optional”, the same as ?, so leaving it unescaped would match lines you never meant to touch. When the search side gets this fiddly, it often helps to build the pattern with grep and its regex flavours first, then carry it into Vim.

Open several files with buffers and splits

A buffer is a file Vim has loaded, a window is a view onto a buffer, and a tab is a layout of windows. You don’t need tabs to work on several files. Open a second file with :e ~/demo/hosts.txt, and the first one stays loaded in the background. :ls lists them:

Output of the Vim :ls command on Rocky Linux 10 listing app.conf and hosts.txt buffers

Read the flags like this: %a is the buffer in the current window and active, # is the alternate buffer you can flip to with :b# or Ctrl+^, and the line number is where the cursor was last. If Vim refuses to switch buffers with E37, the current one has unsaved changes. The set hidden line in the .vimrc further down lets you switch anyway and keeps the changes in memory.

To see two files at once, split the window. :sp file stacks them, :vsp file puts them side by side, and Ctrl+w followed by h, j, k or l moves you between them. In this capture :sp ~/demo/hosts.txt opened the host list above app.conf, and :vsplit then split that top window in two, so the same buffer shows side by side:

Vim with app.conf and hosts.txt open in horizontal and vertical split windows on Ubuntu 26.04

Each window has its own status line with the file name and cursor position. Two windows on one buffer is more useful than it looks. You can keep a section header in view on one side while you edit further down on the other. :only closes every window but the current one, and the buffers stay loaded, so nothing is lost.

Use registers instead of losing your yank

Here’s a classic first-week moment: you yank a line, delete something else, press p, and the deleted text comes back instead of what you copied. That’s because every delete also goes into the unnamed register "", which p pastes from. Your yank is still safe in register 0, so "0p gets it back.

To see it for yourself, copy the first line with yy, move down with j and delete the [server] line with dd, yank the word host into register a with "ayiw, and then run :reg a 0 1 ". This is what came back in the lab.

Vim :reg output showing the unnamed register, register 0, register 1 and named register a

Register 0 still holds the comment line from the first yy, the deleted [server] line went to 1, and the unnamed register follows whatever you used last, here a. The Type column says whether a register holds characters (c) or whole lines (l), and that decides how it pastes: a line register always pastes on a new line, a character register pastes inside the current one. Numbered registers 1 to 9 keep a history of larger deletes, so "1p brings back the last deleted line even after a few small edits, and the delete before it moves to "2.

  • You can append to register a with "Ayy and paste the block once.
  • You can delete a line without touching any register with "_dd.
  • You can’t use "+ on either build out of the box, because both report -clipboard.

On a desktop where you really want the system clipboard, install a build with it compiled in (on Ubuntu the vim-gtk3 package provides one) and check vim --version again for +clipboard before you add any clipboard setting.

Save keystrokes as a macro and replay them

A macro is just keystrokes saved into a register. You record once with q plus a register name, do the edit on one line, stop with q, and replay it with @. The file below lists hosts as name IP, and the goal is to flip every line to IP name, the order /etc/hosts wants:

web01 10.0.1.11
web02 10.0.1.12
db01 10.0.1.21
db02 10.0.1.22
cache01 10.0.1.31
lb01 10.0.1.5

With the cursor on line 1, type these keys exactly. The status line shows recording @q while you’re in the middle of it.

qq              start recording into register q
0dwA <Esc>pxj   0 = line start, dw = delete "web01 " (name and space), A<space><Esc> = append a space at the end, p = paste the name after it, x = drop the trailing space, j = next line
q               stop recording
@q              run on line 2
4@@             repeat the last macro four more times (lines 3 to 6)

Every line flipped, including lb01, whose shorter IP didn’t matter because the macro moves by words rather than columns:

hosts.txt in Vim after the macro ran, with every line reordered to IP address followed by hostname

Two habits make macros reliable. Start each one with 0 or ^ so it doesn’t depend on where the cursor happened to be, and end with j so a count runs it down the file. You can skip the counting entirely with :%normal @q, which runs the macro once on every line. This shell version stores the same keys in register q (without the j, because :normal moves line by line for you) and gives the same result:

cp hosts.txt t3.txt; vim -Nu NONE -es -c 'let @q="0dwA \<Esc>px"' -c '%normal @q' -c 'wq' t3.txt; cat t3.txt

The output matches the interactive run line for line:

10.0.1.11 web01
10.0.1.12 web02
10.0.1.21 db01
10.0.1.22 db02
10.0.1.31 cache01
10.0.1.5 lb01

For one-off edits you don’t even need a register. :2,4normal I# (with a trailing space after the hash) comments out lines 2 to 4, and :%normal A; adds a semicolon to the end of every line. Both ran cleanly on the two distros.

Start from a minimal .vimrc

When there’s no ~/.vimrc, Vim loads its own defaults.vim, which turns on incremental search, a five-line scroll margin and a few other friendly settings. As soon as a ~/.vimrc exists, even an empty one, Vim skips defaults.vim completely. The Vim startup documentation describes this, but it’s easy to miss until your search suddenly stops jumping as you type.

You can check it by listing the loaded scripts and a few option values, first without a vimrc and then after touch ~/.vimrc. On Ubuntu, defaults.vim disappears from the list, incsearch turns into noincsearch and scrolloff drops from 5 to 0.

Vim scriptnames on Ubuntu 26.04 showing defaults.vim loaded without a vimrc and gone after touch ~/.vimrc, with incsearch and scrolloff reset

Rocky Linux hides the same trap. Its /etc/vimrc sets scrolloff=5, incsearch and hlsearch itself, so after touch ~/.vimrc the values look unchanged even though defaults.vim is no longer loaded. Copy that empty file to an Ubuntu machine and the behaviour changes. The two systems reported these values:

SettingUbuntu, no vimrcUbuntu, empty vimrcRocky, no vimrcRocky, empty vimrc
defaults.vim loadedYesNoYesNo
incsearchonoffonon (from /etc/vimrc)
scrolloff5055 (from /etc/vimrc)
hlsearchoffoffonon (from /etc/vimrc)

So load defaults.vim yourself on the first lines of your vimrc, then add your own settings on top. Create the file.

vim ~/.vimrc

Paste in this minimal config, the exact file tested on both distros.

" ~/.vimrc
unlet! skip_defaults_vim
source $VIMRUNTIME/defaults.vim

set number relativenumber
set expandtab shiftwidth=4 softtabstop=4
set ignorecase smartcase
set hlsearch incsearch
set hidden
set splitbelow splitright
set undofile
set undodir=~/.vim/undo//
set clipboard=unnamedplus
let mapleader = " "
nnoremap <leader>w :w<CR>
nnoremap <leader><space> :nohlsearch<CR>
filetype plugin indent on
syntax on

The undofile line needs its directory to exist, otherwise Vim has nowhere to write undo history and quietly keeps none:

mkdir -p ~/.vim/undo

Every line is optional, so drop the ones you don’t want. Once the file is saved, check that:

  • You still have incremental search, because the first two lines load defaults.vim.
  • You see relative line numbers and get four spaces when you press Tab.
  • You can switch buffers with unsaved changes, thanks to hidden.
  • You can undo after reopening a file, because undofile saves history in ~/.vim/undo/.
  • You can save with Space w and clear highlights with Space Space.

To confirm every line took effect, ask Vim where an option was last set. :verbose set names the file and line, which is the fastest way to find out whether your vimrc or a system file won:

Vim verbose set output showing expandtab, shiftwidth, undofile and clipboard last set from ~/.vimrc with line numbers

The undo history worked on both systems. After deleting a line, saving, quitting and reopening the file, pressing u brought the line back and printed 1 more line; before #1 8 seconds ago. The clipboard=unnamedplus line is the one that does nothing here, and it’s worth keeping only if you install a build with +clipboard. On Ubuntu, :verbose set shows it as set, but yanks never reach the system clipboard. On Rocky, the option isn’t supported at all and Vim ignores the line at startup without an error. Your vimrc loads cleanly either way, which you can check with vim -es -u ~/.vimrc -c 'qa!'; echo exit=$?: both distros printed exit=0.

If you’d like a fuller setup with plugins and a colour scheme after this, the guide to install and configure Vim on Linux builds from the same starting point.

Get past the errors you’ll hit first

Each of these was triggered on purpose in the lab, so the heading is the exact text Vim prints. If you see one of them, that’s normal, and none of them means your file is damaged.

E45: ‘readonly’ option is set (add ! to override)

You opened a file your user can’t write, here /etc/hosts as a normal user, made a change and tried :w. Vim opened it read-only (the status line said [readonly] when the file loaded) and refuses to save:

Vim showing E45 readonly option is set after trying to save /etc/hosts as a regular user

Adding ! won’t help, because the operating system still says no. Pick one of these instead:

  • You can quit with :q! and reopen the file with sudoedit /etc/hosts.
  • You can keep your edits and write them through sudo from inside Vim.

The first is cleaner. The second saves retyping when you’ve already made a dozen changes:

:w !sudo tee % > /dev/null

It works, but Vim then notices the file changed underneath it and asks what to do. This prompt appeared right after the write.

W12: Warning: File "/etc/hosts" has changed and the buffer was changed in Vim as well
See ":help W12" for more info.
[O]K, (L)oad File, Load File (a)nd Options:

Press L to load the file you just wrote, then quit with :q. If you hit Enter (OK) by reflex, the buffer still counts as modified and :q answers with E37; the file on disk is already saved, so :q! is safe. Check the result from the shell with tail -n 2 /etc/hosts before you trust it, because a typo in a system file is the kind of thing you want to catch right away.

E37: No write since last change (add ! to override)

You typed :q or :e otherfile with unsaved changes. Vim is protecting your work. Choose :wq to keep the changes, :q! to throw them away, or :e! to reload the file from disk and start over. If it happens every time you switch buffers, add set hidden to your vimrc as shown above.

W24: Clipboard register not available. See :h W24

You tried "+yy on Ubuntu’s vim package, which is built with -clipboard. Vim prints the warning and the yank goes nowhere. On Rocky Linux you don’t even get that warning. "+yy leaves the register empty, and asking for the option with :set clipboard? returns E519: Option not supported: clipboard?. You need a build with clipboard support (check vim --version for +clipboard), or select the text with the mouse and copy it with your terminal’s own shortcut, usually Ctrl+Shift+c.

Once these keys feel normal, Vim becomes the editor you reach for on every remote box. The SSH commands cheat sheet pairs well with it for getting there. On a fresh Rocky or Alma server, installing vim-enhanced is one of the first items in the things to do after installing Rocky Linux, and every printable sheet in this format, including the systemctl commands cheat sheet, lives on the cheat sheets hub.

Print it, keep it next to your keyboard, and pick one new row a day. You don’t have to learn all of it at once: ciw, . and :%s alone will change how fast you edit config files within a week.

Keep reading

Claude Code Cheat Sheet: Commands, Shortcuts and Flags (PDF) AI Claude Code Cheat Sheet: Commands, Shortcuts and Flags (PDF) OpenAI Codex CLI Cheat Sheet: Shortcuts, Commands, Flags (PDF) AI OpenAI Codex CLI Cheat Sheet: Shortcuts, Commands, Flags (PDF) Linux and DevOps Cheat Sheets (Free PDF Pack) Cheat Sheets Linux and DevOps Cheat Sheets (Free PDF Pack) netsh Commands Cheat Sheet: Wi-Fi, Firewall, Port Proxy (PDF) Cheat Sheets netsh Commands Cheat Sheet: Wi-Fi, Firewall, Port Proxy (PDF) VS Code Keyboard Shortcuts Cheat Sheet (Windows, Mac, Linux PDF) Cheat Sheets VS Code Keyboard Shortcuts Cheat Sheet (Windows, Mac, Linux PDF) RPM Cheat Sheet: rpm Query, Verify, Install Commands (PDF) Cheat Sheets RPM Cheat Sheet: rpm Query, Verify, Install Commands (PDF)

Leave a Comment

Press ESC to close