vim配置vimrc詳解

shupan001發表於2011-11-29
phpchina折騰王獨家配置,灰常牛叉的一套vim配置,另附有詳細註釋,自己折騰vim的時候可以參照其中的大部分設定進行一些個性化定製."是否相容VI,compatible為相容,nocompatible為不完全相容
"如果設定為compatible,則tab將不會變成空格
set nocompatible
 
source $VIMRUNTIME/vimrc_example.vim
source $VIMRUNTIME/mswin.vim
"設定滑鼠執行模式為WINDOWS模式
behave mswin
 
" Multi-encoding setting, MUST BE IN THE BEGINNING OF .vimrc!
"
if has("multi_byte")
    " When 'fileencodings' starts with 'ucs-bom', don't do this manually
    "set bomb
    set fileencodings=ucs-bom,utf-8,chinese,taiwan,japan,korea,latin1
    " CJK environment detection and corresponding setting
    if v:lang =~ "^zh_CN"
        " Simplified Chinese, on Unix euc-cn, on MS-Windows cp936
        set encoding=chinese
        set termencoding=chinese
        if &fileencoding == ''
            set fileencoding=chinese
        endif
    elseif v:lang =~ "^zh_TW"
        " Traditional Chinese, on Unix euc-tw, on MS-Windows cp950
        set encoding=taiwan
        set termencoding=taiwan
        if &fileencoding == ''
            set fileencoding=taiwan
        endif
    elseif v:lang =~ "^ja_JP"
        " Japanese, on Unix euc-jp, on MS-Windows cp932
        set encoding=japan
        set termencoding=japan
        if &fileencoding == ''
            set fileencoding=japan
        endif
    elseif v:lang =~ "^ko"
        " Korean on Unix euc-kr, on MS-Windows cp949
        set encoding=korea
        set termencoding=korea
        if &fileencoding == ''
            set fileencoding=korea
        endif
    endif
    " Detect UTF-8 locale, and override CJK setting if needed
    if v:lang =~ "utf8$" || v:lang =~ "UTF-8$"
        set encoding=utf-8
    endif
else
    echoerr 'Sorry, this version of (g)Vim was not compiled with "multi_byte"'
endif
 
"解決選單亂碼
set encoding=utf-8
"fileencodings需要注意順序,前面的字符集應該比後面的字符集大
set fileencodings=ucs-bom,utf-8,cp936,gb18030,big5,euc-jp,euc-kr,latin1
set langmenu=zh_CN.utf-8
set imcmdline
source $VIMRUNTIME/delmenu.vim
source $VIMRUNTIME/menu.vim
 
"解決consle輸出亂碼
language messages zh_CN.utf-8
 
"自動檢測檔案型別並載入相應的設定,snipMate外掛需要開啟這個配置選項
filetype plugin indent on
 
"語法高亮
syntax on
 
"自動縮排
set autoindent
"設定 Backspace 和 Delete 的靈活程度,backspace=2 則沒有任何限制
"設定在哪些模式下使用滑鼠功能,mouse=a 表示所有模式
set mouse=a
set backspace=2
"不自動換行
set nowrap
"設定超過100字元自動換行
"set textwidth=100
"設定超過100列的字元帶下劃線
"au BufWinEnter * let w:m2=matchadd('Underlined', '\%>100v.\+', -1)
"syn match out80 /\%80v./ containedin=ALL
"hi out80 guifg=white guibg=red
"智慧對齊方式
set smartindent
"一個tab是4個字元
set tabstop=4
"按一次tab前進4個字元
set softtabstop=4
"用空格代替tab
set expandtab
"設定自動縮排
set ai!
"縮排的字元個數
set cindent shiftwidth=4
"set autoindent shiftwidth=2
 
"設定摺疊模式
set foldcolumn=4
"游標遇到摺疊,摺疊就開啟
"set foldopen=all
"移開摺疊時自動關閉摺疊
"set foldclose=all
"zf zo zc zd zr zm zR zM zn zi zN
"依縮排摺疊
"   manual  手工定義摺疊
"   indent  更多的縮排表示更高階別的摺疊
"   expr    用表示式來定義摺疊
"   syntax  用語法高亮來定義摺疊
"   diff    對沒有更改的文字進行摺疊
"   marker  對文中的標誌摺疊
set foldmethod=syntax
"啟動時不要自動摺疊程式碼
set foldlevel=100
"依標記摺疊
set foldmethod=marker
 
"顯示行號
set number
 
"開啟游標的行列位置顯示功能
set ruler
 
"顯示中文引號
set ambiwidth=double
 
"行高亮
set cursorline
"列高亮,與函式列表有衝突
set cursorcolumn
 
"設定命令列的高度
set cmdheight=2
 
"高亮搜尋的關鍵字
set hlsearch
 
"搜尋忽略大小寫
set ignorecase
 
"設定命令歷史行數
set history=100
 
"啟動的時候不顯示那個援助索馬利亞兒童的提示
"set shortmess=atI
 
"不要閃爍
"set novisualbell
 
"顯示TAB健
set list
set listchars=tab:>-,trail:-
 
"高亮字元,讓其不受100列限制
":highlight OverLength ctermbg=red ctermfg=white guibg=grey guifg=white
":match OverLength '\%101v.*'
 
"設定VIM狀態列
set laststatus=2 "顯示狀態列(預設值為1, 無法顯示狀態列)
set statusline=
set statusline+=%2*%-3.3n%0*\ " buffer number
set statusline+=%f\ " file name
set statusline+=%h%1*%m%r%w%0* " flag
set statusline+=[
if v:version >= 600
    set statusline+=%{strlen(&ft)?&ft:'none'}, " filetype
    set statusline+=%{&fileencoding}, " encoding
endif
set statusline+=%{&fileformat}] " file format
set statusline+=%= " right align
"set statusline+=%2*0x%-8B\ " current char
set statusline+=0x%-8B\ " current char
set statusline+=%-14.(%l,%c%V%)\ %<%P " offset
if filereadable(expand("$VIM/vimfiles/plugin/vimbuddy.vim"))
    set statusline+=\ %{VimBuddy()} " vim buddy
endif
"狀態行顏色
"highlight StatusLine guifg=SlateBlue guibg=Yellow
"highlight StatusLineNC guifg=Gray guibg=White
 
"設定路徑,多個路徑用逗號分隔
set path=.,"E:/Web/htdocs",,
 
"去掉有關vi一致性模式,避免以前版本的一些bug和侷限
set nocp
 
"增強模式中的命令列自動完成操作
set wildmenu
 
"執行 Vim 預設提供的 .vimrc 檔案的示例,包含了開啟語法加亮顯示等最常用的功能
source $VIMRUNTIME/vimrc_example.vim
 
"預設不產生備份檔案
set nobackup
"在輸入括號時游標會短暫地跳到與之相匹配的括號處,不影響輸入
set showmatch
"正確地處理中文字元的折行和拼接
set formatoptions+=mM
 
"設定檔案瀏覽器目錄為當前目錄
set bsdir=buffer
"自動切換當前目錄為當前檔案所在的目錄
set autochdir
"自動重新載入外部修改內容
"set autoread
 
"使PHP識別EOT字串
hi link phpheredoc string
 
"允許在有未儲存的修改時切換緩衝區
set hidden
 
"選中一段文字並全文搜尋這段文字
vmap <silent> ,/ y/<C-R>=escape(@", '\\/.*$^~[]')<CR><CR>
vmap <silent> ,? y?<C-R>=escape(@", '\\/.*$^~[]')<CR><CR>
 
"進入當前編輯的檔案的目錄
autocmd BufEnter * exec "cd %:p:h"
 
"儲存檔案的格式順序
set fileformats=dos,unix
 
"配色(更多的配色見colors目錄和http://www.cs.cmu.edu/~maverick/VimColorSchemeTest/index-c.html)
"colorscheme peacock_light
colorscheme peacock_desert
 
"設定字型
if has("gui")
    if has("win32")
        "啟動時會彈出字型選擇框,如果取消,則採用系統預設字型
        "set guifont=*
        "Windows預設使用的字型,字型較粗
        "set guifont=Fixedsys
        "中文顯示變形,字型較粗
        "set guifont=Monospace:h9
        "中文顯示變形,字型較細
        "set guifont=Consolas:h9
        "中文顯示變形,字型較細
        "set guifont=Lucida\ Console:h9
        "中文顯示變形,字型較細
        set guifont=Monaco:h9
        "中文顯示變形,字型較細
        "set guifont=Andale\ Mono:h10
        "中文顯示變形,字型較細
        "set guifont=Bitstream\ Vera\ Sans\ Mono:h9
        "需要執行修改版的gvim才能識別
        "set guifont=YaHei\ Consolas\ Hybrid:h9
        "如果guifontwide採用中文字型,漢字將自動使用guifontwide,英文自動使用guifont
        set guifontwide=YaHei\ Consolas\ Hybrid:h9
    else
        set guifont=SimSun:h10
    endif
    "set columns=128 lines=36
endif
 
"啟動後最大化
au GUIEnter * simalt ~x
 
"置貼上模式,這樣貼上過來的程式程式碼就不會錯位了。
"set paste
 
"設定幫助資訊
set helplang=cn
 
"自動儲存session和viminfo
"預設的sessionoptions選項包括:blank,buffers,curdir,folds,help,options,tabpages,winsize
"也就是會話檔案會恢復當前編輯環境的空視窗、所有的緩衝區、當前目錄、摺疊(fold)相關的資訊、幫助視窗、所有的選項和對映、所有的標籤頁(tab)、視窗大小
"set sessionoptions-=curdir
"au VimLeave * mksession! $VIMRUNTIME/Session.vim
"au VimLeave * wviminfo! $VIMRUNTIME/_viminfo
"source $VIMRUNTIME/Session.vim
"rviminfo $VIMRUNTIME/_viminfo
 
"記錄上次關閉的檔案及狀態
set viminfo='10,\"100,:20,%,n$VIMRUNTIME/_viminfo
au BufReadPost * if line("'\"") > 0|if line("'\"") <= line("$")|exe("norm '\"")|else|exe "norm $"|endif|endif
 
"設定外掛SuperTab
"設定按下<Tab>後預設的補全方式, 預設是<C-P>,
"現在改為<C-X><C-O>. 關於<C-P>的補全方式,
"還有其他的補全方式, 可以看看下面的一些幫助:
":help ins-completion
":help compl-omni
let g:SuperTabRetainCompletionType=2
"0 - 不記錄上次的補全方式
"1 - 記住上次的補全方式,直到用其他的補全命令改變它
"2 - 記住上次的補全方式,直到按ESC退出插入模式為止
let g:SuperTabDefaultCompletionType="<C-X><C-O>"
 
set diffexpr=MyDiff()
function! MyDiff()
    let opt = '-a --binary '
    if &diffopt =~ 'icase' | let opt = opt . '-i ' | endif
    if &diffopt =~ 'iwhite' | let opt = opt . '-b ' | endif
    let arg1 = v:fname_in
    if arg1 =~ ' ' | let arg1 = '"' . arg1 . '"' | endif
    let arg2 = v:fname_new
    if arg2 =~ ' ' | let arg2 = '"' . arg2 . '"' | endif
    let arg3 = v:fname_out
    if arg3 =~ ' ' | let arg3 = '"' . arg3 . '"' | endif
    let eq = ''
    if $VIMRUNTIME =~ ' '
        if &sh =~ '\<cmd'
            let cmd = '""' . $VIMRUNTIME . '\diff"'
            let eq = '"'
        else
            let cmd = substitute($VIMRUNTIME, ' ', '" ', '') . '\diff"'
        endif
    else
        let cmd = $VIMRUNTIME . '\diff'
    endif
    silent execute '!' . cmd . ' ' . opt . arg1 . ' ' . arg2 . ' > ' . arg3 . eq
endfunction
 
"phpDocumentor
"this includes the script and maps the combination <ctrl> + p
"to the doc functions.
source $VIM\vimfiles\plugin\php-doc.vim
imap <A-/> <ESC>:call PhpDocSingle()<CR>i
nmap <A-/> :call PhpDocSingle()<CR>
vmap <A-/> :call PhpDocRange()<CR>
 
"You can obtain the completion dictionary file from:
"http://cvs.php.net/viewvc.cgi/phpdoc/funclist.txt
set dictionary+=$VIM\vimfiles\syntax\function.txt
 
"Use the dictionary completion
set complete-=k complete+=k
 
"Alt + -> 開啟下一個檔案
map <M-right> <ESC>:bn<RETURN>
"Alt + <- 開啟上一個檔案
map <M-left> <ESC>:bp<RETURN>
 
"使用TAB鍵自動完成
"This function determines, wether we are on
"the start of the line text(then tab indents)
"or if we want to try auto completion
function! InsertTabWrapper()
    let col=col('.')-1
    if !col || getline('.')[col-1] !~ '\k'
        return "\<TAB>"
    else
        return "\<C-N>"
    endif
endfunction
"使用SuperTab之後,就可以關閉該設定了
"inoremap <TAB> <C-R>=InsertTabWrapper()<CR>
 
"平臺判斷
function! GetSystem()
    if (has("win32") || has("win95") || has("win64") || has("win16"))
        return "windows"
    elseif has("unix")
        return "linux"
    elseif has("mac")
        return "mac"
    endif
endfunction
 
"取得游標處的匹配
function! GetPatternAtCursor(pat)
    let col = col('.') - 1
    let line = getline('.')
    let ebeg = -1
    let cont = match(line, a:pat, 0)
    while (ebeg >= 0 || (0 <= cont) && (cont <= col))
        let contn = matchend(line, a:pat, cont)
        if (cont <= col) && (col < contn)
            let ebeg = match(line, a:pat, cont)
            let elen = contn - ebeg
            break
        else
            let cont = match(line, a:pat, contn)
        endif
    endwh
    if ebeg >= 0
        return strpart(line, ebeg, elen)
    else
        return ""
    endif
endfunction
 
"開啟連結
function! OpenUrl()
    let s:url = GetPatternAtCursor('\v(https?://|ftp://|file:/{3}|www\.)((\w|-)+\.)+(\w|-)+(:\d+)?(/(\w|[~@#$%^&+=/.?-])+)?')
    "echo s:url
    if s:url == ""
        echohl WarningMsg
        echomsg '在游標處未發現URL!'
        echohl None
    else
        if GetSystem() == "windows"
            call system("explorer " . s:url)
        else
            call system("firefox " . s:url . " &")
        endif
    endif
    unlet s:url
endfunction
nmap <C-LeftMouse> :call OpenUrl()<CR>
 
"放大字型
function <SID>FontSize_Enlarge()
    if GetSystem() == "linux"
        let pattern = '\<\d\+$'
    elseif GetSystem() == "windows"
        let pattern = ':h\zs\d\+\ze:'
    endif
    let fontsize = matchstr(&gfn, pattern)
    let cmd = substitute(&gfn, pattern, string(fontsize + 1), 'g')
    let &gfn=cmd
    let fontsize = matchstr(&gfw, pattern)
    let cmd = substitute(&gfw, pattern, string(fontsize + 1), 'g')
    let &gfw=cmd
endfunction
nnoremap <A-+> :call <SID>FontSize_Enlarge()<CR>
 
"縮小字型
function <SID>FontSize_Reduce()
    if GetSystem() == "linux"
        let pattern = '\<\d\+$'
    elseif GetSystem() == "windows"
        let pattern = ':h\zs\d\+\ze:'
    endif
    let fontsize = matchstr(&gfn, pattern)
    let cmd = substitute(&gfn, pattern, string(fontsize - 1), 'g')
    let &gfn=cmd
    let fontsize = matchstr(&gfw, pattern)
    let cmd = substitute(&gfw, pattern, string(fontsize - 1), 'g')
    let &gfw=cmd
endfunction
nnoremap <A--> :call <SID>FontSize_Reduce()<CR>
 
"html自動輸入匹配標籤,輸入>之後自動完成匹配標籤
au FileType xhtml,xml so ~/.vim/ftplugin/html_autoclosetag.vim
 
"能夠漂亮的顯示.NFO檔案
function! SetFileEncodings(encodings)
    let b:myfileencodingsbak=&fileencodings
    let &fileencodings=a:encodings
endfunction
function! RestoreFileEncodings()
    let &fileencodings=b:myfileencodingsbak
    unlet b:myfileencodingsbak
endfunction
au BufReadPre *.nfo call SetFileEncodings('cp437')|set ambiwidth=single
au BufReadPost *.nfo call RestoreFileEncodings()
 
""""""""""""""""""""""""""""""
" 設定lookupfile外掛
""""""""""""""""""""""""""""""
let g:LookupFile_MinPatLength = 2               "最少輸入2個字元才開始查詢
let g:LookupFile_PreserveLastPattern = 0        "不儲存上次查詢的字串
let g:LookupFile_PreservePatternHistory = 1     "儲存查詢歷史
let g:LookupFile_AlwaysAcceptFirst = 1          "回車開啟第一個匹配專案
let g:LookupFile_AllowNewFiles = 0              "不允許建立不存在的檔案
if filereadable("./filenametags")               "設定tag檔案的名字
    let g:LookupFile_TagExpr = '"./filenametags"'
endif
"對映LookupFile為,lf
nmap <silent> ,lf <Plug>LookupFile<CR>
"對映LUBufs為,lb
nmap <silent> ,lb :LUBufs<CR>
"對映LUWalk為,lw
nmap <silent> ,lw :LUWalk<CR>
"對映LUPath為,lp
nmap <silent> ,lp :LUPath<CR>
 
"F2處理行尾的空格以及檔案尾部的多餘空行
"Automatically remove trailing spaces when saving a file.
autocmd BufRead,BufWrite * if ! &bin | silent! %s/\s\+$//ge | endif
"Remove indenting on empty line
map <F2> :w<CR>:call CleanupBuffer(1)<CR>:noh<CR>
function! CleanupBuffer(keep)
    " Skip binary files
    if (&bin > 0)
        return
    endif
    " Remove spaces and tabs from end of every line, if possible
    silent! %s/\s\+$//ge
    " Save current line number
    let lnum = line(".")
    " number of last line
    let lastline = line("$")
    let n        = lastline
    " while loop
    while (1)
        " content of last line
        let line = getline(n)
        " remove spaces and tab
        if (!empty(line))
            break
        endif
        let n = n - 1
    endwhile
    " Delete all empty lines at the end of file
    let start = n+1+a:keep
    if (start < lastline)
        execute n+1+a:keep . "," . lastline . "d"
    endif
    " after clean spaces and tabs, jump back
    exec "normal " . lnum . "G"
endfunction
 
"快速查詢(外掛grep外掛,需要grep軟體)
"nnoremap <silent> <F3> :Grep<CR>
"給n對映一個快捷鍵,習慣上喜歡用F3
nmap <F3> n
"給n對映一個快捷鍵,習慣上喜歡用F3
nmap <S-F3> N
 
"PHP語法檢查
"map <F4> :!E:/Web/Server/PHP/php.exe -l %<CR>
function! CheckPHPSyntax()
    setlocal makeprg=E:/Web/Server/PHP/php.exe\ -l\ -n\ -d\ html_errors=off
    setlocal shellpipe=>
    " Use error format for parsing PHP error output
    setlocal errorformat=%m\ in\ %f\ on\ line\ %l
    make %
endfunction
" Perform :PHP_CheckSyntax()
map <F4> :call CheckPHPSyntax()<CR>
 
"PHP程式碼美化
"map <C-A-F4> :!ZendCodeAnalyzer.exe %<CR>
 
"PHP程式碼通過Zend加密
function! ZendEncodePHP()
    let currentfile=fnamemodify(bufname("%"), ":p")
    let newfile=fnamemodify(bufname("%"), ":p:h") . "\\" . fnamemodify(bufname("%"), ":t:r") . ".zend." . fnamemodify(bufname("%"), ":e")
    execute "!\"E:\\Web\\Tools\\ZendGuard\\bin\\zendenc.exe\"" . ' ' . currentfile . ' ' . newfile
endfunction
map <C-F4> :call ZendEncodePHP()<CR>
 
"使用IE預覽網頁
function! BrowseWebPage()
    let filepath=substitute(getcwd()."\\".bufname("%"), 'E:\\Web\\htdocs\\', "http://localhost/", "g")
    let filepath=substitute(filepath,"\\","\/","g")
    silent execute "!\"explorer\""." ".filepath
endfunction
map <S-F4> :call BrowseWebPage()<CR>
 
"F6開啟或關閉nerd_tree和taglist
"由於nerd_tree和taglist採用了trinity外掛開啟
"所以具體的設定以trinity.vim為準
nmap <F6>  :TrinityToggleTagListAndNERDTree<CR>
 
"F7單獨切換開啟nerd_tree(nerd_tree外掛)
let g:NERDChristmasTree = 1              "色彩顯示
let g:NERDTreeShowHidden = 1             "顯示隱藏檔案
let g:NERDTreeWinPos = 'left'            "視窗顯示位置
let g:NERDTreeHighlightCursorline = 0    "高亮當前行
nmap <F7>  :TrinityToggleNERDTree<CR>
 
"netrw設定(自帶目錄樹外掛)
let g:netrw_winsize=30
let g:netrw_liststyle=1
let g:netrw_timefmt='%Y-%m-%d %H:%M:%S'
nmap <silent> <C-F7> :Sexplore!<cr>
 
"Ctrl + F7開啟project外掛
nmap <silent> <A-F7>  :Project<CR>
 
"F8單獨切換開啟taglist(taglist外掛)
if GetSystem() == "windows"                    "設定Windows系統中ctags程式的位置
    let g:Tlist_Ctags_Cmd = $VIMRUNTIME.'\ctags'
else
    let g:Tlist_Ctags_Cmd = '/usr/bin/ctags'
endif
"let g:Tlist_Sort_Type = 'name'          "以名稱順序排序,預設以位置順序(order)
let g:Tlist_Show_One_File = 1           "不同時顯示多個檔案的tag,只顯示當前檔案的
let g:Tlist_Exit_OnlyWindow = 1         "如果taglist視窗是最後一個視窗,則退出vim
lef g:Tlist_File_Fold_Auto_Close = 1    "當游標不在編輯檔案裡面的時候全部摺疊
let g:Tlist_Use_Right_Window = 1        "在右側視窗中顯示taglist視窗
let g:Tlist_Enable_Fold_Column = 1      "顯示摺疊邊欄
nmap <F8>  :TrinityToggleTagList<CR>
 
"F11檢視開啟的檔案列表(bufexplorer外掛)
let g:bufExplorerDefaultHelp = 1
let g:bufExplorerDetailedHelp = 0
nmap <F11> :BufExplorer <CR>
 
"F12生成/更新tags檔案
set tags=tags;
set autochdir
function! UpdateTagsFile()
    silent !ctags -R --fields=+ianS --extra=+q
endfunction
nmap <F12> :call UpdateTagsFile()<CR>
 
"Ctrl + F12刪除tags檔案
function! DeleteTagsFile()
    "Linux下的刪除方法
    "silent !rm tags
    "Windows下的刪除方法
    silent !del /F /Q tags
endfunction
nmap <C-F12> :call DeleteTagsFile()<CR>
"退出VIM之前刪除tags檔案
"au VimLeavePre * call DeleteTagsFile()