NAME

Vim – Programmer’s text editor.

DESCRIPTION

Vim is a text editor and extension of Vi installed by default on most operating systems. Unless otherwise specified, the keys listed below are for command mode. Command mode is the default state. Press the “i” key to enter insert mode. Press the “Esc” key to exit insert mode and go back into command mode.

COMMAND LINE OPTIONS

$ vim -d file1 file2
Compare the differences between two files.
$ vim -p file1 file2 ...
Open multiple files in tabs.
$ vim -R file
Open a file in read-only mode.
$ vim \grep -l pattern *.c``
Edit all C files that contain “pattern”.

SAVING AND EXITING

:w
Save file.
:wq and ZZ
Save file and quit.
:q
Quit buffer unless changes have been made.
:q! and ZQ.
Quit current buffer.
:qa
Exit Vim, unless changes have been made.
:qa!
Always exit Vim.

METACOMMANDS

Most commands can be prefixed by a number to specify the number of repetitions or location of the operation. For example, 3w moves forward three words.

The ESC key cancels most operations.

WRITING

i
Enter insert mode.
I
Enter insert mode at the first non-blank character of the line.
a
Insert after current selection.
A
Insert at the end of the current line.
o or O
Enter insert mode in the line below or above.
.
Repeat the previous command.

COPYING AND PASTING

Content is yanked using the “y” (yank) key. The “p” (paste) key pastes content in the current register.

What can be yanked: “p” (paragraph), “w” (word), “(“ or “)” (parenthesis), “{“ or “}” (curly brackets).

Y or yy
Yank current line.
ya<CHAR> or yi<CHAR>
Yank inside or around CHAR.
yf<CHAR> or yF<CHAR>
Yank everything up to, and including the next or previous occurrence of CHAR.
yt<CHAR> or yT<CHAR>
Yank up to next or previous occurrence of CHAR.
y)
Yank until end of sentence.
y0
Yank from the start of the line.
y$
Yank until the end of the line.
p or P
Paste after and under or before and above current line.
J
Join all selected lines on a single line. Use gJ to join lines by removing the new lines, but not replacing it with a whitespace.

REGISTERS

By default, Vim operations store the contents in the default register ". To specify a different register, type "[reg] before the operation.

Types of registers:

:registers and :reg
Show registers and their contents.
"[a-z]
Use register [a-z] for the next delete, yank, or put.
"[A-Z]
Append content of next delete, yank, or put to the corresponding lower-case version of the letter.

DELETION

Deletion is performed using the “d” (delete) or “c” (change) keys. The “c” key puts you into insert mode after a deletion.

CHAR examples: “p” (paragraph), “w” (word), “(“ or “)” (parenthesis), “{“ or “}” (curly brackets).

x and dl
Delete the single character under the cursor.
X and dh
Delete character to the left of the cursor.
da<CHAR> and di<CHAR> or ca[CHAR] and cai[CHAR]
Delete or change around and inside CHAR.
df<CHAR> and yf<CHAR> or dF<CHAR> and yF<CHAR>
Delete everything up to, and including the next or previous occurrence of CHAR.
dt<CHAR> and ct<CHAR> or dT<CHAR> and cT<CHAR>
Delete up to the next or previous occurrence of CHAR.
de
Delete until the end of the word.
db or dw
Delete to the previous word or until the next word.
daw or caw
Delete or change from start of current word until next word.
diw or ciw
Delete or change current word.
dis or cis
Delete or change inside of the sentence.
das or cas
Delete or change outside of sentence (includes whitespace and period).
dd or cc and S
Delete or change the current line.
dG
Delete until the end of the file.
dgg
Delete until the start of the file.
d) or c)
Delete or change to the end of the sentence.
D and d$ or C and c$
Delete or change to the end of the line.

REPLACING

r
Replace a single character.
R
Enter replace mode (overrides text as you write).
k
Move up a line.
j
Move down a line.
h
Move left one character.
l
Move right one character.
b
Move back one word.
B
Move back one white-space separated word.
w
Move forward one word.
W
Move forward one white-space separated word.
e
Move forward to the end of the next word.
E
Move forward to end of the next white-space separated word.
0
Move to the start of the line.
^
Move to the first non-blank character in the line.
$
Move to the end of the line.

STRUCTURE NAVIGATION

{ or }
Forward or back a paragraph.
( or )
Forward or back a sentence.
%
Go to the matching parentheses, bracket, or brace.
[<CHAR> or ]<CHAR>
Forward or back to nearest unmatched parentheses/bracket.
CTRL-f or CTRL-b
Page forward or back.
CTRL-u or CTRL-d
Scroll down or up half a screen of text.
CTRL-e or CTRL-y
Scroll down or up one line at a time.
zt or zz or zb
Move screen so that current cursor is in the top, middle, or bottom.

FILE NAVIGATION

gg and 1G
Go to the first line of the file.
G and 100%
Go to the last line of the file.
35G
Go to line number 35.
50%
Go to 50% down the file.
H
Move cursor to the first line on the screen.
M
Move cursor to the middle line on the screen.
L
Move cursor to the last line on the screen.
jj and \’`
Move cursor to position before jump.
\``
Move cursor to position of last jump.
\”`
Move cursor to position where you last edited the file.
\.`
Move cursor to position of the last change in this file.

MARKS

Marks are a way to specify locations in a file.

Possible values for <mark>:

:marks
Show active marks.
:delmarks <mark> and :delm <mark>
Delete specified mark.
:delmarks! and :delm!
Delete all [a-z] marks.
m<mark>
Mark position in local buffer (for lowercase letter) or global buffer (for uppercase letters).
\`
Go to the marked position in the current file (for lowercase letters) or any file (for uppercase letters).
'<mark>
Go to the first non-whitespace character of the marked line.

TEXT NAVIGATION

f<CHAR> or F<CHAR>
Move cursor to the next or previous occurrence of CHAR.
t<CHAR> or T<CHAR>
Move cursor before the next or after the previous occurrence of CHAR.
]s or [s
Next or previous misspelled word.

VISUAL

Enter visual mode using the “v” key. Visual mode is useful for cutting and pasting larger blocks of test.

v
Enter and exit visual selector mode.
V
Enter and exit visual selector mode in line-wise.
CTRL-v
Enter and exit visual selection of a rectangular block of text. Visual block commands: I insert at front of line, A insert at end of line, c delete from column to start of line and go into insert mode, C delete from column to end of line and go into insert mode. To execute the visual block commands, follow them with ESC.
gv
Reselect last visually selected area.
o
Move cursor to other end of the visual selector, allowing you change range selected from the other side. In rectangular block mode, o goes to the other diagonal, while O goes to the other corner in the same line.
:noh
Clear search highlighting.

CASING

~
Toggle the case of the current character.
u or U
Lower- or upper-case the visually selected text.
gu or gU or g~
Make word lower-case, upper-case, or switch case.
gugu or gUgU or g~g~
Make line lower-case, upper-case, or switch case.

INDENTATION

>> or <<
Indent or unindent current line based on shiftwidth option.
> or <
Indent or unindent selected lines based on shiftwidth option.
=
Auto-indent line. use gg=G to auto-indent all lines.

UNDO / REDO CHANGES

u
Undo most recent change.
CTRL-r
Redo most recent change.
:earlier or :later
Go back or forward in history.
:earlier 1f or :later 1f
Go back or forward to last file write.
:earlier 10s
Go back 10 seconds. Other time modifier abbreviations: s seconds, m minutes, d days.

MACROS / RECORDING

q[a-z]q
Start recording macro with name [a-z] and stop recording with q.
q[A-Z]
Append commands to macro in register [a-z].
@[a-z]
Replay macro with register name [a-z].
@@
Replay most recently replayed macro.

FILTERS

Vim allows you to run UNIX commands, through what are known as filters. Use ! to enter into filter mode, then type a UNIX command, followed by ENTER to execute the command on the range.

! or !!
Run filter on selected lines or current line. For example, !!date inserts the date on the current line.
:<RANGE>!
Run filter on the lines in the specified range.
!sort
Sort selected content.
!5G
Run filter from first line to fifth line. For example, !5Gsort sorts lines 1 through 5.
:0read !date -u
Read the date in UTC format into the top of the file.
:write !wc
Write the word count of the current file.

Forward-search for words using /[REGEX]. To backwards-search, prepend ?, ?[REGEX]. Navigate the search results using n and N.

Prepending the pattern with ? will execute a backwards-search.

/[REGEX]
Search for a word, pattern, or regular expression.
/\c[REGEX] or /\C[REGEX]
Make search case-insensitive or case-sensitive.
?[REGEX]
Backwards search for a word, pattern, or regular expression.
\* or #
Search forward or backward for the word under cursor.
n or N
Move to the next or previous occurrence of the searched word, depending on whether the search is forward or backward.

SUBSTITUTION

The default pattern for a search and replace is :[range]s/OLD/NEW/[flag], where [range] is the lines where the substitution will apply, OLD is the old pattern, and NEW is the pattern that will replace the OLD pattern. You can use a separator other than /, for example :s;old;new;g.

Flag values:

:%s/OLD/NEW/g
Replace all occurrences of “OLD” with “NEW”.
:s/\v or :s/\V
Enabled or disable “very magic” (all regex metacharacters).
:&&
Repeat last substitute.
:~
Repeat the last substitute, with the most recent search pattern.

GLOBAL

The global command is similar to the substitution command, but executes a command. The default pattern for a global command is :[range]g/OLD/[command].

:g/,/norm dd
Delete lines containing a comma.

OFFSETS

By default, a search will put your cursor over the matched pattern. Search offsets allow you to specify where to be placed after a search. The meaning of the search offsets change direction when you are using a backward search ? instead of a forward search /.

/the/2
Move two lines down from occurrences of “the”.
/the/b-1
Move cursor to one character before the matching pattern.
/the/e
Put the cursor on the last character of the pattern, in this case “e”.
/the/e+1
Move character to one character after the last character of pattern.
/
Repeat same search, with the same search offset.
//
Repeat the same search, resetting the search offset.

RANGES

Ranges allow you to specify to which lines a command will be applied. The syntax is :[range]<command>. For example, :[range]s/OLD/NEW/g or :[range]d.

These are the values for [range]:

OPTIONS

To reset an option value, append it with an appersand, for example: :set nowrap&.

:set
Show all modified options.
:set {option}
Set Boolean option.
:set no{option}
Reset boolean option.
:set {option}={value}
Set string or number option.
:set {option}+={value}
Append value to string option.
:set {option}-={value}
Remove value to string option.
:set {option}?
See value of option.
:set {option}&
Reset option to its default value.
:options
View available options.

OPTION EXAMPLES

:syntax on and :syntax enable
Turn on syntax highlighting.
:set syntax=LANG
Set syntax highlighting to LANG.
:set nu or :set number
Turn line numbering on.
:set nonu or set nonumber
Turn line numbering off.
:set hlsearch and :set hls or :set nohlsearch and :set nohls
Turn on or off search highlighting.
:nohlsearch and :nohls and :noh
Remove search highlighting.
:set incsearch
Turn on incremental searching.
:set colorcolumn or :set cc
Turn on colored column (:set cc= to turn off).
:set noexpandtab
Make Vim use tabs instead of spaces.
:%retab!
Convert spaces to tabs in the whole file.
:set textwidth=80
Set length of line to maximum of 80 characters.
:set ignorecase or :set noignorecase
Make search case-insensitive or case-sensitive.

FOLDING

Folding allows you to hide and show lines in a file. Folded sections can be nested.

zn or zN
Enabled or disable folding.
zi
Toggle between enabled and disabled folding.
zf
Fold current selected text.
zo
Reopen folded section.
zc
Close fold again.
zr
Open all folds.
zm
Close all folds.
zR
Open all levels of nested folds.
zM
Close all levels of nested folds.

SPELLING AND ABBREVIATIONS

Adding an i before the abbreviate makes the appreviation only apply to insert mode. Adding a c before the abbreviate makes the appreviation only apply to command-line mode. For example, :iabbrev ad advertisement and :iab ad advertisement would set an abbreviation that is only active in insert mode.

:abbreviate teh the
Set abbreviation.
:abbreviate
List current abbreviations.
:unabbreviate teh
Remove abbreviation.
:abclear
Clear all abbreviations.
:set spell [lang]
Turn on spell checking (:set nospell to turn off).
z=
View list of alternative of spellings.

SPECIAL CHARACTERS

CTRL-v <digit>
Insert ASCII character based on digit 0-255 (such as 9, 009) or hexadecimal (such as x7f).
CTRL-k <digraph>
Insert digraph. For example, CTRL-k Co inserts the copyright symbol.
:digraphs
List available digraphs, like Co.
:digraph a" ae
Define new digraph.

NUMBERS

CTRL-a or CTRL-x.
Add or subtract one to the selected numbers. Prefixing the command will increase the count. For example, 5 CTRL-a will add five to each number.
g CTRL-a or g CTRL-x
In a range of lines, increase or decrease each first number in a line by one.

TABS / FILE MANAGEMENT

:tabe [file]
Open a file in a new tab.
:gt / :tabn or :gT / :tabp
Go to next tab or previous in the buffer.
:tabm [index]
Move the current tab to the specified index.

OTHER COMMANDS

/[^\x00-\x7F]
Search for non-ASCII characters.
:put =range(0,10)
Insert 10 lines each containing an incremented number from 0 up to 10.
:sort and :sort!
Sort and inverse sort lines. Options: f (floating-point number sort), i (case-insensitive sort), n (numerical sort).
:his
View history of past commands.