Vim
Modes
i
goes into insert mode
Esc
goes back to command mode.
Commands
Saving and Exiting vim
ZZ
Save and exit vim
:w
Write the file to disk, stay in vim
:wq
Save the file and exit vim
:w !sudo tee %
Saves the file, even you don't have permission to write to the file (do this instead of closing the file, opening with sudo, and re-doing your changes)
:q</code Quit vim (Note: if you've made changes, you'll get a message that the file has changed. To quit without saving changes, use:
:q!
)
/string
search forward for string
?string
search backward for string
n
Repeat the last search forward (search forward in the document for the next occurrence of whatever you searched for last)
N
Repeat the last search backward (search backward in the document for the next occurrence of whatever you searched for last)
CTRL + f
scroll forward one screen
CTRL + b
scroll backword one screen
%
go to the "mate", if one exists, of the parenthesis, brace, or bracket.
zz
Scroll down the screen to make the current line appear in the middle.
line-numberG
Go to the specified line number.
``
(Type two back-ticks) Jump to where you last were in the document.
Manipulating Text
vim + linenumber
Open a file at the specified line number (Run from the command line, not from inside vim)
:set number
show line numbers
:set nonumber
hide line numbers.
:syntax on
turns on syntax color highlighting for code and HTML
Selecting Text
V
Select a whole line (Press an up or down arrow to select multiple lines.)
v</code Select a range of text.
CTRL + v
select a rectangular block
Undo / Redo
:earlier 15m
reverts the document to how it was 15 minutes ago. You can substitute any valid time instead of 15m.
u
undo the latest change
U
Undo all changes in the last modified line.
CTRL + R
Redo last change (undo the last undo... kinda...)
Deleting
d
Deletes the selected text (also the same as "cut", as in you can paste the deleted text)
de
does the same thing as diw, however, you can delete every next word by pressing the period key ( . )
dd
delete the entire current line
diw
delete the current word
di"
delete the text between the quotes
Cut, Copy, and Paste
y
Copies (yanks) the selected text.
yy
Copies the whole line
d
Deletes the selected text (also the same as the cut command in most other programs, as in you can paste the deleted text)
ciw
cuts the current word
ci"
cuts the word inside the quotes
C
cuts to the end of the line
P
Paste before the cursor
p
Paste after the cursor
Substitution
:s substitutes
Example:
:%s/something/something_else/g
This finds the word “something” and replaces it with “something_else” in the entire document.
:s/something/something_else/g
Does the same thing, but for only the current line
:%s/something/something_else/gc
Does the same thing as the first example, but asks for confirmation (that's what the “c” is there for.)
References
- vim man page
- Run
vimtutor
at the command line for an interactive vim tutorial