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

Vim configuration

Vim配置文件vimrc:

""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Description: .vimrc
" History:
"         2013/07/31 Dennis  forbid clang auto-compile, restore ctag, and update cscope
"         2013/07/05 Dennis  use clang-complete instead Omni plugin
"         2013/04/16 Dennis  Add plugin AutoComplPop.vim and snipMate.vim
"         2012/12/29 Dennis  Create
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""

""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" 影响全部用户的配置:
" 插件 *.vim 拷贝到 /usr/share/vim/vim73/plugin/
" 文档 *.txt 拷贝到 /usr/share/vim/vim73/doc/
" 影响当前用户的配置:
" 插件 *.vim 拷贝到 ~/.vim/plugin/
" 文档 *.txt 拷贝到 ~/.vim/doc/
"
" 中文在线帮助
" http://man.chinaunix.net/newsoft/vi/doc/help.html
"
" 更多参考
" http://blog.csdn.net/wooin/article/details/1858917
" https://github.com/easwy/share/blob/master/vim/vimrc/_vimrc
"
" vimrc 语法相关
" help key-notation
" <CR>  回车
" <up> <left> <right> <down> 方向键
" <Esc>
" <C-x> 表示 Ctrl+x
" <S-x> 表示 Shift+x
" <Tab>
" <M-x> Alt+x
" <A-x> Alt+x
" iab 插入模式的缩写
" imap 插入模式的键映射
"

""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
"常规设置

"编码设置
set enc=utf-8
set fencs=utf-8,ucs-bom,shift-jis,gb18030,gbk,gb2312,cp936

" 字体
if has("gui_running")
  if has("gui_gtk2")
    "set guifont=Inconsolata\ 12
    set guifont=Liberation\Mono\ 12
  elseif has("gui_win32")
    set guifont=Consolas:h11:cANSI
  endif
endif

"语言设置
set helplang=cn
set encoding=utf8 
set langmenu=zh_CN.UTF-8 
set imcmdline 
source $VIMRUNTIME/delmenu.vim 
source $VIMRUNTIME/menu.vim

"语法高亮
syntax enable
syntax on
colorscheme desert

set number

set autochdir

set tags=tags

set hlsearch

set tabstop=4 softtabstop=4 shiftwidth=4 expandtab

set nowrap
set nobackup

" default <Leader> map backslash
:let mapleader = ","

"分割为两行
:nnoremap K i<CR><Esc>

:set colorcolumn=81

"全选
"map <C-a> ggVG

"自动对齐
set autoindent 

" 开始折叠
set foldenable
" 设置语法折叠
" manual  手工定义折叠
" indent  更多的缩进表示更高级别的折叠
" expr    用表达式来定义折叠
" syntax  用语法高亮来定义折叠
" diff    对没有更改的文本进行折叠
" marker  对文中的标志折叠
set foldmethod=indent
"折叠相关的快捷键
"zR 打开所有的折叠
"za Open/Close (toggle) a folded group of lines.
"zA Open a Closed fold or close and open fold recursively.
"zi 全部 展开/关闭 折叠
"zo 打开 (open) 在光标下的折叠
"zc 关闭 (close) 在光标下的折叠
"zC 循环关闭 (Close) 在光标下的所有折叠
"zM 关闭所有可折叠区域
" 设置折叠区域的宽度
set foldcolumn=0
" 设置折叠层数为
setlocal foldlevel=1
" 新建的文件,刚打开的文件不折叠
autocmd! BufNewFile,BufRead * setlocal nofoldenable


" splite
" 横向划分
nmap <Leader>h :spl<CR>
" 竖向划分
nmap <Leader>v :vspl<CR>
" 加宽
nmap + <C-W>+
" 减宽
nmap - <C-W>-

map <leader>y "+y
map <leader>p "+gP

" 刷新文件
" :e


" 设置代码自动补全快捷键(这些方法在插件中已经实现)
"设置文件头
:iab ihead <Esc>ggO/*<CR>Copyleft(c) 2014-2015 <CR>Authored by Dennis on:<Esc>:
    \ read !date <CR>kJ$a<CR>@desc:<CR>@history<CR>*/<Esc>

"插入日期和时间
":iab idate A<C-R>=strftime("%c")<CR><Esc>
:iab idate <Esc>:read !date "+\%Y-\%m-\%d \%T" <Esc>

"c框架frame
:iab ifc  #include <stdio.h><CR><CR>int main(int argc, char* argv[])<CR>{<CR>
    \ <Tab>return 0;<CR>}<Esc>2<up>
"c++框架frame
:iab ifcpp #include <iostream><CR>using namespace std;<CR><CR>int main(int argc,
    \ char* argv[])<CR>{<CR><Tab>return 0;<CR>}<Esc>2<up>

:iab iif if ()<CR>{<CR>}<Esc>2<UP>f)i
:iab FF for(int i=0; i<; i++)<CR>{<CR>}<Esc>2<UP>f<a
:iab iswitch switch()<CR>{<CR><Tab>case :<CR><Tab>break;<CR><Tab>default :<CR>
    \ <Tab>break;<CR>}<Esc>7<UP>f)i

filetype plugin on

""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
"Ctags 定位变量、宏和函数的定义
"yum install ctags
"ctags -R
":set tags=/home/***/tags
"<C-]> 定位到定义处 <C-T>返回
" configure tags - add additional tags here or comment out not-used ones
set tags+=~/.vim/tags/system

" build tags with Ctrl-F12
"--c++-kinds=+p  : 为C++文件增加函数原型的标签
"--fields=+iaS   : 在标签文件中加入继承信息(i)、
"                  类成员的访问控制信息(a)、以及函数的指纹(S)
"--extra=+q      : 为标签增加类修饰符。注意,如果没有此选项,将不能对类成员补全
map <C-F12> :!ctags -R -I --c++-kinds=+p --fields=+iaS --extra=+q .<CR>

""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
"clang-complete
"c/c++自动补全插件
"let g:clang_complete_copen=1
"let g:clang_periodic_quickfix=1
"let g:clang_snippets=1
"let g:clang_close_preview=1
"let g:clang_use_library=1
"let g:clang_user_options='-stdlib=libstdc++ -std=c++11 -I/usr/include'

""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
"echofunc.vim 
let g:EchoFuncShowOnStatus = 1

""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
"TagList 高效浏览源码
"http://www.vim.org/scripts/script.php?script_id=273
":Tlist 打开

""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
"WinManager
"http://www.vim.org/scripts/script.php?script_id=95
"wm 关闭/打开netrw和TagList窗口
":help winmanager
let g:winManagerWindowLayout='FileExplorer|TagList'
nmap wm :WMToggle<cr>
"刷新目录信息 :e .

"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" cscope
" yum install cscope
" cscope -Rb
" :cscope add ../cscope.out
" (type ":help :cscope" in vim to show help)
" from http://vim.wikia.com/wiki/Autoloading_Cscope_Database 
function! LoadCscope()
  let db = findfile("cscope.out", ".;")
  if (!empty(db))
    let path = strpart(db, 0, match(db, "/cscope.out$"))
    set nocscopeverbose " suppress 'duplicate connection' error
    exe "cs add " . db . " " . path
    set cscopeverbose
  endif
endfunction
au BufEnter /* call LoadCscope()

" s symbol
" g definition
" d called
" c calling
" t text
" e grep
" f file
" i #include this file
nmap <C-@>s :cs find s <C-R>=expand("<cword>")<CR><CR>
nmap <C-@>g :cs find g <C-R>=expand("<cword>")<CR><CR>
nmap <C-@>c :cs find c <C-R>=expand("<cword>")<CR><CR>
nmap <C-@>t :cs find t <C-R>=expand("<cword>")<CR><CR>
nmap <C-@>e :cs find e <C-R>=expand("<cword>")<CR><CR>
nmap <C-@>f :cs find f <C-R>=expand("<cfile>")<CR><CR>
nmap <C-@>i :cs find i ^<C-R>=expand("<cfile>")<CR>$<CR>
nmap <C-@>d :cs find d <C-R>=expand("<cword>")<CR><CR>

:set cscopequickfix=s-,c-,d-,i-,t-,e-

""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" QuickFix (已是标准,不用单独安装)
" :help quickfix
" :cw 打开 quickfix窗口
nmap <F6> :cn<CR>
nmap <F7> :cp<CR>

""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
"MiniBufExplorer 快速浏览和操作Buffer
"http://www.vim.org/scripts/script.php?script_id=159
"<C-Tab> 向前循环切换到每个buffer上,并在当前窗口打开
"<C-S-Tab> 向后循环切换到每个buffer上,并在当前窗口打开
let g:miniBufExplMapCTabSwitchBufs = 1
"用<C-h,j,k,l>切换到上下左右的窗口
let g:miniBufExplMapWindowNavVim = 1
"用<C-箭头键>切换到上下左右窗口中去
"let g:miniBufExplMapWindowNavArrows = 1
"设定自动开启MiniBufExplorer的文件数目
let g:miniBufExplorerMoreThanOne=2
nmap <C-N> :bn<CR>
nmap <C-P> :bp<CR>
map <leader>b :MiniBufExplorer<cr>
map <leader>c :CMiniBufExplorer<cr>
map <leader>u :UMiniBufExplorer<cr>

""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
"c/h文件间相互切换 -- 插件: A
"http://www.vim.org/scripts/script.php?script_id=31
":A :AS横向窗口 :AV纵向窗口 :AT新建标签
nnoremap <silent> <F12> :A<CR>

""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
"Grep 在工程中查找
"http://www.vim.org/scripts/script.php?script_id=311
"nnoremap <silent> <F3> :Grep<CR>

nnoremap <silent> <F3> :vimgrep <cword>  *.h *.c <CR>

""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
"close error window
nnoremap <silent> <F4> :cclose <CR>

""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
"自动补全
":help complete
"Ctrl+P 向前切换成员
"Ctrl+N 向后切换成员
"Ctrl+E 表示退出下拉窗口, 并退回到原来录入的文字
"Ctrl+Y 表示退出下拉窗口, 并接受当前选项
"Ctrl+X Ctrl+L 整行补全
"Ctrl+X Ctrl+N 根据当前文件里关键字补全
"Ctrl+X Ctrl+K 根据字典补全
"Ctrl+X Ctrl+T 根据同义词字典补全
"Ctrl+X Ctrl+I 根据头文件内关键字补全
"Ctrl+X Ctrl+] 根据标签补全
"Ctrl+X Ctrl+F 补全文件名
"Ctrl+X Ctrl+D 补全宏定义
"Ctrl+X Ctrl+V 补全vim命令
"Ctrl+X Ctrl+U 用户自定义补全方式
"Ctrl+X Ctrl+S 拼写建议

" 字典
" http://www.vim.org/scripts/script.php?script_id=195
" tar xvf ~/Downloads/engspchk.tar.gz CVIMSYN/engspchk.dict

setlocal dictionary+=$VIMRUNTIME/dict/english.dict

""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
"代码自动提示 AutoComplPop 
"http://www.vim.org/scripts/script.php?script_id=1879
"代码模板补全 snipMate 
"http://www.vim.org/scripts/script.php?script_id=2540

""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
"注释代码
"注释 vimrc, 符号"
"nmap <C-M>v :s/^\("\)*/"/g<CR>:nohl<CR>
nmap <C-M>v :s/^/"/g<CR>:nohl<CR>
nmap <S-M>v :s/^\("\)//g<CR>:nohl<CR>
"vmap <C-M>v :s/^\("\)*/"/g<CR>:nohl<CR>
vmap <C-M>v :s/^/"/g<CR>:nohl<CR>
vmap <S-M>v :s/^\("\)//g<CR>:nohl<CR>
"注释 c/c++, 符号//
nmap <C-M>c :s#^\(//\)*#//#g<CR>:nohl<CR>
nmap <S-M>c :s#^\(//\)##g<CR>:nohl<CR>
vmap <C-M>c :s#^\(//\)*#//#g<CR>:nohl<CR>
vmap <S-M>c :s#^\(//\)##g<CR>:nohl<CR>
"注释 shelc, 符号#
nmap <C-M>s :s@^\(#\)*@#@g<CR>:nohl<CR>
nmap <S-M>s :s@^\(#\)@@g<CR>:nohl<CR>
vmap <C-M>s :s@^\(#\)*@#@g<CR>:nohl<CR>
vmap <S-M>s :s@^\(#\)@@g<CR>:nohl<CR>
"注释 batch, 符号::
nmap <C-M>b :s/^\(::\)*/::/g<CR>:nohl<CR>
nmap <S-M>b :s/^\(::\)//g<CR>:nohl<CR>
vmap <C-M>b :s/^\(::\)*/::/g<CR>:nohl<CR>
vmap <S-M>b :s/^\(::\)//g<CR>:nohl<CR>

" Blue:
"      classes structures typedefs interfaces namespaces
" Gray:
"       variables
" Purple:
"      preprocessor macros
" Red:
"       methods
" White:
"      comment
" Green:
"

MS Visual Studio auto compile

文件列表

  • 主程序 main.bat
  • 配置文件 project.cfg
  • 编译器环境设置 vsvars.bat

操作步骤

  • 配置 project.cfg 文件
  • 执行 main.bat

文件源码

project.cfg

compiler:2008
pri_name:SampleProject
prj_dir:../SampleProject

vsvars.bat

@ECHO off

SET /a retval=0

GOTO CASE_%1
:CASE_2005
    IF NOT "%VS80COMNTOOLS%"=="" (
        CALL "%VS80COMNTOOLS%"vsvars32.bat
        SET /a retval=1
    )
    GOTO END_SWITCH
:CASE_2008
    IF NOT "%VS90COMNTOOLS%"=="" (
        CALL "%VS90COMNTOOLS%"vsvars32.bat
        SET /a retval=1
    )
    GOTO END_SWITCH
:CASE_2010
    IF NOT "%VS100COMNTOOLS%"=="" (
        CALL "%VS100COMNTOOLS%"vsvars32.bat
        SET /a retval=1
    )
    GOTO END_SWITCH
:END_SWITCH

EXIT /B %retval%

main.bat

:: Function: Build/Clean Visual Studio Project
:: Author:   Dennis
:: Date:     2012-09-18

@ECHO off&setlocal enabledelayedexpansion 

mode con lines=30 cols=100
title Build/Clean Visual Studio project

REM +++++++++++++++++++++++++++++++++
REM Get project name from config file
REM +++++++++++++++++++++++++++++++++
SET prj_name=
SET compiler=
SET prj_dir=

FOR /f "tokens=1* delims=:" %%a IN (project.cfg) DO (
    IF "%%a"=="compiler" SET compiler=%%b
    IF "%%a"=="pri_name" SET prj_name=%%b
    IF "%%a"=="prj_dir" SET prj_dir=%%b
)

IF "%compiler%"=="" (
    ECHO "Config project compiler first."
    GOTO End
)

IF "%prj_name%"=="" (
    ECHO "Config project name first."
    GOTO End
)

IF "%prj_dir%"=="" (
    ECHO "Config project diretory first."
    GOTO End
)

REM +++++++++++++++++++++++++++++++++
REM Set compile environment
REM +++++++++++++++++++++++++++++++++
:Vars
CALL vsvars.bat %compiler%
IF %ERRORLEVEL% LEQ 0 (
    ECHO "Error code: %ERRORLEVEL%"
    ECHO "Failed to SET VS %compiler% complile enviroment."
    ECHO "Please check and try again."
    GOTO End
)

REM +++++++++++++++++++++++++++++++++
REM Main process
REM +++++++++++++++++++++++++++++++++
:Main
CLS
ECHO.
ECHO. %prj_name% project manager
ECHO.
ECHO. Porject type:
ECHO.     1.Release
ECHO.     2.Debug
ECHO.
ECHO. Opereate type:
ECHO.     1.Build
ECHO.     2.Clean
ECHO. __________________________________________________
ECHO.

SET choice=
SET /p choice= Please select project type(EXIT IF enter):
IF "%choice%"=="1" ( SET prj_type="Release" & GOTO Next_Choise )
IF "%choice%"=="2" ( SET prj_type="Debug" & GOTO Next_Choise )
IF DEFINED choice GOTO Main
EXIT

:Next_Choise
ECHO Your selected is %prj_type%
SET /p choice= Please select operate type(EXIT IF enter):
IF "%choice%"=="1" GOTO Case_Operate_%choice%
IF "%choice%"=="2" GOTO Case_Operate_%choice%
IF DEFINED choice GOTO Main
EXIT

:Case_Operate_1
    devenv.com %prj_dir%\%prj_name%.vcproj /build %prj_type%
    GOTO End_Switch
:Case_Operate_2
    devenv.com %prj_dir%\%prj_name%.vcproj /clean %prj_type%
    GOTO End_Switch
:End_Switch
    PAUSE
    GOTO Main


:End
PAUSE

Notepad++ support highlight of markdown

Notepad++默认不支持Markdown格式文件md高亮显示.

Github上的thomsmits童鞋填补了该空缺
https://github.com/thomsmits/markdown_npp

这里也贴一下步骤:

  • 浏览器打开userDefineLang.xml
  • 复制全部代码,即从<NotepadPlus></NotepadPlus>, 粘贴并保存为文件userDefineLang.xml
  • 打开Notepad++设置目录, 开始 > 运行, 输入 (或粘贴)%APPDATA%\Notepad++, 点击确定
  • 复制刚才保存的userDefineLang.xml到Notepad++设置目录
  • 重启Notepad++

就可以在Noepad++的菜单项语言下找到Markdown

WinIO Sample

// winio_sample.cpp

#include <stdio.h>
#include <tchar.h>

#include <windows.h>

typedef bool (*InitializeWinIo)();
typedef void (*ShutdownWinIo)();
typedef bool (*GetPortVal)(WORD wPortAddr, PDWORD pdwPortVal, BYTE bSize);
typedef bool (*SetPortVal)(WORD wPortAddr, DWORD dwPortVal, BYTE bSize);
typedef bool (*InstallWinIoDriver)(PWSTR pszWinIoDriverPath, bool IsDemandLoaded);

InitializeWinIo        pInitializeWinIo    = NULL;
ShutdownWinIo        pShutdownWinIo        = NULL;
GetPortVal            pGetPortVal            = NULL;
SetPortVal            pSetPortVal            = NULL;
InstallWinIoDriver    pInstallWinIoDriver = NULL;

HINSTANCE hinstLib = NULL;

VOID SafeGetNativeSystemInfo(__out LPSYSTEM_INFO lpSystemInfo)
{
    if (NULL==lpSystemInfo)    return;
    typedef VOID (WINAPI *LPFN_GetNativeSystemInfo)(LPSYSTEM_INFO lpSystemInfo);
    LPFN_GetNativeSystemInfo fnGetNativeSystemInfo = 
        (LPFN_GetNativeSystemInfo)GetProcAddress( GetModuleHandle(_T("kernel32")), "GetNativeSystemInfo");
    if (NULL != fnGetNativeSystemInfo)
    {
        fnGetNativeSystemInfo(lpSystemInfo);
    }
    else
    {
        GetSystemInfo(lpSystemInfo);
    }
}

int GetSystemBits()
{
    SYSTEM_INFO si;
    SafeGetNativeSystemInfo(&si);
    if (si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64 ||
        si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_IA64 )
    {
        return 64;
    }
    return 32;
}

int LoadLib()
{
    TCHAR *tcLib = NULL;
    tcLib = (32 == GetSystemBits()) ? TEXT("WinIo32.dll") : TEXT("WinIo64.dll");
    hinstLib = LoadLibrary(tcLib); 
    if (!hinstLib) 
    {
        wprintf(TEXT("Failed to load %s\n"), tcLib);
        return 1;
    }
    return 0;
}

void FreeLib()
{
    if (hinstLib)
    {
        FreeLibrary(hinstLib);
        hinstLib = NULL;
    }
}

int GetFuncAddr()
{
    if (hinstLib != NULL) 
    { 
        pInitializeWinIo = (InitializeWinIo) GetProcAddress(hinstLib, "InitializeWinIo");
        if (!pInitializeWinIo) return 1;

        pShutdownWinIo = (ShutdownWinIo) GetProcAddress(hinstLib, "ShutdownWinIo");
        if (!pShutdownWinIo) return 1;

        pGetPortVal = (GetPortVal) GetProcAddress(hinstLib, "GetPortVal");
        if (!pGetPortVal) return 1;

        pSetPortVal = (SetPortVal) GetProcAddress(hinstLib, "SetPortVal");
        if (!pSetPortVal) return 1;

        pInstallWinIoDriver = (InstallWinIoDriver) GetProcAddress(hinstLib, "InstallWinIoDriver");
        if (!pInstallWinIoDriver) return 1;
    }

    return 0;
}

void MyGetPortVal(WORD wPortAddr, BYTE bSize)
{
    DWORD dwPortVal = 0;
    pGetPortVal(wPortAddr, &dwPortVal, bSize);
    char tmp = (char)dwPortVal;
    printf("port:0x%x, value:0x%x value:0x%x \n", wPortAddr, dwPortVal, tmp);
}

int GetPortValLoop()
{
    char *pBuf = NULL;
    char line[255] = {0};
    DWORD dwPortVal = 0;
    WORD wPortAddr = 0;
    BYTE bSize = 1;
    char bytePortVal = 0;

    printf("Enter get port value loop.\nType q can to quit application.\n");

    while(1)
    {
        printf("Please enter port address :");
        memset(line, 0, sizeof(line));
        pBuf = fgets(line, sizeof(line), stdin);

        // Type q and Enter to end loop
        if (!strcmp(pBuf,"q\n")) break;

        wPortAddr = atoi(pBuf);

        pGetPortVal(wPortAddr, &dwPortVal, bSize);

        bytePortVal = (char)dwPortVal;
        printf("port:0x%x, value:0x%x value:0x%x \n", wPortAddr, dwPortVal, bytePortVal);
    }

    getchar();
    return 0;
}

int _tmain(int argc, _TCHAR* argv[])
{
    if (0 != LoadLib())
    {
        goto ExitApp;
    }

    if(0 != GetFuncAddr())
    {
        printf("Failed to get function address.\n");
        goto ExitApp;
    }

    if (!pInitializeWinIo())
    {
        printf("Failed to initialize winio.\n");
        goto ExitApp;
    }

    Sleep(1000);

    printf("start to get port value.\n");
    printf("press any key to continue.\n");
    getchar();

    GetPortValLoop();

    printf("Shutdown WinIo.\n");
    printf("press any key to continue.\n");
    getchar();
    pShutdownWinIo();

ExitApp:
    FreeLib();
    printf("Press any key to continue.\n");
    getchar();
    return 0;
}

Dll write by C# use on VC++

##C#工程

  1. 修改项目属性

    属性 -> 应用程序 -> 输出类型 -> 类库

  2. 编译工程,生成类库文件

    projectName.dll

##VC++工程

  1. 修改项目属性

    配置属性 -> 常规 -> 项目默认值 -> 公共语言运行时支持 -> 公共语言运行时支持(/clr)

  2. 加入代码
  • 类库路径 #using "./bin/CSharp.dll"
  • 设定使用的命名空间 using namespace CSharpNamespaceSample;
  • 使用类成员和方法

方法一:

void TestFunc()
{
    CSharpClassSample ^cs = gcnew CSharpClassSample();

    cs->member_sample = 1;
    cs->func_sample();
}

方法二:

ref class A{
public:
    static CSharpClassSample obj;
};

void TestFunc_1(void)
{
    A::obj.member_sample = 1;
}

void TestFunc_2(void)
{
    A::obj.func_sample();
}

write blog on github

2012年9月9日,在github创建blog日志

2012年9月14日

2012年9月16日

2012年9月24日

配置git环境 用户名和邮件(配置文件目录~/.gitconfig)
git config --global user.name "Your Name"
git config --global user.email you@example.com
如:
  dennis@dennis-VirtualBox:~git config --global user.name "Dennis"
  dennis@dennis-VirtualBox:~git config --global user.emal "dennis.cpp@gmail.com"
确认配置是否成功:
git config user.name
git config user.email
也可以直接编辑文件:
$ cat ~/.gitconfig

2012年12月14日

环境windows xp,git
git status 查看状态
git pull 更新
在_post目录中加入新的文章后如:2012-12-14-visual-studio-project-clean.md 
执行下面的命令更新上传
git push origin master
下面这三行是执行上一个命令要求输入用户名和密码
    Username for 'github.com':
    Password for 'github.com':
    Everything up-to-date
git add .
git commit -m "create my site"
git push

2013年01月04日

Fedora17安装Jekyll预览github博客文章
1.安装工具
    yum install ruby-devel
    gem install jekyll
2.在blog目录下运行jekyll服务
    jekyll --server
3.预览blog
    打开http://localhost:4000
4.rake产生post文章
    gem install rake
    rake post title="***"

2013年01月25日

2013年01月26日

2014年05月23日

2014年06月05日

2014年06月21日

  • How do you uninstall Ruby 1.8.7 and install Ruby 1.9.2?

  • Install jekyll on Ubuntu

    dennis@dennis:~/work/git/matrix207.github.com$ sudo gem install jekyll
    ERROR:  Error installing jekyll:
        celluloid requires Ruby version >= 1.9.2.
    dennis@dennis:~/work/git/matrix207.github.com$ ruby --version
    ruby 1.8.7 (2011-06-30 patchlevel 352) [x86_64-linux]
    dennis@dennis:~/work/git/matrix207.github.com$ sudo apt-get install ruby1.9.3
    Reading package lists... Done
    Building dependency tree       
    ......
    dennis@dennis:~/work/git/matrix207.github.com$ sudo update-alternatives --config ruby
    There are 2 choices for the alternative ruby (providing /usr/bin/ruby).
    
      Selection    Path                Priority   Status
    ------------------------------------------------------------
    * 0            /usr/bin/ruby1.8     50        auto mode
      1            /usr/bin/ruby1.8     50        manual mode
      2            /usr/bin/ruby1.9.1   10        manual mode
    
    Press enter to keep the current choice[*], or type selection number: 2
    update-alternatives: using /usr/bin/ruby1.9.1 to provide /usr/bin/ruby (ruby) in manual mode.
    dennis@dennis:~/work/git/matrix207.github.com$ ruby -v
    ruby 1.9.3p0 (2011-10-30 revision 33570) [x86_64-linux]
    dennis@dennis:~/work/git/matrix207.github.com$ sudo update-alternatives --config gem
    There are 2 choices for the alternative gem (providing /usr/bin/gem).
    
      Selection    Path               Priority   Status
    ------------------------------------------------------------
    * 0            /usr/bin/gem1.8     180       auto mode
      1            /usr/bin/gem1.8     180       manual mode
      2            /usr/bin/gem1.9.1   10        manual mode
    
    Press enter to keep the current choice[*], or type selection number: 2
    update-alternatives: using /usr/bin/gem1.9.1 to provide /usr/bin/gem (gem) in manual mode.
    dennis@dennis:~/work/git/matrix207.github.com$ gem -v
    1.8.11
    
  • install nodejs for JavaScript runtime environment
    sudo apt-get install nodejs

  • jekyll --server change to jekyll server