VIM cheatsheet
PS: I'm an Emacs user
VIM stands for Vi IMproved.
Below N is used to indicate an optional count that can be given before the command.
Left-right motions | |
---|---|
N h | left (also: CTRL-H, <BS>, or <Left> key) |
N l | right (also: <Space> or <Right> key) |
0 | to first character in the line (also: <Home> key) |
^ | to first non-blank character in the line |
N $ | to the last character in the line (N-1 lines lower) (also: <End> key) |
N g0 | to first character in screen line (differs from "0" when lines wrap) |
N g^ | to first non-blank character in screen line (differs from "0" when lines wrap) |
N g$ | to last character in screen line (differs from "$" when lines wrap) |
N | | to column N (default: 1) |
N f<char> | to the Nth occurrence of <char> to the right |
N F<char> | to the Nth occurrence of <char> to the left |
N t<char> | till before the Nth occurrence of <char> to the right |
N T<char> | till before the Nth occurrence of <char> to the left |
N ; | repeat the last "f", "F", "t", or "T" N times |
N , | repeat the last "f", "F", "t", or "T" N times in opposite direction |
Up-down motions | |
N k | up N lines (also: CTRL-P and <Up>) |
N j | down N lines (also: CTRL-J, CTRL-N, <NL>, and <Down>) |
N - | up N lines, on the first non-blank character |
N + | down N lines, on the first non-blank character (also: CTRL-M and <CR>) |
N _ | down N-1 lines, on the first non-blank character |
N G | goto line N (default: last line), on the first non-blank character |
N gg | goto line N (default: first line), on the first non-blank character |
N % | goto line N percentage down in the file. N must be given, otherwise it is the % command. |
N gk | up N screen lines (differs from "k" when line wraps) |
N gj | down N screen lines (differs from "j" when line wraps) |
Text object motions | |
N w | N words forward |
N W | N blank-separated WORDS forward |
N e | forward to the end of the Nth word |
N E | forward to the end of the Nth blank-separated WORD |
N b | N words backward |
N B | N blank-separated WORDS backward |
N ge | backward to the end of the Nth word |
N gE | backward to the end of the Nth blank-separated WORD |
N ) | N sentences forward |
N ( | N sentences backward |
N } | N paragraphs forward |
N { | N paragraphs backward |
N ]] | N sections forward, at start of section |
N [[ | N sections backward, at start of section |
N ][ | N sections forward, at end of section |
N [] | N sections backward, at end of section |
N [( | N times back to unclosed '(' |
N [{ | N times back to unclosed '{' |
N ]) | N times forward to unclosed ')' |
N ]} | N times forward to unclosed '}' |
N [# | N times back to unclosed "#if" or "#else" |
N ]# | N times forward to unclosed "#else" or "#endif" |
N [* | N times back to start of comment "/*" |
N ]* | N times forward to end of comment "*/" |
Pattern searches | |
N /{pattern}[/[offset]]<CR> | search forward for the Nth occurrence of {pattern} |
N ?{pattern}[?[offset]]<CR> | search backward for the Nth occurrence of {pattern} |
N /<CR> | repeat last search, in the forward direction |
N ?<CR> | repeat last search, in the backward direction |
N n | repeat last search |
N N | repeat last search, in opposite direction |
N * | search forward for the identifier under the cursor |
N # | search backward for the identifier under the cursor |
N g* | like "*", but also find partial matches |
N g# | like "#", but also find partial matches |
gd | goto local declaration of identifier under the cursor |
gD | goto global declaration of identifier under the cursor |
Regular expression search pattern | |
Value of magic option --------------------- meaning magic nomagic matches any single character . \. matches start of line ^ ^ matches end of line $ $ matches start of word \< \< matches end of word \> \> matches a single char from the range [a-z] \[a-z] matches a single char not in the range [^a-z] \[^a-z] matches an identifier char \i \i idem but excluding digits \I \I matches a keyword character \k \k idem but excluding digits \K \K matches a filename character \f \f idem but excluding digits \F \F matches a printable character \p \p idem but excluding digits \P \P matches <Esc> \e \e matches <Tab> \t \t matches <CR> \r \r matches <BS> \b \b matches 0 or more of the preceding atom * \* matches 1 or more of the preceding atom \+ \+ matches 0 or 1 of the preceding atom \= \= matches from n to m {n,m} matches exacly n {n} matches at most m {,m} matches at least n {n,} non greed matches - press ? after specifier: eg: *? separates two branches \| \| group a pattern into an atom \(\) \(\) | |
Offsets after search command | |
[num] | [num] lines downwards, in column 1 |
+[num] | [num] lines downwards, in column 1 |
-[num] | [num] lines upwards, in column 1 |
e[+num] | [num] characters to the right of the end of the match |
e[-num] | [num] characters to the left of the end of the match |
s[+num] | [num] characters to the right of the start of the match |
s[-num] | [num] characters to the left of the start of the match |
b[+num] | [num] characters to the right of the start (begin) of the match |
b[-num] | [num] characters to the left of the start (begin) of the match |
;{search command} | execute {search command} next |
Examples: | |
pattern | cursor position |
/test/+1 | one line below "test", in column 1 |
/test/e | on the last t of "test" |
/test/s+2 | on the 's' of "test" |
/test/b-3 | three characters before "test" |
Marks and motions | |
m<a-zA-Z> | mark current position with mark <a-zA-Z> |
`<a-z> | go to mark <a-z> within current file |
`<A-Z> | go to mark <A-Z> in any file |
`<0-9> | go to the position where Vim was last exited |
`` | go to the position before the last jump |
`" | go to the position when last editing this file |
`[ | go to the start of the previously operated or put text |
`] | go to the end of the previously operated or put text |
`< | go to the start of the (previous) Visual area |
`> | go to the end of the (previous) Visual area |
'<a-zA-Z0-9[]'"<>> | same as `, but on the first non-blank in the line |
:marks | print the active marks |
N CTRL-O | go to Nth older position in jump list |
N CTRL-I | go to Nth newer position in jump list |
:ju[mps] | print the jump list |
Various motions | |
%% | find the next brace, bracket, comment, or "#if"/ "#else"/"#endif" in this line and go to its match |
N H | go to the Nth line in the window, on the first non-blank |
M | go to the middle line in the window, on the first non-blank |
N L | go to the Nth line from the bottom, on the first non-blank |
Using tags | |
:ta[g][!] {tag} | Jump to tag {tag} |
:[count]ta[g][!] | Jump to [count]'th newer tag in tag list |
CTRL-] | Jump to the tag under cursor, unless changes have been made |
N CTRL-T | Jump back from Nth older tag in tag list |
:[count]po[p][!] | Jump back from [count]'th older tag in tag list |
:tags | Print tag list |
Scrolling | |
N CTRL-E | window N lines downwards (default: 1) |
N CTRL-D | window N lines Downwards (default: 1/2 window) |
N CTRL-F | window N pages Forwards (downwards) |
N CTRL-Y | window N lines upwards (default: 1) |
N CTRL-U | window N lines Upwards (default: 1/2 window) |
N CTRL-B | window N pages Backwards (upwards) |
z<CR> or zt | redraw, current line at top of window |
z. or zz | redraw, current line at center of window |
z- or zb | redraw, current line at bottom of window |
N zh | scroll screen N characters to the right |
N zl | scroll screen N characters to the left |
Inserting text | |
N a | append text after the cursor (N times) |
N A | append text at the end of the line (N times) |
N i | insert text before the cursor (N times) (also: <Insert>) |
N I | insert text before the first non-blank in the line (N times) |
N gI | insert text in column 1 (N times) |
N o | open a new line below the current line, append text (N times) |
N O | open a new line above the current line, append text (N times) |
Keys in Insert mode | |
char | action in Insert mode |
<Esc> | end Insert mode, back to Normal mode |
CTRL-C | like <Esc>, but do not do an abbreviation |
CTRL-A | insert previously inserted text |
CTRL-@ | insert previously inserted text and stop insert |
CTRL-R <0-9a-z%:.-"> | insert contents of register <0-9a-z%:.-"> |
<NL> or <CR> | or CTRL-M or CTRL-J begin new line |
CTRL-E | insert the character from below the cursor |
CTRL-Y | insert the character from above the cursor |
CTRL-V <char>.. | insert character literally, or enter decimal byte value |
CTRL-N | insert next match of identifier before the cursor |
CTRL-P | insert previous match of identifier before the cursor |
CTRL-X ... | complete the word before the cursor in various ways |
<BS> or CTRL-H | delete the character before the cursor |
<Del> | delete the character under the cursor |
CTRL-W | delete word before the cursor |
CTRL-U | delete all entered characters in the current line |
CTRL-T | insert one shiftwidth of indent in front of the current line |
CTRL-D | delete one shiftwidth of indent in front of the current line |
0 CTRL-D | delete all indent in the current line |
^ CTRL-D | delete all indent in the current line, restore indent in next line |
CTRL-K {char1} {char2} | enter digraph |
{char1} <BS> {char2} | enter digraph if 'digraph' option set |
CTRL-B | toggle 'revins' (reverse insert) option |
Special keys in Insert mode | |
cursor keys | move cursor left/right/up/down |
shift-left/right | one word left/right |
shift-up/down | one screenful backward/forward |
CTRL-O {command} | execute {command} |
<End> | cursor after last character in the line |
<Home> | cursor to first character in the line |
Digraphs | |
:dig[raphs] | show current list of digraphs |
:dig[raphs] {char1}{char2} {number} ... | sadd digraph(s) to the list |
Special inserts | |
:r [file] | insert the contents of [file] below the cursor |
:r! {command} | insert the standard output of {command} below the cursor |
Deleting text | |
N x | delete N characters under and after the cursor |
N <Del> | delete N characters under and after the cursor |
N X | delete N characters before the cursor |
N d{motion} | delete the text that is moved over with {motion} |
{visual}d | delete the highlighted text |
N dd | delete N lines |
N D | delete to end-of-line (and N-1 more lines) |
N J | join N-1 lines (delete newlines) |
{visual}J | join the highlighted lines |
:[range]d [x] | delete [range] lines [into register x] |
Copying and moving text | |
"<char> | use register <char> for the next delete, yank, or put |
:reg | show the contents of all registers |
:reg {arg} | show the contents of registers mentioned in {arg} |
N y{motion} | yank the text moved over with {motion} |
{visual}y | yank the highlighted text |
N yy | yank N lines |
N Y | yank N lines |
ggVG"+y | copy to clipboard |
"+p or "+P | paste from clipboard |
N p | put a register after the cursor position (N times) |
N P | put a register before the cursor position (N times) |
N ]p | like p, but adjust indent to current line |
N [p | like P, but adjust indent to current line |
Changing text | |
N R | enter Replace mode (repeat the entered text N times) |
N c{motion} | change the text that is moved over with {motion} |
N {visual}c | change the highlighted text |
N cc | change N lines |
N S | change N lines |
N C | change to end-of-line (and N-1 more lines) |
N s | change N characters |
N r<char> | replace N characters with <char> |
N ~ | switch case for N characters and advance cursor |
N {visual}~ | switch case for highlighted text |
N {visual}u | make highlighted text lowercase |
N {visual}U | make highlighted text uppercase |
N g~{motion} | switch case for the text that is moved over with {motion} |
N gu{motion} | make the text that is moved over with {motion} lowercase |
N gU{motion} | make the text that is moved over with {motion} uppercase |
N CTRL-A | add N to the number at or after the cursor |
N CTRL-X | subtract N from the number at or after the cursor |
N <{motion} | move the lines that are moved over with {motion} one shiftwidth left |
N << | move N lines one shiftwidth left |
N >{motion} | move the lines that are moved over with {motion} one shiftwidth right |
N >> | move N lines one shiftwidth right |
N gq{motion} | format the lines that are moved over with {motion} to 'textwidth' length |
:[range]ce[nter] [width] | center the lines in [range] |
:[range]le[ft] [indent] | left-align the lines in [range] [with indent] |
:[range]ri[ght] [width] | right-align the lines in [range] |
Complex changes | |
N !{motion}{command}<CR> | filter the lines that are moved over through {command} |
N !!{command}<CR> | filter N lines through {command} |
N {visual}!{command}<CR> | filter the highlighted lines through {command} |
:[range]! {command}<CR> | filter [range] lines through {command} |
N ={motion} | filter the lines that are moved over through "indent" |
N == | filter N lines through "indent" |
N {visual}= | filter the highlighted lines through "indent" |
:[range]s[ubstitute]/{pattern}/{string}/[g][c] | substitute {pattern} by {string} in [range] lines; with [g], replace all occurrences of {pattern}; with [c], confirm each replacement |
:[range]s[ubstitute] [g][c] | repeat previous ":s" with new range and options |
& | Repeat previous ":s" on current line without options |
:[range]ret[ab][!] [tabstop] | set 'tabstop' to new value and adjust white space accordingly |
Visual mode | |
v | start highlighting characters } move cursor and use |
V | start highlighting linewise } operator to affect |
CTRL-V | start highlighting blockwise } highlighted text |
o | exchange cursor position with start of highlighting |
gv | start highlighting on previous visual area |
v | highlight characters or stop highlighting |
V | highlight linewise or stop highlighting |
CTRL-V | highlight blockwise or stop highlighting |
Text objects | |
Used only in Visual mode or after an operator | |
a | Select current word |
A | Select current WORD |
s | Select current sentence |
p | Select current paragraph |
S | Select current block (from "[(" to "])") |
P | Select current block (from "[{" to "]}") |
Repeating commands | |
N . | repeat last change (with count replaced with N) |
N q<a-z> | record typed characters into register <a-z> |
N q<A-Z> | record typed characters, appended to register <a-z> |
N q | stop recording |
N @<a-z> | execute the contents of register <a-z> (N times) |
N @@ | repeat previous @<a-z> (N times) |
:@<a-z> | execute the contents of register <a-z> as an Ex command |
:@@ | repeat previous :@<a-z> |
:[range]g[lobal]/{pattern}/[cmd] | Execute Ex command [cmd] (default: ":p") on the lines within [range] where {pattern} matches. |
:[range]g[lobal]!/{pattern}/[cmd] or :[range]v/{pattern}/[cmd] | Execute Ex command [cmd] (default: ":p") on the lines within [range] where {pattern} does NOT match. |
Examples: | |
:%g/^a/-1join | join lines starting with character 'a' to previous line |
:%g/^ *$/d | delete empty lines |
:%v/vim/m 1 | move lines not matching the word 'vim' to line 1 |
:%g/^a/+1d | delete lines after the ones starting with character 'a' |
:so[urce] {file} | Read Ex commands from {file}. |
:so[urce]! {file} | Read Vim commands from {file}. |
:sl[eep] [N] | don't do anything for N seconds |
N gs | Goto Sleep for N seconds |
Key mapping | |
:ma[p] {lhs} {rhs} | Map {lhs} to {rhs} in Normal and Visual mode. |
:ma[p]! {lhs} {rhs} | Map {lhs} to {rhs} in Insert and Command-line mode. |
:no[remap][!] {lhs} {rhs} | Same as ":map", no remapping for this {rhs} |
:unm[ap] {lhs} | Remove the mapping of {lhs} for Normal and Visual mode. |
:unm[ap]! {lhs} | Remove the mapping of {lhs} for Insert and Command-line mode. |
:ma[p] [lhs] | List mappings (starting with [lhs]) for Normal and Visual mode. |
:ma[p]! [lhs] | List mappings (starting with [lhs]) for Insert and Command-line mode. |
:cmap/:cunmap/:cnoremap | like ":map!"/":unmap!"/":noremap!" but for Command-line mode only |
:imap/:iunmap/:inoremap | like ":map!"/":unmap!"/":noremap!" but for Insert mode only |
:nmap/:nunmap/:nnoremap | like ":map"/":unmap"/":noremap" but for Normal mode only |
:vmap/:vunmap/:vnoremap | like ":map"/":unmap"/":noremap" but for Visual mode only |
:mk[exrc][!] [file] | write current mappings, abbreviations, and settings to [file] (default: ".exrc"; use ! to overwrite) |
:mkv[imrc][!] [file] | same as ":mkexrc", but with default ".vimrc" |
:mapc[lear] | remove mappings for Normal and Visual mode |
:mapc[lear]! | remove mappings for Insert and Cmdline mode |
:imapc[lear] | remove mappings for Insert mode |
:vmapc[lear] | remove mappings for Visual mode |
:nmapc[lear] | remove mappings for Normal mode |
:cmapc[lear] | remove mappings for Cmdline mode |
Abbreviations | |
:ab[breviate] {lhs} {rhs} | add abbreviation for {lhs} to {rhs} |
:ab[breviate] {lhs} | show abbr's that start with {lhs} |
:ab[breviate] | show all abbreviations |
:una[bbreviate] {lhs} | remove abbreviation for {lhs} |
:norea[bbrev] [lhs] [rhs] | like ":ab", but don't remap [rhs] |
:iab/:iunab/:inoreab | like ":ab", but only for Insert mode |
:cab/:cunab/:cnoreab | like ":ab", but only for Command-line mode |
:abc[lear] | remove all abbreviations |
:cabc[lear] | remove all abbr's for Cmdline mode |
:iabc[lear] | remove all abbr's for Insert mode |
Options | |
:se[t] | Show all modified options. |
:se[t] all | Show all options. |
:se[t] {option} | Set toggle option on, show string or number option. |
:se[t] no{option} | Set toggle option off. |
:se[t] inv{option} | invert toggle option. |
:se[t] {option}={value} | Set string or number option to {value}. |
:se[t] {option}? | Show value of {option}. |
:se[t] {option}& | Reset {option} to its default value. |
:fix[del] | Set value of 't_kD' according to value of 't_kb'. |
Options Overview | |
name (short name) | explanation |
aleph al | ASCII code of the letter Aleph (RIGHTLEFT) |
autoindent ai | take indent for new line from previous line |
autowrite aw | automatically write file if changed |
backspace bs | how backspace works at start of line |
backup bk | keep backup file after overwriting a file |
backupdir bdir | list of directories for the backup file |
backupext bex | extension used for the backup file |
binary bin | edit binary file mode |
bioskey biosk | MS-DOS: use bios calls for input characters |
breakat brk | characters that may cause a line break |
cindent cin | do C program indenting |
cinkeys cink | keys that trigger indent when 'cindent' is set |
cinoptions cino | how to do indenting when 'cindent' is set |
cinwords cinw | words where 'si' and 'cin' add an indent |
cmdheight ch | number of lines to use for the command-line |
columns co | number of columns in the display |
comments com | patterns that can start a comment line |
compatible cp | behave Vi-compatibly as much as possible |
cpoptions cpo | flags for Vi-compatible behaviour |
define def | pattern to be used to find a macro definition |
dictionary dict | list of filenames used for keyword completion |
digraph dg | enable the entering of digraphs in Insert mode |
directory dir | list of directory names for the swapfile |
edcompatible ed | toggle flags of ":substitute" command |
endofline eol | write end-of-line for last line in file |
equalalways ea | windows are automatically made the same size |
equalprg ep | external program to use for "=" command |
errorbells eb | ring the bell for error messages |
errorfile ef | name of the error file for the QuickFix mode |
errorformat efm | description of the lines in the error file |
esckeys ek | recognize function keys in Insert mode |
expandtab et | use spaces when <Tab> is inserted |
exrc | read .vimrc and .exrc in the current directory |
formatoptions fo | how automatic formatting is to be done |
formatprg fp | name of external program used with "gq" command |
gdefault gd | the ":substitute" flag 'g' is default on |
guifont gfn | GUI: Name(s) of font(s) to be used |
guioptions go | GUI: Which components and options are used |
guipty | GUI: try to use a pseudo-tty for ":!" commands |
helpfile hf | name of this help file |
helpheight hh | minimum height of a new help window |
hidden hid | don't unload buffer when it is abandoned |
highlight hl | sets highlighting mode for various occasions |
history hi | number of command-lines that are remembered |
hkmap hk | Hebrew keyboard mapping (RIGHTLEFT) |
icon | set icon of the window to the name of the file |
ignorecase ic | ignore case in search patterns |
include inc | pattern to be used to find an include file |
incsearch is | highlight match while typing search pattern |
infercase inf | adjust case of match for keyword completion |
insertmode im | start the edit of a file in Insert mode |
isfname isf | characters included in filenames and pathnames |
isident isi | characters included in identifiers |
isprint isp | printable characters |
iskeyword isk | characters included in keywords |
joinspaces js | two spaces after a period with a join command |
keywordprg kp | program to use for the "K" command |
langmap lmap | alphabetic characters for other language mode |
laststatus ls | tells when last window has status lines |
linebreak lbr | wrap long lines at a blank |
lines | number of lines in the display |
lisp | automatic indenting for Lisp |
list | show <Tab> and end-of-line |
magic | changes special characters in search patterns |
makeprg mp | program to use for the ":make" command |
maxmapdepth mmd | maximum recursive depth for mapping |
maxmem mm | maximum memory (in Kbyte) used for one buffer |
maxmemtot mmt | maximum memory (in Kbyte) used for all buffers |
modeline ml | recognize modelines at start or end of file |
modelines mls | number of lines checked for modelines |
modified mod | buffer has been modified |
more | pause listings when the whole screen is filled |
mouse | enable the use of mouse clicks |
mousetime mouset | max time between mouse double-click |
number nu | print the line number in front of each line |
paragraphs para | nroff macros that separate paragraphs |
paste | allow pasting text |
patchmode pm | keep the oldest version of a file |
path pa | list of directories searched with "gf" et.al. |
readonly ro | disallow writing the buffer |
remap | allow mappings to work recursively |
report | threshold for reporting nr. of lines changed |
restorescreen rs | Win32: restore screen when exiting |
revins ri | inserting characters will work backwards |
rightleft rl | window is right-to-left oriented (RIGHTLEFT) |
ruler ru | show cursor line and column in the status line |
scroll scr | lines to scroll with CTRL-U and CTRL-D |
scrolljump sj | minimum number of lines to scroll |
scrolloff so | minimum nr. of lines above and below cursor |
sections sect | nroff macros that separate sections |
secure | secure mode for reading .vimrc in current dir |
shell sh | name of shell to use for external commands |
shellcmdflag shcf | flag to shell to execute one command |
shellpipe sp | string to put output of ":make" in error file |
shellquote shq | quote character(s) for around shell command |
shellredir srr | string to put output of filter in a temp file |
shelltype st | Amiga: influences how to use a shell |
shiftround sr | round indent to multiple of shiftwidth |
shiftwidth sw | number of spaces to use for (auto)indent step |
shortmess shm | list of flags, reduce length of messages |
shortname sn | non-MS-DOS: File names assumed to be 8.3 chars |
showbreak sbr | string to use at the start of wrapped lines |
showcmd sc | show (partial) command in status line |
showmatch sm | briefly jump to matching bracket if insert one |
showmode smd | message on status line to show current mode |
sidescroll ss | minimum number of columns to scroll horizontal |
smartcase scs | no ignore case when pattern has uppercase |
smartindent si | smart autoindenting for C programs. For perl |
script editing set this option and the following | |
key mapping: inoremap # x<BS># | |
smarttab sta | use 'shiftwidth' when inserting <Tab> |
splitbelow sb | new window from split is below the current one |
startofline sol | commands move cursor to first blank in line |
suffixes su | suffixes that are ignored with multiple match |
swapsync sws | how to sync swapfile |
tabstop ts | number of spaces that <Tab> in file uses |
taglength tl | number of significant characters for a tag |
tagrelative tr | filenames in tag file are relative |
tags tag | list of filenames used by the tag command |
term | name of the terminal |
terse | shorten some messages |
textauto ta | set 'textmode' automatically when reading file |
textmode tx | lines are separated by <CR><NL> |
textwidth tw | maximum width of text that is being inserted |
tildeop top | tilde command "~" behaves like an operator |
timeout to | time out on mappings and key codes |
ttimeout | time out on mappings |
timeoutlen tm | time out time in milliseconds |
ttimeoutlen ttm | time out time for key codes in milliseconds |
title | set title of window to the name of the file |
ttybuiltin tbi | use built-in termcap before external termcap |
ttyfast tf | indicates a fast terminal connection |
ttyscroll tsl | maximum number of lines for a scroll |
ttytype tty | alias for 'term' |
undolevels ul | maximum number of changes that can be undone |
updatecount uc | after this many characters flush swapfile |
updatetime ut | after this many milliseconds flush swapfile |
viminfo vi | use .viminfo file upon startup and exiting |
visualbell vb | use visual bell instead of beeping |
warn | warn for shell command when buffer was changed |
weirdinvert wi | for terminals that have weird inversion method |
whichwrap ww | allow specified keys to cross line boundaries |
wildchar wc | command-line character for wildcard expansion |
winheight wh | minimum number of lines for the current window |
wrap | long lines wrap and continue on the next line |
wrapmargin wm | chars from the right where wrapping starts |
wrapscan ws | searches wrap around the end of the file |
writeany wa | write to file with no need for "!" override |
writebackup wb | make a backup before overwriting a file |
writedelay wd | delay this many msec for each char (for debug) |
Undo/Redo commands | |
N u | undo last N changes |
N CTRL-R | redo last N undone changes |
U | restore last changed line |
External commands | |
:sh[ell] | start a shell |
:!{command} | execute {command} with a shell |
K | lookup keyword under the cursor with 'keywordprg' program (default: "man") |
Quickfix commands | |
:cc [nr] | display error [nr] (default is the same again) |
:cn | display the next error |
:cp | display the previous error |
:cl | list all errors |
:cf | read errors from the file 'errorfile' |
:cq | quit without writing and return error code (to the compiler) |
:make [args] | start make, read errors, and jump to first error |
Various commands | |
CTRL-L | Clear and redraw the screen. |
CTRL-G | show current file name (with path) and cursor position |
ga | show ascii value of character under cursor in decimal, hex, and octal |
g CTRL-G | show cursor column, line, and character position |
CTRL-C | during searches: interrupt the search |
CTRL-BREAK | MS-DOS: during searches: interrupt the search |
<Del> | while entering a count: delete last character |
:ve[rsion] | show exact version number of this Vim |
:mode N | MS-DOS: set screen mode to N (number, C80, C4350, etc.) |
:norm[al][!] {commands} | Execute Normal mode commands. |
Command-line editing | |
<Esc> | abandon command-line (if 'wildchar' is <Esc>, type it twice) |
CTRL-V {char} | insert {char} literally |
CTRL-V {number} | enter decimal value of character (up to three digits) |
CTRL-K {char1} {char2} | enter digraph, eg, CTRL-K - > will make → |
CTRL-R <0-9a-z"%:-> | insert contents of register <0-9a-z"%:-> |
<Left>/<Right> | cursor left/right |
<S-Left>/<S-Right> | cursor one word left/right |
CTRL-B/CTRL-E | cursor to beginning/end of command-line |
<BS> | delete the character in front of the cursor |
<Del> | delete the character under the cursor |
CTRL-W | delete the word in front of the cursor |
CTRL-U | remove all characters |
<Up>/<Down> | recall older/newer command-line that starts with current command |
<S-Up>/<S-Down> | recall older/newer command-line from history |
Command Line Completion | |
'wildchar' | (default: <Tab>) do completion on the pattern in front of the cursor. If there are multiple matches, beep and show the first one; further 'wildchar' will show the next ones. |
CTRL-D | list all names that match the pattern in front of the cursor |
CTRL-A | insert all names that match pattern in front of cursor |
CTRL-L | insert longest common part of names that match pattern |
CTRL-N | after 'wildchar' with multiple matches: go to next match |
CTRL-P | after 'wildchar' with multiple matches: go to previous match |
Ex ranges | |
, | separates two line numbers |
; | idem, set cursor to the first line number before interpreting the second one |
{number} | an absolute line number |
. | the current line |
$ | the last line in the file |
%% | equal to 1,$ (the entire file) |
* | equal to '<,'> (visual area) |
't | position of mark t |
/{pattern}[/] | the next line where {pattern} matches |
?{pattern}[?] | the previous line where {pattern} matches |
+[num] | add [num] to the preceding line number (default: 1) |
-[num] | subtract [num] from the preceding line number (default: 1) |
Special Ex characters | |
| | separates two commands (not for ":global" and ":!") |
" | begins comment |
%% | current filename (only where filename is expected) |
#[number] | alternate filename [number] (only where filename is expected) |
Note: The next four are typed literally; these are not special keys! | |
<cword> | word under the cursor (only where filename is expected) |
<cWORD> | WORD under the cursor (only where filename is expected) |
<cfile> | file name under the cursor (only where filename is expected) |
<afile> | file name for autocommand (only where filename is expected) |
After "%", "#", "<cfile>", or "<afile>" | |
:p | full path |
:h | head |
:t | tail |
:r | root |
:e | extension |
Editing a file | |
:e[dit] | Edit the current file, unless changes have been made. |
:e[dit]! | Edit the current file always. Discard any changes. |
:e[dit] {file} | Edit {file}, unless changes have been made. |
:e[dit]! {file} | Edit {file} always. Discard any changes. |
N CTRL-^ | Edit alternate file N (equivalent to ":e #N"). |
gf or ]f | Edit the file whose name is under the cursor |
:pwd | Print the current directory name. |
:cd [path] | Change the current directory to [path]. |
:f[ile] | Print the current filename and the cursor position. |
:f[ile] {name} | Set the current filename to {name}. |
:files | Show alternate filenames. |
Using the argument list | |
:ar[gs] | Print the argument list, with the current file in "[]". |
:all or :sall | Open a window for every file in the arg list. |
:wn[ext][!] | Write file and edit next file. |
:wn[ext][!] {file} | Write to {file} and edit next file, unless {file} exists. With !, overwrite existing file. |
:wN[ext][!] [file] | Write file and edit previous file. |
in current window / new window | - |
:argu[ment] N / :sar[gument] N | Edit file N |
:n[ext] / :sn[ext] | Edit next file |
:n[ext] {arglist} / :sn[ext] {arglist} | define new arg list and edit first file |
:N[ext] / :sN[ext] | Edit previous file |
:rew[ind][!] / :srew[ind] | Edit first file |
:last / :slast | Edit last file |
Writing and quitting | |
:[range]w[rite][!] | Write to the current file. |
:[range]w[rite] {file} | Write to {file}, unless it already exists. |
:[range]w[rite]! {file} | Write to {file}. Overwrite an existing file. |
:[range]w[rite][!] >> | Append to the current file. |
:[range]w[rite][!] >> {file} | Append to {file}. |
:[range]w[rite] !{cmd} | Execute {cmd} with [range] lines as standard input. |
:wall[!] | write all changed buffers |
:q[uit] | Quit current buffer, unless changes have been made. Exit Vim when there are no other non-help buffers |
:q[uit]! | Quit current buffer always, discard any changes. Exit Vim when there are no other non-help buffers |
:qall | Exit Vim, unless changes have been made. |
:qall! | Exit Vim always, discard any changes. |
:cq | Quit without writing and return error code. |
:wq[!] | Write the current file and exit. |
:wq[!] {file} | Write to {file} and exit. |
:x[it][!] [file] | Like ":wq" but write only when changes have been made |
ZZ | Same as ":x". |
ZQ | Same as ":q!". |
:xall[!] or :wqall[!] | Write all changed buffers and exit |
:st[op][!] | Suspend VIM or start new shell. If 'aw' option is set and [!] not given write the buffer. |
CTRL-Z | Same as ":stop!" |
Offsets after search command | |
vim [options] | start editing with an empty buffer |
vim [options] {file ..} | start editing one or more files |
vim [options] -t {tag} | edit the file associated with {tag} |
vim [options] -e [fname] | start editing in QuickFix mode, display the first error |
Vim Command Line Arguments | |
-g | start GUI (also allows other options) |
+[num] | put the cursor at line [num] (default: last line) |
+{command} | execute {command} after loading the file |
+/{pat} {file ..} | put the cursor at the first occurrence of {pat} |
-v | read-only mode (View), implies -n |
-R | read-only mode, same as -v |
-b | binary mode |
-l | lisp mode |
-H | Hebrew mode ('hkmap' and 'rightleft' are set) |
-r | give list of swap files |
-r {file ..} | recover aborted edit session |
-n | do not create swapfile |
-o [N] | open N windows (default: one for each file) |
-x | Amiga: do not restart VIM to open a window (for e.g., mail) |
-s {scriptin} | first read commands from the file {scriptin} |
-w {scriptout} | write typed chars to file {scriptout} (append) |
-W {scriptout} | write typed chars to file {scriptout} (overwrite) |
-T {terminal} | set terminal name |
-d {device} | Amiga: open {device} to be used as a console |
-u {vimrc} | read inits from {vimrc} instead of other inits |
-i {viminfo} | read info from {viminfo} instead of other files |
-- | end of options, other arguments are file names |
Automatic Commands | |
Read registers, marks, history at startup, save when exiting. | |
:rv[iminfo] [file] | Read info from viminfo file [file] |
:rv[iminfo]! [file] | idem, overwrite exisiting info |
:wv[iminfo] [file] | Add info to viminfo file [file] |
:wv[iminfo]! [file] | Write info to viminfo file [file] |
Automatic option setting when editing a file | |
vim:{set-arg}: .. | In the first and last lines of the file (see 'ml' option), {set-arg} is given as an argument to ":set" |
Automatic execution of commands on certain events. | |
:au | List all autocommands |
:au {event} | List all autocommands for {event} |
:au {event} {pat} | List all autocommands for {event} with {pat} |
:au {event} {pat} {cmd} | Enter new autocommands for {event} with {pat} |
:au! | Remove all autocommands |
:au! {event} | Remove all autocommands for {event} |
:au! * {pat} | Remove all autocommands for {pat} |
:au! {event} {pat} | Remove all autocommands for {event} with {pat} |
:au! {event} {pat} {cmd} | Remove all autocommands for {event} with {pat} and enter new one |
Multi-window functions | |
CTRL-W s or :split | Split window into two parts |
:split {file} | Split window and edit {file} in one of them |
CTRL-W ] | Split window and jump to tag under cursor |
CTRL-W f | Split window and edit file name under the cursor |
CTRL-W CTRL-^ | Split window and edit alternate file |
CTRL-W n or :new | Create new empty window |
CTRL-W q or :q[uit] | Quit editing and close window |
CTRL-W c or :cl[ose] | Make buffer hidden and close window |
CTRL-W o or :on[ly] | Make current window only one on the screen |
CTRL-W j | Move cursor to window below |
CTRL-W k | Move cursor to window above |
CTRL-W CTRL-W | Move cursor to window below (wrap) |
CTRL-W W | Move cursor to window above (wrap) |
CTRL-W t | Move cursor to top window |
CTRL-W b | Move cursor to bottom window |
CTRL-W p | Move cursor to previous active window |
CTRL-W r | Rotate windows downwards |
CTRL-W R | Rotate windows upwards |
CTRL-W x | Exchange current window with next one |
CTRL-W = | Make all windows equal height |
CTRL-W - | Decrease current window height |
CTRL-W + | Increase current window height |
CTRL-W _ | Set current window height (default: very high) |
Buffer list functions | |
:buffers or :files | list all known buffer and file names |
:ball or :sball | edit all args/buffers |
:unhide or :sunhide | edit all loaded buffers |
:bunload[!] [N] | unload buffer [N] from memory |
:bdelete[!] [N] | unload buffer [N] and delete it from the buffer list |
in current window / in new window | |
:[N]buffer [N] / :[N]sbuffer [N] | to arg/buf N |
:[N]bnext [N] / :[N]sbnext [N] | to Nth next arg/buf |
:[N]bNext [N] / :[N]sbNext [N] | to Nth previous arg/buf |
:[N]bprevious [N] / :[N]sbprevious [N] | to Nth previous arg/buf |
:brewind / :sbrewind | to first arg/buf |
:blast / :sblast | to last arg/buf |
:[N]bmod [N] / :[N]sbmod [N] | to Nth modified buf |
Folding | |
zfm | create fold of movement m |
:[R]fo | create fold for range R |
zd / zE | delete fold at cursor / window |
zo / zc | open /close one fold |
zD / zC | open /close folds recursively |
[z / z] | move to start /end of current fold |
zj / zk | move down / up to start /end of cthe next fold |
Advanced editing | |
YANKING / DELETEING ranges: [y|d|c|..]i|a[M] (np: yiw, ci(, ca..) [yank | delete | ..] in / all M = move: w,(,[,{,",'... (copy) body of the word/parentases (.. when we ar in the middle of the word/parenthases | |
ctz, cfz zap to char, zap with char | |
Displaying the current Vim environment | |
:abbreviate | list abbreviations |
:args | argument list |
:augroup | augroups |
:autocmd | list auto-commands |
:buffers | list buffers |
:breaklist | list current breakpoints |
:cabbrev | list command mode abbreviations |
:changes | changes |
:cmap | list command mode maps |
:command | list commands |
:compiler | list compiler scripts |
:digraphs | digraphs |
:file | print filename, cursor position and status (like Ctrl-G) |
:filetype | on/off settings for filetype detect/plugins/indent |
:function | list user-defined functions (names and argument lists but not the full code) |
:function Foo | user-defined function Foo() (full code list) |
:highlight | highlight groups |
:history c | command history |
:history = | expression history |
:history s | search history |
:history | your commands |
:iabbrev | list insert mode abbreviations |
:imap | list insert mode maps |
:intro | the Vim splash screen, with summary version info |
:jumps | your movements |
:language | current language settings |
:let | all variables |
:let FooBar | variable FooBar |
:let g: | global variables |
:let v: | Vim variables |
:list | buffer lines (many similar commands) |
:lmap | language mappings (set by keymap or by lmap) |
:ls | buffers |
:ls! | buffers, including "unlisted" buffers |
:map! | Insert and Command-line mode maps (imap, cmap) |
:map | Normal and Visual mode maps (nmap, vmap, xmap, smap, omap) |
:map | buffer local Normal and Visual mode maps |
:map! | buffer local Insert and Command-line mode maps |
:marks | marks |
:menu | menu items |
:messages | message history |
:nmap | Normal-mode mappings only |
:omap | Operator-pending mode mappings only |
display buffer lines (useful after :g or with a range) | |
:reg | registers |
:scriptnames | all scripts sourced so far |
:set all | all options, including defaults |
:setglobal | global option values |
:setlocal | local option values |
:set | options with non-default value |
:set termcap | list terminal codes and terminal keys |
:smap | Select-mode mappings only |
:spellinfo | spellfiles used |
:syntax | syntax items |
:syn sync | current syntax sync mode |
:tabs | tab pages |
:tags | tag stack contents |
:undolist | leaves of the undo tree |
:verbose | show info about where a map or autocmd or function is defined |
:version | list version and build options |
:vmap | Visual and Select mode mappings only |
:winpos | Vim window position (gui) |
:xmap | visual mode maps only |
Tabs | |
vim -p fl1, fl2... | opens fl1, fl2 in new tabs in vim |
vim -p `grep -l TODO *.py` | opens all python files containing TODO string in vim. Each files is opened in newtab |
gt, gT | :tabn / :tabg
,we can join with number argument np: 0gt, 8gt |
:tabe | :tabedit , make new tab, asking for new file to edit |
:tabnew | make new empty tab |
:tabdo %s/2\.5\.2\/2\.6\.2/gc | perform substutution in each tab |
vimgrep | |
:vimgrep "pattern" files | serch for pattern in files and put result to error list error list can be open with :copen and then we can arrows or
:cnext, :cprev to move on entries.ignore case - put "\c" at the beginning of the pattern **/*. - pattern for all txt files |
NERD comments | |
check :help nerdcommenter for a complete list | |
,c | toggle comment, :NERDCommenterToggle |
NERDtree | |
leader n | toggle NERDTree |
Git (throught Fugitive) | |
leader gb | :Gblame |
leader gs | :Gstatus |
leader gd | :Gdiff |
leader gl | :Glog |
leader gc | :Gcommit |
leader gp | :Git push |
Unimpaired | |
check :help unimpaired for a complete list | |
[b / ]b | next / previous buffer |
[n / ]n | next / previous SCM conflict |
[space / ]space | add new line before / after cursor |
vimdiff | |
Vimdiff starts Vim on two (or three) files in diff mode (highlighting differencess of each file wich gets its own window). running:
vimdiff [options] file1 file2 [file3] | |
do | diff obtain. Get changes from other window into the current window. |
:diffget 3 | If you were in buffer 1, writing this command would obtain the difference in buffer 3 |
dp | diff put.Put the changes from current window into the other window |
:diffpu 1 | write this in buffer 3 and it will place the change in buffer 1 |
]c | Jump to the next change |
[c | Jump to the previous change |
Ctr+w Ctr+w | Switch to the other split window. The same with Ctr+arrows |
:diffupdate | update diff |
Filetype / encoding | |
:setf filetype | :setfiletype , filetype is xml/html/python... sets the mode and syntax for filetype |
:set syntax=syntax | set syntax for current buffer |
Other tips | |
:map prefix | list key-map starting from prefix |
:makesession session_file.vim | save your vim session in file |
vim -S session_file.vim | open session |
Interesting links: