Vim CHEAT SHEET

A useful collection of Vim 8.2 quick reference cheat sheets to help you learn vim editor faster.

vitexteditorterminalshortcut
9
Sections
48
Cards

#Getting Started

Motion Diagrams
▼/▶ Cursor   ▽/▷ Target

Left-right motions

┌───────────── |
├───────────── 0      $ ──────────────┐
│  ┌────────── ^      fe ────────┐    │
│  │  ┌─────── Fo     te ───────┐│    │
│  │  │┌────── To     30| ───┐  ││    │
│  │  ││ ┌──── ge     w ───┐ │  ││    │
│  │  ││ │ ┌── b      e ─┐ │ │  ││    │
│  │  ││ │ │  ┌h      l┐ │ │ │  ││    │
▽  ▽  ▽▽ ▽ ▽  ▽▼      ▼▽ ▽ ▽ ▽  ▽▽    ▽
   echo "A cheatsheet from quickref.me"

Up-down motions

                 - SCREEN 1 START
   ┌─┬─────────▷ #!/usr/bin/python
   │ │     ┌───▷
   │ │     │     print("Hello")
   │ │     { } ▶ print("Vim")
   │ │       │   print("!")
   │ │       └─▷
   │ │ ┌───┬───▷ print("Welcome")
G gg H M L k j ▶ print("to")
│        │   └─▷ print("cheatsheets.zip")
│        │       print("/vim")
│        │
│        └─────▷
│                - SCREEN 1 END
└──────────────▷ print("SCREEN 2")
Motions
ShortcutDescription
h | j | k | lArrow keys
<C-u> / <C-d>Half-page up/down
<C-b> / <C-f>Page up/down

{.shortcuts}

Words{.left-text}

ShortcutDescription
b / wPrevious/Next word
ge / ePrevious/Next end of word

{.shortcuts}

Line

ShortcutDescription
0 (zero) / $Start/End of line
^Start of line (non-blank)

{.shortcuts}

Character

ShortcutDescription
Fe / feMove to previous/next e
To / toMove before/after previous/next o
|/ n|Go to first/nth column

{.shortcuts}

Document

ShortcutDescription
gg / GFirst/Last line
:n | nGGo to line n
} / {Next/Previous empty line

{.shortcuts}

Window

ShortcutDescription
H / M / LTop/Middle/Bottom screen
zt / zz / zbTop/Center/Bottom this line

{.shortcuts}

Insert Mode
ShortcutDescription
i / aInsert before/after cursor
I / AInsert start/end of line
o / O (letter)Insert new line below/above
s / SDelete char/line and insert
C / ccChange to end of/current line
giInsert at last insert point
Esc | <C-[>Exit insert mode

{.shortcuts}

Saving and Exiting
ShortcutDescription
:wSave
:qClose file
:wq | :x | ZZSave and quit
:wqaSave and quit all files
:q! | ZQForce quit
:qaClose all files
:qa!Force quit all files
:w now.txtWrite to now.txt
:sav new.txtSave and edit new.txt
:w !sudo tee %Write to readonly file

{.shortcuts}

Normal Mode
ShortcutDescription
rReplace one character
REnter Replace mode
u / 3uUndo changes 1 / 3 times
UUndo changes on one line
JJoin with next line
<C-r> / 5 <C-r>Redo changes 1 / 5 times

{.shortcuts}

Cut and paste
ShortcutDescription
xDelete character (Cut)
p / PPaste after/before
xpSwap two characters
DDelete to end of line (Cut)
dwDelete word (Cut)
ddDelete line (Cut)
ddpSwap two lines
yyYank line (Copy)
"*p | "+pPaste from system clipboard
"*y | "+yPaste to system clipboard

{.shortcuts}

In visual mode

ShortcutDescription
d | xDelete selection (Cut)
sReplace selection
yYank selection (Copy)

{.shortcuts}

Repeating
ShortcutDescription
.Repeat last command
;Repeat latest f, t, F or T
,Repeat latest f, t, F or T reversed
&Repeat last :s
@:Repeat a command-line command

{.shortcuts}

Visual mode
ShortcutDescription
vEnter visual mode
VEnter visual line mode
<C-v>Enter visual block mode
ggVGSelect all text
> / <Shift text right/left

{.shortcuts}

Macros
--
qiRecord macro i
qStop recording macro
@iRun macro i
7@iRun macro i 7 times
@@Repeat last macro

{.shortcuts}

You can save macro for any letters not just i

#Vim Operators

Usage
ShortcutDescription
dw
OperatorMotion

Combine operators with motions to use them

Available Operators
ShortcutDescription
dDelete
yYank (copy)
cChange (delete then insert)
pPaste
=Formats code
g~Toggle case
gUUppercase
guLowercase
>Indent right
<Indent left
!Filter through external program
Examples
CombinationDescription
ddDelete current line
djDelete two lines
dwDelete to next word
dbDelete to beginning of word
dfaDelete until a char
d/helloDelete until hello
ccChange current line, synonym with S
yyCopy current line
>jIndent 2 lines
ggdGDelete a complete document
gg=GIndent a complete document
ggyGCopy a whole document

{.show-header}

Counts
[count] <operator> <motion>
<operator> [count] <motion>

CombinationDescription
2ddDelete 2 lines
6yyCopy 6 lines
d3wDelete 3 words
d5jDelete 5 lines downwards
>4kIndent 4 lines upwards

#Vim Text objects

Usage
ShortcutDescription-
vi / ap
Operatorinner / aroundText object

Operate with an operator inner or around text blocks

Text objects
ShortcutDescription
pParagraph
wWord
WWORD
(surrounded by whitespace)
sSentence
[ ( { <A , (), or {} block
] ) } >A , (), or {} block
' " `A quoted string
bA block [(
BA block in [{
tA HTML tag block

See :help text-objects

Delete
ShortcutDescription
diwDelete inner word
disDelete inner sentence
di"Delete in quotes
da"Delete in quotes (including quotes)
dipDelete a paragraph
Selections
Misc
ShortcutDescription
ciwChange inner word
ci"Change inner quotes
citChange inner tags (HTML)
cipChange inner paragraph
yipYank inner paragraph
yapYank paragraph (including newline)

#Vim Multiple files

Buffers
--
:e fileEdit a file in a new buffer
:bnGo to the next buffer
:bpGo to the previous buffer
:bdRemove file from buffer list
:b 5Open buffer #5
:b fileGo to a buffer by file
:lsList all open buffers
:sp fileOpen and split window
:vs fileOpen and vertically split window
:hidHide this buffer
:wnWrite file and move to next
:tab baEdit all buffers as tabs
Windows
--
<C-w> sSplit window
<C-w> vSplit window vertically
<C-w> wSwitch windows
<C-w> qQuit a window
<C-w> TBreak out into a new tab
<C-w> xSwap current with next
<C-w> - / +Decrease/Increase height
<C-w> < / >Decrease/Increase width
<C-w> |Max out the width
<C-w> _Max out the height
<C-w> =Equally high and wide
<C-w> h / lGo to the left/right window
<C-w> j / kGo to the up/down window

{.shortcuts}

Tabs
ShortcutDescription
:tabe [file]Edit file in a new tab
:tabf [file]Open if exists in new tab
:tabcClose current tab
:taboClose other tabs
:tabsList all tabs
:tabrGo to first tab
:tablGo to last tab
:tabm 0Move to position 0
:tabnGo to next tab
:tabpGo to previous tab

Normal mode

ShortcutDescription
gtGo to next tab
gTGo to previous tab
2gtGo to tab number 2

{.shortcuts}

#Vim Search and Replace

Search
--
/fooSearch forward
/foo\cSearch forward (case insensitive)
?fooSearch backward
/\v\d+Search with regex
nNext matching search pattern
NPrevious match
*Search for current word forward
#Search for current word backward

{.shortcuts}

Replace LINE
:[range]s/{pattern}/{str}/[flags]

:s/old/newReplace first
:s/old/new/gReplace all
:s/\vold/new/gReplace all with regex
:s/old/new/gcreplace all (Confirm)
:s/old/new/iIgnore case replace first
:2,6s/old/new/gReplace between lines 2-6
Replace FILE
:%s/{pattern}/{str}/[flags]

:%s/old/newReplace first
:%s/old/new/gReplace all
:%s/old/new/gcReplace all (Confirm)
:%s/old/new/giReplace all (ignore case)
:%s/\vold/new/gReplace all with regex
Ranges
--
%Entire file
’<,’>Current selection
5Line 5
5,10Lines 5 to 10
$Last line
2,$Lines 2 to Last
.Current line
,3Next 3 lines
-3,Forward 3 lines
Global command
:[range]g/{pattern}/[command]

:g/foo/dDelete lines containing foo
:g!/foo/dDelete lines not containing foo
:g/^\s*$/dDelete all blank lines
:g/foo/t$Copy lines containing foo to EOF
:g/foo/m$Move lines containing foo to EOF
:g/^/m0Reverse a file
:g/^/t.Duplicate every line
Inverse :g
:[range]v/{pattern}/[command]

:v/foo/dDelete lines not containing foo
(also :g!/foo/d)
Flags
--
gReplace all occurrences
iIgnore case
IDon't ignore case
cConfirm each substitution
Substitute expression (magic)
--
& | \0Replace with the whole matched
\1...\9Replace with the group 0-9
\uUppercase next letter
\UUppercase following characters
\lLowercase next letter
\LLowercase following characters
\eEnd of \u, \U, \l and \L
\EEnd of \u, \U, \l and \L
Examples
:s/a\|b/xxx\0xxx/g               # Modifies "a b"      to "xxxaxxx xxxbxxx"
:s/test/\U& file/                # Modifies "test"     to "TEST FILE"
:s/\(test\)/\U\1\e file/         # Modifies "test"     to "TEST file"
:s/\v([abc])([efg])/\2\1/g       # Modifies "af fa bg" to "fa fa gb"
:s/\v\w+/\u\0/g                  # Modifies "bla bla"  to "Bla Bla"
:s/\v([ab])|([cd])/\1x/g         # Modifies "a b c d"  to "ax bx x x"
:%s/.*/\L&/                      # Modifies "HTML"     to "html"
:s/\v<(.)(\w*)/\u\1\L\2/g        # Make every first letter of a word uppercase
:%s/^\(.*\)\n\1/\1/              # Remove duplicate lines
:%s/<\/\=\(\w\+\)\>/\U&/g        # Convert HTML-Tags to uppercase
:g/^pattern/s/$/mytext           # Find and append text to the end
:g/pattern/norm! @i              # Run a macro on matching lines
/^\(.*\)\(\r\?\n\1\)\+$          # View the duplicates lines
/\v^(.*)(\r?\n\1)+$              # View the duplicates lines (very magic)
:v/./,/./-j                      # Compress blank lines into a blank line
:g/<p1>/,/<p2>/d                 # Delete inclusively from <p1> to <p2>

#Vimdiff

Usage

$ vimdiff file1 file2 [file3]
$ vim -d file1 file2 [file3]
Editing
:[range]diffget [bufspec]
:[range]diffput [bufspec]

ShortcutDescription
do / :diffgetObtain (get) difference
dp / :diffputPut difference
:difRe-scan differences
:diffoSwitch off diff mode
:1,$+1diffgetGet all differences
ZQQuit without changes

{.shortcuts}

See: Ranges

Folds
ShortcutDescription
zo / zOOpen
zc / zCClose
za / zAToggle
zvOpen folds for this line
zMClose all
zROpen all
zmFold more (foldlevel += 1)
zrFold less (foldlevel -= 1)
zxUpdate folds

{.shortcuts}

Jumping

ShortcutDescription
]cNext difference
[cPrevious difference

{.shortcuts}

#Quickfix List (Advanced)

Usage

The Quickfix List is primarily used to navigate a list of errors/warnings (or file locations) generated by a compiler or linter.

ShortcutDescription
:copenOpen the quickfix window
:ccloseClose the quickfix window
:cnextGo to the next error/location (:cn also works)
:cpreviousGo to the previous error/location (:cp also works)
:clistList all errors/locations in the list
:cf [file]Populate the list with errors from a file (e.g., a compiler log)

Quickfix Do (`:cdo` and `:cfdo`)

The :cdo (quickfix do) and :cfdo (quickfix file do) commands execute a command in every file listed in the quickfix list. :cdo iterates over every location in the list, while :cfdo iterates over every unique file in the list.

CommandDescription
:cdo [cmd]Execute [cmd] for every location in the quickfix list.
:cfdo [cmd]Execute [cmd] for every unique file in the quickfix list.

#Miscellaneous

Case
ShortcutDescription
vUUppercase character
vuLowercase character
~Toggle case character
viw UUppercase word
viw uLowercase word
viw ~Toggle case word
VU / gUUUppercase line
Vu / guuLowercase line
V~ / g~~Toggle case line
gggUGUppercase all text
ggguGLowercase all text
ggg~GToggle case all text

{.shortcuts}

Jumping
ShortcutDescription
<C-o>Go back to previous
<C-i>Go forward
gfGo to file in cursor
gaDisplay hex, ascii value

{.shortcuts}

Misc command-lines
--
:hHelp open help view
:edit!Reload current file
:2,8m0Move lines 2-8 to 0
:nohClear search highlights
:sortSort lines
:terOpen a terminal window
:set pasteEnable Insert Paste sub-mode
:set nopastedisable Insert Paste sub-mode
:cqExiting with an error
(aborting Git)
Navigating
ShortcutDescription
%Nearest/matching {[()]}
[( | [{Previous ( or {
]) | ]{Next ) or }
[mPrevious method start
[MPrevious method end

{.shortcuts}

Counters
ShortcutDescription
<C-a>Increase number
<C-x>Decrease number

{.shortcuts}

Tags
ShortcutDescription
:tag ClassnameJump to first definition of Classname
<C-]>Jump to definition
g]See all definitions
<C-t>Go back to last tag
<C-o> <C-i>Back/forward
:tselect ClassnameFind definitions of Classname
:tjump ClassnameFind definitions of Classname (auto-select 1st)

{.shortcuts}

Formatting
--
:ce 8Center lines between 8 columns
:ri 4Right-align lines at 4 columns
:leLeft-align lines

See :help formatting

Marks
ShortcutDescription
`^Last position of cursor in insert mode
`.Last change in current buffer
`"Last exited current buffer
`0In last file edited
''Back to line in current buffer where jumped from
``Back to position in current buffer where jumped from
`[To beginning of previously changed or yanked text
`]To end of previously changed or yanked text
`<To beginning of last visual selection
`>To end of last visual selection
maMark this cursor position as a
`aJump to the cursor position a
'aJump to the beginning of the line with position a
d'aDelete from current line to line of mark a
d`aDelete from current position to position of mark a
c'aChange text from current line to line of a
y`aYank text from current position to position of a
:marksList all current marks
:delm aDelete mark a
:delm a-dDelete marks a, b, c, d
:delm abcDelete marks a, b, c

{.shortcuts}

Calculator
ShortcutDescription
<C-r> = 7*7Shows the result
<C-r> = 10/2Shows the result

{.shortcuts}

Do this in INSERT mode

Shell
--
:!<shell>Interpret Shell Command
:r!<shell>Read in output of shell
:r!dateInsert date
:!!dateReplace current line with date
Command line
ShortcutDescription
<C-r><C-w>Insert current word into the command line
<C-r>"Paste from " register
<C-x><C-f>Auto-completion of path in insert mode

{.shortcuts}

Tricks

Remove duplicate lines

:sort | %!uniq -u

To number the lines in the file

:%!cat -n

Copy whole doc to clipboard

:%w !pbcopy            # Mac OS X
:%w !xclip -i -sel c   # GNU/Linux
:%w !xsel -i -b        # GNU/Linux

#Also see