You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Nearly all commands can be preceded by a number for a repeat count. eg. 5dd delete 5 lines.
The escape key gets you out of any mode and back to command mode.
Commands preceded by : are executed on the command line at the bottom of the screen.
:help CmdName
Help with any command
:h CmdName
:help shorthand
Navigation
Use h j k l for cursor movement:
h
Move left
j
Move down
k
Move up
l
Move right
Many terminals also support arrow keys for movement
On gvim, can also use Ctrl+left and Ctrl+right
By character
fx
To next occurrence of x to the right (allows [a-zA-Z0-9])
Fx
To next occurrence of x to the left
4fx
To 4th occurrence of x to the right
3Fx
To 3rd occurrence of x to the left
tx
Till before next occurrence of x to the right
Tx
Till before next occurrence of x to the left
4tr
Go to the 4th r to the right
;
Repeat the latest f or t [count] times (on the same line)
,
Repeat the latest f or t [count] times in the opposite direction (on the same line)
%
To matching marker, one of ([{}]) or /* */ or #if #endif
[(
Go to previous unmatched (
[{
Go to previous unmatched {
](
Go to next unmatched (
]{
Go to next unmatched }
By words
w
Next word (by punctuation)
W
Next word (by spaces)
b
Back word (by punctuation)
B
Back word (by spaces)
e
End word (by punctuation)
E
End word (by spaces)
ge
Backward to the end of the word
gE
Backward to the end of the Word
By line
0
Start of line
^
First non-whitespace
$
End of line
By paragraph
{
Previous blank line
}
Next blank line
By sentence
(
Previous sentence
)
Next sentence
By file
gg
Start of file
G
End of file
123G
Go to line 123
50%
Go to 50% point
512go
Go to byte 512
g <Ctrl+g>
View current position in status line
In Visual mode, shows the size of the block
By marker
mx
Set a mark named x
'x
Go to mark named
'.
Go to position of last edit
' '
Go back to last point before jump (two apostrophes, no space)
=== By edit history ===
{| class="wikitable"
|-
| <code><CTRL+o>
Go to [count] Older cursor position in jump list
<CTRL+i>
Go to [count] Newer cursor position in jump list
:ju[mps]
Print the jump list
g;
Go to [count] older cursor position in change list
g,
Go to [count] newer cursor position in change list
:changes
View changes
Scrolling
<CTRL+f>
Forward full screen
<CTRL+b>
Backward full screen
<CTRL+d>
Down half screen
<CTRL+u>
Up half screen
<CTRL+e>
Scroll one line up
<CTRL+y>
Scroll one line down (not on Windows if Ctrl+y is redo)
zz
Center the cursor line
H
Top of screen
L
Bottom of screen
<CTRL+l>
Redraw the screen
Editing
u
Undo
<CTRL+r>
Redo
.
Repeat last editing command
<CTRL+g> u
While in insert mode, marks a new undo point
:earlier 2m
Undo back to the state 2 minutes ago
:later 2m
Redo forward in time (2 minutes)
g-
Previous text state
g+
Next text state
wundo {file}
Write undo history to a file
rundo {file}
Read undo history from a file
<CTRL+o>
While in insert mode, switches to normal mode for a single command, then back to insert mode
Inserting
All insertion commands are terminated with to return to command mode.
i
Insert text at cursor
10i
Repeat whatever is typed next 10 times. Insert 10 spaces with: 10i space
I
Insert text at start of line
a
Append text after cursor
A
Append text after end of line
o
Open new line below
O
Open new line above
<Shift+Enter>
Command defined in .vimrc to insert a blank line above the cursor
Enable with: map <S-Enter> O<ESC>
Changing
Changing means to delete the character, word, line, etc. and enter Insert mode.
The deleted item does get placed into the paste buffer
r
Replace single character. In visual mode, replace highlighted text with the character.
15rx
Change 15 characters to x, starting at the cursor
R
Replace multiple characters as you type
s
Change (substitute) single character (stays in insert mode)
S
Change whole line (delete the line and enter insert mode)
c
In visual mode, change (replace) the highlighted text (using insert mode)
cw
Change (replace) word
C
Change to end of line
c$
Change to end of line
c<motion>
Changes text in the direction of the motion
c^
Change to beginning of line
cc
Change whole line (delete the line and enter insert mode)
ci(
Change inside parentheses
ca(
Change around parentheses (delete text within the parentheses, then enter insert mode)
ci<
Change inside < and >
ci{
Change inside { and }
ci[
Change inside [and]
ciw
Change inside word (replace the word)
ct<letter>
Change to letter: change from current character to the next occurrence of the letter
Deleting
Deleting deletes the item, but does not enter insert mode
The deleted item does get placed into the paste buffer
x
Delete single char
20x
Delete 20 characters
dw
Delete word
D
Delete to end of line
d$
Delete to end of line
dd
Delete whole line
d<motion>
Deletes in the direction of the motion, e.g. d$ or d0
In visual mode, d deletes the current selection
d0
Delete to start of line
d^
Delete to start of line
d4j
Delete from here through 4 lines down
di(
Delete inside parentheses
da(
Delete around parentheses (delete all text within the parentheses and remove them)
di<
Delete inside < and >
di{
Delete inside { and }
di[
Delete inside [and]
diw
Delete inside word
dis
Delete inside sentence
dip
Delete inside paragraph
dt<letter>
Delete to letter: delete from current character to the next occurrence of the letter
Cut and paste (put)
yy
Copy line into paste buffer
y$
Copy from character to the end of the line
yi"
Yank inside " and "
yi<
Yank inside < and >
dd
Cut line into paste buffer
dw
Cut word into paste buffer
p
Paste buffer below cursor line
P
Paste buffer above cursor line
xp
Swap two characters (x to delete one character, then p to put it back after the cursor position)
"4p
Paste from register 4 (auto-populated with recent cut/copy operations)
"bp
Paste from register b
Registers
Registers allow you to store the next delete, yank, or put operation in a variable
Use a combination of {a-zA-Z0-9.%#:-"} to control how data is stored in the register
" means to use a register
0-9
Registers 0-9 hold the most recent delete / yank contents
They are auto-populated
a-z and A-Z are named registers
Only populate when " is explicitly used
Use A-Z to append the operation to the register
* and + are the GUI clipboard
:reg[isters]
Show all registers
:reg 1a
Show registers 1 and a
"byy
Copy the entire line into register b
"bY
Sorting
:[range]sor[t]
Sort lines in [range]. If no range, sort all lines
:1,50sort
Sort lines 1 to 50
:1,50sort!
Reverse sort lines 1 to 50
:1,50sort i
Ignore case
:1,50sort n
Sort by number
:1,50sort u
Remove duplicates (u for unique)
:10,$sort
Sort from line 10 to the end
:.,$sort
Sort from the current line to the end
:.+1,$sort
Sort from the next line to the end
:sort /{pattern}/
Begin sorting after the match to a pattern
:sort /.*\%10v/
Sort starting at virtual column 10
:sort /.\{-}\ze\d/ n
Sort on the first number (the \ze flag means to end the match while \d is a digit)
:sort /\a\a\a/ r
Only use the first three letters to sort (\a is a character class)
Optionally use visual mode to select a range of rows to sort.
Case
~
Change case of single character
15~
Change the case of 15 characters
g~<motion>
Swap case in the specified direction
g~~
Swap case of every character in the line
gu<motion>
Make lowercase
gU<motion>
Make uppercase
20g~l
Swap case of 20 characters to the right
20g~h
Swap case of 20 characters to the left
15gUl
Make this line and the next 15 characters uppercase to the right
5gUj
Make this line and the next 5 lines uppercase
Vu
Make this line lowercase (use Capital V)
VU
Make this line uppercase (use Capital V)
Macros
qa
Start recording macro a
q
Stop recording
@a
Playback macro a
@@
Playback the most recent macro
5@@
Playback the most recent macro 5 times
qaq
Erase a macro (start a recording of macro a, then stop it)
To edit a macro, paste it into a new buffer, then update the register:
:new
Create a new buffer
"xp
Paste register x into the buffer
Edit the keystrokes
<Esc>
Return to normal mode
0"xy$
Go to beginning of line; into register x, yank to end of line
:bd!
Delete the new buffer without saving (same as :q!)
@x
Execute modified recording
Blocks (Visual Mode)
Note: in gvim, visual mode is exited if you use arrow keys; you must use: h j k l
Or, with mswin enabled, just use shift+arrow as works in other windows programs
To select a block with the mouse use Alt+LeftClick
v
Visual block stream
vE
Visual block one word
V
Visual block line
<CTRL+v>
Visual block column
Alternatively, Q when CTRL+v is mapped to paste
Defined in .vimrc with: nnoremap Q
Alternatively, use Alt+LeftClick
<CTRL+g>
Toggle between visual mode and select mode
Use motion commands to extend the block to the new cursor position.
These include h j k l plus:
w
Select the next word and any space following
W
Select the next word and any space or punctuation following
e
Select to the end of the next word
E
Select to the end of the next word, plus any punctuation following
b
Select the previous word
B
Select the previous word, skipping over punctuation
o
Moves the cursor to the other end of the block
d or x
Cut block into paste buffer
y
Copy block into paste buffer
c
Change text (cut into paste buffer then enter Insert mode)
s
Same as c
rx
Replace the selected text with x
>
Indent block
<
Unindent block
~
Change case
vEU
Change word to uppercase
vEu
Change word to lowercase
gv
Reselect last visual block
I
Visual Block insert mode; typed text will appear at the start of each line
A
Visual Block append mode; typed text will appear at the end of each line
<Ctrl+r>"
Insert the contents of the unnamed register (last yank or delete)
<Ctrl+r>*
Insert the contents of the GUI clipboard
<Ctrl+r>b
Insert the contents of register b
Searching
/
Search forward
/\v
Search forward using a regex
:/
Search forward
:/\v
Search forward using a regex
?
Search backward
:?
Search backward
:g/
See all of the matches to the previous search (can copy with mouse on some systems)
:g/pattern
See all of the matches to a pattern
q/
See menu of recent searches. The list can be navigated and entries edited
*
Search forward for word under cursor
#
Search backward for word under cursor
n
Next match in same direction
N
Next match in opposite direction
/http:\/\/
Search for http://
:noh
Disable highlighting of the matches (temporarily)
.vimrc setting to disable highlighting of search matches (temporarily); type \ then a space
nnoremap <leader><space> :noh<CR>
Replacing (Substituting)
:s/this/that/
Replace this with that; only changes the first match of the current line (or of selected lines)
:s/this/that/g
Replace all occurrences on the line (or selected lines)
:s/this/that/gc
Ask for confirmation before replacing.
y/n/a/q/l for yes, no, all remaining, quit, and last (yes to this one but quit)
Also available while confirming replacements is CTRL+E and CTRL+Y to scroll the screen
:s/this/that/gi
Count number of matches, but do not replace
:s/this/this\r/g
Replace "this" with "this" followed by a carriage return
:s/this|\that/other\r/g
Replace "this" or "that" with "other"
:set gdefault
Remove the need for /g
:set gdefault?
Check current setting
:set nogdefault
Restore /g requirement
Note: if you use ":set gdefault" in the .vimrc file, the g is no longer needed for :s or :%s because it becomes implied
Furthermore, if you use the /g when gdefault is enabled, the search behavior will switch back to replacing the first occurrence only in each line
Global Replace
:%s/foo/bar/g
Replace all occurrences of "foo" with "bar", on all lines
:.,$s/foo/bar/g
Replace all occurrences of "foo" with "bar", from the current line to the end
:10,20s/foo/bar/g
Replace all occurrences of "foo" with "bar", on lines 10 through 20
:%s/this/that/gc
Ask for confirmation for each; "q" to quit the search/replace
:%s/\(\d\+\)/\1,/gc
Find all sequential numbers (\d\+) and add a comma after them
:%s/\v(\d+)/\1\,/gc
Use \v to remove the need for all of the extra \ characters
i.e., to tell vim that you are intentionally using regex symbols
:%s/pattern//gn
Count the number of matches (leave out the g to count the lines)
To remove the need to type \v, update .vimrc to have the following.
nnoremap / /\v
vnoremap / /\v
Note: with ":set gdefault" in the .vimrc file, the behavior of the g flag is reversed
Global Operator
The g operator acts on a specified range (default whole file), by executing the given command
for each line matching the pattern. Before executing the cmd, "." is set to the current line.
:g/foo/
Show all occurrences of foo
:g/foo/z.3
Show all occurrences of foo, with context
:g/foo/z=3
Show all occurrences of foo, with context, matched line is highlighted with ----------
:g/foo/z#=3
Show all occurrences of foo, with context, number the output lines
:g/re/p
Show all lines containing "re"; origin of the word grep
:g/foo/d
Delete all lines containing foo
:g!/pattern/d
Delete all lines that do not match the pattern
:v/pattern/d
Same as g!
:g/^\s*$/d
Delete all blank lines (zero or more whitespace characters)
:qaq:g/pattern/y A
Copy (yank) all matching lines into register a (must type qaq first to clear register a)
:g/pattern/normal @q
Run macro q on all matching lines
Examples:
:g!/^.\+[*].\+$/d
Delete all lines that do not contain *
:g!/\v^.+[*].+$/d
Equivalent command using \v
Search/replace in gvim on Windows
:prompt
See a search dialog
:promptr
See a search/replace dialog
:ret[ab]
Replace all tabs with spaces (default spaces per tab, see :set tabstop?)
Only works if ":set expandtab" is enabled
:set expandtab
Note that expandtab is a per-file extension setting
:ret 8
Replace all tabs with 8 spaces; also updates tabstop
Commands
:CommandName
Enter a command
:help CommandName
Get help on a command
q:
See menu of recent commands. The list can be navigated and entries edited
To see this list while typing a command
:q
Close the window showing recent commands
Files
:w
Write buffer to disk (whether or not it has changes)
:w name
Write buffer to disk as name (but original filename remains unchanged)
:DiffOrig
Compare buffer text to file on disk to see changes
:saveas name
Save under a new name
:update
Write buffer to disk if it has changed (mapped to Ctrl+S in mswin.vim)
:n
Edit a new file; :n! edit a new file without saving current changes
:q
Quit editing a file; :q! quit editing without saving changes
:e
Refresh file contents (if changed outside vim)
:e!
Reload even though buffer has changed
:edit Test.txt
Edit a new file named Test.txt (or open Test.txt if it already exists)
ZZ
Write file to disk and quit immediately
:qa[all]
Close all buffers, unless they're modified
:close
Close the current window (when multiple windows are visible)
:conf qa
Confirm qall; see save prompt for each modified buffer
:file
Print the current filename to the status line (same as Ctrl+G)
:file!
Print the filename and do not truncate if a very long name
:!echo %
Echo full path to console (allow for copy on Windows)
:rec[over]
Recover lost changes after VIM crashes; uses the :sw[ap] file
:browse oldfiles
See recent files; type a number to open one; if lots of files, press q to exit the "more" listing
:bro ol
Shorthand
:ol[dfiles]
See recent files
:MRU
Use mru plugin (see also File->Recent Files in the GUI)
'0
Open most recent file
'1
Open second most recent file (works through '9)
"Most recent" files are saved when you exit vim
Directory Explorer
:e .
Start directory explorer (in current window; file must be unchanged)
:Explore
Directory explorer in the path of the current file (split if file modified, otherwise file closed)
:Hexplore
Directory explorer in the path of the current file (split window)
:Texplore
Directory explorer in the path of the current file (new tab)
Directory Explorer Shortcuts
<Enter>
Open the selected file (and close the explorer)
v
Open the selected file with a vertical split (explorer on the right)
P
Edit selected file in the previously used (last accessed) window
s
Change sort
r
Reverse sort
i
Change listing style
u
Change to earlier directory
U
Change to later directory
p
Preview selected file
%
Create a new file
d
Create a new directory
x
Execute application for selected file (e.g. open .html file in a browser)
Also, type gx while editing a file to have that file opened in the application
R
Rename the current file
<CTRL+l>
Refresh the listing
<CTRL+h>
Define the hiding list (patterns to hide); comma separated list
a
Cycle from showing all files, hiding the specified files, or only showing the specified files from
mf
Mark files. After marking, could show/hide with "a". Many other commands exist list cut, copy, delete, etc.
mF
Unmark all files
md
Vimdiff two marked files
mh
Add a marked file's suffix to the hiding list
qb
Query bookmarks
Windows, Tabs, and Buffers
<CTRL+w>s
Split window horizonally
:sp
Split window (or :split)
<CTRL+w>v
Vertical split the window
:vsp
Vertical split the window (or :vsplit)
<CTRL+w>n
New window
<CTRL+w>j
Down to next window of horizontal split
<CTRL+w>k
Up to previous window of horizontal split
<CTRL+w>h
Over to left window of vertical split
<CTRL+w>l
Over to right window of vertical split
<CTRL+w>p
Previous window
<CTRL+w>w
Next window (same as ; Ctrl+Tab works with gvim)
<CTRL+w>c
Close the window
:close
Close the window
:q
Close (quit) the window
.vimrc setting so that \ then v creates a new vertical split and moves to it
nnoremap <leader>v <C-w>v<C-w>l
<CTRL+w>_
Maximize current window
<CTRL+w>=
Make all windows equal size
<CTRL+w>+
Increase horizontal window size
5<CTRL+w>-
Decrease horizontal window size by 5 lines
<CTRL+w>>
Move vertical slider one column to the right
5<CTRL+w><
Move vertical slider 5 columns to the left
<CTRL+w>r
Swap two windows
<CTRL+w>H
Go from horizontal to vertical layout (use capital H)
<CTRL+w>J
Go from vertical to horizontal layout (use capital J)
:new
New buffer
:enew
New file in the current buffer (use :enew! to discard changes)
:tabe
Create a new tab (:tabedit)
:tab
new Create a new tab
:tabnew
Create a new tab
Ctrl+PageUp
Next tab
gt
Next tab
2gt
Go to tab #2
:tabn[ext]
Next tab
Ctrl+PageDown
Previous tab
gT
Previous tab
:tabp[revious]
Previous tab
:tabr[ewind]
Go to the first tab
:tabl[ast]
Go to the last tab
:tabm[ove] [N]
Move the tab to after tab page N (or to the end with N)
:+tabm
Move the tab to the right
:-tabm
Move the tab to the left
:windo {cmd}
for a series of commands
:tabdo {cmd}
Perform the specified command on each tab.
:bn[ext]
Go to the next buffer
:bp[revious]
Go to the previous buffer
:bmod
Go to the next modified buffer
:sball
Display all buffers in a horizontal split
:tab sball
Convert all buffers to tabs
Source Navigation
%
Jump to matching parenthesis/bracket/brace, or language block if language module loaded
gd
Go to definition of local symbol under cursor: jumps to first occurrence of the word in the file
<CTRL+]>
Jump to definition of global symbol (requires tags file)
<CTRL+t>
Return to previous position (arbitrary stack of positions maintained)
<CTRL+n>
(in insert mode) automatic word completion
Syntax Coloring
Vim auto-selects the highlighting method based on the file extension
To override, use:
:setf language
Set current language
:set filetype
View current language
:syn list
View current syntax rules; use d and u to move down and up
:syn clear
Turn off highlighting
:syn on
Turn on highlighting
:hi[light]
List all highlight groups; use d and u to move down and up
:set syntax=c
Use the c syntax rules
:set showmatch
When a bracket is typed, briefly jump to the matching bracket (if visible on the screen)
Diagnosing Performance
Use :syntime to find out what patterns are consuming most time
:syntime on
Ctrl+L
Redraw the text (one or more times)
:syntime report
See results
Line Numbers and Line Highlighting
:set nu[mber]
Show line numbers
:set nonu[mber]
Disable line numbers
:set cursorline
Highlight the current line
:set nocul
Disable highlighting the line
Show local changes
Vim has some features that make it easy to highlight lines that have been changed from a base version in source control.
See the small vim script that makes this easy: http://github.com/ghewgill/vim-scmdiff
Formatting
:set textwidth=80
Set the wrap width
Optionally define this in vimrc on a file-type basis
au BufRead,BufNewFile *.txt setlocal textwidth=80
gq
Wrap existing lines, selected with V (or with the mouse)
J
Join two adjacent lines together
A space will be added between the two joined lines
:Comma
Call a custom function (defined in _vimrc) to add a comma to each line
:Commaq
Similar to :Comma but surrounds each line with single quotes
VimDiff
VimDiff shows two files side-by-side
[c
Jump to previous change (difference)
]c
Jump to next change (difference)
zo
Open one fold under the cursor
zO
Open all folds under the cursor (recursively)
zc
Close one fold under the cursor
zC
Close all folds under the cursor
za
Toggle one fold under the cursor
zA
Toggle all folds under the cursor
zX
Undo manually opened and closed folds
dp
Put the selected section in the other file
do
Obtain the selected section from the other file
dp and do do not work with Visual Mode
Settings
:set gdefault?
View the current value for the gdefault setting
:verbose map <C-Y>
See what the Ctrl+Y key combination is mapped to
:map
See key bindings
:unmap <C-Y>
Place this in _vmrc to unmap Ctrl+Y
:scriptnames
See loaded scripts, including .vimrc
See the mswin.vim file to see the overridden key combos and find those to remove/tweak
Summary of uses of the g key
ge
Navigate backward to the end of the word
gE
Navigate backward to the end of the Word
gg
Go to the start of file
G
Go to the end of file
gt
View the next tab
gT
View the previous tab
<ctrl+g>
View the current file path and status
g <Ctrl+g>
View current position in status line
g;
Go to [count] older cursor position in change list
g,
Go to [count] newer cursor position in change list
g-
Undo to the previous text state
g+
Redo to the next text state
gg"*yG
Copy all, but moves the cursor
g~<motion>
Swap case in the specified direction
gu<motion>
Make lowercase
gU<motion>
Make uppercase
gv
Reselect last visual block
gd
Go to definition of local symbol under cursor:
jumps to first occurrence of the word in the file
gq{motion}
Wrap existing lines in the motion direction
gq
Wrap the selected text, when selected using V or the mouse
{gq}
Wrap the current paragraph: { moves to the start of the paragraph and } the end
gw{motion}
Wrap existing lines like gq, but leave the cursor in the same position
gwj
Example use, wrapping the current line and the next
Shortcuts customized in .vimrc
The default leader key is \
To use a comma as the leader, update .vimrc to have:
let mapleader = ","
LeaderKey v Open a vertical split and switch over to the new window (\v or ,v)
LeaderKey n Create a new tab
LeaderKey t Create a new tab
LeaderKey T Change all buffers to tabs
F3 View YankRing buffers
LeaderKey N Cycle through YankRing buffers
LeaderKey P Cycle through YankRing buffers
LeaderKey O Change the working directory to use the current file's folder (see :cd)
LeaderKey <space> Disable highlighting of search matches (temporarily); type \ then a space
LeaderKey W Remove trailing whitespace
:Comma
Add a comma to the end of each line
:Commaq
Surround each line with single quotes and add a comma