VIM

I use a variety of vi(m) commands for my job, so many that I can’t always
remember how to do something that I have done before. Therefore I keep notes
them here, for my bad memory.

What is the difference between Vi and Vim

Vim is Vi improve, everything that in vi is available in vim.
Here is some of the extended vim features:ref

  1. Vim support syntax highlighting, code folding, etc.
  2. Vim allows the screen to be split for editing multiple files.
  3. Vim includes a built in diff for comparing files (vimdiff)
  4. Vim support plugins

General command use in VIM

### insert mode
i -> insert mode at cursor
I -> insert mode at the beginning of Line
a -> append after the cursor
A -> append at the end ot line
o -> insert bank line below current line
O -> insert bank line above current line

### Cursor move
h,j,k,l ←, ↓, ↑, →
w      -> jump to the head of next word
W      -> jump to the head of next word which begin with bank
e      -> jump to the end of next word
E      -> jump to the end of next word which begin with bank
b      -> jump to the head of previous word
B      -> jump to the head of previous word which begin with bank
0      -> jump to the first character of current line
$      -> jump to the end of current line
^      -> jump to the first not-white-space character of current line
g_     -> jump to the last not-white-space character of current line
gg     -> jump to the first not-while-space character of first line
G      -> jump to the first not-while-space character of last line
`.     -> jump the position of last edit
''     -> jump the previous position of cursor
H      -> jump to first line of screen
M      -> jump to the middle line of screen
L      -> jump to the last line of screen
%      -> jump to the match symbol
{      -> paragraph backward
}      -> paragraph backward
[      -> jump to previous
]      -> jump to next
zt     -> move current line to the top of window
zz     -> move current line to the center of window
zb     -> move current line to the bottom of window
ctrl+e -> scroll screen backward
ctrl+y -> scrool screen forward
ctrl+u -> scroll half screen backward
ctrl+d -> scroll half screen backward
ctrl+f -> scrool to next screen
ctrl+b -> scrool to previous screen

### Edit
cw     -> change word
C      -> change to the end of line
u      -> undo
~      -> switch case
gu     -> uppercase select characters
gU     -> lowercase select characters
>>     -> indent line one column right
<<     -> indent line one column left
==     -> auto-indent current line
ctrl+r -> redo

### Cut, copy and paste
dd    -> delete current line, and put it to clipboard
x     -> delete current character
X     -> delete previous character
dw    -> delete to end of word
D     -> delete to end of line
yy    -> copy current line
yw    -> copy to end of word
y$    -> copy to end of line
p     -> paste after the cursor
P     -> paste befor the cursor
"+y   -> copy to system clipboard
"+gP  -> paste from system clipboard
[N]yy -> copy N lines

### Fold
zm -> increase the foldlevel by one
zM -> close all open folds
zr -> decrease the foldlevel by one
zR -> decrease the foldlevel to zero -- all folds will be open
zo -> opens a fold at the curse
zO -> opens all folds at the curse
zc -> close one fold
zC -> close all folds at the curse
zj -> jump to next fold
zk -> jump to previous fold
zf -> fold manual, using `V` to select lines and type `zf` to fold them

### split
:split
:vspl
ctrl+w+h/j/k/l  move cursor between split windows

### Search
*          -> search string forward
#          -> search string backward
/pattern   -> search for pattern
/\cpattern -> search for pattern, ignore upper and lower case
/pattern\c -> search for pattern, ignore upper and lower case
?pattern   -> search backwards for pattern
n          -> repeat search in same direction
N          -> repeat search in opposite direction
f          -> search character forward
F          -> search character backward

### Save and quit
:w  -> save
:wq -> save and quit
:x  -> save and quit
:q  -> quit, fail to quit if not save the changed
:q! -> force quit
ZZ  -> save and quit

### File 
use `vim file1 file2 ...` to open multiple files
:bn     -> next buffer
:bp     -> previous buffer 
:bd!    -> delete current buffer tag  
:e path -> edit file
:e      -> reload current file
:r !cmd -> read the result the command to the cursor of current file

### simple skills
xp   -> swap two characters
gg=G -> indent the file
[N]G -> jump to Nth line
yyp  -> copy and paste current line
yw   -> yank to the end of word
yiw  -> yank word
=    -> auto-indent selected lines
==   -> auto-indent current lines
n==  -> auto-indent [count] lines (start from current line)
gd   -> jump to the defined position of variable

### Other
.             -> repeat last change
J             -> join [count] lines
:nohl         -> not highlight
:set          -> nu show number
:set          -> wrap
:set          -> nowrap
:set          -> syntax=python` manual set syntax language
C-x or C-a    -> minus or add 1 to current digit
:%!xxd        -> hex edit
:%!xxd -r     -> return from hex edit
:set mouse =  -> available right button of mouse
:set mouse =a -> disable right button of mouse
:set paste    -> useful for paste text to vim
:set nopaste  -> disable paste mode

### substitute
(use command ":help substitue" for more information)
:[range]s/pattern/string/[c,e,g,i]
  range   1,7 line 1 to 7  1,$ line 1 to last  % all lines
  pattern string  be searched
  string  string for substitute
  c    comfirm
  e    not show error
  g    global, match all search of current line
  i    ignore
e.g.
  :%s/\s\+$//        delete all spaces between first space to the end of line
  :%s/h14/h12/g   replace h14 to be h12 for all occurrence in the file
  :1,$s/h14/h12/g replace h14 to be h12 from first line to the last line

### Visual Mode
(use command ":help v" for more information)
v      start visual mode per character
V      start visual mode linewise
ctrl+v start visual mode blockwise

### Text object (multiple lines possible)
(use command ":help objects" for more information)
Operator Mapping
v|c|d|y     i|a          {|[|(|"|'|w|p
visual  Inner Object      Region
change     An Object      {} [] () "" '' word paragraph
delete
yank
e.g.
  vi{ : select characters between brace
  va" : select characters, include double quotes
  viw : visual a word
  di" : delete characters between quotes
  ci( : change characters between bracket

### do operation to string (single line only)
v|c|d|y  f|t  character, work on current line only
e.g:
  vf{ : select characters to the first '{', include '{'.
  vt{ : select characters to the first '{', exclude '{'.
  using `;` to select the next character
v|c|d|y  /|?  character, work on the whole paper
e.g:
  v/{<CR> : select characters to the first '{', include '{'.
  v///<CR> : select characters to the first '//', include '//'.
  v?{ : select characters to the first '{', exclude '{'.
  using `n` or `N` to select the next character

### do operation on lines
[N]yy : copy N lines
[N]dd : delete N lines
:.,+2d : delete current line through the next 2 lines
:3,5m10 : move lines 3 through 5 to follow 10 (like delete and put in vi)
:3,5co10 : copy lines 3 through 5 to after 10 (like yank and put in vi)
:3,5t. : copy lines 3 through 5 to current line (like yank and put in vi)

### Auto completion
C-p
C-n
C-x C-p Word completion, backward
C 10 -x C-n Word completion, forward
C-x C-l Line completion
C-x C-f File name completion

### regular expression
:help regexp  -> for more information
. any character without new line
* 0 or more
^ begin of the line
$ end of the line
\+ 1 or more
\? 0 or 1
\
|
[] -> [abc], [^abc], [a-z]
()
{} -> {n}, {n,}, {n,m}
\d -> digit, [0-9]
\D -> non-digit, [^0-9]
\s -> whitespace character: <Space> and <Tab>
\S -> non-whitespace character
\w
\x    hex digit:            [0-9A-Fa-f]
\X    non-hex digit:            [^0-9A-Fa-f]
\o    octal digit:            [0-7]
\O    non-octal digit:        [^0-7]
\w    word character:            [0-9A-Za-z_]
\W    non-word character:        [^0-9A-Za-z_]
\h    head of word character:        [A-Za-z_]
\H    non-head of word character:    [^A-Za-z_]
\a    alphabetic character:        [A-Za-z]
\A    non-alphabetic character:    [^A-Za-z]
\l    lowercase character:        [a-z]
\L    non-lowercase character:    [^a-z]
\u    uppercase character:        [A-Z]
\U    non-uppercase character:    [^A-Z]

### Session
:mksession .mysession.vim make a session for current documents, use "gvim -S 
.mysession.vim" to open it.

### History
q: enter history commands, then choose and execute the command

### Marks
(use command ":help mark-motions" for more information)
mx     set mark x, x can use a..z characters
'x     jump to mark x
:marks show all marks

### Register
:reg  view register content
"0p   paste from register 0
"1p   paste from register 1
"_D   delete contents to back hole register

### Complex repeats
qq operators q   record all operators to q register
100@q            repeat the operators 100 times

### Editing Files in other places
vim scp://[user@]hostname[:port]//FilePath
e.g.: vim scp://root@172.16.110.39//root/a.c

### Merge code by vimdiff
`]c` go to next difference
`[c` go to previous difference
`do` diff get, get the change from another file to current file
`dp` diff put, put the change from current file to another file

### source vimrc, not need to exit vim to make config effective
:so %        -> source current file(.vimrc)
:so ~/.vimrc -> source specified file

### run vi scripts under terminal
vi -e -s -c ":%s/pattern/string/g" -c ":wq" file-name

### Help
:help symbol

skills for program

  1. open file on current cursor, use command gf; if the file is not in current
    directory, use :set path+=yourfilepath to add more dir to the path, use
    :help path for more info.

some skills

  1. command mode type :nohl cancel high light

  2. substituttion
    sample lines:

    + (http://www.google.com)\[google\]
    + (http://www.wolframalpha.com/)\[wolfram\]
    into the lines:
    + [google](http://www.google.com)
    + [wolfram](http://www.wolframalpha.com/)
    Here is the command to do this:
    :%s/+ \(.*\)\(\[.*\]\)/+ \2\1/g

  3. compare file
    vimdiff file1 file2 or gvim -d file1 file2

  4. digit operator
    ctrl+a increment 1
    ctrl+x subtract 1

  5. delete all comments
    :%s/\/\*\_.\{-}\*\//g or :%s#\M/*\m\_.\{-}\M*/##g

  6. delete match/unmatch lines
    :g/.*patternSearch.*/d
    :v/#include/d Delete all lines except “#include” lines

  7. more substitution
    Substituting all lines with its line number
    :%s/^/\=line(".") . ". "/g
    Resort numeric
    :4,$s/\d\+/\=submatch(0) + 1/
    Insert sequence number to column position
    :%s/table\[\]/\='table[' . printf("%d",line(".")) . ']'/g
    :%s/table\[\]/\='table[' . printf("%d",line(".")+9) . ']'/g start from 10

  8. delete bank line
    :g/^$/d
    :g/^ *$/d delete lines only contain space

  9. add “inline” to all function
    :%s/\(.*(\)/inline \1/g this can work, but not perfect!!
    %s/\(^[□tab]*\)\(.*(.*\)/\1inline \2/g

  10. delete all spaces at the end of every line:
    :%s/\(.*\) *$/\1/

  11. read range of lines from another file to current file
    :r! sed -n 100,158p /home/dennis/test.c

  12. list all the match lines of searching on screen
    :g/pattern/p In its longer format: :global/regular-expression/print
    If pattern is leave out, like :g//p, vim will uses previous search item.
    You can leave p out too, because p(rint) is the default action.

  13. copy all lines containing a search pattern
    qaq clear register a
    :g/pattern/y A append all matching lines to register, then use p to paster them.

  14. make a list number, reference this

    first, add this code to vimrc:

    " Add argument (can be negative, default 1) to global variable i.
    " Return value of i before the change.
    function Inc(...)
      let result = g:i
      let g:i += a:0 > 0 ? a:1 : 1
      return result
    endfunction
    

    then type :so ~/.vimrc to make it effective, and use command
    :let i = 1 | %s/ /\=' ' . Inc() . '.'/

    before:

    * How do you write a fast network server?
    * How do you write a network server that can handle 10000 clients?
    * What bottlenecks are there and how do you avoid them?
    

    after:

    * 10.How do you write a fast network server?
    * 11.How do you write a network server that can handle 10000 clients?
    * 12.What bottlenecks are there and how do you avoid them?
    

    Test command :let i = 0 | %s/f0/\='f' . Inc()/

    before:

    <f0>int state;\l|\
    <f0>int iostate;\l|\
    <f0>int fd;\l|\
    <f0>struct session *session;\l|\
    

    after:

    <f0>int state;\l|\
    <f1>int iostate;\l|\
    <f2>int fd;\l|\
    <f3>struct session *session;\l|\
    
  15. delete all space character at the end of each line
    :%s/\s\+$//g
    and for the beginning of each line is :%s/^\s\+//g

  16. g? translate the selected content by ROT13, using u to cancel operation

  17. :%TOhtml translate to html format

  18. Encrypt
    method one :set key=123456, then save and quit :wq
    method two :X, type the passwd twice,save and quit :wq
    clean passwd :set key=, save and quit :wq

  19. autocmd FileType c,cpp set shiftwidth=4 | set expandtab add to .vimrc, expand tab to be four space

  20. 23,38w newfile write the content between specify lines to file, 320,$ >>newfile append to file

  21. 23,38!sort sort lines 23 through 38

  22. %s/ */\r/g replace space as return
    %s/[ \t][ \t]*/\r/g replace space or tab as return

  23. %s/\(\S\) \+/\1/g delete all whitespace characters which after non-whitespace.

  24. :g/\[/,/\]/j join multiple line to one

other valued skills

other version

Vundle, plugin manager

  • Git时代的VIM不完全使用教程
  • install
    • git clone http://github.com/gmarik/vundle.git ~/.vim/bundle/vundle
  • .vimrc(put plugin name behind Bundle, more plugin see vim-scripts.org)

    set nocompatible " be iMproved
    filetype off " required!
    
    set rtp+=~/.vim/bundle/vundle/
    call vundle#rc()
    
    " let Vundle manage Vundle
    " required!
    Bundle 'gmarik/vundle'
    
    " vim-scripts repos
    Bundle 'vim-plugin-foo'
    Bundle 'vim-plugin-bar'
    
    filetype plugin indent on " required!
    
  • manage plugin

    • :BundleInstall
    • :BundleUpdate
    • :BundleClean
  • powerful plugin
    • Bundle ‘ag.vim’
    • Bundle ‘ctrlp.vim’
    • Bundle ‘EasyMotion’
    • Bundle ‘The-NERD-tree’
    • Bundle ‘The-NERD-Commenter’
    • Bundle ‘UltiSnips’
    • Bundle ‘Tabular’
    • Bundle ‘Valloric/YouCompleteMe’

install vim by source

  • ./configure –prefix=path-to-install
  • make && make install
  • export PATH=path-to-install:PATH

some useful configuration of vimrc

reference