globals
vim arguments
| -h | help |
| 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.c | automate editing of a file with normal commands in vimCmds.txt |
| -u NONE -U NONE -N | load vim without .vimrc and plugins (clean vim) |
normal mode
movement
| h | to move one character left |
| j | to move one line down |
| k | to move one line up |
| l | to move one character right |
| b w | move the cursor forward, backward to the first character of the next word |
| B W | space-separated word left, right |
| e ge | move the cursor forward, backward to the last character of the next word |
| gE E | end 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 |
| gm | move to the middle of the line |
| ) ( | move the cursor forward, backward to the next sentence |
| { } | move to the previous, next paragraph |
| ]c [c | jump to the next/previous change. |
| [[ ]] | start of section backward, forward |
| [] ][ | end of section backward, forward |
| [( ]) | unclosed (, ) backward, forward |
| [{ ]} | unclosed {, } backward, forward |
| [m ]m | start of backward, forward java method |
| [# ]# | unclosed #if, #else, #endif backward, forward |
| [* ]* | start, end of /* */ backward, forward |
| f | will move to the first occurence of the ch selected |
| t | same as above, but moves the cursor to right before the ch |
| F | will move to the first occurence of the ch selected backwards |
| T | same as above, but moves the cursor to right before the ch |
| ; , | will move forward/backwards with in the above 'fFtT' action |
| G | goes to the last line of the file |
| 5G 5gg | goes to the 5th line of the file |
| gg | goes to the beginning of the file |
| H | move the cursor to the top of the screen |
| M | move the cursor to the middle of the screen |
| L | move the cursor to the bottom of the screen |
| nH | move the cursor to the 'n'th line from the top of the screen |
| nL | move 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 gD | local, global definition of symbol under cursor |
| K | will 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 |
| ^o | retrace your movements in through out the edited files (starting from most recent) |
| ^i | reverse direction |
| n | last / or ? search |
| N | last / or ? search in opposite direction |
misc
| . | repeat the previous command |
| i^A | will 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~m | switch case of chars following the motion command 'm' |
| gum gUm | switch lowcase, upcase of chars following the motion command 'm' |
| g?m | perform rot13 encoding on movement m |
| shifts left, right lines following the motion command 'm' | |
| n<< n>> | shifts left,right 'n' no.of lines |
| ^a ^x | will increment/decreament the first number after cursor |
| n^a n^x | will increament/decreament the number under cursor to n times |
| g^a | sequence generator, under visual mode, will increament the first numbers after cursor with reference to the above number |
| J gJ | join current line with next line with, without space |
| gJ | join current line with next without space |
| gqm | format lines of movement m to fixed width |
| u U | undo last command, restore last changed line |
| . ^R | repeat last changes, redo last undo |
| n. | repeat last changes with count replaced by n |
| /s ?s | search forward, backward for s |
| /s/o ?s?o | search 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 |
| ^l | will redraw the screen |
| 5gs | do nothing for 5 seconds |
| g^g | counts words |
| [I | show lines matching word under cursor |
| ={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) |
| K | lookup keyword under cursor with man |
| ^l ^g | redraw screen, show filename and position |
| g^g | show cursor column, line, and character position |
| gf | open file which filename is under cursor |
| ^@ ^k ^_ \ fn ^fn | unmapped keys |
| gq} | format a paragraph |
| gqap | format a paragraph |
| ggVGgq | reformat entire file |
| Vgq | current line |
searching
| /joe/e | cursor set to end of match |
| 3/joe/e+1 | find 3rd joe cursor set to end of match plus 1 |
| /joe/s-2 | cursor set to start of match minus 2 |
| /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 |
| /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 |
| /\<\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 |
| /^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 |
| /^\([^,]*,\)\{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\(\_.\)*bunny | bugs followed by bunny anywhere in file |
| /\c\v([^aeiou]&\a){4} | search for 4 consecutive consonants |
| /\%>20l\%<30lgoat | search for goat between lines 20 and 30 |
| /^.\{-}home.\{-}\zshome/e | match 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
| q | starts the recording and stores the vim events in variable |
| q | stops the recording |
| "qp | display contents of register q (normal mode) |
| ^rq | display contents of register q (insert mode) |
| "qdd | put changed contacts back into q |
| @w | for repeating the edit actions on present line |
| @@ | will repeats the last ran command |
| 5@@ | to repeat 5 times |
| 15@w | for repeating the edit actions on 15 line after the present line |
scrolling
| ^e ^y | scroll line up, down |
| ^d ^u | scroll half a page up, down |
| ^f ^b | scroll page up, down |
| zt z | set 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 zl | scroll one character to the right, left |
| zh zl | scroll half a screen to the right, left |
multi-windowing
| ^ws | splits the current file into two window |
| ^wR | swap top/bottom or left/right split |
| ^wn | create new empty window |
| ^w_ ^wo | make 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 ^wl | move to window below, above, right, left |
| ^ww ^w^w | move to window below, above (wrap) |
| :new | r!perl # | opens new buffer,read other buffer |
| :new +put q|%!sort | create a new buffer, paste a register "q" into it, then sort new buffer |
folding
| zfm | create fold of movement m |
| zd ze | delete fold at cursor, all in window |
| zo zc | open, close one fold |
| [z ]z | move to start, end of current open fold |
| zj zk | move down, up to start, end of next fold |
| zr zm | reducing folding level, one more folding level |
| zR zM | reduce completely the folding, fold most!. |
copying and moving text
| nx | cuts n character under the cursor. |
| nX | cuts n character before the cursor. |
| dm | cuts the chars following the motion m |
| ndd | cuts count no.of lines |
| D | deletes character under the cursor untill the end of the line |
| ym | copies the chars following the motion m |
| nyy nY | copies count no.of lines |
| p P | put register after, before cursor position |
| ]p [p | like p, P with indent adjusted |
| gp gP | like p, P leaving cursor after new text |
| "x dd | cuts one line of cursor to a x register |
| "x yy | copies one line of cursor to a x register |
| "X yy | appends one more line of cursor to a x register |
| "x p | puts the content of the x register |
| @x | execute the content of x register as a vim command |
registers
| "5p | retrieve 5th "ring" |
| "1p.... | retrieve numeric registers one by one |
| "_dd | delete to blackhole register "_ , don't affect any register |
| qaq | empty register "a" |
tags
| ^w} | preview tag under cursor, tag t |
| ^w] | split window and show tag under cursor |
| ^wz | close tag preview window |
entering to insert mode
| a | append text after the cursor [count] times. |
| A | append text at the end of the line [count] times. |
| i | insert text before the cursor [count] times. |
| I | insert text before the first non-blank in the line [count] times. |
| gI | insert text in column 1 [count] times. |
| o | begin a new line below the cursor and insert text, repeat [count] times. |
| O | begin a new line above the cursor and insert text, repeat [count] times. |
| gi | insert text in the same position as where insert mode was stopped. |
| s | will delete the char under cursor and start insert mode |
| cc (or) S | will cut the present line and enters into the insert mode. |
| c{motion} | will delete the text and enters into insert mode |
| C | will cut to the end of line |
to replace mode
| rc | will replace the character under cursor with 'c' character. |
| grc | like r, but without affecting layout |
| R | replace characters starting at the cursor |
| gR | like R, but without affecting layout |
| ctrl + [ | used to come out of replace mode |
to visual mode
| v | will enters into the visual mode |
| ^v | will enters into the 'visual block' mode |
| V | will enters into the 'line visual' mode |
| v{motion} | will take you to visual mode and select some text. |
| gv | start highlighting on previous visual area |
marking
| mc | mark current position with mark c ∈[a..Z] |
| 'c 'C | go 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..9 | go to last exit file and position |
| n^O | go to nth older position in jump list |
| n^I | go to nth newer position in jump list |
spell checking
| ]s or [s | move to next (]s) or previous ([s) misspelled word |
| z= | suggest corrections for the word under cursor |
| zg | add word under cursor as good word |
digraphs (non alpha-numerics symbols)
| i | enters é |
| i | enters é (unix) |
| i | enters é (win32) |
| ga | view 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 |
| :%&gic | last 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,'b | selects lines from mark 'a' to 'b' |
| :^rv | will substutes the register(v) value. |
| :^r=5*5 | insert 25 into text (mini-calculator) |
| :^aw | will substutes the word under cursor. |
| :^r^w | will substutes the word under cursor |
| :e f | edit file f, unless changes have been made |
| :e! f | edit file f always (by default reload current) |
| :q :q! | quit and confirm, quit and discard changes |
| : | recall commands starting with current |
| :r f | insert 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!c | insert output of command c below cursor |
| :.!c :!!c | replaces the current line with the output of command c |
| :r!ls -R | reads in output of ls into current file |
| :put=glob('**') | same as above |
| :sort /.*\%2v/ | sort all lines on second column |
| :args | display the argument list |
| :rco a :rm a | copy, move range r below line a |
| :history | list of all your commands |
| :his c | commandline history |
| :his s | search 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 |
| :scriptnames | list all plugins, _vimrcs loaded (super) |
| :verbose set history? | reveals value of history and where set |
| :retab | correct the tabs as per the current 'expandtab' or 'noexpantab' setting |
| :^f | history window (exit ctrl-c) |
| :sh :!c | start shell, execute command c in shell |
| :make | start make, read errors and jump to first |
| :cn :cp | display the next, previous error |
| :cl :cf | list all errors, read errors from file |
| :redir>f | redirect output to file f |
| :mkview [f] | save view configuration [to file f] |
| :loadview [f] | load view configuration [from file f] |
| :runtime! syntax/2html.vim | convert txt to html |
| :grep some_keyword *.c | get list of all c-files containing keyword |
| :cn | go to next occurrence |
| :imap ] @@@ | reproduce previous line |
| :nmap ] i@@@ | reproduce previous line word by word |
| :autocmd bufenter *.tex map | programming keys depending on file type |
| :autocmd bufenter *.tex map | programming keys depending on file type |
| :autocmd BufReadPre *.doc set ro | make 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 ro | protect a file from unintentional writes |
| :set rl[!] | reverse lines right to left [toggles] |
| :g/^/m0 | reverse lines top to bottom [toggles] |
| :redir @* | redirect commands to paste buffer |
| :redir END | end redirect |
| :redir >> out.txt | redirect to a file |
| "*yy | yank curent line to paste |
| "*p | insert from paste buffer |
| :'a,'by* | yank range into paste |
| :%y* | yank whole buffer into paste |
| :.y* | yank current line to paster |
| :nmap | filter 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 | endfor | will insert 10 successive ip address at current line |
saving files
| :wq :x | write to current file and exit |
| :rw | write range r to current file |
| :rw f | write range r to file f |
| :rw>>f | append range r to file f |
| :wn :wp(rev) | write file and edit next, previous one |
| :w newFilename | save file |
| :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. |
| :help filename-modifiers | help page |
searching
| :bufdo /searchstr/ | to recommence search |
| :nmap gx yiw/^\(sub\ | search for declaration of subroutine/function under cursor |
| :h \_ | help |
| :bufdo %s/searchstr/&/gic | multiple file search, say a to stop |
| :%s/home.\{-}\zshome/alone | substitute only the occurrence of home in any line |
| :v/tongue/s/nose/&/gic | find str but not on lines containing tongue |
| :/fred/;/joe/-2,/sid/+3s/sally/alley/gIC | find fred before beginning search for joe |
| :d/str/ | delete until str |
| :y/str/ | yank until str |
| :c/str/e | change until str end |
normal commands
| : | executes normal cmds on range of lines |
external commands
| :r !ls | writes ls command output into the files under the cursor |
| : | will take the range of lines and exec `sort` cmd on them and gets the o/p of it. |
movement
| :goto 100 :go 100 :100go | move the cursor to file offset position 100 from begining |
| :changes | will print the changelist |
| :ju(mps) | list of your movements |
| :h changelist | help for above |
| :help jump-motions | help page |
multiple files
| :split :sp | splits the current file into two window |
| :10sp | opens file1 in new window of 10 lines height |
| :vsp :vsplit | vertical spliting |
| :sview | same as split, but readonly |
| :new | will open another file in horizontal window |
| :e | also adds another file into the vim file buffer |
| :on | make 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 |
| :ls | list the file list of buffer. |
| :bd | closes the present file without quiting from the vim. |
| :bd | closes the selected file |
| :badd file.c | file from buffer list |
| :b | switches vim to edit another file. |
| :b | switches to the ':ls' count located file. |
| :bn | switches vim to next file of present file within the vim file buffer. |
| :bp | switches vim to previous file of present file within the vim file buffer. |
| :e# | jumps back to the previous file |
| :n | switches vim to next file within the vim file buffer. |
| :prev | switches vim to previous file within the vim file buffer. |
| :rew :first | switches vim to first file of the buffer. |
| :brew | buffer rewind |
| :last | switches vim to the last file of the buffer. |
| :argdo %s/foo/bar/e | operate on all files in arg |
| :bufdo %s/foo/bar/e | operate on all files in buffer |
| :windo %s/foo/bar/e | operate on all files in window |
| :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 |
| :sp fred.txt | open fred.txt into a split |
| :sball,:sb | split all buffers (super) |
| :scrollbind | in each split window |
| :set hidden | allows to change buffer w/o saving current buffer |
folding
| :set | foldmethod=manual/indent/marker |
| :set | foldmarker=, or <,> or <<<,>>> |
| :rfo | create fold for range r |
| :help folding | help page |
registers
| :reg | to get list of all used registers and their contents. |
| :reg x :di x | to get the content of x register. |
| :reg 12a | display content of registers 1,2 & a |
| :let @y='yy@"' | pre-loading registers (put in .vimrc) |
| :reg .-/%:*" | the seven special registers |
| :reg 0 | what 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 @*=@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 |
key mapping
| :map c e | map c ↦ e in normal & visual mode |
| :map! c e | map c ↦ e in insert & cmd-line mode |
| :unmap c :unmap! c | remove mapping c |
| :mk f | write current mappings, settings to file f |
| :ab c e | add abbreviation for c ↦ e |
| :ab c | show abbreviations starting with c |
| :una c | remove abbreviation c |
| :vmap // y/ | search for visually highlighted text |
| :vmap | with spec chars |
tags
| :pt t | preview tag under cursor, tag t |
| :pc | close tag preview window |
| :ta t | jump to tag t |
| :nta | jump to nth newer tag in list |
| ^] ^t | jump to the tag under cursor, return from tag |
| :ts t | list matching tags and select one for jump |
| :tj t | jump to tag or select one if multiple matches |
| :tags | print tag list |
| :npo :n^t | jump back from, to nth older tag |
| :tl | jump to last matching tag |
substitutes ranges
| , ; | separates two lines numbers, set to first line |
| n | an absolute line number n |
| . $ | the current line, the last line in file |
| % * | entire file, visual area |
| 't | position of mark t |
| /p/ ?p? | the next, previous line where p matches |
| +n -n | to 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 \K | an identifier, keyword; excl. digits |
| \f \p \F \P | a file name, printable char.; excl. digits |
| \s \S | a 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 |
| \& \n | the whole matched pattern, nth () group |
| \u \l | next character made upper, lowercase |
| \U \L | everything after \L|\U, stopping at \E|\e, is converted to lowercase/upper |
| \c \C | ignore, match case on next pattern |
| \%V | do a substitute on last visual area |
marking
| :marks | print the active marks list |
| :jumps | print 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 |
| :make | will compile the current .c file with gcc command |
| :cnext | show next compilation error |
| :cprevious | show previous compilation error |
| :copen | open errors window |
| :cclose | close errors window |
| :map | :useful key mapping for compilation |
| :map | :useful key mapping for showing next compilation error |
| :map | :useful key mapping for showing previous compilation error |
| :map | : useful key mapping for execution |
undo branching
| :undol | show the undo branches (the leaves of these branches) |
| :earlier | go to older state. time or steps can be specified |
| :later | go to newer state. time or steps can be specified |
session
| :mksession | save session to |
spell checking
| :setlocal spell spelllang=en_us | set language to english us |
highlights
| :hi | show current highlight settings |
| :hi comment cterm=bold ctermfg=white ctermbg=black | changes the hilighting settings for comments |
| :syn match DoubleSpace " " | example of setting your own highlighting |
| :hi def DoubleSpace guibg=#e0e0e0 | highlighting python functions |
settings
| :set ai :set noai | set or unset auto indent |
| :set ic :set noic | set or unset case-insensitive |
| :setfiletype c | will make 'c' syntax on for filenames ending with other extensions |
| :set smartcase | overrides ignorecase if uppercase used in search string (cool) |
| :syntax on | colour syntax in perl,html,php etc |
| :set syntax=perl | force syntax (usually taken from file extension) |
| :h regexp<^d> | type ^d and get a list all help topics containing regexp |
| :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 number | show line numbers |
| :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) |
| :colorscheme blue | change coloring scheme blue |
| :colorscheme default | change coloring scheme (any file in ~vim/vim??/colors) |
| :set noma (non modifiable) | prevents modifications |
| :set list | displaying "non-asciis" |
| :h listchars | help page |
file explorer
| :e . | file explorer |
| :Exp(lore) | file explorer note capital Ex |
| :Sex(plore) | file explorer in split window |
| :browse e | windows style browser |
| :ls | list of buffers |
| :cd .. :cd dirpath | change directory |
| :args | list of files |
| :args *.py | open list of files (you need this!) |
| :lcd %:p:h | change to directory of current file |
| :autocmd BufEnter * lcd %:p:h | change to directory of current file automatically (put in _vimrc) |
copying and moving lines
| : | copy a range of lines to the address |
| : | move a range of lines to the address |
plugins:
| :Pydoc os.fork | opens a python docs of os.fork() in the another horizontal window |
| :PydocSearch fork | searching for fork |
substitution examples
| :%s/str/joe/igc | general substitute command |
| :%s//joe/igc | substitute what you last searched for |
| :%s/~/sue/igc | substitute your last replacement string |
| :%s/\r//g | delete dos returns ^M |
| :%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 |
| :%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) |
| %s#><\([^/]\)#>\r<\1#g | split jumbled up xml file into one tag per line |
| :'a,'b g/str/ s/dick/joe/igc | vim 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_]\+\>#\Lgc | lowercase with optional leading characters |
| :%s/// | delete possibly multi-line comments |
| :help /\{-} | help non-greedy |
| :s/fred/ | sub "fred" with contents of register "a" |
| :s/fred/ | sub "fred" with contents of register "a" and some text |
| :s/fred/\=@a/g | better 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|:next | then use @: to repeat |
| :%s/goat\|cow/sheep/gc | ORing (must break pipe) |
| :'a,'bs#\[\|\]##g | remove [] from lines between markers a and b |
| :%s/\v(.*\n){5}/&\r | insert a blank line every 5 lines |
| :s/__date__/\=strftime("%c")/ | insert datestring |
| :inoremap \zd | 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#\ | format a mysql query |
| :redir @*|sil exec 'g#<\(input\|select\|textarea\|/\=form\)\>#p'|redir END | |
| :nmap ,z | redir @* |
| :%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-width | help page |
| :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 | pull word under cursor into lhs of a substitute |
| :vmap | pull visually highlighted text into lhs of a substitute |
| :'a,'bs/bucket\(s\)*/bowl\1/gic | |
| :%s,\(all/.*\)\@<=/,_,g | replace 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/^//n | count lines between markers a and b |
| :'a,'bs/somestring//gn | count occurences of a string |
| :%s/\<\(on\|off\)\>/\=strpart("offon", 3 * ("off" == submatch(0)), 3)/g | |
| :vnoremap | |
| :nmap | |
| :s#_\([a-z]\)#\u\1#g | |
| :s#\(\<\u\l\+\|\l\+\)\(\u\)#\l\1_\l\2#g | camel case variable names to under score type |
| :s/.\{,69\};\s*\|.\{,69\}\s\+/&\r/g | break lines at 70 chars, if possible after a ; |
| :% s/=\([^ ]\)/= \1/gc | |
| :% s/\([^ !<>=]\)=/\1 =/gc | add spaces before and after '=' |
| :%s/class \([A-Z]\)\([A-Z]\+\)(/class \1\L\2\E(/gc | replaces '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*$/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 |
| :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/ | ORing |
| :g/^/put_ | double space file (pu = put) |
| :g/^/m0 | reverse file (m = move) |
| :g/^/m$ | no effect! |
| :'a,'bg/^/m'b | reverse a section a to b |
| :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 .) |
| :g/^Chapter/t.|s/./-/g | automatically underline selecting headings |
| :g/\(^I[^^I]*\)\{80}/d | delete 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 jdd | delete every other line |
| :.,$g/^\d/exe "norm! \ | 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/ | display with context, display prettily |
| :g/ | display beautifully |
| :g/|/norm 2f|r* | replace 2nd | with a star, combining g// with normal mode commands |
| :nmap | send output of previous global command to a new window |
| :'a,'bg/fred/s/joe/susan/gic | can use memory to extend matching |
| :/fred/,/joe/s/fred/joe/gic | non-line based (ultra) |
| :/biz/,/any/g/article/s/wheel/bucket/gic | non-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 expression | to get all documentation of vim scripting syntax |
| :help function-list | to get the brief description of vim functions |
| :function | list functions presently exported |
| :func tolower() | list particular function |
encryption (use with care: don't forget your key)
| :X | you will be prompted for a key |
| :set key= | will disable the encryption |
| :help :X | help on encryption |
modelines
| :set modeline | set modelines |
| :set nomodeline | unset modelines |
| :help modeline | help on modelines |
| # vim: noai ts=2 sw=4 readonly | add this line in the file within first/last 5 lines |
help
| :help eval | help page on all vim functions |
| :help py | help page on all vim-py functions |
digraphs (non alpha-numerics symbols)
| :digraphs | display table |
| :h dig | help |
| :%s/[\x00-\x1f\x80-\xff]/ /g | type this as you see it to delete non-ascii |
| :%s/[ | where you have to type the control-v |
| :%s/[€-ÿ]//gi | should see a black square & a dotted y |
| :%s/[ | all 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 | endfor | prints numbers in new lines |
insert mode
text editing
| ^h | will delete one char before the cursor |
| ^w | will delete one word before the cursor |
| ^W | delete word before cursor |
| ^u | will delete all the characters before the cursor untill the start of line |
| ^U | delete all inserted character in current line |
| ^A | insert previously inserted text |
| ^@ | same as ^A and stop insert mode |
| ^Rx ^R^Rx | insert content of register x, literally |
| ^N ^P | word completion from the list of words before, after cursor |
| ^X^L | combination of these two commands will work as line completion |
| ^D ^T | shift left, right one shift width |
| ^Oc | execute normal mode command 'c' in insert mode |
| ^X^E ^X^Y | scroll 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 |
| o | exchange cursor position with start of highlighting |
| aw | select a word |
| as | select a sentence |
| ap | select a paragraph |
| ab | select a block () |
| aB | select a block { } |
| u | change to lower case |
| U | change to upper case |
| V% | visualise what you match |
| V}J | join visual block |
| V}gJ | join visual block w/o adding spaces |
| `[v`] | highlight last insert |
vimdiff
normal mode
| do | get changes from other window into the current window. |
| dp | put the changes from current window into the other window. |
command mode
| :diffupdate | diff update |
| :diffget :diffget | get changes from other window into the current window. |
| :diffput :diffput | put the changes from current window into the other window. |
files/folders paths prompt
misc
| /usr/share/vim/vimcurrent/doc | this dir will have all the docs related to the vim editor |