vim使用配置(轉)

 

在終端下使用vim進行編輯時,默認狀況下,編輯的界面上是沒有行號的、語法高亮度顯示、智能縮進等功能的。javascript

爲了更好的在vim下進行工做,須要手動配置一個配置文件: .vimrcphp

在啓動vim時,當前用戶根目錄下的 .vimrc 文件會被自動讀取,該文件能夠包含一些設置甚至腳本,因此,通常狀況下把 .vimrc文件建立在當前用戶的根目錄下比較方便,即建立的命令爲:css

$vim ~/.vimrchtml

設置完成後java

$:x 或者 $:wqpython

進行保存退出便可。jquery

下面給出一個例子,已經很詳細了,是某位大神的配置文件,這裏對其表示敬意。css3

"雙引號開始的行爲註釋行,下同。c++

" File: _vimrc
" Author: xuleaper<xuleaper@gmail.com>
" Description: xuleaper's personal vim config file.
" Last Modified: $Id: _vimrc 467 2012-09-08 03:49:05Z  $
" Blog: http://www.gracecode.com/
" Since:2010-06-15
" History:
" 2012-06-08
" +vundle支持,更加靈活的管理插件
" 2012-01-20
" +整理vimrc結構
" 2011-09-08
" +在網絡配置文件的基礎上,編寫本身的vimrc
"=============================
" vimrc_structure
"   |
"   +--Environment setting
"   |
"   +--Multi_language setting
"   |
"   +--GUI_laguage setting
"   |
"   +--AutoCmd
"   |
"   +--Plugin configure
"   |
"   +--Script's function
"   |
"   +--Key shortcut
"   |
"   ---Bundle setting
"=============================
if exists("mingcheng")
    finish
endif
let g:mingcheng = 1
if v:version < 700
    echoerr 'This _vimrc requires Vim 7 or later.'
    quit
endif
" ============
" Environment
" ============
" Color Scheme
if has('syntax')
    " 默認編輯器配色
    au BufNewFile,BufRead,BufEnter,WinEnter * colo desert
    " 各不一樣類型的文件配色不一樣
    au BufNewFile,BufRead,BufEnter,WinEnter *.wiki colo void
    " 保證語法高亮
    syntax on
endif
" 保留歷史記錄
set history=500
" 行控制
set linebreak
set nocompatible
set textwidth=80
set wrap
" 標籤頁
set tabpagemax=9
set showtabline=2
" 控制檯響鈴
set noerrorbells
set novisualbell
set t_vb=
" 行號和標尺
set number
set ruler
set rulerformat=%15(%c%V\ %p%%%)
" 命令行於狀態行
set ch=2
set stl=\ [File]\ %F%m%r%h%y[%{&fileformat},%{&fileencoding}]\ %w\ \ [PWD]\ %r%{GetPWD()}%h\ %=\ [Line]%l/%L\ %=\[%P]
set ls=2 " 始終顯示狀態行
set wildmenu "命令行補全以加強模式運行
" 定義 <Leader> 爲逗號
let mapleader = ","
let maplocalleader = ","
" Search Option
set hlsearch  " Highlight search things
set magic     " Set magic on, for regular expressions
set showmatch " Show matching bracets when text indicator is over them
set mat=2     " How many tenths of a second to blink
set noincsearch
" 製表符
set tabstop=4
set expandtab
set smarttab
set shiftwidth=4
set softtabstop=4
" 狀態欄顯示目前所執行的指令
set showcmd 
" 縮進
set autoindent
set smartindent
" 自動從新讀入
set autoread
" 插入模式下使用 <BS>、<Del> <C-W> <C-U>
set backspace=indent,eol,start
" 設定在任何模式下鼠標均可用
" 自動改變當前目錄
if has('netbeans_intg')
    set autochdir
endif
" 備份和緩存
set nobackup
"set noswapfile
" 自動完成
set complete=.,w,b,k,t,i
set completeopt=longest,menu
" 代碼摺疊
set foldmethod=marker
" 共享外部剪貼板
set clipboard+=unnamed
"設置快速編輯.vimrc文件 ,e 編輯.vimrc
" 快速修改 vimrc 文件
if has("win32")
    map <silent> <leader>e :e $VIM/_vimrc<cr>
else
    map <silent> <leader>e :e $VIM/.vimrc<cr>
endif
"保存.vimrc文件後會自動調用新的.vimrc
autocmd! bufwritepost _vimrc source $VIM/_vimrc
" ======================
" Multi_language setting
" default encoding UTF  
" ======================
if has("multi_byte")
    set encoding=utf-8
    "set fenc=cp936
    " English messages only
    "language messages zh_CN.utf-8
    if has('win32')
        language chinese
        let &termencoding=&encoding
    endif
    set fencs=utf-8,gbk,chinese,latin1
    set formatoptions+=mM
    set nobomb " 不使用 Unicode 簽名
    if v:lang =~? '^\(zh\)\|\(ja\)\|\(ko\)'
        set ambiwidth=double
    endif
else
    echoerr "Sorry, this version of (g)vim was not compiled with +multi_byte"
endif
" 永久撤銷,Vim7.3 新特性
if has('persistent_undo')
    set undofile
    " 設置撤銷文件的存放的目錄
    if has("unix")
        set undodir=/tmp/,~/tmp,~/Temp
    else
        set undodir=d:/temp/
    endif
    set undolevels=1000
    set undoreload=10000
endif
" Diff 模式的時候鼠標同步滾動 for Vim7.3
if has('cursorbind')
    set cursorbind
end
"============
" GUI setting
" ===========
if has('gui_running')
    " 只顯示菜單
    set guioptions=mcr
    " 高亮光標所在的行
    set cursorline
    if has("win32")
        " Windows 兼容配置
        source $VIMRUNTIME/mswin.vim
        source $VIMRUNTIME/menu.vim
        source $ViMRUnTIME/delmenu.vim
        " f11 最大化
        nmap <f11> :call libcallnr('fullscreen.dll', 'ToggleFullScreen', 0)<cr>
        nmap <Leader>ff :call libcallnr('fullscreen.dll', 'ToggleFullScreen', 0)<cr>
        " 字體配置
        exec 'set guifont='.iconv('Consolas', &enc, 'gbk').':h12:cANSI'
        exec 'set guifontwide='.iconv('Microsoft\ YaHei', &enc, 'gbk').':h12:cGB2312'
    endif
    " Under Linux/Unix etc.
    if has("unix") && !has('gui_macvim')
        set guifont=Courier\ 10\ Pitch\ 11
    endif
    " Under the Mac(MacVim)
    if has("mac") || has("gui_macvim")
        if has("gui_macvim")
            " MacVim 下的字體配置
            set guifont=Courier_New:h14
            set guifontwide=YouYuan:h14
            " 半透明和窗口大小
            set transparency=2
            set lines=200 columns=120
            " 使用 MacVim 原生的全屏幕功能
            let s:lines=&lines
            let s:columns=&columns
            func! FullScreenEnter()
                set lines=999 columns=999
                set fu
            endf
            func! FullScreenLeave()
                let &lines=s:lines
                let &columns=s:columns
                set nofu
            endf
            func! FullScreenToggle()
                if &fullscreen
                    call FullScreenLeave()
                else
                    call FullScreenEnter()
                endif
            endf
            set guioptions+=e
            " Mac 下,按 <Leader>ff 切換全屏
            nmap <f11> :call FullScreenToggle()<cr>
            nmap <Leader>ff  :call FullScreenToggle()<cr>
            " I like TCSH :^)
            set shell=/bin/tcsh
            " Set input method off
            set imdisable
            " Set QuickTemplatePath
            let g:QuickTemplatePath = $HOME.'/.vim/templates/'
            " 若是爲空文件,則自動設置當前目錄爲桌面
            lcd ~/Desktop/
        endif
    endif
endif
" =========
" AutoCmd
" =========
if has("autocmd")
    filetype plugin indent on
    " 括號自動補全
    func! AutoClose()
        :inoremap ( ()<ESC>i
        :inoremap " ""<ESC>i
        :inoremap ' ''<ESC>i
        :inoremap { {}<ESC>i
        :inoremap [ []<ESC>i
        :inoremap ) <c-r>=ClosePair(')')<CR>
        :inoremap } <c-r>=ClosePair('}')<CR>
        :inoremap ] <c-r>=ClosePair(']')<CR>
    endf
    func! ClosePair(char)
        if getline('.')[col('.') - 1] == a:char
            return "\<Right>"
        else
            return a:char
        endif
    endf
"""""""""""""""""""""""""""""""""""""""""""""
    augroup vimrcEx
        au!
        autocmd FileType text setlocal textwidth=80
        autocmd BufReadPost *
                    \ if line("'\"") > 0 && line("'\"") <= line("$") |
                    \   exe "normal g`\"" |
                    \ endif
    augroup END
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
    " Auto close quotation marks for PHP, Javascript, etc, file
    au FileType php,javascript,c,cpp exe AutoClose()
    " JavaScript 語法高亮
    au FileType html,javascript let g:javascript_enable_domhtmlcss = 1
    au BufRead,BufNewFile *.js setf jquery
    " 給各語言文件添加 Dict
    if has('win32')
        let s:dict_dir = $VIM.'\vimfiles\dict\'
    else
        let s:dict_dir = $HOME."/.vim/dict/"
    endif
    let s:dict_dir = "setlocal dict+=".s:dict_dir
    au FileType php exec s:dict_dir."php_funclist.dict"
    au FileType css exec s:dict_dir."css.dict"
    au FileType javascript exec s:dict_dir."javascript.dict"
    " 格式化 JavaScript 文件
    au FileType javascript map <f12> :call g:Jsbeautify()<cr>
    au FileType javascript set omnifunc=javascriptcomplete#CompleteJS
    " 增長 ActionScript 語法支持
    au BufNewFile,BufRead,BufEnter,WinEnter,FileType *.as setf actionscript 
    " CSS3 語法支持
    au BufRead,BufNewFile *.css set ft=css syntax=css3
    " 增長 Objective-C 語法支持
    au BufNewFile,BufRead,BufEnter,WinEnter,FileType *.m,*.h setf objc
    " 將指定文件的換行符轉換成 UNIX 格式
    au FileType php,javascript,html,css,python,vim,vimwiki set ff=unix
    " 自動最大化窗口
    if has('gui_running')
        if has("win32")
            au GUIEnter * simalt ~x
            "elseif has("unix")
            "au GUIEnter * winpos 0 0
            "set lines=999 columns=999
            " 給 Win32 下的 gVim 窗口設置透明度
            au GUIEnter * call libcallnr("vimtweak.dll", "SetAlpha", 225)
        endif
    endif
endif
" =================
" Plugin Configure
" =================
"neocomplcache setting
" VIM HTML 插件
let g:no_html_toolbar = 'yes'
"""""""""""""""""""""""""""""""""""""""""""""""""""""
" VimWiki 配置
if !exists("g:vimwiki_list")
    let g:vimwiki_list = [
                \{"path": "~/Wiki/Default/", "path_html": "~/Sites/wiki/",  
                \   "html_footer": "~/Wiki/Default/footer.tpl", "html_header": "~/Wiki/Default/header.tpl",
                \   "auto_export": 1},
                \{"path": "~/Wiki/WebWW/",   "path_html": "~/Sites/webww/", "auto_export": 1}
                \]
    let g:vimwiki_auto_checkbox = 0
    if has('win32')
        " 注意!
        " 一、若是在 Windows 下,盤符必須大寫
        " 二、路徑末尾最好加上目錄分隔符
        let s:vimwiki_root = "$VIM/Vimwiki"
        let g:vimwiki_list = [
                    \{"path": s:vimwiki_root."/Default/", 
                    \   "html_footer": s:vimwiki_root."/Default/footer.html", 
                    \   "html_header": s:vimwiki_root."/Default/header.html",
                    \   "path_html": s:vimwiki_root."/Default/_output/", "auto_export": 1},
                    \{"path": s:vimwiki_root."/WebWW/", 
                    \"path_html": s:vimwiki_root."/WebWW/html/",   "auto_export": 1}
                    \]
        let g:vimwiki_w32_dir_enc = 'cp936'
    endif
    au FileType vimwiki set ff=unix fenc=utf8 noswapfile nobackup
    "au FileType vimwiki imap <C-t> <c-r>=TriggerSnippet()<cr>
    nmap <C-i><C-i> :VimwikiTabGoHome<cr>
    nmap <Leader>ii :VimwikiTabGoHome<cr>
endif
" on Windows, default charset is gbk
if has("win32")
    let g:fontsize#encoding = "cp936"
endif
""""""""""""""""""""""""""""""""""""
" PYTHON 相關的設置
"設置= + - * 先後自動空格
"設置,後面自動添加空格
au FileType python inoremap <buffer>= <c-r>=EqualSign('=')<CR>
au FileType python inoremap <buffer>+ <c-r>=EqualSign('+')<CR>
au FileType python inoremap <buffer>- <c-r>=EqualSign('-')<CR>
au FileType python inoremap <buffer>* <c-r>=EqualSign('*')<CR>
au FileType python inoremap <buffer>/ <c-r>=EqualSign('/')<CR>
au FileType python inoremap <buffer>> <c-r>=EqualSign('>')<CR>
au FileType python inoremap <buffer>< <c-r>=EqualSign('<')<CR>
au FileType python inoremap <buffer>: <c-r>=Swap()<CR>
au FileType python inoremap <buffer>, ,<space>
" ==================
" script's functions  
"===================
" 獲取當前目錄
func! GetPWD()
    return substitute(getcwd(), "", "", "g")
endf
" 跳過頁頭註釋,到首行實際代碼
func! GotoFirstEffectiveLine()
    let l:c = 0
    while l:c<line("$") && (
                \ getline(l:c) =~ '^\s*$'
                \ || synIDattr(synID(l:c, 1, 0), "name") =~ ".*Comment.*"
                \ || synIDattr(synID(l:c, 1, 0), "name") =~ ".*PreProc$"
                \ )
        let l:c = l:c+1
    endwhile
    exe "normal ".l:c."Gz\<CR>"
endf
" 返回當前時期
func! GetDateStamp()
    return strftime('%Y-%m-%d')
endfunction
" 全選
func! SelectAll()
    let s:current = line('.')
    exe "norm gg" . (&slm == "" ? "VG" : "gH\<C-O>G")
endfunc
" From an idea by Michael Naumann
func! VisualSearch(direction) range
    let l:saved_reg = @"
    execute "normal! vgvy"
    let l:pattern = escape(@", '\\/.*$^~[]')
    let l:pattern = substitute(l:pattern, "\n$", "", "")
    if a:direction == 'b'
        execute "normal ?" . l:pattern . "^M"
    elseif a:direction == 'gv'
        call CmdLine("vimgrep " . '/'. l:pattern . '/' . ' **/*.')
    elseif a:direction == 'f'
        execute "normal /" . l:pattern . "^M"
    endif
    let @/ = l:pattern
    let @" = l:saved_reg
endfunc
"函數後面加上!是防止vimrc文件從新載入時報錯
"實現光標位置自動交換:) -->  ):
function! Swap()
    if getline('.')[col('.') - 1] =~ ")"
        return "\<ESC>la:"
    else
        return ":"
    endif
endf
""""""""""""""""""""""""""""""""""""""""
"實現+-*/先後自動添加空格,逗號後面自動添加空格,適用python
"支持+= -+ *= /+格式
function! EqualSign(char)
    if a:char  =~ '='  && getline('.') =~ ".*("
        return a:char
    endif
    let ex1 = getline('.')[col('.') - 3]
    let ex2 = getline('.')[col('.') - 2]
    if ex1 =~ "[-=+><>\/\*]"
        if ex2 !~ "\s"
            return "\<ESC>i".a:char."\<SPACE>"
        else
            return "\<ESC>xa".a:char."\<SPACE>"
        endif
    else
        if ex2 !~ "\s"
            return "\<SPACE>".a:char."\<SPACE>\<ESC>a"
        else
            return a:char."\<SPACE>\<ESC>a"
        endif
    endif
endf 
"""""""""""""""""""""""""""""""""""""""""""""""""""""""
"SwitchToBuf()實現它在全部標籤頁的窗口中查找指定的文件名,若是找到這樣一個窗口,
"就跳到此窗口中;不然,它新建一個標籤頁來打開vimrc文件
"上面自動編輯.vimrc文件用到的函數
function! SwitchToBuf(filename)
    let bufwinnr = bufwinnr(a:filename)
    if bufwinnr != -1
    exec bufwinnr . "wincmd w"
        return
    else
        " find in each tab
        tabfirst
        let tab = 1
        while tab <= tabpagenr("$")
            let bufwinnr = bufwinnr(a:filename)
            if bufwinnr != -1
                exec "normal " . tab . "gt"
                exec bufwinnr . "wincmd w"
                return
            endif
            tabnext
            let tab = tab + 1
        endwhile
        " not exist, new tab
        exec "tabnew " . a:filename
    endif
endfunction
""""""""""""""""""""""""""""""""""""""""""""""""""
"Last change用到的函數,返回時間,可以自動調整位置
function! TimeStamp(...)
    let sbegin = ''
    let send = ''
    if a:0 >= 1
        let sbegin = a:1.'\s*'
    endif
    if a:0 >= 2
        let send = ' '.a:2
    endif
    let pattern =  'Last Change: .\+'
        \. send
    let pattern = '^\s*' . sbegin . pattern . '\s*$'
    let now = strftime('%Y-%m-%d %H:%M:%S',
        \localtime())
    let row = search(pattern, 'n')
    if row  == 0
        let now = a:1 .  ' Last Change:  '
            \. now . send
        call append(2, now)
    else
        let curstr = getline(row)
        let col = match( curstr , 'Last')
        let spacestr = repeat(' ',col - 1)
        let now = a:1 . spacestr . 'Last Change:  '
            \. now . send
        call setline(row, now)
    endif
endfunction
" =============
" Key Shortcut
" =============
nmap <C-t>   :tabnew<cr>
nmap <C-p>   :tabprevious<cr>
nmap <C-n>   :tabnext<cr>
nmap <C-k>   :tabclose<cr>
nmap <C-Tab> :tabnext<cr> 
for i in range(1, &tabpagemax)
    exec 'nmap <A-'.i.'> '.i.'gt'
endfor
" 插件快捷鍵
nmap <C-d> :NERDTree<cr>
nmap <C-e> :BufExplorer<cr>
nmap <F2>  :BufExplorer<cr>
" 插入模式按 F4 插入當前時間
imap <F4> <C-r>=GetDateStamp()<cr>
map <F6> zM    " 關閉全部折
map <F7> zR    " 打開全部摺疊
nmap <F8> :TagbarToggle<cr>
map <F12> :!ctags -R<CR>
map <C-F12> :!ctags -R --c++-kinds=+p --fields=+iaS --extra=+q .<CR>
" 新建 XHTML 、PHP、Javascript 文件的快捷鍵
nmap <C-c><C-h> :NewQuickTemplateTab xhtml<cr>
nmap <C-c><C-p> :NewQuickTemplateTab php<cr>
nmap <C-c><C-j> :NewQuickTemplateTab javascript<cr>
nmap <C-c><C-c> :NewQuickTemplateTab css<cr>
nmap <Leader>ca :Calendar<cr>
nmap <Leader>mr :MRU<cr>
nmap <Leader>dd :NERDTreeToggle<cr>
nmap <Leader>bf :BufExplorer<cr>
nmap <Leader>tb :TagbarToggle<cr>
" 直接查看第一行生效的代碼
nmap <C-g><C-f> :call GotoFirstEffectiveLine()<cr>
" 按下 Q 不進入 Ex 模式,而是退出
nmap Q :x<cr>
"==================
" Bundle setting
" =================
set nocompatible               " be iMproved
 filetype off                   " required!
 set rtp+=$VIM/vimfiles/bundle/vundle/
 "call vundle#rc('$VIM/vimfiles/bundle')
 " let Vundle manage Vundle
 " required! 
 " My Bundles here:
 " original repos on github
 "========================================
 " non github repos
 "========================================
 "call pathogen#infect("$vim/vimfiles/bundle")
 filetype plugin indent on     " required!
相關文章
相關標籤/搜索