Saturday, April 2, 2016

Vim Commands

globals

vim arguments

-hhelp
...opens multiple files into one instance of the vim.
-o to open two files in horizontal windows
-O to open two files in vertical windows
-S restore session from
-R read only
+run command on file and edit
-c "" run command on file and exit
-s vimCmds.txt file.cautomate editing of a file with normal commands in vimCmds.txt
-u NONE -U NONE -Nload vim without .vimrc and plugins (clean vim)

normal mode

movement

hto move one character left
jto move one line down
kto move one line up
lto move one character right
b wmove the cursor forward, backward to the first character of the next word
B Wspace-separated word left, right
e gemove the cursor forward, backward to the last character of the next word
gE Eend of space-separated word left, right
0 ^move the cursor to the beginning, first of the current line
$move the cursor to the end of the line
gmmove to the middle of the line
) (move the cursor forward, backward to the next sentence
{ }move to the previous, next paragraph
]c [cjump to the next/previous change.
[[ ]]start of section backward, forward
[] ][end of section backward, forward
[( ])unclosed (, ) backward, forward
[{ ]}unclosed {, } backward, forward
[m ]mstart of backward, forward java method
[# ]#unclosed #if, #else, #endif backward, forward
[* ]*start, end of /* */ backward, forward
fwill move to the first occurence of the ch selected
tsame as above, but moves the cursor to right before the ch
Fwill move to the first occurence of the ch selected backwards
Tsame as above, but moves the cursor to right before the ch
; ,will move forward/backwards with in the above 'fFtT' action
Ggoes to the last line of the file
5G 5gggoes to the 5th line of the file
gggoes to the beginning of the file
Hmove the cursor to the top of the screen
Mmove the cursor to the middle of the screen
Lmove the cursor to the bottom of the screen
nHmove the cursor to the 'n'th line from the top of the screen
nLmove the cursor to the 'n'th line before the bottom of the screen
*will take to the next occurence of the same word under the cursor
%if you press this when ur on '{', will take to its associated '}' character.
n%moves to the 'n' percentage of the file
n|moves to the column 'n' of current line
gd gDlocal, global definition of symbol under cursor
Kwill take you to the man page of the function under cursor.
`.jump to exact spot in last modification line
g;will take you to the backward in the changelist(modified history)
g,will take you to the forward in the changelist
^oretrace your movements in through out the edited files (starting from most recent)
^ireverse direction
nlast / or ? search
Nlast / or ? search in opposite direction

misc

.repeat the previous command
i^Awill repeat the text insertion of last insert
g%normal mode repeat last substitute
g&last substitute on all lines
@@last recording
@:last command-mode command
~will change the aphabatic case of the char under cursor
g~mswitch case of chars following the motion command 'm'
gum gUmswitch lowcase, upcase of chars following the motion command 'm'
g?mperform rot13 encoding on movement m
mshifts left, right lines following the motion command 'm'
n<< n>>shifts left,right 'n' no.of lines
^a ^xwill increment/decreament the first number after cursor
n^a n^xwill increament/decreament the number under cursor to n times
g^asequence generator, under visual mode, will increament the first numbers after cursor with reference to the above number
J gJjoin current line with next line with, without space
gJjoin current line with next without space
gqmformat lines of movement m to fixed width
u Uundo last command, restore last changed line
. ^Rrepeat last changes, redo last undo
n.repeat last changes with count replaced by n
/s ?ssearch forward, backward for s
/s/o ?s?osearch fwd, bwd for s with offset o
n or /repeat forward last search
N or ?repeat backward last search
# *search backward, forward for word under cursor
g# g*same, but also find partial matches
^lwill redraw the screen
5gsdo nothing for 5 seconds
g^gcounts words
[Ishow lines matching word under cursor (super)
={motion}correct the indentation as per the c standard
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)
Klookup keyword under cursor with man
^l ^gredraw screen, show filename and position
g^gshow cursor column, line, and character position
gfopen file which filename is under cursor
^@ ^k ^_ \ fn ^fnunmapped keys
gq}format a paragraph
gqapformat a paragraph
ggVGgqreformat entire file
Vgqcurrent line

searching

/joe/ecursor set to end of match
3/joe/e+1find 3rd joe cursor set to end of match plus 1
/joe/s-2cursor set to start of match minus 2
/joe/+3find joe move cursor 3 lines down
/^joe.*fred.*bill/find joe and fred and bill (joe at start of line)
/^[A-J]/search for lines beginning with one or more A-J
/begin\_.*endsearch over possible multiple lines
/fred\_s*joe/any whitespace including newline
/fred\|joesearch for fred or joe
/.*fred\&.*joesearch for fred and joe in any order!
/\/search for fred but not alfred or frederick
/\<\d\d\d\d\>search for exactly 4 digit numbers
/\D\d\d\d\d\Dsearch for exactly 4 digit numbers
/\<\d\{4}\>same thing
/\([^0-9]\|^\)%.*%search for absence of a digit or beginning of line
/^\n\{3}find 3 empty lines
/^str.*\nstrfind 2 successive lines starting with str
/\(^str.*\n\)\{2}find 2 successive lines starting with str
/\(fred\).*\(joe\).*\2.*\1using rexexp memory in a search
/^\([^,]*,\)\{8}repeating the Regexp (rather than what the Regexp finds)
/<\zs[^>]*\ze>search for tag contents, ignoring chevrons
/<\@<=[^>]*>\@=search for tag contents, ignoring chevrons
/<\@<=\_[^>]*>\@=search for tags across possible multiple lines
/search for multiple line comments
/fred\_s*joe/any whitespace including newline
/bugs\(\_.\)*bunnybugs followed by bunny anywhere in file
/\c\v([^aeiou]&\a){4}search for 4 consecutive consonants
/\%>20l\%<30lgoatsearch for goat between lines 20 and 30
/^.\{-}home.\{-}\zshome/ematch only the 2nd occurence in a line of "home"
\^\(.*tongue.*\)\@!.*nose.*$find str but not on lines containing tongue
\v^((tongue)@!.)*nose((tongue)@!.)*$find str but not on lines containing tongue
\.*nose.*\&^\%(\%(tongue\)\@!.\)*$ find str but not on lines containing tongue

recording

qstarts the recording and stores the vim events in variable
qstops the recording
"qpdisplay contents of register q (normal mode)
^rqdisplay contents of register q (insert mode)
"qddput changed contacts back into q
@wfor repeating the edit actions on present line
@@will repeats the last ran command
5@@to repeat 5 times
15@wfor repeating the edit actions on 15 line after the present line

scrolling

^e ^yscroll line up, down
^d ^uscroll half a page up, down
^f ^bscroll page up, down
zt zset current line at top of window
zz z.set current line at center of window
zb z-set current line at bottom of window
zh zlscroll one character to the right, left
zh zlscroll half a screen to the right, left

multi-windowing

^wssplits the current file into two window
^wRswap top/bottom or left/right split
^wncreate new empty window
^w_ ^womake current window one on screen
10^w+increase window size by 10 lines
^w_ max out the height of the current split
^w| max out the width of the current split
^w= make all equal size
^wj ^wk ^wh ^wlmove to window below, above, right, left
^ww ^w^wmove to window below, above (wrap)
:new | r!perl #opens new buffer,read other buffer
:new +put q|%!sortcreate a new buffer, paste a register "q" into it, then sort new buffer

folding

zfmcreate fold of movement m
zd zedelete fold at cursor, all in window
zo zcopen, close one fold
[z ]zmove to start, end of current open fold
zj zkmove down, up to start, end of next fold
zr zmreducing folding level, one more folding level
zR zMreduce completely the folding, fold most!.

copying and moving text

nxcuts n character under the cursor.
nXcuts n character before the cursor.
dmcuts the chars following the motion m
nddcuts count no.of lines
Ddeletes character under the cursor untill the end of the line
ymcopies the chars following the motion m
nyy nYcopies count no.of lines
p Pput register after, before cursor position
]p [plike p, P with indent adjusted
gp gPlike p, P leaving cursor after new text
"x ddcuts one line of cursor to a x register
"x yycopies one line of cursor to a x register
"X yyappends one more line of cursor to a x register
"x pputs the content of the x register
@xexecute the content of x register as a vim command

registers

"5pretrieve 5th "ring"
"1p....retrieve numeric registers one by one
"_dddelete to blackhole register "_ , don't affect any register
qaqempty register "a"

tags

^w}preview tag under cursor, tag t
^w]split window and show tag under cursor
^wzclose tag preview window

entering to insert mode

aappend text after the cursor [count] times.
Aappend text at the end of the line [count] times.
iinsert text before the cursor [count] times.
Iinsert text before the first non-blank in the line [count] times.
gIinsert text in column 1 [count] times.
obegin a new line below the cursor and insert text, repeat [count] times.
Obegin a new line above the cursor and insert text, repeat [count] times.
giinsert text in the same position as where insert mode was stopped.
swill delete the char under cursor and start insert mode
cc (or) Swill cut the present line and enters into the insert mode.
c{motion}will delete the text and enters into insert mode
Cwill cut to the end of line

to replace mode

rcwill replace the character under cursor with 'c' character.
grclike r, but without affecting layout
Rreplace characters starting at the cursor
gRlike R, but without affecting layout
ctrl + [used to come out of replace mode

to visual mode

vwill enters into the visual mode
^vwill enters into the 'visual block' mode
Vwill enters into the 'line visual' mode
v{motion}will take you to visual mode and select some text.
gvstart highlighting on previous visual area

marking

mcmark current position with mark c ∈[a..Z]
'c 'Cgo to mark c in current, c in any file
'.jumps to last edited line
'' '"go to position before jump, at last edit
'[ ']go to start, end of previously operated text
'0..9go to last exit file and position
n^Ogo to nth older position in jump list
n^Igo to nth newer position in jump list

spell checking

]s or [smove to next (]s) or previous ([s) misspelled word
z=suggest corrections for the word under cursor
zgadd word under cursor as good word

digraphs (non alpha-numerics symbols)

ie'enters é
i233enters é (unix)
i233enters é (win32)
gaview hex value of any character
/[^a-zA-Z0-9_[:space:][:punct:]]search for all non-ascii

command prompt

basics

:&last substitute
:%&last substitute every line
:%&giclast substitute every line confirm
:~last substitute
:/to search from in the file
:?to search from the bottom of the file
:!excutes a command in the bash shell being in vim
:!!last :! command
:!./%to excute the present script in the terminal. where '%' is a present file name
:'a,'bselects lines from mark 'a' to 'b'
:^rvwill substutes the register(v) value.
:^r=5*5insert 25 into text (mini-calculator)
:^awwill substutes the word under cursor.
:^r^wwill substutes the word under cursor
:e fedit file f, unless changes have been made
:e! fedit file f always (by default reload current)
:q :q!quit and confirm, quit and discard changes
: :recall commands starting with current
:r finsert content of file f below cursor
:4 r will put the content of 'filename' at 4th line of the current file
:r !will put the output of the 'cmd' into the current file
:r!cinsert output of command c below cursor
:.!c :!!creplaces the current line with the output of command c
:r!ls -Rreads in output of ls into current file
:put=glob('**')same as above
:sort /.*\%2v/sort all lines on second column
:argsdisplay the argument list
:rco a :rm acopy, move range r below line a
:historylist of all your commands
:his ccommandline history
:his ssearch history
:{range} norm[al][!] {cmds}{cmds} are executed like they are typed.
:!{cmd}execute {cmd} with the shell
:!!repeat last ":!{cmd}"
:redi[r][!] > {file}redirect output of cmds to file
:scriptnameslist all plugins, _vimrcs loaded (super)
:verbose set history?reveals value of history and where set
:retabcorrect the tabs as per the current 'expandtab' or 'noexpantab' setting
:^fhistory window (exit ctrl-c)
:sh :!cstart shell, execute command c in shell
:makestart make, read errors and jump to first
:cn :cpdisplay the next, previous error
:cl :cflist all errors, read errors from file
:redir>fredirect output to file f
:mkview [f]save view configuration [to file f]
:loadview [f]load view configuration [from file f]
:runtime! syntax/2html.vimconvert txt to html
:grep some_keyword *.cget list of all c-files containing keyword
:cngo to next occurrence
:imap ] @@@hhkyWjl?@@@P/@@@3sreproduce previous line
:nmap ] i@@@hhkyWjl?@@@P/@@@3sreproduce previous line word by word
:autocmd bufenter *.tex map :!latex %programming keys depending on file type
:autocmd bufenter *.tex map :!xdvi -hush %<.dvi&programming keys depending on file type
:autocmd BufReadPre *.doc set romake all doc files as readonly
:autocmd BufReadPre *.doc set hlsearch!make highlighted searching for doc files
:autocmd BufReadPost *.doc %!antiword "%"reading ms-word documents, requires antiword (not docx)
:set roprotect a file from unintentional writes
:set rl[!]reverse lines right to left [toggles]
:g/^/m0reverse lines top to bottom [toggles]
:redir @*redirect commands to paste buffer
:redir ENDend redirect
:redir >> out.txtredirect to a file
"*yyyank curent line to paste
"*pinsert from paste buffer
:'a,'by*yank range into paste
:%y*yank whole buffer into paste
:.y*yank current line to paster
:nmap p :let @* = substitute(@*,'[^[:print:]]','','g')"*pfilter non-printable characters from the paste buffer useful when pasting from some gui application
:for i in range(1,10) | put = '192.168.0.'.i | endforwill insert 10 successive ip address at current line

saving files

:wq :xwrite to current file and exit
:rwwrite range r to current file
:rw fwrite range r to file f
:rw>>fappend range r to file f
:wn :wp(rev)write file and edit next, previous one
:w newFilenamesave file
:sav php.htmlsave current file as php.html and "move" to php.html
:sav! %<.baksave current file to alternative extension (old way)
:sav! %:r.cfmsave current file to alternative extension
:sav %:s/fred/joe/do a substitute on file name
:sav %:s/fred/joe/:r.bak2do a substitute on file name & ext.
:help filename-modifiershelp page

searching

:bufdo /searchstr/to recommence search
:nmap gx yiw/^\(sub\function\)\s\+"search for declaration of subroutine/function under cursor
:h \_ help
:bufdo %s/searchstr/&/gicmultiple file search, say a to stop
:%s/home.\{-}\zshome/alonesubstitute only the occurrence of home in any line
:v/tongue/s/nose/&/gicfind str but not on lines containing tongue
:/fred/;/joe/-2,/sid/+3s/sally/alley/gICfind fred before beginning search for joe
:d/str/delete until str
:y/str/yank until str
:c/str/echange until str end

normal commands

:normal executes normal cmds on range of lines

external commands

:r !lswrites ls command output into the files under the cursor
:!sortwill take the range of lines and exec `sort` cmd on them and gets the o/p of it.

movement

:goto 100 :go 100 :100gomove the cursor to file offset position 100 from begining
:changeswill print the changelist
:ju(mps)list of your movements
:h changelisthelp for above
:help jump-motionshelp page

multiple files

:split :spsplits the current file into two window
:10sp opens file1 in new window of 10 lines height
:vsp :vsplit :80vspvertical spliting
:sviewsame as split, but readonly
:new will open another file in horizontal window
:e also adds another file into the vim file buffer
:onmake current window one on screen
:e!return to unmodified file
:e #edit alternative file (also cntrl-^)
:find finds and adds 'filename' from vim-path folders into the vim buffer
:lslist the file list of buffer.
:bdcloses the present file without quiting from the vim.
:bd closes the selected file
:badd file.cfile from buffer list
:b /switches vim to edit another file.
:bswitches to the ':ls' count located file.
:bnswitches vim to next file of present file within the vim file buffer.
:bpswitches vim to previous file of present file within the vim file buffer.
:e#jumps back to the previous file
:nswitches vim to next file within the vim file buffer.
:prevswitches vim to previous file within the vim file buffer.
:rew :firstswitches vim to first file of the buffer.
:brewbuffer rewind
:lastswitches vim to the last file of the buffer.
:argdo %s/foo/bar/eoperate on all files in arg
:bufdo %s/foo/bar/eoperate on all files in buffer
:windo %s/foo/bar/eoperate on all files in window
:argdo exe '%!sort'|w!include an external command
:bufdo exe "normal @q" | wperform a recording on open files
:silent bufdo !zip proj.zip %:pzip all current files
:sp fred.txtopen fred.txt into a split
:sball,:sbsplit all buffers (super)
:scrollbindin each split window
:set hiddenallows to change buffer w/o saving current buffer

folding

:setfoldmethod=manual/indent/marker
:setfoldmarker=, or <,> or <<<,>>>
:rfocreate fold for range r
:help foldinghelp page

registers

:regto get list of all used registers and their contents.
:reg x :di xto get the content of x register.
:reg 12adisplay content of registers 1,2 & a
:let @y='yy@"'pre-loading registers (put in .vimrc)
:reg .-/%:*"the seven special registers
:reg 0what you last yanked, not affected by a delete
:let @a=@_clear register a
:let @a=""clear register a
:let @a=@"save unnamed register *N*
:let @*=@acopy 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

key mapping

:map c emap c ↦ e in normal & visual mode
:map! c emap c ↦ e in insert & cmd-line mode
:unmap c :unmap! cremove mapping c
:mk fwrite current mappings, settings to file f
:ab c eadd abbreviation for c ↦ e
:ab cshow abbreviations starting with c
:una cremove abbreviation c
:vmap // y/"search for visually highlighted text
:vmap // y/=escape(@", '\\/.*$^~[]')with spec chars

tags

:pt tpreview tag under cursor, tag t
:pcclose tag preview window
:ta tjump to tag t
:ntajump to nth newer tag in list
^] ^tjump to the tag under cursor, return from tag
:ts tlist matching tags and select one for jump
:tj tjump to tag or select one if multiple matches
:tagsprint tag list
:npo :n^tjump back from, to nth older tag
:tljump to last matching tag

substitutes ranges

, ;separates two lines numbers, set to first line
nan absolute line number n
. $the current line, the last line in file
% *entire file, visual area
'tposition of mark t
/p/ ?p?the next, previous line where p matches
+n -nto the preceding line number

special characters in substitute pattern

. ^ $any single character, start, end of line
\< \>start, end of word
[c1-c2]a single character in range c1..c2
[^c1-c2]a single character not in range
\i \k \I \Kan identifier, keyword; excl. digits
\f \p \F \Pa file name, printable char.; excl. digits
\s \Sa white space, a non-white space
\e \t \r \b, , < >, <←>
\= * \+match 0..1, 0..∞, 1..∞ of preceding atoms
\|separate two branches ( ≡ or)
\( \)group patterns into an atom
\& \nthe whole matched pattern, nth () group
\u \lnext character made upper, lowercase
\U \Leverything after \L|\U, stopping at \E|\e, is converted to lowercase/upper
\c \Cignore, match case on next pattern
\%Vdo a substitute on last visual area

marking

:marksprint the active marks list
:jumpsprint the jump list

compiling and executing of c/python programs

:set makeprg=gcc\ %set command to use for make
:set makeprg=python\ %set command to use for make
:makewill compile the current .c file with gcc command
:cnextshow next compilation error
:cpreviousshow previous compilation error
:copenopen errors window
:ccloseclose errors window
:map :mak:useful key mapping for compilation
:map :cn:useful key mapping for showing next compilation error
:map :cp:useful key mapping for showing previous compilation error
:map :!./a.out: useful key mapping for execution

undo branching

:undolshow the undo branches (the leaves of these branches)
:earliergo to older state. time or steps can be specified
:latergo to newer state. time or steps can be specified

session

:mksession save session to

spell checking

:setlocal spell spelllang=en_usset language to english us

highlights

:hishow current highlight settings
:hi comment cterm=bold ctermfg=white ctermbg=blackchanges the hilighting settings for comments
:syn match DoubleSpace " "example of setting your own highlighting
:hi def DoubleSpace guibg=#e0e0e0highlighting python functions

settings

:set ai :set noaiset or unset auto indent
:set ic :set noicset or unset case-insensitive
:setfiletype cwill make 'c' syntax on for filenames ending with other extensions
:set smartcaseoverrides ignorecase if uppercase used in search string (cool)
:syntax oncolour syntax in perl,html,php etc
:set syntax=perlforce syntax (usually taken from file extension)
:h regexp<^d>type ^d and get a list all help topics containing regexp
:set incsearchjumps to search word as you type (annoying but excellent)
:set wildignore=*.o,*.obj,*.bak,*.exetab complete now ignores these
:set shiftwidth=3for shift/tabbing
:set vb t_vb=".set silent (no beep)
:set browsedir=buffermaki gui file open use current directory
:set numbershow line numbers
:set syntax=perlforce syntax coloring for a file that has no extension .pl
:set syntax offremove syntax coloring (useful for all sorts of reasons)
:colorscheme bluechange coloring scheme blue
:colorscheme defaultchange coloring scheme (any file in ~vim/vim??/colors)
:set noma (non modifiable)prevents modifications
:set listdisplaying "non-asciis"
:h listcharshelp page

file explorer

:e .file explorer
:Exp(lore)file explorer note capital Ex
:Sex(plore)file explorer in split window
:browse ewindows style browser
:lslist of buffers
:cd .. :cd dirpathchange directory
:argslist of files
:args *.pyopen list of files (you need this!)
:lcd %:p:hchange to directory of current file
:autocmd BufEnter * lcd %:p:hchange to directory of current file automatically (put in _vimrc)

copying and moving lines

: co(py)
copy a range of lines to the address
: mo(ve)
move a range of lines to the address

plugins:

:Pydoc os.forkopens a python docs of os.fork() in the another horizontal window
:PydocSearch forksearching for fork

substitution examples

:%s/str/joe/igcgeneral substitute command
:%s//joe/igcsubstitute what you last searched for
:%s/~/sue/igcsubstitute your last replacement string
:%s/\r//gdelete dos returns ^M
:%s/\r/\r/gturn 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
:%s/^\n\{3}//delete blocks of 3 empty lines
:%s/^\n\+/\r/compressing empty lines
:%s#<[^>]\+>##gdelete html tags, leave text (non-greedy)
:%s#<\_.\{-1,}>##gdelete html tags possibly multi-line (non-greedy)
:%s#.*\(\d\+hours\).*#\1#delete all but memorised string (\1)
%s#><\([^/]\)#>\r<\1#gsplit jumbled up xml file into one tag per line
:'a,'b g/str/ s/dick/joe/igcvim power substitute
:g/def cfg/ norm oconf.tearDownFuncPointer = [nicCfgMngr.set^N]insert line after every 'def cfg' found
:%s= [^ ]\+$=&&=duplicate end column
:%s= \f\+$=&&=same thing
:%s= \S\+$=&&usually the same
:%s#.*\(tbl_\w\+\).*#\1#extract list of all strings tbl_* from text
:s/\(.*\):\(.*\)/\2 : \1/reverse fields separated by :
:%s/^\(.*\)\n\1$/\1/delete duplicate lines
:%s/^\(.*\)\(\n\1\)\+$/\1/delete multiple duplicate lines
:%s/^.\{-}pdf/new.pdf/delete to 1st occurence of pdf only (non-greedy)
:%s#\<[zy]\?tbl_[a-z_]\+\>#\L&#gclowercase with optional leading characters
:%s///delete possibly multi-line comments
:help /\{-}help non-greedy
:s/fred/a/gsub "fred" with contents of register "a"
:s/fred/asome_texts/gsub "fred" with contents of register "a" and some text
:s/fred/\=@a/gbetter alternative as register not displayed
:%s/\f\+\.gif\>/\r&\r/g | v/\.gif$/d | %s/gif/jpg/ORing substitute commands
:%s/a/but/gie|:update|:nextthen use @: to repeat
:%s/goat\|cow/sheep/gcORing (must break pipe)
:'a,'bs#\[\|\]##gremove [] from lines between markers a and b
:%s/\v(.*\n){5}/&\rinsert a blank line every 5 lines
:s/__date__/\=strftime("%c")/insert datestring
:inoremap \zd =strftime("%d%b%y")insert date eg 31jan11
:%s:\(\(\w\+\s\+\)\{2}\)str1:\1str2:working with columns sub any str1 in col3
:%s:\(\w\+\)\(.*\s\+\)\(\w\+\)$:\3\2\1:swapping first & last column (4 columns)
:%s#\\|\\|\\|\<\inner join\>#\r&#gformat a mysql query
:redir @*|sil exec 'g#<\(input\|select\|textarea\|/\=form\)\>#p'|redir END
:nmap ,zredir @*sil exec 'g@<\(input\select\textarea\/\=form\)\>@p'redir END
:%s/^\(.\{30\}\)xx/\1yy/substitute string in column 30
:%s/\d\+/\=(submatch(0)-3)/decrement numbers by 3
:g/loc\|function/s/\d/\=submatch(0)+6/increment numbers by 6 on certain lines only
:%s#txtdev\zs\d#\=submatch(0)+1#g
:h /\zs
:%s/\(gg\)\@<=\d\+/\=submatch(0)+6/
:h zero-widthhelp page
:let i=10 | 'a,'bg/Abc/s/yy/\=i/ |let i=i+1convert yy to 10,11,12 etc, rename a string with an incrementing number
:let i=10 | 'a,'bg/Abc/s/xx\zsyy\ze/\=i/ |let i=i+1 # convert xxyy to xx11,xx12,xx13as above but more precise
:%s/"\([^.]\+\).*\zsxx/\1/find replacement text, put in memory, then use \zs to simplify substitute
:nmap z :%s#\<=expand("")\>#pull word under cursor into lhs of a substitute
:vmap z :%s/\<*\>/pull visually highlighted text into lhs of a substitute
:'a,'bs/bucket\(s\)*/bowl\1/gic
:%s,\(all/.*\)\@<=/,_,greplace all / with _ after "all/", substitute within substitution
:s#all/\zs.*#\=substitute(submatch(0), '/', '_', 'g')#substitute within substitution
:s#all/#&^M#|s#/#_#g|-j!
:%s/.*/\='cp '.submatch(0).' all/'.substitute(submatch(0),'/','_','g')/
:echo line("'b")-line("'a")count lines between markers a and b
:'a,'bs/^//ncount lines between markers a and b
:'a,'bs/somestring//gncount occurences of a string
:%s/\<\(on\|off\)\>/\=strpart("offon", 3 * ("off" == submatch(0)), 3)/g
:vnoremap `.``gvP``P
:nmap gw "_yiw:s/\(\%#\w\+\)\(\_W\+\)\(\w\+\)/\3\2\1/
:s#_\([a-z]\)#\u\1#g
:s#\(\<\u\l\+\|\l\+\)\(\u\)#\l\1_\l\2#gcamel case variable names to under score type
:s/.\{,69\};\s*\|.\{,69\}\s\+/&\r/gbreak lines at 70 chars, if possible after a ;
:% s/=\([^ ]\)/= \1/gc
:% s/\([^ !<>=]\)=/\1 =/gcadd spaces before and after '='
:%s/class \([A-Z]\)\([A-Z]\+\)(/class \1\L\2\E(/gcreplaces 'class ADC(' to 'class Adc('

global substitution examples

:g/gladiolli/#display with line numbers
:g/fred.*joe.*dick/display all lines fred,joe & dick
:g/\/display all lines fred but not freddy
:g/^\s*$/ddelete all blank lines
:g!/^dd/ddelete lines not containing string
:v/^dd/ddelete lines not containing string
:g/joe/,/fred/dnot line based (very powerfull)
:g/fred/,/joe/jjoin lines
:g/-------/.-10,.ddelete string & 10 previous lines
:g/{/ ,/}/- s/\n\+/\r/gdelete empty lines but only between {...}
:v/\S/ddelete empty lines (and blank lines ie whitespace)
:v/./,/./-jcompress empty lines
:g/^$/,/./-jcompress empty lines
:g/ORing
:g/^/put_double space file (pu = put)
:g/^/m0reverse file (m = move)
:g/^/m$no effect!
:'a,'bg/^/m'breverse a section a to b
:g/^/t.duplicate every line
:g/fred/t$copy(transfer) lines matching fred to eof
:g/stage/t'acopy (transfer) lines matching stage to marker a (cannot use .)
:g/^Chapter/t.|s/./-/gautomatically underline selecting headings
:g/\(^I[^^I]*\)\{80}/ddelete all lines containing at least 80 tabs
:g/^/ if line('.')%2|s/^/zz /perform a substitute on every other line
:'a,'b g/somestr/co/otherstr/ :co(py) or mo(ve)match all lines containing "somestr" between markers a & b, copy after line containing "otherstr"
:'a,'bg/str1/s/str1/&&&/|mo/str2/
:%norm jdddelete every other line
:.,$g/^\d/exe "norm! \"increment numbers
:'a,'bg/\d\+/norm! ^Aincrement numbers
:g/fred/y Aappend all lines fred to register a
:g/fred/y A | :let @*=@aput into paste buffer
:let @a=''|g/Barratt/y A |:let @*=@a
:'a,'bg/^Error/ . w >> errors.txtfilter lines to a file (file must already exist)
:g/./yank|put|-1s/'/"/g|s/.*/Print '&'/duplicate every line in a file wrap a print '' around each duplicate
:g/^MARK$/r tmp.txt | -dreplace string with contents of a file, -d deletes the "mark"
:g//z#.5display with context, display prettily
:g//z#.5|echo "=========="display beautifully
:g/|/norm 2f|r*replace 2nd | with a star, combining g// with normal mode commands
:nmap :redir @a:g//:redir END:new:put! asend output of previous global command to a new window
:'a,'bg/fred/s/joe/susan/giccan use memory to extend matching
:/fred/,/joe/s/fred/joe/gicnon-line based (ultra)
:/biz/,/any/g/article/s/wheel/bucket/gicnon-line based
:g/^/exe ".w ".line(".").".txt"create a new file for each line of file eg 1.txt,2.txt,3,txt etc
:.g/^/ exe ".!sed 's/N/X/'" | s/I/Q/chain an external command

functions

:help expressionto get all documentation of vim scripting syntax
:help function-listto get the brief description of vim functions
:functionlist functions presently exported
:func tolower()list particular function

encryption (use with care: don't forget your key)

:Xyou will be prompted for a key
:set key=will disable the encryption
:help :Xhelp on encryption

modelines

:set modelineset modelines
:set nomodelineunset modelines
:help modelinehelp on modelines
# vim: noai ts=2 sw=4 readonlyadd this line in the file within first/last 5 lines

help

:help evalhelp page on all vim functions
:help pyhelp page on all vim-py functions

digraphs (non alpha-numerics symbols)

:digraphsdisplay table
:h dighelp
:%s/[\x00-\x1f\x80-\xff]/ /gtype this as you see it to delete non-ascii
:%s/[128-255]//giwhere you have to type the control-v
:%s/[€-ÿ]//gishould see a black square & a dotted y
:%s/[128-25501-31]//giall pesky non-asciis
:exec "norm /[\x00-\x1f\x80-\xff]/"same thing

programming

:put = range(10)puts 0 to 9 under the cursor
:put =map(range(1,10), 'printf(''%04d'', v:val)')puts 0 to 9 under the cursor as printf format
:for i in range(1,10) | put ='192.168.0.'.i | endforprints numbers in new lines

insert mode

text editing

^hwill delete one char before the cursor
^wwill delete one word before the cursor
^Wdelete word before cursor
^uwill delete all the characters before the cursor untill the start of line
^Udelete all inserted character in current line
^Ainsert previously inserted text
^@same as ^A and stop insert mode
^Rx ^R^Rxinsert content of register x, literally
^N ^Pword completion from the list of words before, after cursor
^X^Lcombination of these two commands will work as line completion
^D ^Tshift left, right one shift width
^Ocexecute normal mode command 'c' in insert mode
^X^E ^X^Yscroll up, down
ctrl + [used to come out of insert mode

visual mode

misc

$in visual block mode extends to the rightmost column of the longest line
oexchange cursor position with start of highlighting
awselect a word
asselect a sentence
apselect a paragraph
abselect a block ()
aBselect a block { }
uchange to lower case
Uchange to upper case
V%visualise what you match
V}Jjoin visual block
V}gJjoin visual block w/o adding spaces
`[v`]highlight last insert

vimdiff

normal mode

doget changes from other window into the current window.
dpput the changes from current window into the other window.

command mode

:diffupdatediff update
:diffget :diffget :diffget get changes from other window into the current window.
:diffput :diffput :diffput put the changes from current window into the other window.

files/folders paths prompt

misc

/usr/share/vim/vimcurrent/docthis dir will have all the docs related to the vim editor