zz to center the cursor vertically on your screen. useful when you 250gzz, for instance. % git config --global core.editor "gvim --nofork" % ci" inside a " " will erase everything between "" and place you in insertion mode. % :set guifont=* in gvim or MacVim to get a font selection dialog. Useful while giving presentations. % :h slash to get a list of all help topics containing the word 'slash'. % guu converts entire line to lowercase. gUU converts entire line to uppercase. ~ inverts case of current character. % : trace your movements backwards in a file. trace your movements forwards in a file. % :ju(mps) : list your movements {{help|jump-motions}} % :history lists the history of your recent commands, sans duplicates. % "+y to copy to the X11 (or Windows) clipboard. "+p to paste from it. % noremap ' ` and noremap ` ' to make marks easier to navigate. Now ` is easier to reach! % 2f/ would find the second occurrence of '/' in a line. % :tab sball will re-tab all files in the buffers list. % :%s/joe|fred/jerks/g will replace both 'fred' and 'joe' with 'jerks'. % * # g* g# each searches for the word under the cursor (forwards/backwards) % :vimgrep pattern **/*.txt will search all *.txt files in the current directory and its subdirectories for the pattern. % == will auto-indent the current line. Select text in visual mode, then = to auto-indent the selected lines. % Count the number of occurences of a word in a file with :%s///gn % :set foldmethod=syntax to make editing long files of code much easier. zo to open a fold. zc to close it. See more http://is.gd/9clX % Need to edit and run a previous command? q: then find the command, edit it, and Enter to execute the line. % @: to repeat the last executed command. % :e $MYVIMRC to directly edit your vimrc. :source $MYVIMRC to reload. Mappings may make it even easier. % g to see technical information about the file, such as how many words are in it, or how many bytes it is. % gq{movement} to wrap text, or just gq while in visual mode. gqap will format the current paragraph. % :E to see a simple file explorer. (:Ex will too, if that's easier to remember.) % :vimgrep pattern *.txt will search all .txt files in the current directory for the pattern. % :match ErrorMsg '\%>80v.\+' uses matching to highlight lines longer than 80 columns. % :%s/\r//g to remove all those nasty ^M from a file, or :%s/\r$//g for only at the end of a line. % % matches opening and closing chars (){}[], and with matchit.vim, def/end, HTML tags, etc. as well! % offers word-completion while in insert mode. % offers line completion in insert mode. % / will pull the word under the cursor into search. % gf will open the file under the cursor. (Killer feature.) % Ctrl-a, Ctrl-x will increment and decrement, respectively, the number under the cursor. May be precede by a count. % :scriptnames will list all plugins and _vimrcs loaded. % :tabdo [some command] will execute the command in all tabs. Also see windo, bufdo, argdo. % :vsplit filename will split the window vertically and open the file in the left-hand pane. Great when writing unit tests! % qa starts a recording in register 'a'. q stops it. @a repeats the recording. 5@a repeats it 5 times. % :%s/\v(.*\n){5}/&\r will insert a blank line every 5 lines % Ctrl-c to quickly get out of command-line mode. (Faster than hitting ESC a couple times.) % Use '\v' in your regex to set the mode to 'very magic', and avoid confusion. (:h \v for more info.) % ; is a motion to repeat last find with f. f' would find next quote. c; would change up to the next ' % /\%>80v.\+ with search highlighting (:set hlsearch) will highlight any text after column 80. % ga will display the ASCII, hex, and octal value of the character under the cursor. % :%s/[.!?]\_s\+\a/\U&\E/g will uppercase the first letter of each sentence (except the very first one). % :r !date will insert the current date/time stamp (from the 'date' command -- a bit OS-specific). % :lcd %:p:h will change to the directory of the current file. % % matches brackets {} [] (), and with matchit.vim, also matches def/end, < ?php/?>, < p>/< /p>, etc. % :g/search_term/# display each line containing 'search_term' with line numbers. % :%s/// will delete HTML comments, potentially spanning multiple lines. % '. jumps to the last modified line. `. jumps to the exact position of last modification % [I (that's bracket open, capital i) show lines containing the word under the cursor. % :%s/\\/\//g replaces all backslashes with forward slashes % :vimgrep /stext/ **/*.txt | :copen searches for stext recursively in *.txt files and show results in separate window % ysiw' to surround current word with ',cs' {changes word to {word}} using the surround plugin: http://t.co/7QnLiwP3 % use \v in your regex to set the mode to 'very magic' and avoid confusion (:h \v for more info) http://t.co/KWtRFNPI % in gvim, change the cursor depending on what mode you are (normal, insert, etc...) http://is.gd/9dq0 % In visual mode, use " to surround the selected text with " using the surround plugin http://is.gd/fpwJQ % :tabo closes all tabs execpt the current one. % / move the cursor up/down half a page (also handy :set nosol) % :set titlestring=%f set the file name as the terminal title. % p / P paste after/before the cursor. Handy when inserting lines. % daw/caw deletes/changes the word under the cursor. % vim -d file1 file2 shows the differences between two files. % :set smartcase case sensitive if search contains an uppercase character and ignorecase is on. % :sh or :shell to open a console (then exit to come back to vim). % = : re-indent (e.g. == to re-indent the current line). % :%y c copies the entire buffer into register c. "cp inserts the content of register c in the current document. % ctrl-v blockwise visual mode (rectangular selection). % I/A switch to insert mode before/after the current line. % o/O insert a new line after/before the current line and switch to insert mode. % I/A in visual blockwise mode (ctrl-v) insert some text at the star/end of each line of the block text. % Need to edit a file in hex ? :help hex-editing gives you the manual. % 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-r x (insert mode): insert the contents of buffer x. For example: "ctrl-r +" would insert the contents of the clipboard. % ctrl-r ctrl-w: Pull the word under the cursor in a : command. eg. :s/ctrl-r ctrl-w/foo/g % ':%y c': yank entire file into register c. '"cp': Paste contents of c into document. % a/A : append at the cursor position / at the end of the line (enters 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) % set mouse=a - enable mouse in terminal (selection, scroll, window resizing, ...). % J: join two lines % gg/G: go to start/end of file. % Ctrl-y (insert mode): insert character which is on the line above cursor. example: handy to initialize a structure. % :set nowrap - disable line wrapping % vim -p - load all files listed in separate tabs. e.g. vim -p *.c % vmap out "zdmzO#if 0"zp'zi#endif - macro to comment out a block of code using #if 0 % v == :vsplit like s == :split % 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 % Prefixing G or gg (command mode) with a number will cause vim to jump to that line number. % set showbreak - set characters to prefix wrapped lines with. e.g. ":set showbreak=+++\ " (white space must be escaped) % 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 % :split - split the current window in two % vim --remote - open a file in an existing vim session % A - enter insert mode at the end of the line (Append); I - insert before the first non-blank of the line % %< - resolves the current filename without extension. e.g. :e %<.h - open the header file for the current file % :set softtabstop - set the number of spaces to insert when using the tab key (converted to tabs and spaces if expandtab is off). % :set expandtab - use spaces rather than the tab character to insert a tab. % :set guioptions - set various GUI vim options. e.g. to remove the menubar and toolbar, :set guioptions-=Tm % "vim - " - start vim and read from standard input. e.g. with syntax enabled, get a coloured diff from git: git diff | vim - % set mousemodel=popup - enable a popup menu on right click in GUI vim % r!cat - reads into the buffer from stdin and avoids using :set paste (use ctrl-d to finish) % :set title - display info in terminal title. Add let &titleold=getcwd() to .vimrc to set it to something useful on quit % :set pastetoggle=key - specify a key sequence that toggles the paste option, e.g. set pastetoggle= % :set paste - allows you to paste from the clipboard correctly, especially when vim is running in a terminal % substitute flag 'n' - count how many substitutions would be made, but don't actually make any % set wildmenu - enhanced filename completion. left and right navigates matches; up and down navigates directories % zt, zz, zb: scroll so that the current position of the cursor is moved to the top, middle or bottom of the screen % [range]sort - sort the lines in the [range], or all lines if [range] is not given. e.g. :'<,'>sort - sort the current visual selection % %: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 % noh - stop highlighting the current search (if 'hlsearch' is enabled). Highlighting is automatically restored for the next search. % when substituting, \u makes just first character upper (like \l for lower) and \U is upper equivalent for \L % :retab - convert strings of white-space containing with new strings using the value if given or current value of 'tabstop' % ctrl-v u - enter a unicode character in insert mode % :set laststatus=2 - always show the status line (0 = never, 1 = (default) only if there are two or more windows, 2 = always) % b - go back a word (opposite of w) % } - move to the next blank line ( { - move to previous blank line) % s - delete characters and start insert mode (s stands for Substitute). e.g. 3s - delete three characters and start insert mode. % 0 - Move to the first character of the line % :set columns=X - set the width of the window to X columns. For GUI vim, this is limited to the size of the screen % :only - close all windows except the current one (alternatives: ctrl-w ctrl-o or :on) % ctrl- / ctrl- - switch to next/previous tab. (alternatives: gt/gT, :tabn/:tabp, etc) % :tabe - open in a new tab (same as :tabedit and :tabnew) % Ctrl-T and Ctrl-D - indent and un-indent the current line in insert mode % vim + - start vim and place the cursor on line . If lnum is not specified, start at the end of the file % gj, gk (or g g) - move up or down a display line (makes a difference for wrapped lines) % >{motion} and <{motion} - (normal mode) increase/decrease the current indent. e.g. << - decrease the indent of the current line % "+ and "* - clipboard and current selection registers under X. e.g. "+p to paste from the clipboard and "+y to copy to the clipboard % :r! - insert the result of into the current buffer at the cursor. e.g. :r!ls *.h % & - re-run last :s command (&& to remember flags) % set wildignore - ignore matching files when using tab complete on filenames. e.g. :set wildignore=*.o,*.lo % CTRL-V - in insert mode, enters a real tab character, disregarding tab and indent options % CTRL-U/CTRL-D - scroll up/down, moving the cursor the same number of lines if possible (unlike /) % :set cursorline - Highlight the current line under the cursor % :set showcmd - show the number of lines/chacters in a visual selection % :x is like ":wq", but write only when changes have been made % 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 % 0/joe/+3 -- find 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\_.*end -- search over possible multiple lines % /fred\_s*joe/ -- any whitespace including newline [C] % /fred\|joe -- Search for FRED OR JOE % /.*fred\&.*joe -- Search for FRED AND JOE in any ORDER! % /\/ -- search for fred but not alfred or frederick [C] % /\<\d\d\d\d\> -- Search for exactly 4 digit numbers % /\D\d\d\d\d\D -- Search 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 -- finding empty lines % /^str.*\nstr -- find 2 successive lines starting with str % /\(^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* % /^\([^,]*,\)\{8} -- Repeating the Regexp (rather than what the Regexp finds) % :vmap // y/" -- search for visually highlighted text -- visual searching % :vmap // y/=escape(@", '\\/.*$^~[]') -- with spec chars % /<\zs[^>]*\ze> -- search for tag contents, ignoring chevrons -- \zs and \ze regex delimiters :h /\zs % /<\@<=[^>]*>\@= -- search for tag contents, ignoring chevrons -- zero-width :h /\@= % /<\@<=\_[^>]*>\@= -- search for tags across possible multiple lines % / -- search for multiple line comments -- searching over multiple lines \_ means including newline % /fred\_s*joe/ -- any whitespace including newline *C* % /bugs\(\_.\)*bunny -- bugs followed by bunny anywhere in file % :h \_ -- help % :nmap gx yiw/^\(sub\function\)\s\+" -- search for declaration of subroutine/function under cursor % :bufdo /searchstr/ -- use :rewind to recommence search -- multiple file search % :bufdo %s/searchstr/&/gic -- say n and then a to stop -- multiple file search better but cheating % ?http://www.vim.org/ -- (first) search BACKWARDS!!! clever huh! -- How to search for a URL without backslashing % /\c\v([^aeiou]&\a){4} -- search for 4 consecutive consonants -- Specify what you are NOT searching for (vowels) % /\%>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 occurrence of home in any line [N] % ^\(.*tongue.*\)\@!.*nose.*$ -- find str but not on lines containing tongue % \v^((tongue)@!.)*nose((tongue)@!.)*$ % .*nose.*\&^\%(\%(tongue\)\@!.\)*$ % :v/tongue/s/nose/&/gic % :%s/fred/joe/igc -- general substitute command -- *best-substitution* % :%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 % :%s/\r/\r/g -- Turn DOS returns ^M into real returns -- Is your Text File jumbled onto one line? use following % :%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 -- deleting 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] % %s#><\([^/]\)#>\r<\1#g -- split jumbled up XML file into one tag per line [N] % :'a,'bg/fred/s/dick/joe/igc -- VERY USEFUL -- VIM Power Substitute % :%s= [^ ]\+$=&&= -- duplicate end column -- duplicating columns % :%s= \f\+$=&&= -- same thing % :%s= \S\+$=&& -- usually the same % :%s#example#& = &#gic -- duplicate entire matched string [N] -- memory % :%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] % :%s/^.\{-}pdf/new.pdf/ -- delete to 1st occurence of pdf only (non-greedy) -- non-greedy matching \{-} % :%s#\<[zy]\?tbl_[a-z_]\+\>#\L&#gc -- lowercase with optional leading characters -- use of optional atom \? % :%s/// -- delete possibly multi-line comments -- over possibly many lines % :help /\{-} -- help non-greedy % :s/fred/a/g -- sub "fred" with contents of register "a" -- substitute using a register % :s/fred/asome_texts/g % :s/fred/\=@a/g -- better alternative as register not displayed (not *) [C] % :%s/\f\+\.gif\>/\r&\r/g | v/\.gif$/d | %s/gif/jpg/ -- multiple commands on one line % :%s/a/but/gie|:update|:next -- then use @: to repeat % :%s/goat\|cow/sheep/gc -- ORing (must break pipe) -- ORing % :'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] % :s/__date__/\=strftime("%c")/ -- insert datestring -- Calling a VIM function % :inoremap \zd =strftime("%d%b%y") -- insert date eg 31Jan11 [N] % :%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&#g -- format a mysql query % :redir @*|sil exec 'g#<\(input\|select\|textarea\|/\=form\)\>#p'|redir END -- filter all form elements into paste register % :nmap ,z :redir @*sil exec 'g@<\(input\select\textarea\/\=form\)\>@p'redir END % :%s/^\(.\{30\}\)xx/\1yy/ -- substitute string in column 30 [N] % :%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 -- better % :h /\zs % :%s/\(gg\)\@<=\d\+/\=submatch(0)+6/ -- increment only numbers gg\d\d by 6 (another way) % :h zero-width % :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 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 % :%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 [N] -- substitute singular or plural % :%s,\(all/.*\)\@<=/,_,g -- replace all / with _ AFTER "all/" % :s#all/\zs.*#\=substitute(submatch(0), '/', '_', 'g')# -- Same thing % :s#all/#&^M#|s#/#_#g|-j! -- Substitute by splitting line, then re-joining % :%s/.*/\='cp '.submatch(0).' all/'.substitute(submatch(0),'/','_','g')/ -- Substitute inside substitute % :g/gladiolli/# -- display with line numbers (YOU WANT THIS!) -- *best-global* command % :g/fred.*joe.*dick/ -- display all lines fred,joe & dick % :g/\/ -- display all lines fred but not freddy % :g/^\s*$/d -- delete all blank lines % :g!/^dd/d -- delete lines not containing string % :v/^dd/d -- delete lines not containing string % :g/joe/,/fred/d -- not line based (very powerfull) % :g/fred/,/joe/j -- Join Lines [N] % :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/" -- increment numbers % :'a,'bg/\d\+/norm! ^A -- increment numbers % :g/fred/y A -- append all lines fred to register a % :g/fred/y A | :let @*=@a -- put into paste buffer % :let @a=''|g/Barratt/y A |:let @*=@a % :'a,'bg/^Error/ . w >> errors.txt -- filter 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 | -d -- replace string with contents of a file, -d deletes the "mark" % :g//z#.5 -- display 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! a -- send output of previous global command to a new window % :'a,'bg/fred/s/joe/susan/gic -- can use memory to extend matching -- *Best-Global-combined-with-substitute* (*power-editing*) % :/fred/,/joe/s/fred/joe/gic -- non-line based (ultra) % :/biz/,/any/g/article/s/wheel/bucket/gic: non-line based [N] % :/fred/;/joe/-2,/sid/+3s/sally/alley/gIC -- Find fred before beginning search for joe % :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/ [N] -- chain an external command % d/fred/ :delete until fred -- Operate until string found [N] % y/fred/ :yank until fred % c/fred/e :change until fred end % . last edit (magic dot) -- Summary of editing repeats [N] % :& 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 % ; last f, t, F or T -- Summary of repeated searches % , last f, t, F or T in opposite direction % n last / or ? search % N last / or ? search in opposite direction % * # g* g# -- find word under cursor () (forwards/backwards) % % -- match brackets {}[]() % . -- repeat last modification % @: -- repeat last : command (then @@) % matchit.vim -- % now matches tags