Tabla de Contenidos
VIM
Compilar VIM
Descargar de Download
Descomprimir
./configure --with-features=huge --enable-multibyte --prefix=$HOME/local make install
Eliminar luego directorio de fuentes
MAPPING
launching Win IE
nmap ,f :update<CR>:silent !start c:\progra~1\intern~1\iexplore.exe file://%:p<CR> nmap ,i :update<CR>: !start c:\progra~1\intern~1\iexplore.exe <cWORD><CR>
MAKE IT EASY TO UPDATE/RELOAD .vimrc
nmap ,s :source $VIM/.vimrc nmap ,v :e $VIM/.vimrc
Pull word under cursor into LHS of a substitute
nmap <leader>z :%s#\<<c-r>=expand("<cword>")<cr>\>#
send output of previous global command to a new window
nmap <F3> :redir @a<CR>:g//<CR>:redir END<CR>:new<CR>:put! a<CR><CR>
Pull word under cursor into LHS of a substitute
nmap <leader>z :%s#\<<c-r>=expand("<cword>")<cr>\>#
nmap ,t :s/.*/\L&/<bar>:s/\<./\u&/g<cr> [N] " titlise a line nmap ,z :redir @*<Bar>sil exec 'g@<\(input\<Bar>select\<Bar>textarea\<Bar>/\=form\)\>@p'<Bar>redir END<CR> nmap <leader>p :let @* = substitute(@*,'[^[:print:]]','','g')<cr>"*p nnoremap <F2> :let @*=expand("%:p")<cr> :unix " pull full path name into paste buffer for attachment to email etc nnoremap <F2> :let @*=substitute(expand("%:p"), "/", "\\", "g")<cr> :win32
Following 4 maps enable text transfer between VIM sessions
:map <f7> :'a,'bw! c:/aaa/x " save text to file x :map <f8> :r c:/aaa/x " retrieve text :map <f11> :.w! c:/aaa/xr<CR> " store current line :map <f12> :r c:/aaa/xr<CR> " retrieve current line :ab php " list of abbreviations beginning php :map , " list of maps beginning ,
allow use of F10 for mapping (win32)
set wak=no " :h winaltkeys
For use in Maps
<CR> " carriage Return for maps <ESC> " Escape <LEADER> " normally \ <BAR> " | pipe <BACKSPACE> " backspace <SILENT> " No hanging shell window
type table,,, to get <table></table> ### Cool ###
imap ,,, <esc>bdwa<<esc>pa><cr></<esc>pa><esc>kA
list current mappings of all your function keys
:for i in range(1, 12) | execute("map <F".i.">") | endfor [N]
get the original vim command on a mapped key [N]
unmap =
list current mappings of all your function keys
:for i in range(1, 12) | execute("map <F".i.">") | endfor
Pull Visually Highlighted text into LHS of a substitute
:vmap <leader>z :<C-U>%s/\<<c-r>*\>/
insert date eg 31Jan11 [N]
:inoremap \zd <C-R>=strftime("%d%b%y")<CR>
Titlise Visually Selected Text (map for .vimrc)
vmap ,c :s/\<\(.\)\(\k*\)\>/\u\1\L\2/g<CR>
Title Case A Line Or Selection (better)
vnoremap <F6> :s/\%V\<\(\w\)\(\w*\)\>/\u\1\L\2/ge<cr> [N]
titlise a line
nmap ,t :s/.*/\L&/<bar>:s/\<./\u&/g<cr> [N]
Pressing F5 lists all buffer, just type number
:map <F5> :ls<CR>:e #
Quick jumping between splits
map <C-J> <C-W>j<C-W>_ map <C-K> <C-W>k<C-W>_
running file thru an external program (eg php)
map <f9> :update<CR>:!c:/php/php.exe %<CR> map <f2> :update<CR>:!perl -c %<CR>
visual shifting (builtin-repeat)
:vnoremap < <gv :vnoremap > >gv
Swap word with next word
nmap <silent> gw "_yiw:s/\(\%#\w\+\)\(\_W\+\)\(\w\+\)/\3\2\1/<cr><c-o><c-l> [N]
pull full path name into paste buffer for attachment to email etc
nnoremap <F2> :let @*=expand("%:p")<cr> :unix nnoremap <F2> :let @*=substitute(expand("%:p"), "/", "\\", "g")<cr> :win32
reproduce previous line word by word
imap ] @@@<ESC>hhkyWjl?@@@<CR>P/@@@<CR>3s nmap ] i@@@<ESC>hhkyWjl?@@@<CR>P/@@@<CR>3s
Programming keys depending on file type
:autocmd bufenter *.tex map <F1> :!latex %<CR> :autocmd bufenter *.tex map <F2> :!xdvi -hush %<.dvi&<CR>
macro to comment out a block of code using #if 0
vmap out "zdmzO#if 0<ESC>"zp'zi#endif<CR><ESC>
visual searching
:vmap // y/<C-R>"<CR> " search for visually highlighted text
with spec chars
:vmap <silent> // y/<C-R>=escape(@", '\\/.*$^~[]')<CR><CR>
search for declaration of subroutine/function under cursor
:nmap gx yiw/^\(sub\<bar>function\)\s\+<C-R>"<CR>
BUFFERS
:close " close a tab but leave the buffer *N* :tab sball " retab all files in buffer (repair) [N] :ls " list of buffers :bn " goto next buffer :bp " goto previous buffer :wn " save file and move to next (super) :wp " save file and move to previous :bd " remove file from buffer list (super) :bun " Buffer unload (remove window but not from list) :badd file.c " file from buffer list :b3 " go to buffer 3 [C] :b main " go to buffer with main in name eg main.c (ultra) :brew " buffer rewind :sball,:sb " Split all buffers (super) :scrollbind " in each split window :set hidden " Allows to change buffer w/o saving current buffer
capturing output of current script in a separate buffer
:new | r!perl # " opens new buffer,read other buffer :new! x.out | r!perl # " same with named file :new+read!ls
create a new buffer, paste a register “q” into it, then sort new buffer
:new +put q|%!sort
VIMDIFF
local and remote files via ssh
vimdiff /path/to/file scp://remotehost//path/to/file
vim -d file1 file2 " vimdiff (compare differences) dp " "put" difference under cursor to other file do " "get" difference under cursor from other file [c " jump backwards to change ]c " jump forwards to change :set diffopt+=icase " switch case sensitivity on and off
complex diff parts of same file [N]
:1,2yank a | 7,8yank b
Sorting
Sorting with internal sort
[range]sort - sort the lines in the [range], or all lines if [range] is not
given. e.g. :'<,'>sort - sort the current visual selection
:'a,'b!sort -u “ use an external program to filter content
!1} sort -u ” sorts paragraph (note normal mode!!)
:sort /.*\%2v/ " sort all lines on second column [N]
Sorting with external sort
:%!sort -u " use an external program to filter content :'a,'b!sort -u " use an external program to filter content !1} sort -u " sorts paragraph (note normal mode!!) :g/^$/;/^$/-1!sort " Sort each block (note the crucial ;) :let @s=":%!sort -u " :g/^$/;/^$/-1!sort " Sort each block (note the crucial ;)
Searching
searching over multiple lines \_ means including newline
/begin\_.*end " search over possible multiple lines /<!--\_p\{-}--> " search for multiple line comments /fred\_s*joe/ " any whitespace including newline [C]
How to search for a URL without backslashing
?joe " (first) search BACKWARDS!!! clever huh! /joe/e " cursor set to End of match 3/joe/e+1 " find 3rd joe cursor set to End of match plus 1 [C] /joe/s-2 " cursor set to Start of match minus 2 /joe/+3 " find joe move cursor 3 lines down /.*fred\&.*joe " Search for FRED AND JOE in any ORDER! /\<fred\>/ " search for fred but not alfred or frederick [C] /\(^str.*\n\)\{2} " find 2 successive lines starting with str [I " show lines matching word under cursor <cword> (super)
multiple file search
:bufdo /searchstr/ " use :rewind to recommence search :bufdo %s/searchstr/&/gic " say n and then a to stop
Specify what you are NOT searching for (vowels)
/\c\v([^aeiou]&\a){4} " search for 4 consecutive consonants /\%>20l\%<30lgoat " Search for goat between lines 20 and 30 [N] /^.\{-}home.\{-}\zshome/e " match only the 2nd occurence in a line of "home" [N] :%s/home.\{-}\zshome/alone " Substitute only the 2nd occurrence of home in any line [U]
find str but not on lines containing tongue
^\(.*tongue.*\)\@!.*nose.*$ \v^((tongue)@!.)*nose((tongue)@!.)*$ .*nose.*\&^\%(\%(tongue\)\@!.\)*$ :v/tongue/s/nose/&/gic
Substitute
Substitute range and search conditional
:'a,'bg/fred/s/dick/joe/igc " VERY USEFUL
substitute using a register
:s/fred/<c-r>a/g " sub "fred" with contents of register "a" :s/fred/<c-r>asome_text<c-r>s/g :s/fred/\=@a/g " better alternative as register not displayed (not *) [C]
substitute string in column 30 [N]
:%s/^\(.\{30\}\)xx/\1yy/
find replacement text, put in memory, then use \zs to simplify substitute
:%s/"\([^.]\+\).*\zsxx/\1/
substitute singular or plural
:'a,'bs/bucket\(s\)*/bowl\1/gic [N]
Same thing
:s#all/\zs.*#\=substitute(submatch(0), '/', '_', 'g')#
Substitute by splitting line, then re-joining
:s#all/#&^M#|s#/#_#g|-j!
Substitute inside substitute
:%s/.*/\='cp '.submatch(0).' all/'.substitute(submatch(0),'/','_','g')/
perform a substitute on every other line
:g/^/ if line('.')%2|s/^/zz /
Best-Global-combined-with-substitute (*power-editing*)
:'a,'bg/fred/s/joe/susan/gic " can use memory to extend matching :/biz/,/any/g/article/s/wheel/bucket/gic: non-line based [N]
Do a substitute on last visual area [N]
:%s/\%Vold/new/g
duplicating columns
:%s= [^ ]\+$=&&= " duplicate end column :%s= \f\+$=&&= " Dupicate filename :%s= \S\+$=&& " usually the same
Working with Columns sub any str1 in col3
:%s:\(\(\w\+\s\+\)\{2}\)str1:\1str2:
Swapping first & last column (4 columns)
:%s:\(\w\+\)\(.*\s\+\)\(\w\+\)$:\3\2\1:
Substitute string
:%s/^\(.\{30\}\)xx/\1yy/ " substitute string in column 30 [N]
best-substitution
:%s/fred/joe/igc " general substitute command :%s//joe/igc " Substitute what you last searched for [N] :%s/~/sue/igc " Substitute your last replacement string [N] :%s/\r//g " Delete DOS returns ^M
non-greedy matching \{-}
:%s/^.\{-}pdf/new.pdf/ " delete to 1st occurence of pdf only (non-greedy)
%s#^.\{-}\([0-9]\{3,4\}serial\)#\1#gic " delete up to 123serial or 1234serial [N]
Is your Text File jumbled onto one line? use following
:%s/\r/\r/g " Turn DOS returns ^M into real returns :%s= *$== " delete end of line blanks :%s= \+$== " Same thing :%s#\s*\r\?$## " Clean both trailing spaces AND DOS returns :%s#\s*\r*$## " same thing
deleting empty lines
:%s/^\n\{3}// " delete blocks of 3 empty lines :%s/^\n\+/\r/ " compressing empty lines :%s#<[^>]\+>##g " delete html tags, leave text (non-greedy) :%s#<\_.\{-1,}>##g " delete html tags possibly multi-line (non-greedy) :%s#.*\(\d\+hours\).*#\1# " Delete all but memorised string (\1) [N]
Deleting non-ascii characters (some invisible)
:%s/[\x00-\x1f\x80-\xff]/ /g " type this as you see it :%s/[<C-V>128-<C-V>255]//gi " where you have to type the Control-V :%s/[€-ÿ]//gi " Should see a black square & a dotted y :%s/[<C-V>128-<C-V>255<C-V>01-<C-V>31]//gi " All pesky non-asciis :exec "norm /[\x00-\x1f\x80-\xff]/" " same thing
parse xml/soap
%s#><\([^/]\)#>\r<\1#g " split jumbled up XML file into one tag per line [N] %s#><\([^/]\)#>\r<\1#g " split jumbled up XML file into one tag per line [N] %s/</\r&/g " simple split of html/xml/soap [N] :%s#<[^/]#\r&#gic " simple split of html/xml/soap but not closing tag [N] :%s#<[^/]#\r&#gi " parse on open xml tag [N] :%s#\[\d\+\]#\r&#g " parse on numbered array elements [1] [N] ggVGgJ " rejoin XML without extra spaces (gJ) [N] %s=\\n#\d=\r&=g " parse PHP error stack [N] :%s#^[^\t]\+\t## " Delete up to and including first tab [N]
Copy a set of columns using VISUAL BLOCK (NOT BY ordinary v command)
<C-V> then select "column(s)" with motion commands (win32 <C-Q>) then c,d,y,r etc
columnise a csv file for display only as may crop wide columns
:let width = 20 :let fill=' ' | while strlen(fill) < width | let fill=fill.fill | endwhile :%s/\([^;]*\);\=/\=strpart(submatch(1).fill, 0, width)/ge :%s/\s\+$//ge
Highlight a particular csv column (put in .vimrc)
function! CSVH(x)
execute 'match Keyword /^\([^,]*,\)\{'.a:x.'}\zs[^,]*/'
execute 'normal ^'.a:x.'f,'
endfunction
command! -nargs=1 Csv :call CSVH(<args>)
call with
:Csv 5 " highlight fifth column
zf1G " fold everything before this line [N]
memory
:%s#example#& = &#gic " duplicate entire matched string [N] :%s#.*\(tbl_\w\+\).*#\1# " extract list of all strings tbl_* from text [NC] :s/\(.*\):\(.*\)/\2 : \1/ " reverse fields separated by : :%s/^\(.*\)\n\1$/\1/ " delete duplicate lines :%s/^\(.*\)\(\n\1\)\+$/\1/ " delete multiple duplicate lines [N]
use of optional atom \?
:%s#\<[zy]\?tbl_[a-z_]\+\>#\L&#gc " lowercase with optional leading characters
over possibly many lines
:%s/<!--\_.\{-}-->// " delete possibly multi-line comments
:help /\{-} " help non-greedy
multiple commands on one line
:%s/\f\+\.gif\>/\r&\r/g | v/\.gif$/d | %s/gif/jpg/ :%s/a/but/gie|:update|:next " then use @: to repeat
ORing
:%s/goat\|cow/sheep/gc " ORing (must break pipe) :'a,'bs#\[\|\]##g " remove [] from lines between markers a and b [N] :%s/\v(.*\n){5}/&\r " insert a blank line every 5 lines [N]
Calling a VIM function
:s/__date__/\=strftime("%c")/ " insert datestring
format a mysql query
:%s#\<from\>\|\<where\>\|\<left join\>\|\<\inner join\>#\r&#g
filter all form elements into paste register
:redir @*|sil exec 'g#<\(input\|select\|textarea\|/\=form\)\>#p'|redir END :nmap ,z :redir @*<Bar>sil exec 'g@<\(input\<Bar>select\<Bar>textarea\<Bar>/\=form\)\>@p'<Bar>redir END<CR>
decrement numbers by 3
:%s/\d\+/\=(submatch(0)-3)/
increment numbers by 6 on certain lines only
:g/loc\|function/s/\d/\=submatch(0)+6/
better
:%s#txtdev\zs\d#\=submatch(0)+1#g :h /\zs
increment only numbers gg\d\d by 6 (another way)
:%s/\(gg\)\@<=\d\+/\=submatch(0)+6/ :h zero-width
rename a string with an incrementing number
:let i=10 | 'a,'bg/Abc/s/yy/\=i/ |let i=i+1 # convert yy to 10,11,12 etc
as above but more precise
:let i=10 | 'a,'bg/Abc/s/xx\zsyy\ze/\=i/ |let i=i+1 # convert xxyy to xx11,xx12,xx13
best-global command
:g/joe/,/fred/d " not line based (very powerfull) :g/fred/,/joe/j " Join Lines [N] :g/-------/.-10,.d " Delete string & 10 previous lines :g/{/ ,/}/- s/\n\+/\r/g " Delete empty lines but only between {...} :v/\S/d " Delete empty lines (and blank lines ie whitespace) :v/./,/./-j " compress empty lines :g/^$/,/./-j " compress empty lines :g/^/t. " duplicate every line :g/fred/t$ " copy (transfer) lines matching fred to EOF :g/stage/t'a " copy (transfer) lines matching stage to marker a (cannot use .) [C] :g/^Chapter/t.|s/./-/g " Automatically underline selecting headings [N] :g/\(^I[^^I]*\)\{80}/d " delete all lines containing at least 80 tabs
copy after line containing "otherstr"
:'a,'bg/somestr/co/otherstr/ " co(py) or mo(ve)
as above but also do a substitution
:'a,'bg/str1/s/str1/&&&/|mo/str2/ :%norm jdd " delete every other line
incrementing numbers (type <c-a> as 5 characters)
:.,$g/^\d/exe "norm! \<c-a>": increment numbers :'a,'bg/\d\+/norm! ^A " increment numbers
storing glob results (note must use APPEND) you need to empty reg a first with qaq.
:g/fred/y A " append all lines fred to register a :g/fred/y A | :let @*=@a " put into paste buffer :g//y A | :let @*=@a " put last glob into paste buffer [N] :let @a=''|g/Barratt/y A |:let @*=@a
filter lines to a file (file must already exist)
:'a,'bg/^Error/ . w >> errors.txt
duplicate every line in a file wrap a print '' around each duplicate
:g/./yank|put|-1s/'/"/g|s/.*/Print '&'/
replace string with contents of a file, -d deletes the "mark"
:g/^MARK$/r tmp.txt | -d
display prettily
:g/<pattern>/z#.5 " display with context :g/<pattern>/z#.5|echo "==========" " display beautifully
Combining g// with normal mode commands
:g/|/norm 2f|r* " replace 2nd | with a star
Find fred before beginning search for joe
:/fred/;/joe/-2,/sid/+3s/sally/alley/gIC
create a new file for each line of file eg 1.txt,2.txt,3,txt etc
:g/^/exe ".w ".line(".").".txt"
chain an external command
:.g/^/ exe ".!sed 's/N/X/'" | s/I/Q/ [N]
Operate until string found [N]
d/fred/ "delete until fred y/fred/ "yank until fred c/fred/e "change until fred end v12| " visualise/change/delete to column 12 [N]
Summary of editing repeats [N]
. last edit (magic dot) :& last substitute :%& last substitute every line :%&gic last substitute every line confirm g% normal mode repeat last substitute g& last substitute on all lines @@ last recording @: last command-mode command :!! last :! command :~ last substitute :help repeating
Summary of repeated searches
; last f, t, F or T , last f, t, F or T in opposite direction n last / or ? search N last / or ? search in opposite direction
Absolutely-essential
* # g* g# " find word under cursor (<cword>) (forwards/backwards) % " match brackets {}[]() . " repeat last modification @: " repeat last : command (then @@) matchit.vim " % now matches tags <tr><td><script> <?php etc <C-N><C-P> " word completion in insert mode <C-X><C-L> " Line complete SUPER USEFUL /<C-R><C-W> " Pull <cword> onto search/command line /<C-R><C-A> " Pull <CWORD> onto search/command line
MAKE IT EASY TO UPDATE/RELOAD .vimrc
:e $MYVIMRC " edits your .vimrc whereever it might be [N]
How to have a variant in your .vimrc for different PCs [N]
if $COMPUTERNAME == "NEWPC" ab mypc vista else ab mypc dell25 endif
splitting windows
:vsplit other.php # vertically split current file with other.php [N]
VISUAL MODE (easy to add other HTML Tags)
:vmap sb "zdi<b><C-R>z</b><ESC> " wrap <b></b> around VISUALLY selected Text :vmap st "zdi<?= <C-R>z ?><ESC> " wrap <?= ?> around VISUALLY selected Text
vim tabs
vim -p fred.php joe.php " open files in tabs :tabe fred.php " open fred.php in a new tab :tab ball " tab open files
vim forcing use of tabs from .vimrc
:nnoremap gf <C-W>gf :cab e tabe
Exploring
:e . " file explorer :Exp(lore) " file explorer note capital Ex :Sex(plore) " file explorer in split window :browse e " windows style browser :cd .. " move to parent directory :args " list of files :pwd " Print Working Directory (current directory) [N] :args *.php " open list of files (you need this!) :lcd %:p:h " change to directory of current file :cd %:p:h " change to directory of current file [N] :autocmd BufEnter * lcd %:p:h " change to directory of current file automatically (put in .vimrc)
Changing Case
guu " lowercase line gUU " uppercase line Vu " lowercase line VU " uppercase line g\~\~ " flip case line vEU " Upper Case Word vE~ " Flip Case Word ggguG " lowercase entire file
Uppercase first letter of sentences
:%s/[.!?]\_s\+\a/\U&\E/g
gf " open file name under cursor (SUPER)
:nnoremap gF :view <cfile><cr> " open file under cursor, create if necessary
ga " display hex,ascii value of char under cursor
ggVGg? " rot13 whole file
ggg?G " rot13 whole file (quicker for large file)
:8 | normal VGg? " rot13 from line 8
:normal 10GVGg? " rot13 from line 8
<C-A>,<C-X> " increment,decrement number under cursor
win32 users must remap CNTRL-A
<C-R>=5*5 " insert 25 into text (mini-calculator)
Make all other tips superfluous
:h 42 " also http://www.google.com/search?q=42 :h holy-grail :h!
disguise text (watch out) [N]
ggVGg? " rot13 whole file (toggles)
:set rl! " reverse lines right to left (toggles)
:g/^/m0 " reverse lines top to bottom (toggles)
:%s/\(\<.\{-}\>\)/\=join(reverse(split(submatch(1), '.\zs')), '')/g " reverse all text *N*
History, Markers & moving about (what Vim Remembers) [C]
'. " jump to last modification line (SUPER) `. " jump to exact spot in last modification line g; " cycle thru recent changes (oldest first) g, " reverse direction :changes :h changelist " help for above <C-O> " retrace your movements in file (starting from most recent) <C-I> " retrace your movements in file (reverse direction) :ju(mps) " list of your movements :help jump-motions :history " list of all your commands :his c " commandline history :his s " search history q/ " Search history Window (puts you in full edit mode) (exit CTRL-C) q: " commandline history Window (puts you in full edit mode) (exit CTRL-C) :<C-F> " history Window (exit CTRL-C)
Abbreviations & Maps
chain commands in abbreviation
cabbrev vrep tabe class.inc \| tabe report.php ## chain commands [N]
Simple PHP debugging display all variables yanked into register a
iab phpdb exit("<hr>Debug <C-R>a ");
Using a register as a map (preload registers in .vimrc)
:let @m=":'a,'bs/" :let @s=":%!sort -u"
ayy@a " execute "Vim command" in a text file
yy@" " same thing using unnamed register u@. " execute command JUST typed in ddw " store what you delete in register d [N] ccaw " store what you change in register c [N]
Get output from other commands (requires external programs)
:r!ls -R " reads in output of ls
:put=glob('**') " same as above [N]
:r !grep "^ebay" file.txt " grepping in content [N]
:20,25 !rot13 " rot13 lines 20 to 25 [N]
!!date " same thing (but replaces/filters current line)
number lines (linux or cygwin only)
:new | r!nl # [N]
Multiple Files Management (Essential)
:sav php.html " Save current file as php.html and "move" to php.html :sav! %<.bak " Save Current file to alternative extension (old way) :sav! %:r.cfm " Save Current file to alternative extension :sav %:s/fred/joe/ " do a substitute on file name :sav %:s/fred/joe/:r.bak2 " do a substitute on file name & ext. :!mv % %:r.bak " rename current file (DOS use Rename or DEL) :help filename-modifiers :e! " return to unmodified file :w c:/aaa/% " save file elsewhere :e # " edit alternative file (also cntrl-^) :rew " return to beginning of edited files list (:args) :sp fred.txt " open fred.txt into a split :w !sudo tee % " Write to read only file on linux (trick) [N]
Recording (BEST Feature of ALL)
qq " record to q your complex series of commands q " end recording @q to execute @@ to Repeat 5@@ to Repeat 5 times qQ@qq " Make an existing recording q recursive [N]
editing a register/recording
qp "display contents of register q (normal mode)
<ctrl-R>q "display contents of register q (insert mode)
you can now see recording contents, edit as required
qdd "put changed contacts back into q @q "execute recording/register q
Operating a Recording on a Visual BLOCK (blockwise)
1) define recording/register qq:s/ to/ from/g^Mq 2) Define Visual BLOCK V} 3) hit : and the following appears :'<,'> 4)Complete as follows :'<,'>norm @q
Visual basics
v " enter visual mode V " visual mode whole line <C-V> " enter VISUAL BLOCKWISE mode (remap on Windows to say C-Q *C* gv " reselect last visual area (ultra) o " navigate visual area # *y or "+y " yank visual area into paste buffer [C]
V% " visualise what you match V}J " Join Visual block (great) V}gJ " Join Visual block w/o adding spaces ''[v''] " Highlight last insert
Delete 8th and 9th characters of 10 successive lines [C]
08l<c-v>10j2ld (use Control Q on win32) [C]
text objects :h text-objects [C]
daW " delete contiguous non whitespace
di< yi< ci< " Delete/Yank/Change HTML tag contents
da< ya< ca< " Delete/Yank/Change whole HTML tag
dat dit " Delete HTML tag pair
diB daB " Empty a function {}
das " delete a sentence
.vimrc essentials
:imap <TAB> <C-N> " set tab to complete [N] :set incsearch " jumps to search word as you type (annoying but excellent) :set wildignore=*.o,*.obj,*.bak,*.exe " tab complete now ignores these :set shiftwidth=3 " for shift/tabbing :set vb t_vb=". " set silent (no beep) :set browsedir=buffer " Maki GUI File Open use current directory
set iminsert=0 (or toggle CTRL-shift-^) " reset "stuck" caps lock/capslock key [N]
FTPing from VIM
cmap ,r :Nread ftp://209.51.134.122/public_html/index.html cmap ,w :Nwrite ftp://209.51.134.122/public_html/index.html gvim ftp://www.somedomain.com/index.html # uses netrw.vim
appending to registers (use CAPITAL) yank 5 lines into "a" then add a further 5
a5yy 10j A5yy
Conventional Shifting/Indenting
:'a,'b>>
Block shifting (magic)
>i{
>a{
also
>% and <% == " index current line same as line above [N]
Redirection & Paste register *
:redir @* " redirect commands to paste buffer :redir END " end redirect :redir >> out.txt " redirect to a file
Working with Paste buffer
- yy “ yank current line to paste
- p ” insert from paste buffer
yank to paste buffer (ex mode)
:'a,'by* " Yank range into paste :%y* " Yank whole buffer into paste :.y* " Yank Current line to paster
filter non-printable characters from the paste buffer
:nmap <leader>p :let @* = substitute(@*,'[^[:print:]]','','g')<cr>"*p :set paste " prevent vim from formatting pasted in text *N*
Re-Formatting text
gq} " Format a paragraph gqap " Format a paragraph ggVGgq " Reformat entire file Vgq " current line
break lines at 70 chars, if possible after a ;
:s/.\{,69\};\s*\|.\{,69\}\s\+/&\r/g
Operate command over multiple files
:argdo %s/foo/bar/e " operate on all files in :args :bufdo %s/foo/bar/e :windo %s/foo/bar/e :argdo exe '%!sort'|w! " include an external command :bufdo exe "normal @q" | w " perform a recording on open files :silent bufdo !zip proj.zip %:p " zip all current files
Command line tricks
gvim -h " help ls | gvim - " edit a stream!! cat xx | gvim - -c "v/^\d\d\|^[3-9]/d " " filter a stream gvim -o file1 file2 " open into a horizontal split (file1 on top, file2 on bottom) [C] gvim -O file1 file2 " open into a vertical split (side by side,for comparing code) [N]
execute one command after opening file
gvim.exe -c "/main" joe.c " Open joe.c & jump to "main"
execute multiple command on a single file
vim -c "%s/ABC/DEF/ge | update" file1.c
execute multiple command on a group of files
vim -c "argdo %s/ABC/DEF/ge | update" *.c
remove blocks of text from a series of files
vim -c "argdo /begin/+1,/end/-1g/^/d | update" *.c
Automate editing of a file (Ex commands in convert.vim)
vim -s "convert.vim" file.c
load VIM without .vimrc and plugins (clean VIM) e.g. for HUGE files
gvim -u NONE -U NONE -N
Access paste buffer contents (put in a script/batch file)
gvim -c 'normal ggdG"*p' c:/aaa/xp
print paste contents to default printer
gvim -c 's/^/\=@*/|hardcopy!|q!'
gvim's use of external grep (win32 or *nix)
:!grep somestring *.php " creates a list of all matching files [C]
use :cn(ext) :cp(rev) to navigate list
:h grep
Using vimgrep with copen [N]
:vimgrep /keywords/ *.php :copen
complex diff parts of same file [N]
:1,2yank a | 7,8yank b :tabedit | put a | vnew | put b :windo diffthis
Vim traps
In regular expressions you must backslash + (match 1 or more)
In regular expressions you must backslash | (or)
In regular expressions you must backslash ( (group)
In regular expressions you must backslash { (count)
/fred\+/ " matches fred/freddy but not free
/\(fred\)\{2,3}/ " note what you have to break
\v or very magic (usually) reduces backslashing
/codes\(\n\|\s\)*where " normal regexp /\vcodes(\n|\s)*where " very magic
pulling objects onto command/search line (SUPER)
<C-R><C-W> " pull word under the cursor into a command line or search <C-R><C-A> " pull WORD under the cursor into a command line or search <C-R>- " pull small register (also insert mode) <C-R>[0-9a-z] " pull named registers (also insert mode) <C-R>% " pull file name (also #) (also insert mode) <C-R>=somevar " pull contents of a variable (eg :let sray="ray[0-9]")
List your Registers
:reg " display contents of all registers :reg a " display content of register a :reg 12a " display content of registers 1,2 & a [N] 5p " retrieve 5th "ring" 1p.... " retrieve numeric registers one by one :let @y='yy@"' " pre-loading registers (put in .vimrc) qqq " empty register "q" qaq " empty register "a" :reg .-/%:*" " the seven special registers [N] :reg 0 " what you last yanked, not affected by a delete [N]
_dd " Delete to blackhole register "_ , don't affect any register [N]
manipulating registers
:let @a=@_ " clear register a :let @a="" " clear register a :let @a=@" " Save unnamed register [N] :let @*=@a " copy register a to paste buffer :let @*=@: " copy last command to paste buffer :let @*=@/ " copy last search to paste buffer :let @*=@% " copy current filename to paste buffer
help for help (USE TAB)
:h quickref " VIM Quick Reference Sheet (ultra)
:h tips " Vim's own Tips Help
:h visual<C-D><tab> " obtain list of all visual help topics
" Then use tab to step thru them
:h ctrl<C-D> " list help of all control keys
:helpg uganda " grep HELP Files use :cn, :cp to find next
:helpgrep edit.*director: grep help using regexp
:h :r " help for :ex command
:h CTRL-R " normal mode
:h /\r " what's \r in a regexp (matches a <CR>)
:h \\zs " double up backslash to find \zs in help
:h i_CTRL-R " help for say <C-R> in insert mode
:h c_CTRL-R " help for say <C-R> in command mode
:h v_CTRL-V " visual mode
:h tutor " VIM Tutor
<C-]> " jump to {keyword} under cursor in help file [C]
<C-[>, <C-T> " Move back & Forth in HELP History
gvim -h " VIM Command Line Help
:cabbrev h tab help " open help in a tab [N]
where was an option set
:scriptnames " list all plugins, _vimrcs loaded (super) :verbose set history? " reveals value of history and where set :function " list functions :func SearchCompl " List particular function
making your own VIM help
:helptags /vim/vim64/doc " rebuild all *.txt help files in /doc :help add-local-help
save this page as a VIM Help File [N]
:sav! $VIMRUNTIME/doc/vimtips.txt|:1,/^__BEGIN__/d|:/^__END__/,$d|:w!|:helptags $VIMRUNTIME/doc
Inserting DOS Carriage Returns
:%s/$/\<C-V><C-M>&/g " that's what you type :%s/$/\<C-Q><C-M>&/g " for Win32 :%s/$/\^M&/g " what you'll see where ^M is ONE character
automatically delete trailing Dos-returns,whitespace
autocmd BufRead * silent! %s/[\r \t]\+$// autocmd BufEnter *.php :%s/[ \t\r]\+$//e
perform an action on a particular file or file type
autocmd VimEnter c:/intranet/note011.txt normal! ggVGg?
autocmd FileType *.pl exec('set fileformats=unix')
Retrieving last command line command for copy & pasting into text
i<c-r>:
Retrieving last Search Command for copy & pasting into text
i<c-r>/
more completions
<C-X><C-F> "insert name of a file in current directory
Substituting a Visual area
select visual area as usual (:h visual) then type :s/Emacs/Vim/ etc
:'<,'>s/Emacs/Vim/g " REMEMBER you dont type the '<.'> gv " Re-select the previous visual area (ULTRA)
inserting line number into file
:g/^/exec "s/^/".strpart(line(".")."### , 0, 4)
:%s/^/\=strpart(line(".")." ### , 0, 5)
:%s/^/\=line('.'). ' '
*numbering lines VIM way*
:set number " show line numbers
:map <F12> :set number!<CR> " Show linenumbers flip-flop
:%s/^/\=strpart(line('.')." ### ,0,&ts)
numbering lines (need Perl on PC) starting from arbitrary number
:'a,'b!perl -pne 'BEGIN{$a=223} substr($_,2,0)=$a++'
Produce a list of numbers
Type in number on line say 223 in an empty file
qqmnYP`n^Aq " in recording q repeat with @q
increment existing numbers to end of file (type <c-a> as 5 characters)
:.,$g/^\d/exe "normal! \<c-a>"
eg create list starting from 223 incrementing by 5 between markers a,b
:let I=223 :'a,'bs/^/\=INC(5)/
create a map for INC
cab viminc :let I=223 \| 'a,'bs/$/\=INC(5)/
*generate a list of numbers* 23-64
o23<ESC>qqYp<C-A>q40@q
editing/moving within current insert (Really useful)
<C-U> " delete all entered <C-W> " delete last word <HOME><END> " beginning/end of line <C-LEFTARROW><C-RIGHTARROW> " jump one word backwards/forwards <C-X><C-E>,<C-X><C-Y> " scroll while staying put in insert
encryption (use with care: DONT FORGET your KEY)
:X " you will be prompted for a key :h :X
Digraphs (non alpha-numerics)
:digraphs " display table :h dig " help i<C-K>e' " enters é i<C-V>233 " enters é (Unix) i<C-Q>233 " enters é (Win32) ga " View hex value of any character
Pull a non-ascii character onto search bar
yl/<C-R>" " /[^a-zA-Z0-9_[:space:][:punct:]] " search for all non-ascii
All file completions grouped (for example main_c.c)
:e main_<tab> " tab completes gf " open file under cursor (normal) main_<C-X><C-F> " include NAME of file in text (insert mode)
swap two words
:%s/\<\(on\|off\)\>/\=strpart("offon", 3 * ("off" == submatch(0)), 3)/g
Convert Text File to HTML
:runtime! syntax/2html.vim " convert txt to html :h 2html
VIM has internal grep
:grep some_keyword *.c " get list of all c-files containing keyword :cn " go to next occurrence
Change coloring scheme (any file in ~vim/vim??/colors)
:colorscheme blue :colorscheme morning " good fallback colorscheme *N* :set syntax=perl " Force Syntax coloring for a file that has no extension .pl :set syntax off " Remove syntax coloring (useful for all sorts of reasons)
Force syntax automatically (for a file with non-standard extension)
au BufRead,BufNewFile */Content.IE?/* setfiletype html
make cursor standout against highlighted text for vim terminal (linux) [N]
:highlight search term=reverse ctermbg=5 :highlight Normal guibg=white " restore white background [N] :set noma (non modifiable) " Prevents modifications :set ro (Read Only) " Protect a file from unintentional writes
Sessions (Open a set of files)
gvim file1.c file2.c lib/lib.h lib/lib2.h " load files for "session" :mksession " Make a Session file (default Session.vim) :mksession MySession.vim " Make a Session file named file [C] :q gvim -S " Reload all files (loads Session.vim) [C] gvim -S MySession.vim " Reload all files from named session [C]
tags (jumping to subroutines/functions)
taglist.vim " popular plugin :Tlist " display Tags (list of functions) <C-]> " jump to function under cursor
displaying "non-asciis"
:set list :h listchars
How to paste "normal vim commands" w/o entering insert mode
:norm qqy$jq
manipulating file names
:h filename-modifiers " help :w % " write to current file name :w %:r.cfm " change file extention to .cfm :!echo %:p " full path & file name :!echo %:p:h " full path only :!echo %:t " filename only :reg % " display filename <C-R>% " insert filename (insert mode) %p " insert filename (normal mode) /<C-R>% " Search for file name in text
delete without destroying default buffer contents
_d " what you've ALWAYS wanted _dw " eg delete word (use blackhole)
Simple Shell script to rename files w/o leaving vim
:r! ls *.c :%s/\(.*\).c/mv & \1.bla :w !sh :q!
count words/lines in a text file
g<C-G> # counts words :echo line("'b")-line("'a") # count lines between markers a and b [N] :'a,'bs/^//n # count lines between markers a and b :'a,'bs/somestring//gn # count occurences of a string :s/,/,/gn # count commas in a line (csv/parameters)
example of setting your own highlighting
:syn match DoubleSpace " " :hi def DoubleSpace guibg=#e0e0e0
allow yanking of php variables with their dollar [N]
:autocmd bufenter *.php :set iskeyword+=\$
reading Ms-Word documents, requires antiword (not docx)
:autocmd BufReadPre *.doc set ro :autocmd BufReadPre *.doc set hlsearch! :autocmd BufReadPost *.doc %!antiword "%"
folding
vim: filetype=help foldmethod=marker foldmarker=<<<,>>> A really big section closed with a tag <<< --- remember folds can be nested --- Closing tag >>>
zf} " fold paragraph using motion v}zf " fold paragraph using visual zf'a " fold to mark zo " open fold zc " re-close fold zfG " fold everything after this line [N]
Return to last edit position (You want this!) [N]
autocmd BufReadPost *
\ if line("'\"") > 0 && line("'\"") <= line("$") |
\ exe "normal! g`\"" |
\ endif
encryption (use with care: DON'T FORGET your KEY)
:X " you will be prompted for a key :h :X // vim:noai:ts=2:sw=4:readonly: " modeline (make a file readonly etc) must be in first/last 5 lines :h modeline " vim:ft=html: " says use HTML Syntax highlighting map ,p :call SaveWord() :g/^/ call Del() :digraphs " display table " Digraphs (non alpha-numerics) :h dig " help i<C-K>e' " enters é i<C-V>233 " enters é (Unix) i<C-Q>233 " enters é (Win32) ga " View hex value of any character
tags (jumping to subroutines/functions)
taglist.vim " popular plugin :Tlist " display Tags (list of functions) <C-]> " jump to function under cursor
Pull a non-ascii character onto search bar yl/<C-R>"
/[^a-zA-Z0-9_[:space:][:punct:]] " search for all non-ascii :e main_<tab> " tab completes " All file completions grouped (for example main_c.c) main_<C-X><C-F> " include NAME of file in text (insert mode) :%s/\<\(on\|off\)\>/\=strpart( "offon", 3 * ("off" == submatch(0)), 3)/g nmap <silent> gw "_yiw:s/\(\%#\w\+\)\(\_W\+\)\(\w\+\)/\3\2\1/<cr><c-o><c-l> [N] " Swap word with next word :runtime! syntax/2html.vim " convert txt to html " Convert Text File to HTML :h 2html :grep some_keyword *.c " get list of all c-files containing keyword " VIM has internal grep :cn " go to next occurrence au BufRead,BufNewFile */Content.IE?/* setfiletype html " Force syntax automatically (for a file with non-standard extension) :set noma (non modifiable) " Prevents modifications :set ro (Read Only) " Protect a file from unintentional writes gvim file1.c file2.c lib/lib.h lib/lib2.h " load files for "session" " Sessions (Open a set of files) :mksession " Make a Session file (default Session.vim) :mksession MySession.vim " Make a Session file named file [C] gvim -S " Reload all files (loads Session.vim) [C] gvim -S MySession.vim " Reload all files from named session [C]
Mixed
!!date " same thing (but replaces/filters current line) "%p " insert filename (normal mode) "*p " insert from paste buffer "*y or "+y " yank visual area into paste buffer [C] "*yy " yank curent line to paste " Working with Paste buffer "+ and "* - clipboard and current selection registers under X. e.g. "+p to paste from the clipboard and "+y to copy to the clipboard "1p.... " retrieve numeric registers one by one "2p will put the second to last thing yanked, "3p will put the third to last, etc. "5p " retrieve 5th "ring" "_d " what you've ALWAYS wanted " delete without destroying default buffer contents "_d will delete the selection without adding it to the yanked stack (sending it to the black hole register). "_dd " Delete to blackhole register "_ , don't affect any register [N] "_dw " eg delete word (use blackhole) "ayy@a " execute "Vim command" in a text file " Useful tricks "ccaw " store what you change in register c [N] "ddw " store what you delete in register d [N] "qdd " put changed contacts back into q " you can now see recording contents, edit as required "qp " display contents of register q (normal mode) " editing a register/recording % " match brackets {}[]() % matches brackets {} [] (), and with matchit.vim, also matches def/end, < ?php/?>, < p>/< /p>, etc. % matches opening and closing chars (){}[], and with matchit.vim, def/end, HTML tags, etc. as well! %:exec ":new ".(substitute(expand("%"), ".c$", ".h", "")) - open the associated .h file for the current .c file in a new window; more concisely :new %:p:r.h %< - resolves the current filename without extension. e.g. :e %<.h - open the header file for the current file %s/<C-R>a/bar/g will place the contents of register 'a' in the search, and replace it with 'bar'. & - re-run last :s command (&& to remember flags) '0 opens the last modified file ('1 '2 '3 works too) ':%y c': yank entire file into register c. '"cp': Paste contents of c into document. * # g* g# " find word under cursor (<cword>) (forwards/backwards) , last f, t, F or T in opposite direction . " repeat last modification .*nose.*\&^\%(\%(tongue\)\@!.\)*$ /.*fred&.*joe/ will search for fred AND joe, in any order. /.*fred\&.*joe " Search for FRED AND JOE in any ORDER! /<!--\_p\{-}--> " search for multiple line comments " searching over multiple lines \_ means including newline /<C-R>% " Search for file name in text /<C-R><C-A> " Pull <CWORD> onto search/command line /<C-R><C-W> " Pull <cword> onto search/command line /<\@<=[^>]*>\@= " search for tag contents, ignoring chevrons " zero-width :h /\@= /<\@<=\_[^>]*>\@= " search for tags across possible multiple lines /<\zs[^>]*\ze> " search for tag contents, ignoring chevrons " \zs and \ze regex delimiters :h /\zs /<fred>/ will search for fred, but not alfred or frederick. /\%>20l\%<30lgoat " Search for goat between lines 20 and 30 [N] /\%>80v.\+ with search highlighting (:set hlsearch) will highlight any text after column 80. /\([^0-9]\|^\)%.*% " Search for absence of a digit or beginning of line /\(^str.*\n\)\{2} " find 2 successive lines starting with str /\(fred\).*\(joe\).*\2.*\1 " using rexexp memory in a search find fred.*joe.*joe.*fred *C* /\(fred\)\{2,3}/ " note what you have to break /\<\d\d\d\d\> " Search for exactly 4 digit numbers /\<\d\{4}\> " same thing /\<fred\>/ " search for fred but not alfred or frederick [C] /\D\d\d\d\d\D " Search for exactly 4 digit numbers /\c\v([^aeiou]&\a){4} " search for 4 consecutive consonants " Specify what you are NOT searching for (vowels) /\vcodes(\n|\s)*where " very magic /^.\{-}home.\{-}\zshome/e " match only the 2nd occurence in a line of "home" [N] /^[A-J]/ " search for lines beginning with one or more A-J /^\([^,]*,\)\{8} " Repeating the Regexp (rather than what the Regexp finds) /^\n\{3} " find 3 empty lines " finding empty lines /^joe.*fred.*bill/ " find joe AND fred AND Bill (Joe at start of line) /^str.*\nstr " find 2 successive lines starting with str /begin\_.*end " search over possible multiple lines /begin\_.*end will search for begin AND end over multiple lines. /bugs\(\_.\)*bunny " bugs followed by bunny anywhere in file /codes\(\n\|\s\)*where " normal regexp " \v or very magic (usually) reduces backslashing /fred\+/ " matches fred/freddy but not free /fred\_s*joe/ " any whitespace including newline *C* /fred\_s*joe/ " any whitespace including newline [C] /fred\_s*joe/ will search for fred AND joe with whitespace (including newline) in between. /fred\|joe " Search for FRED OR JOE /fred|joe/ will search for either fred OR joe. /joe.*fred.*bill/ will search for joe AND fred AND bill, in that order. /joe/+3 will search for joe and place the cursor three lines below the match. /joe/e will search for joe and place the cursor at the end of the match. /joe/e+1 will search for joe and place the cursor at the end of the match, plus on character. /joe/s-2 will search for joe and place the cursor at the start of the match, minus two characters. 0 - Move to the first character of the line 0/joe/+3 " find joe move cursor 3 lines down 08l<c-v>10j2ld (use Control Q on win32) [C] " Delete 8th and 9th characters of 10 successive lines [C] 5@@ " Repeat a macro 5 times :!! last :! command :!echo %:p " full path & file name :!echo %:p:h " full path only :!echo %:t " filename only :!grep somestring *.php " creates a list of all matching files :!mv % %:r.bak " rename current file (DOS use Rename or DEL) :%& last substitute every line :%&gic last substitute every line confirm :%norm jdd " delete every other line :%s#.*(hours).*#1# will delete everything on a line except for the string 'hours'. :%s#.*\(\d\+hours\).*#\1# " Delete all but memorised string (\1) [N] :%s#.*\(tbl_\w\+\).*#\1# " extract list of all strings tbl_* from text [NC] :%s#<[^>]\+>##g " delete html tags, leave text (non-greedy) :%s#<\_.\{-1,}>##g " delete html tags possibly multi-line (non-greedy) :%s#\<[zy]\?tbl_[a-z_]\+\>#\L&#gc " lowercase with optional leading characters " use of optional atom \? :%s#\s*\r\?$## " Clean both trailing spaces AND DOS returns :%s#example#& = &#gic " duplicate entire matched string [N] " memory :%s#txtdev\zs\d#\=submatch(0)+1#g " better :%s,\(all/.*\)\@<=/,_,g " replace all / with _ AFTER "all/" :%s/"\([^.]\+\).*\zsxx/\1/ " find replacement text, put in memory, then use \zs to simplify substitute :%s/$/\<C-Q><C-M>&/g " for Win32 :%s/$/\<C-V><C-M>&/g " that's what you type " Inserting DOS Carriage Returns :%s/$/\^M&/g " what you'll see where ^M is ONE character :%s/.*/\='cp '.submatch(0).' all/'.substitute(submatch(0),'/','_','g')/ " Substitute inside substitute :%s//joe/igc " Substitute what you last searched for [N] :%s//joe/igc substitute your last search with joe. :%s/<!--\_.\{-}-->// " delete possibly multi-line comments " over possibly many lines :%s/[.!?]\_s\+\a/\U&\E/g " Uppercase first letter of sentences :%s/\%Vold/new/g " Do a substitute on last visual area [N] :%s/\(.*\).c/mv & \1.bla :%s/\([^;]*\);\=/\=strpart(submatch(1).fill, 0, width)/ge :%s/\(\<.\{-}\>\)/\=join(reverse(split(submatch(1), '.\zs')), '')/g " reverse all text *N* :%s/\(gg\)\@<=\d\+/\=submatch(0)+6/ " increment only numbers gg\d\d by 6 (another way) :%s/\\/\//g replaces all backslashes with forward slashes :%s/\d\+/\=(submatch(0)-3)/ " decrement numbers by 3 :%s/\f\+\.gif\>/\r&\r/g | v/\.gif$/d | %s/gif/jpg/ " multiple commands on one line :%s/\r//g " Delete DOS returns ^M :%s/\s\+$//ge :%s/\v(.*\n){5}/&\r " insert a blank line every 5 lines [N] :%s/\v(.*\n){5}/&\r will insert a blank line every 5 lines :%s/^.\{-}pdf/new.pdf/ " delete to 1st occurence of pdf only (non-greedy) " non-greedy matching \{-} :%s/^/\=line('.'). ' ' :%s/^/\=strpart(line(".")." ", 0, 5) :%s/^/\=strpart(line('.')." ",0,&ts) :%s/^\(.*\)\(\n\1\)\+$/\1/ " delete multiple duplicate lines [N] :%s/^\(.*\)\n\1$/\1/ " delete duplicate lines :%s/^\n\+/\r/ " compressing empty lines :%s/^\n\{3}// will delete a block of 3 empty lines. :%s/a/but/gie|:update|:next " then use @: to repeat :%s/fred/joe/igc " general substitute command " *best-substitution* :%s/goat\|cow/sheep/gc " ORing (must break pipe) " ORing :%s/home.\{-}\zshome/alone " Substitute only the occurrence of home in any line [N] :%s/~/sue/igc " Substitute your last replacement string [N] :%s/~/sue/igc substitute your last replacement string with 'sue'. :%s= *$== " delete end of line blanks :%s= \+$== " Same thing :%y c copies the entire buffer into register c. "cp inserts the content of register c in the current document. :%y* " Yank whole buffer into paste :& last substitute :'a,'b!perl -pne 'BEGIN{$a=223} substr($_,2,0)=$a++' " numbering lines (need Perl on PC) starting from arbitrary number " Produce a list of numbers " Type in number on line say 223 in an empty file :'a,'b>> " Conventional Shifting/Indenting :'a,'bg/\d\+/norm! ^A " increment numbers :'a,'bg/^/m'b " Reverse a section a to b :'a,'bg/^Error/ . w >> errors.txt " filter lines to a file (file must already exist) :'a,'bg/fred/s/dick/joe/igc " VERY USEFUL " VIM Power Substitute :'a,'bg/fred/s/joe/susan/gic " can use memory to extend matching " *Best-Global-combined-with-substitute* (*power-editing*) :'a,'bg/somestr/co/otherstr/ " co(py) or mo(ve) :'a,'bg/str1/s/str1/&&&/|mo/str2/ copy or move or substitute :'a,'bs#\[\|\]##g " remove [] from lines between markers a and b [N] :'a,'bs/^//n # count lines between markers a and b :'a,'bs/^/\=INC(5)/ :'a,'bs/bucket\(s\)*/bowl\1/gic [N] " substitute singular or plural :'a,'bs/somestring//gn # count occurences of a string :'a,'by* " Yank range into paste " yank to paste buffer (ex mode) :.,$g/^\d/exe "norm! \<c-a>" " increment numbers :.,$g/^\d/exe "normal! \<c-a>" " increment existing numbers to end of file (type <c-a> as 5 characters) :.g/^/ exe ".!sed 's/N/X/'" | s/I/Q/ [N] " chain an external command :/biz/,/any/g/article/s/wheel/bucket/gic: non-line based [N] :/fred/,/joe/s/fred/joe/gic " non-line based (ultra) :/fred/;/joe/-2,/sid/+3s/sally/alley/gIC " Find fred before beginning search for joe :20,25 !rot13 " rot13 lines 20 to 25 [N] :40,50m30 will move lines 40 through 50 to line 30. Most visual mode commands can be used with line numbers. :8 | normal VGg? " rot13 from line 8 :<C-F> " history Window (exit CTRL-C) :Csv 5 " highlight fifth column " call with :E to see a simple file explorer. (:Ex will too, if that's easier to remember.) :Exp(lore) " file explorer note capital Ex :Sex(plore) " file explorer in split window :argdo %s/foo/bar/e " operate on all files in :args " Operate command over multiple files :argdo exe '%!sort'|w! " include an external command :args " list of files :args *.php " open list of files (you need this!) :autocmd BufEnter * lcd %:p:h " change to directory of current file automatically (put in .vimrc) :b main " go to buffer with main in name eg main.c (ultra) :b3 " go to buffer 3 [C] :badd file.c " file from buffer list :bd " remove file from buffer list (super) :bn " goto next buffer " Multiple Files Management (Essential) :bp " goto previous buffer :brew " buffer rewind :browse e " windows style browser :bufdo %s/foo/bar/e " operate on all files in :args " Operate command over multiple files :bufdo %s/searchstr/&/gic " say n and then a to stop " multiple file search better but cheating :bufdo /searchstr/ " use :rewind to recommence search " multiple file search :bufdo exe "normal @q" | w " perform a recording on open files :bun " Buffer unload (remove window but not from list) :cab e tabe :cab ,f :for i in range(1, 12) \| execute("map <F".i.">") \| endfor " for your .vimrc :cabbrev h tab h " open help in a tab [N] :cd .. " move to parent directory :close " close a tab but leave the buffer *N* :copen :e # " edit alternative file (also cntrl-^) :e $MYVIMRC " edits your .vimrc whereever it might be [N] :e . " file explorer " Exploring :e! " return to unmodified file :echo line("'b")-line("'a") # count lines between markers a and b [N] :func SearchCompl " List particular function :function " list functions :g!/^dd/d " delete lines not containing string :g/./yank|put|-1s/'/"/g|s/.*/Print '&'/ " duplicate every line in a file wrap a print '' around each duplicate :g/<input\|<form/p " ORing :g/<pattern>/z#.5 " display with context " display prettily :g/<pattern>/z#.5|echo "==========" " display beautifully :g/\(^I[^^I]*\)\{80}/d " delete all lines containing at least 80 tabs :g/\<fred\>/ " display all lines fred but not freddy :g/^$/,/./-j " compress empty lines :g/^/ if line('.')%2|s/^/zz / " perform a substitute on every other line :g/^/exe ".w ".line(".").".txt" " create a new file for each line of file eg 1.txt,2.txt,3,txt etc :g/^/exec "s/^/".strpart(line(".")." ", 0, 4) " inserting line number into file :g/^/m$ " No effect! [N] :g/^/m0 " Reverse file (m = move) :g/^/m0 " reverse lines top to bottom (toggles) :g/^/put_ " double space file (pu = put) :g/^/t. " duplicate every line :g/^Chapter/t.|s/./-/g " Automatically underline selecting headings [N] :g/^MARK$/r tmp.txt | -d " replace string with contents of a file, -d deletes the "mark" :g/^\s*$/d " delete all blank lines :g/_pattern_/s/^/#/g will comment out lines containing _pattern_ (if '#' is your comment character/sequence) :g/fred.*joe.*dick/ " display all lines fred,joe & dick :g/fred/,/joe/j " Join Lines [N] :g/fred/t$ " copy (transfer) lines matching fred to EOF :g/fred/y A " append all lines fred to register a :g/fred/y A | :let @*=@a " put into paste buffer :g/gladiolli/# " display with line numbers (YOU WANT THIS!) " *best-global* command :g/joe/,/fred/d " not line based (very powerfull) :g/loc\|function/s/\d/\=submatch(0)+6/ " increment numbers by 6 on certain lines only :g/search_term/# display each line containing 'search_term' with line numbers. :g/stage/t'a " copy (transfer) lines matching stage to marker a (cannot use .) [C] :g/{/ ,/}/- s/\n\+/\r/g " Delete empty lines but only between {...} :g/|/norm 2f|r* " replace 2nd | with a star " Combining g// with normal mode commands :h /\r " what's \r in a regexp (matches a <CR>) :h :r " help for :ex command :h CTRL-R " normal mode :h \\zs " double up backslash to find \zs in help :h \_ " help :h c_CTRL-R " help for say <C-R> in command mode :h ctrl<C-D> " list help of all control keys :h filename-modifiers " help " manipulating file names :h grep " use :cn(ext) :cp(rev) to navigate list :h i_CTRL-R " help for say <C-R> in insert mode :h listchars :h quickref " VIM Quick Reference Sheet (ultra) " help for help (USE TAB) :h regexp<C-D> " type control-D and get a list all help topics containing regexp (plus use TAB to Step thru list) :h slash<CTRL-d> to get a list of all help topics containing the word 'slash'. :h tips " Vim's own Tips Help :h tutor " VIM Tutor :h v_CTRL-V " visual mode :h visual<C-D><tab> " obtain list of all visual help topics :help /\{-} " help non-greedy :help add-local-help :help filename-modifiers :help repeating :helpgrep edit.*director: grep help using regexp use :cn, :cp to find next :helptags /vim/vim64/doc " rebuild all *.txt help files in /doc " making your own VIM help :imap <TAB> <C-N> " set tab to complete [N] " .vimrc essentials :inoremap \zd <C-R>=strftime("%d%b%y")<CR> " insert date eg 31Jan11 [N] :ju(mps) " list your movements {{help|jump-motions}} :lcd %:p:h " change to directory of current file :lcd %:p:h will change to the directory of the current file. :let @*=@% " copy current filename to paste buffer :let @*=@/ " copy last search to paste buffer :let @*=@: " copy last command to paste buffer :let @*=@a " copy register a to paste buffer :let @a="" " clear register a :let @a=''|g/Barratt/y A |:let @*=@a :let @a=@" " Save unnamed register [N] :let @a=@_ " clear register a " manipulating registers :let @m=":'a,'bs/" " Using a register as a map (preload registers in .vimrc) :let @y='yy@"' " pre-loading registers (put in .vimrc) :let I=223 " eg create list starting from 223 incrementing by 5 between markers a,b :let i=10 | 'a,'bg/Abc/s/xx\zsyy\ze/\=i/ |let i=i+1 # convert xxyy to xx11,xx12,xx13 " as above but more precise :let i=10 | 'a,'bg/Abc/s/yy/\=i/ |let i=i+1 # convert yy to 10,11,12 etc " rename a string with an incrementing number :let width = 20 " columnise a csv file for display only as may crop wide columns :ls " list of buffers :map <F5> :ls<CR>:e # " Pressing F5 lists all buffer, just type number :map <F11> :.w! c:/aaa/xr<CR> " store current line :map <F12> :r c:/aaa/xr<CR> " retrieve current line :map <F7> :'a,'bw! c:/aaa/x " save text to file x :map <F8> :r c:/aaa/x " retrieve text :map <F12> :set number!<CR> " Show linenumbers flip-flop :match ErrorMsg '\%>80v.\+' uses matching to highlight lines longer than 80 columns. :new +put q|%!sort " create a new buffer, paste a register "q" into it, then sort new buffer :new | r!nl # [N] " number lines (linux or cygwin only) :new | r!perl # " opens new buffer,read other buffer " capturing output of current script in a separate buffer :new! x.out | r!perl # " same with named file :new+read!ls :nnoremap gF :view <cfile><cr> " open file under cursor, create if necessary :nnoremap gf <C-W>gf " vim 7 forcing use of tabs from .vimrc :norm qqy$jq " How to paste "normal vim commands" w/o entering insert mode :normal 10GVGg? " rot13 from line 8 :only - close all windows except the current one (alternatives: ctrl-w ctrl-o or :on) :put=glob('**') " same as above [N] :pwd " Print Working Directory (current directory) [N] :r !date will insert the current date/time stamp (from the 'date' command " a bit OS-specific). :r !grep "^ebay" file.txt " grepping in content [N] :r!<cmd> - insert the result of <cmd> into the current buffer at the cursor. e.g. :r!ls *.h :r!ls -R " reads in output of ls " Get output from other commands (requires external programs) :redir >> out.txt " redirect to a file :redir @* " redirect commands to paste buffer " Redirection & Paste register * :redir END " end redirect :reg " display contents of all registers " List your Registers :reg % " display filename :reg .-/%:*" " the seven special registers [N] :reg 0 " what you last yanked, not affected by a delete [N] :reg 12a " display content of registers 1,2 & a [N] :reg a " display content of register a :retab <ts> - convert strings of white-space containing <Tab> with new strings using the <ts> value if given or current value of 'tabstop' :rew " return to beginning of edited files list (:args) :s#all/#&^M#|s#/#_#g|-j! " Substitute by splitting line, then re-joining :s#all/\zs.*#\=substitute(submatch(0), '/', '_', 'g')# " Same thing :s/.\{,69\};\s*\|.\{,69\}\s\+/&\r/g " break lines at 70 chars, if possible after a ; :s/\(.*\):\(.*\)/\2 " \1/ " reverse fields separated by : :s/\(.*\):\(.*\)/\2 " \1/ will reverse fields separated by ':' :s/__date__/\=strftime("%c")/ " insert datestring " Calling a VIM function :s/fred/<c-r>a/g " sub "fred" with contents of register "a" " substitute using a register :s/fred/<c-r>asome_text<c-r>s/g :s/fred/\=@a/g " better alternative as register not displayed (not *) [C] :sav %:s/fred/joe/ " do a substitute on file name :sav %:s/fred/joe/:r.bak2 " do a substitute on file name & ext. :sav php.html " Save current file as php.html and "move" to php.html :sav! $VIMRUNTIME/doc/vimtips.txt|:1,/^__BEGIN__/d|:/^__END__/,$d|:w!|:helptags $VIMRUNTIME/doc " save this page as a VIM Help File [N] :sav! %:r.cfm " Save Current file to alternative extension :sball,:sb " Split all buffers (super) :scriptnames " list all plugins, _vimrcs loaded (super) " where was an option set :scrollbind " in each split window :set cursorline - Highlight the current line under the cursor :set expandtab - use spaces rather than the tab character to insert a tab. :set hidden " Allows to change buffer w/o saving current buffer :set ignorecase " you nearly always want this :set incsearch " jumps to search word as you type (annoying but excellent) :set laststatus=2 - always show the status line (0 = never, 1 = (default) only if there are two or more windows, 2 = always) :set list " displaying "non-asciis" :set nowrap - disable line wrapping :set number " show line numbers " *numbering lines VIM way* :set paste " prevent vim from formatting pasted in text :set pastetoggle=key - specify a key sequence that toggles the paste option, e.g. set pastetoggle=<F2> :set rl! " reverse lines right to left (toggles) :set shiftwidth=3 " for shift/tabbing :set showcmd - show the number of lines/chacters in a visual selection :set smartcase " overrides ignorecase if uppercase used in search string (cool) :set smartcase case sensitive if search contains an uppercase character and ignorecase is on. :set softtabstop <n> - set the number of spaces to insert when using the tab key (converted to tabs and spaces if expandtab is off). :set syntax=perl " force syntax (usually taken from file extension) :set title - display info in terminal title. Add let &titleold=getcwd() to .vimrc to set it to something useful on quit :set titlestring=%f set the file name as the terminal title. :set vb t_vb=". " set silent (no beep) :set wildignore=*.o,*.obj,*.bak,*.exe " tab complete now ignores these :sh or :shell to open a console (then exit to come back to vim). :silent bufdo !zip proj.zip %:p " zip all current files :sp fred.txt " open fred.txt into a split :split - split the current window in two :syn match DoubleSpace " " " example of setting your own highlighting :syntax on " colour syntax in Perl,HTML,PHP etc :tab ball " tab open files :tab sball " retab all files in buffer (repair) [N] :tabdo [some command] will execute the command in all tabs. Also see windo, bufdo, argdo. :tabe <filename> - open <filename> in a new tab (same as :tabedit and :tabnew) :tabe fred.php " open fred.php in a new tab :tabedit | put a | vnew | put b :tabo closes all tabs execpt the current one. :v/./,/./-j " compress empty lines :v/\S/d " Delete empty lines (and blank lines ie whitespace) :v/^dd/d " delete lines not containing string :v/tongue/s/nose/&/gic :verbose set history? " reveals value of history and where set :vimgrep /keywords/ *.php " Using vimgrep with copen :vimgrep /stext/ **/*.txt | :copen searches for stext recursively in *.txt files and show results in separate window :vimgrep pattern **/*.txt will search all *.txt files in the current directory and its subdirectories for the pattern. :vimgrep pattern *.txt will search all .txt files in the current directory for the pattern. :vmap <leader>z :<C-U>%s/\<<c-r>*\>/ " Pull Visually Highlighted text into LHS of a substitute :vmap sb "zdi<b><C-R>z</b><ESC> " wrap <b></b> around VISUALLY selected Text :vmap st "zdi<?= <C-R>z ?><ESC> " wrap <?= ?> around VISUALLY selected Text :vnoremap < <gv " visual shifting (builtin-repeat) :vnoremap > >gv :vsplit filename will split the window vertically and open the file in the left-hand pane. Great when writing unit tests! :vsplit other.php # vertically split current file with other.php [N] " splitting windows :w !sudo tee % will use sudo to write the open file (have you ever forgotten to `sudo vim /path/to/file`?) :w % " write to current file name :w %:r.cfm " change file extention to .cfm :w c:/aaa/% " save file elsewhere :w!|sav! vimtips.html|:/^__BEGIN__/,/^__END__/s#<#\<#g|:w!|:!vimtipsftp :windo %s/foo/bar/e " operate on all files in :args " Operate command over multiple files :windo diffthis :wn " save file and move to next (super) :wp " save file and move to previous :x is like ":wq", but write only when changes have been made :~ last substitute ; last f, t, F or T " Summary of repeated searches ; is a motion to repeat last find with f. f' would find next quote. c; would change up to the next ' <C-A>,<C-X> " increment,decrement number under cursor <C-N><C-P> " word completion in insert mode <C-R>% " insert filename (insert mode) <C-R>% " pull file name (also #) (also insert mode) <C-R>- " pull small register (also insert mode) <C-R><C-A> " pull WORD under the cursor into a command line or search <C-R><C-W> " pull word under the cursor into a command line or search " pulling objects onto command/search line (SUPER) <C-R>=5*5 " insert 25 into text (mini-calculator) <C-R>=somevar " pull contents of a variable (eg :let sray="ray[0-9]") <C-R>[0-9a-z] " pull named registers (also insert mode) <C-U> " delete all entered " editing/moving within current insert (Really useful) <C-U> / <C-D> move the cursor up/down half a page (also handy :set nosol) <C-V> " enter VISUAL BLOCKWISE mode (remap on Windows to say C-Q *C* <C-V> then select "column(s)" with motion commands (win32 <C-Q>) <C-X><C-E>,<C-X><C-Y> " scroll while staying put in insert <C-X><C-F> :insert name of a file in current directory " more completions <C-X><C-L> " Line complete SUPER USEFUL <C-[>, <C-T> " Move back & Forth in HELP History <CTRL-o> " trace your movements backwards in a file. <CTRL-i> trace your movements forwards in a file. <CTRT-W>v == :vsplit like <CTRL-w>s == :split <ctrl-R>q " display contents of register q (insert mode) = " re-indent (e.g. == to re-indent the current line). == " index current line same as line above [N] >% and <% " Block shifting (magic) >a{ " Block shifting (magic) >i{ " Block shifting (magic) @: last command-mode command @: " repeat last " command (then @@) @@ last recording @@ " Repeat a macro A - enter insert mode at the end of the line (Append); I - insert before the first non-blank of the line Basic commands 'f' and 't' (like first and 'til) are very powerful. See :help t or :help f. CTRL-U/CTRL-D - scroll up/down, moving the cursor the same number of lines if possible (unlike <PageUp>/<PageDown>) CTRL-V <tab> - in insert mode, enters a real tab character, disregarding tab and indent options CTRL-w K will switch vertical split into horizontal, CTRL-w H will switch a horizontal into a vertical. CTRL-w s CTRL-w T will open current buffer in new tab Ctrl + o " Execute a command while in insert mode, then go back to insert mode. e.g. ctrl+o, p; paste without exiting insert mode Ctrl-T and Ctrl-D - indent and un-indent the current line in insert mode Ctrl-a, Ctrl-x will increment and decrement, respectively, the number under the cursor. May be precede by a count. Ctrl-c to quickly get out of command-line mode. (Faster than hitting ESC a couple times.) Ctrl-y (insert mode): insert character which is on the line above cursor. example: handy to initialize a structure. Edit a command output in Vim as a file: $ command | vim - Edit and encrypt a file: vim -x filename From a command-line, vim scp://username@host//path/to/file to edit a remote file locally. I/A in visual blockwise mode (ctrl-v) insert some text at the star/end of each line of the block text. I/A switch to insert mode before/after the current line. If gvim is started from a terminal it opens at the same width as the terminal. To prevent this, add "set columns=80" to ~/.vimrc In insert mode do Ctrl+r=53+17<Enter>. This way you can do some calcs with vim. In regular expressions you must backslash ( (group) In regular expressions you must backslash + (match 1 or more) " Vim traps In regular expressions you must backslash { (count) In regular expressions you must backslash | (or) K runs a prgrm to lookup the keyword under the cursor. If writing C, it runs man. In Ruby, it (should) run ri, Python (perhaps) pydoc. N last / or ? search in opposite direction Need to edit a file in hex ? :help hex-editing gives you the manual. Prefixing G or gg (command mode) with a number will cause vim to jump to that line number. Use '\v' in your regex to set the mode to 'very magic', and avoid confusion. (:h \v for more info.) V " visual mode whole line V% " visualise what you match VU " uppercase line Vgq " current line Vu " lowercase line V}J " Join Visual block (great) V}gJ " Join Visual block w/o adding spaces When editing multiple files (e.g. vim *.c), use :n to move to the next file and :N to move to the previous file. :ar shows the list of files [I " show lines matching word under cursor <cword> (super) [I (big i) shows lines containing the word under the cursor [I (that's bracket open, capital i) show lines containing the word under the cursor. \v^((tongue)@!.)*nose((tongue)@!.)*$ ] " Highlight last insert ^\(.*tongue.*\)\@!.*nose.*$ " find str but not on lines containing tongue `:'<,'>s/Emacs/Vim/g` " REMEMBER you dont type the `'<.'>` `:act<` " Change Till `<` [N] " store text that is to be changed or deleted in register a `:let fill=' ' | while strlen(fill) < width | let fill=fill.fill | endwhile` `:sav! %<.bak` " Save Current file to alternative extension (old way) a/A " append at the cursor position / at the end of the line (enters insert mode) autocmd BufEnter *.php :%s/[ \t\r]\+$//e autocmd BufRead * silent! %s/[\r \t]\+$// " automatically delete trailing Dos-returns,whitespace autocmd FileType *.pl exec('set fileformats=unix') autocmd VimEnter c:/intranet/note011.txt normal! ggVGg? " perform an action on a particular file or file type b - go back a word (opposite of w) c/fred/e "change until fred end cab viminc :let I=223 \| 'a,'bs/$/\=INC(5)/ " create a map for INC cat xx | gvim - -c "v/^\d\d\|^[3-9]/d " -- filter a stream ci" inside a " " will erase everything between "" and place you in insertion mode. cmap ,r :Nread ftp://209.51.134.122/public_html/index.html " FTPing from VIM cmap ,w :Nwrite ftp://209.51.134.122/public_html/index.html command! -nargs=1 Csv :call CSVH(<args>) ctrl-<pagedown> / ctrl-<pageup> - switch to next/previous tab. (alternatives: gt/gT, :tabn/:tabp, etc) ctrl-b / ctrl-f " page up / page down ctrl-clic / ctrl-t " go to symbol definition (= ctrl-]) (using tags) and back. You can use "make tags" autotooled projects to create tags ctrl-r ctrl-w: Pull the word under the cursor in a : command. eg. :s/ctrl-r ctrl-w/foo/g ctrl-r x (insert mode): insert the contents of buffer x. For example: "ctrl-r +" would insert the contents of the clipboard. ctrl-v blockwise visual mode (rectangular selection). ctrl-v u <hex code> - enter a unicode character in insert mode ctrl-x ctrl-f (insert mode): complete with the file names in the current directory (ctrl-p/n to navigate through the candidates) d/fred/ "delete until fred " Operate until string found [N] da< ya< ca< " Delete/Yank/Change whole HTML tag daW " delete contiguous non whitespace " text objects :h text-objects [C] das " delete a sentence dat dit " Delete HTML tag pair daw/caw deletes/changes the word under the cursor. di< yi< ci< " Delete/Yank/Change HTML tag contents diB daB " Empty a function {} g% normal mode repeat last substitute g& last substitute on all lines g, " reverse direction g; " cycle thru recent changes (oldest first) g; will cycle through your recent changes (or g, to go in reverse). g<C-G> # counts words " count words/lines in a text file g<CTRL-G> to see technical information about the file, such as how many words are in it, or how many bytes it is. g\~\~ " flip case line ga " display hex,ascii value of char under cursor ga will display the ASCII, hex, and octal value of the character under the cursor. gf " open file name under cursor (SUPER) ggVG= will auto-format the entire document ggVGg? " rot13 whole file (toggles) " disguise text (watch out) [N] ggVGgq " Reformat entire file ggg?G " rot13 whole file (quicker for large file) ggguG " lowercase entire file gj, gk (or g<Up> g<Down>) - move up or down a display line (makes a difference for wrapped lines) gqap " Format a paragraph gq{movement} to wrap text, or just gq while in visual mode. gqap will format the current paragraph. gq} " Format a paragraph " Re-Formatting text gv " Re-select the previous visual area (ULTRA) gv " reselect last visual area (ultra) gvim -O file1 file2 " open into a vertical split (side by side,for comparing code) [N] gvim -c 'normal ggdG"*p' c:/aaa/xp " Access paste buffer contents (put in a script/batch file) gvim -c 's/^/\=@*/|hardcopy!|q!' " print paste contents to default printer gvim -h " VIM Command Line Help gvim -h " help " Command line tricks gvim -o file1 file2 " open into a horizontal split (file1 on top, file2 on bottom) [C] gvim -u NONE -U NONE -N " load VIM without .vimrc and plugins (clean VIM) e.g. for HUGE files gvim ftp://www.somedomain.com/index.html # uses netrw.vim gvim.exe -c "/main" joe.c " Open joe.c & jump to "main" " execute one command after opening file i<c-r>/ " Retrieving last Search Command for copy & pasting into text i<c-r>: " Retrieving last command line command for copy & pasting into text iab phpdb exit("<hr>Debug <C-R>a "); " Simple PHP debugging display all variables yanked into register a imap ,,, <esc>bdwa<<esc>pa><cr></<esc>pa><esc>kA " type table,,, to get <table></table> ### Cool ### jumps to the last modified line. \`. jumps to the exact position of last modification let g:I=0 ls | gvim - " edit a stream!! map <f2> :w<CR>:!perl -c %<CR> map <f9> :w<CR>:!c:/php/php.exe %<CR> " running file thru an external program (eg php) map <C-J> <C-W>j<C-W>_ " Quick jumping between splits map <C-K> <C-W>k<C-W>_ matchit.vim " % now matches html tags nYP\`n^Aq " in recording q repeat with @q noh - stop highlighting the current search (if 'hlsearch' is enabled). Highlighting is automatically restored for the next search. o/O insert a new line after/before the current line and switch to insert mode. qQ@qq " Make an existing recording q recursive [N] qa starts a recording in register 'a'. q stops it. @a repeats the recording. 5@a repeats it 5 times. qaq " empty register "a" qqq " empty register "q" r!cat - reads into the buffer from stdin and avoids using :set paste (use ctrl-d to finish) s - delete characters and start insert mode (s stands for Substitute). e.g. 3s - delete three characters and start insert mode. set showbreak - set characters to prefix wrapped lines with. e.g. ":set showbreak=+++\ " (white space must be escaped) set wildignore - ignore matching files when using tab complete on filenames. e.g. :set wildignore=*.o,*.lo set wildmenu - enhanced filename completion. left and right navigates matches; up and down navigates directories substitute flag 'n' - count how many substitutions would be made, but don't actually make any u@. " execute command JUST typed in use \v in your regex to set the mode to 'very magic' and avoid confusion (:h \v for more info) v " enter visual mode vEU " Upper Case Word vE~ " Flip Case Word vim +<num> - start vim and place the cursor on line <lnum>. If lnum is not specified, start at the end of the file vim - " - start vim and read from standard input. e.g. with syntax enabled, get a coloured diff from git: git diff | vim - vim --remote <file> - open a file in an existing vim session vim -c "%s/ABC/DEF/ge | update" file1.c " execute multiple command on a single file vim -c "argdo %s/ABC/DEF/ge | update" *.c " execute multiple command on a group of files vim -c "argdo /begin/+1,/end/-1g/^/d | update" *.c " remove blocks of text from a series of files vim -c [command] will launch vim and run a : command at launch, e.g. "vim -c NERDTree." vim -d file1 file2 shows the differences between two files. vim -p <files> - load all files listed in separate tabs. e.g. vim -p *.c vim -p fred.php joe.php " open files in tabs vim -s "convert.vim" file.c " Automate editing of a file (Ex commands in convert.vim) vmap ,c :s/\<\(.\)\(\k*\)\>/\u\1\L\2/g<CR> " Titlise Visually Selected Text (map for .vimrc) vnoremap <F6> :s/\%V\<\(\w\)\(\w*\)\>/\u\1\L\2/ge<cr> [N] " Title Case A Line Or Selection (better) v}zf " fold paragraph using visual when substituting, \u makes just first character upper (like \l for lower) and \U is upper equivalent for \L win32 users must remap CNTRL-A y/fred/ "yank until fred ysiw' to surround current word with ',cs' {changes word to {word}} using the surround plugin yy@" " same thing using unnamed register zc " re-close fold zf'a " fold to mark zf1G " fold everything before this line [N] zfG " fold everything after this line [N] zo " open fold zt, zz, zb: scroll so that the current position of the cursor is moved to the top, middle or bottom of the screen } - move to the next blank line ( { - move to previous blank line)