1. 程式人生 > >vim 配置 比較全轉自GitHub

vim 配置 比較全轉自GitHub

轉自https://github.com/erasin/notes/blob/master/linux/vim/vimrc.md

" GLOBAL 環境配置
" ------------------------------------------------------------------

" 中文幫助
set helplang=cn

" 保留歷史 
set history=500

" 行控制
set linebreak               " 英文單詞在換行時不被截斷
set nocompatible            " 設定不相容VI
"set textwidth=80           " 設定每行80個字元自動換行,加上換行符
set wrap                    " 設定自動折行
"set nowrap                 " 設定不自動換行

" 標籤頁
set tabpagemax=15           " 最多15個標籤
"set showtabline=2          " 總是顯示標籤欄

" 關閉錯誤時的聲音提示
set noerrorbells
set novisualbell
set t_vb=                   " close visual bell

" 行號與標尺
set ruler                   " 右下角顯示游標位置的狀態行
set number                  " 顯示行號
set cursorline              " 突出顯示當前行
"set rulerformat=%15(%c%V\ %p%%%)

" 製表符(設定所有的tab和縮排為4個空格)
set tabstop=4               " 設定tab鍵的寬度
set shiftwidth=4            " 換行時行間交錯使用4個空格
"set cindent shiftwidth=4   " 自動縮排4空格
set softtabstop=4
set expandtab               " 使用空格來替換tab
set smarttab                " 開啟新行時使用智慧 tab 縮排

set list                     " 顯示Tab符,
set listchars=tab:\|\ ,      " 使用一高亮豎線代替 把符號顯示為 |
"set listchars=tab:>-,trail:-
"set listchars=tab:\|\ ,nbsp:%,trail:-

highlight LeaderTab guifg=#666666   " 設定行首tab為灰色
match LeaderTab /\t/        " 匹配行首tab

" 縮排
set autoindent              " 設定自動縮排
set smartindent             " 設定智慧縮排

" 搜尋
set hlsearch                " 開啟高亮顯示結果
set incsearch               " 開啟實時搜尋功能
"set noincsearch             " 關閉顯示查詢匹配過程
"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 ignorecase              " 搜尋時無視大小寫
set nowrapscan              " 搜尋到檔案兩端時不重新搜尋

" 狀態列顯示目前所執行的指令
set showcmd

" 自動重新讀入
set autoread                " 當檔案在外部被修改,自動更新該檔案


" 備份與快取
set nobackup
set nowb
"set noswapfile
set writebackup             " 設定無備份檔案

" 自動完成
set complete=.,w,b,k,t,i
set completeopt=longest,menu    " 只在下拉選單中顯示匹配專案,並且會自動插入所有匹配專案的相同文字


set showmatch               " 顯示括號配對情況
set iskeyword+=_,$,@,%,#,-  " 帶有如下符號的單詞不要被換行分割
"set wildmenu "開啟 wildmenu 選項,啟動具有選單項提示的命令列自動完成。
"set matchpairs=(:),{:},[:],<:>
"set whichwrap=b,s,<,>,[,]

set backspace=2             " 設定退格鍵可用
set mouse=a                 " 滑鼠可用
set ve=block                "游標可以定位在沒有實際字元的地方
"set fullscreen             " 啟動後自動全屏

set nocompatible            " 關閉相容模式
set hidden                  " 允許在有未儲存的修改時切換緩衝區
set relativenumber          " 行標跟隨
set clipboard+=unnamed      " 共享外部剪貼簿
set autochdir               " 設定檔案瀏覽器目錄為當前目錄

colorscheme default         " 配色方案

filetype indent on          " 針對不同的檔案型別採用不同的縮排格式
filetype plugin on          " 針對不同的檔案型別載入對應的外掛
filetype plugin indent on
filetype on                 " for taglist

" 預設為 UTF-8 編碼
" --------------------------------------------------------------- 
if has("multi_byte")
    set encoding=utf-8
    " English messages only
    "language messages zh_CN.utf-8

    if has('win32')
        language english
        let &termencoding=&encoding " 處理consle輸出亂碼
    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

" 編碼設定
" -------------------------------------------------------------
"set fileencoding=utf-8
set encoding=utf-8 "緩衝編碼
set fileencodings=utf-8,cp936,gb18030,big5,gbk,euc-jp,latin1
set fileencoding=utf-8
set termencoding=utf-8 "編碼轉換
"set fileformats=unix

" 命令列與狀態行
" -----------------------------------------------------------------------
set laststatus=2                          " 開啟狀態列資訊
set cmdheight=1                           " 命令列的高度,預設為1,這裡設為2
" 狀態行顯示的內容 [包括系統平臺、檔案型別、座標、所佔比例、時間等]
set statusline=%{fugitive#statusline()}\ %F%m%r%h%w\ [FORMAT=%{&ff}]\ [TYPE=%Y]\ [POS=%l,%v][%p%%]\ %y%r%m%*%=\ %{strftime(\"%d/%m/%y\ -\ %H:%M\")}

" line color
" now set it up to change the status line based on mode
if version >= 700
  au InsertEnter * hi StatusLine term=reverse ctermbg=5 gui=undercurl guisp=Magenta
  au InsertLeave * hi StatusLine term=reverse ctermfg=0 ctermbg=2 gui=bold,reverse
endif

function! InsertStatuslineColor(mode)
  if a:mode == 'i'
    hi statusline guibg=magenta
  elseif a:mode == 'r'
    hi statusline guibg=blue
  else
    hi statusline guibg=red
  endif
endfunction

au InsertEnter * call InsertStatuslineColor(v:insertmode)
au InsertChange * call InsertStatuslineColor(v:insertmode)
au InsertLeave * hi statusline guibg=green

" GUI MODEL 圖形介面
" ---------------------------------------------
if has("gui_running")
    colorscheme neon 
    "set guifont=Monospace\ 11
    "set gfw=Zhenyuan:h12:cGB2312
    "au GUIEnter * simalt ~x " 視窗啟動時自動最大化
    set guioptions-=m        " 隱藏選單欄
    set guioptions-=T        " 隱藏工具欄
    set guioptions-=L        " 隱藏左側滾動條
    set guioptions-=r        " 隱藏右側滾動條
    "set guioptions-=b       " 隱藏底部滾動條
    "set showtabline=0       " 隱藏Tab欄
    "colorscheme tango2 
    set lines=42
    set columns=136
    "set guifontset=-dt-interface
    set encoding=utf-8
    "language messages zh_CN.UTF-8  "解決consle輸出亂碼 
    set fdm=indent           "按照縮排進行摺疊 manual

    "Toggle Menu and Toolbar 使用F2隱藏/顯示選單
    map <silent> <F2> :if &guioptions =~# 'T' <Bar>
            \set guioptions-=T <Bar>
            \set guioptions-=m <bar>
        \else <Bar>
            \set guioptions+=T <Bar>
            \set guioptions+=m <Bar>
        \endif<CR>

    if has("win32")
        " Windows 相容配置
        source $VIMRUNTIME/mswin.vim

        " F11 最大化
        map <f11> :call libcallnr('fullscreen.dll', 'ToggleFullScreen', 0)<cr>

        " 字型配置
        "exec 'set guifont='.iconv('Courier_New', &enc, 'gbk').':h10:cANSI'
        "exec 'set guifontwide='.iconv('微軟雅黑', &enc, 'gbk').':h10'
        set guifont=YaHei_Consolas_Hybrid:h12:cANSI
        set guifontwide=YaHei_Consolas_Hybrid:h12
    endif

    if has("unix") && !has('gui_macvim')
        set guifont=Ubuntu\ Mono\ 11
    endif

endif

" Floding 摺疊
" ------------------------------------------------
"set foldmethod=syntax " 選擇程式碼摺疊型別
"set foldlevel=100 " 禁止自動摺疊
"
set foldenable " Enables folding.
" 摺疊方法  
" manual    手工摺疊  
" indent    使用縮排表示摺疊  
" expr      使用表示式定義摺疊  
" syntax    使用語法定義摺疊  
" diff      對沒有更改的文字進行摺疊  
" marker    使用標記進行摺疊, 預設標記是 {{{ 和 }}} 
set foldmethod=manual " Set fold method to 'manual'.
""set fdc=0 " Show where folds start and end, when they are opened.
"nnoremap @=((foldclosed(line('.')) < 0 )? 'zc':'zo')

:set foldtext=MyFoldText()
:function MyFoldText()
:  let line = getline(v:foldstart)
:  let sub = substitute(line, '/\*\|\*/\|{{{\d\=', '', 'g')
:  return v:folddashes . sub
:endfunction

" 語法高亮 
" ----------------------------------------------
syntax enable               " 開啟語法高亮
syntax on                   " 開啟檔案型別偵測
au BufRead,BufNewFile *.txt setlocal ft=txt
au BufRead,BufNewFile *.tpl setlocal ft=smarty 		" 支援 Smarty
au BufRead,BufNewFile *.as setlocal ft=actionscript	" 支援 ActionScript
"au BufRead,BufNewFile *.js set ft=javascript syntax=jquery
au BufRead,BufNewFile jquery.*.js set ft=javascript syntax=jquery
"autocmd BufRead *.as set filetype=actionscript
"autocmd BufRead *.js set filetype=javascript
autocmd BufRead,BufNewFile *.txtfmt set filetype=txtfmt
"autocmd BufRead,BufNewFile *.txt set filetype=txtfmt
autocmd BufRead,BufNewFile *.mxml set filetype=mxml
autocmd BufRead,BufNewFile *.bash set filetype=bash
autocmd BufRead,BufNewFile *.php set filetype=php
autocmd BufRead,BufNewFile *.c set filetype=c

au BufNewFile,BufRead,BufEnter,WinEnter,FileType *.m,*.h setf objc  " 增加 Objective-C 語法支援
" fencview 自動編碼識別     :FencView   檢視檔案編碼和更改檔案編碼
let g:fencview_autodetect=1

" dict
autocmd FileType javascript set dictionary=~/.vim/dict/javascript.dict

" 每行超過80個的字元用下劃線標示
au BufRead,BufNewFile *.asm,*.c,*.cpp,*.java,*.cs,*.sh,*.lua,*.pl,*.pm,*.py,*.rb,*.hs,*.vim 2match Underlined /.\%81v/

" 將指定檔案的換行符轉換成 UNIX 格式
au FileType php,javascript,html,css,python,vim,vimwiki set ff=unix

" 關閉VIM的時候儲存會話,按F122讀取會話
set sessionoptions=buffers,sesdir,help,tabpages,winsize
au VimLeave * mks! ~/Session.vim
nmap <F7> :so ~/Session.vim<CR>

" 自動重新整理firefox
autocmd BufWriteCmd *.html,*.js,*.css,*.gtpl :call Refresh_firefox()
function! Refresh_firefox()
    if &modified
        write
        silent !echo ‘vimYo = content.window.pageYOffset;
                    \ vimXo = content.window.pageXOffset;
                    \ BrowserReload();
                    \ content.window.scrollTo(vimXo,vimYo);
                    \ repl.quit();’ |
                    \ nc localhost 4242 2>&1 > /dev/null
    endif
endfunction

" 自動載入VIM配置檔案
autocmd! bufwritepost vimrc source $MYVIMRC

" 自動匹配括號
" -----------------------------------
:inoremap ( ()<ESC>i
:inoremap ) <c-r>=ClosePair(')')<CR>
:inoremap { {}<ESC>i
:inoremap } <c-r>=ClosePair('}')<CR>
:inoremap [ []<ESC>i
:inoremap ] <c-r>=ClosePair(']')<CR>
":inoremap < <><ESC>i
":inoremap > <c-r>=ClosePair('>')<CR>
:inoremap " ""<ESC>i
:inoremap ' ''<ESC>i
:inoremap ` ``<ESC>i

function ClosePair(char)
    if getline('.')[col('.') - 1] == a:char
        return "\<Right>"
    else
        return a:char
    endif
endf

" 快捷鍵
" --------------------------------------

"設定','為leader快捷鍵
let mapleader = ","
let g:mapleader = ","

" Ctrl + S 儲存檔案
map <C-s> <ESC>:w<CR>
imap <C-s> <ESC>:w<CR>a
vmap <C-s> <ESC>:w<CR>

" Ctrl + C 選中狀態下複製
vnoremap <C-c> "+y

" Ctrl + V 貼上剪下板中的內容
map <C-v> "+p
imap <C-v> <esc>"+pa
vmap <C-v> d"+P

"設定快速儲存和退出
"快速儲存為,s
"快速退出(儲存)為,w
"快速退出(不儲存)為,q
nmap <leader>s :w!<cr>
nmap <leader>w :wq!<cr>
nmap <leader>q :q!<cr>

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>

"切換buffer
nmap bn :bn<cr>
nmap bp :bp<cr>

" 插入模式按 F4 插入當前時間
imap <f4> <C-r>=GetDateStamp()<cr>

" 返回當前時期
func! GetDateStamp()
    return strftime('%Y-%m-%d')
endfunction

" 選中一段文字並全文搜尋這段文字
vnoremap  *  y/<C-h>=escape(@", '\\/.*$^~[]')<CR><CR>
vnoremap  #  y?<C-h>=escape(@", '\\/.*$^~[]')<CR><CR>

"----------------------------------------------------------------------------
" Plugin TagList
" ---------------------------------------------------------------------------
" TagList 鍵入:Tlist開啟
" if MySys() == "windows"                "設定windows系統中ctags程式的位置
" 	let Tlist_Ctags_Cmd = 'ctags'
" elseif MySys() == "linux"              "設定windows系統中ctags程式的位置
    let Tlist_Ctags_Cmd = '/usr/bin/ctags'
" endif
map t :TlistToggle<cr>
let Tlist_Show_One_File = 1            "不同時顯示多個檔案的tag,只顯示當前檔案的
let Tlist_Compact_Format = 1 		   " 使用小視窗.
let Tlist_Exit_OnlyWindow = 1          "如果taglist視窗是最後一個視窗,則退出vim
let Tlist_Enable_Fold_Column = 0 	   " 使taglist外掛不顯示左邊的摺疊行
let Tlist_Use_Right_Window = 1         "在右側視窗中顯示taglist視窗
"let Tlist_Use_Left_Window = 1          " Split to the left side of the screen.
let Tlist_GainFocus_On_ToggleOpen = 1
let Tlist_Inc_Winwidth = 0 			   " 防止taglist改變終端視窗的大小
let Tlist_WinWidth = 25 			   " taglist視窗寬度
let Tlist_Sort_Type = 'name'           " 排序 name.

" ---------------------------------------------------------------------------
" Plugin NERDTree
" ----------------------------------------------------------------------------
" plugin - NERD_tree.vim 以樹狀方式瀏覽系統中的檔案和目錄
" :NERDtree 開啟NERD_tree         :NERDtreeClose    關閉NERD_tree
" o 開啟關閉檔案或者目錄         t 在標籤頁中開啟
" T 在後臺標籤頁中開啟           ! 執行此檔案
" p 到上層目錄                   P 到根目錄
" K 到第一個節點                 J 到最後一個節點
" u 開啟上層目錄                 m 顯示檔案系統選單(新增、刪除、移動操作)
" r 遞迴重新整理當前目錄             R 遞迴重新整理當前根目錄
"-----------------------------------------------------------------
let loaded_netrwPlugin = 0 					" 不啟動netrw
let NERDTreeCaseSensitiveSort=1 			" 讓檔案排列更有序
let NERDTreeHijackNetrw = 0 				" 輸入:e filename不再顯示netrw,而是顯示nerdtree
let NERDTreeChDirMode = 2 					" 改變tree目錄的同時不改變工程的目錄
let NERDTreeWinPos = 'left' 				" NERDTree顯示位置在視窗右側
let NERDTreeWinSize = 25 					" NERDTREE的大小
let NERDTreeIgnore = [ '^\.svn$', '\~$' ] 	" 忽略.svn的顯示
" F3 NERDTree 切換
map <F3> :NERDTreeToggle<CR>
imap <F3> <ESC>:NERDTreeToggle<CR>

"-----------------------------------------------------------------
" plugin - NERD_commenter.vim 註釋程式碼用的
" 將 mapleader 設定為 `,`
" [count],cc 游標以下count行逐行添加註釋(7,cc)
" [count],cu 游標以下count行逐行取消註釋(7,cu)
" [count],cm 游標以下count行嘗試新增塊註釋(7,cm)
" ,cA 在行尾插入 /* */,並且進入插入模式。 這個命令方便寫註釋
" ,c<space> toggle 註釋
" 注:count引數可選,無則預設為選中行或當前行
"-----------------------------------------------------------------
let NERDSpaceDelims=1       " 讓註釋符與語句之間留一個空格
let NERDCompactSexyComs=1   " 多行註釋時樣子更好看

" Plugin MiniBufExplorer 多個檔案切換 可使用滑鼠雙擊相應檔名進行切換
""let g:miniBufExplMapWindowNavVim = 1
""let g:miniBufExplMapWindowNavArrows = 1
""let g:miniBufExplMapCTabSwitchBufs = 1
""let g:miniBufExplModSelTarget = 1

" --------------------------------------------------------------------
" plugin Load_Template 根據檔案字尾自動載入模板,使用:LoadTemplate撥出
" --------------------------------------------------------------------
" let g:template_path = '~/.vim/templates'

" ---------------------------------------------------------------------
" plugin indent guides 對齊線
" ---------------------------------------------------------------------
" <Leader>ig     toggle
let g:indent_guides_guide_size=1    "設定寬度

" ---------------------------------------------------------------------
" 處理檔案
" ---------------------------------------------------------------------
" **** PHP **** {{{
" 不顯示PHP變數再Taglist中
let tlist_php_settings = 'php;c:class;d:constant;f:function'
" 高亮顯示sql語句
let php_sql_query = 1 
" }}}

" **** Python *** {{{
" For lines that end with \n\ or \ and continue on the next one.
"let g:pyindent_continue = '&sw - &sw'
let g:pyindent_continue = 0
autocmd Filetype python set completefunc=pythoncomplete#Complete
" }}}


" 一鍵儲存和編譯 
" -----------------------------------------
" Ctrl + G 一鍵儲存、編譯
" Ctrl + R 一鍵儲存、執行
"
" 編譯C原始檔
func! CompileGcc()
    exec "w"
    let compilecmd="!gcc -Wall -std=c99 "
    let compileflag="-o %<"
    exec compilecmd." % ".compileflag
endfunc

" 編譯C++原始檔
func! CompileCpp()
    exec "w"
    let compilecmd="!g++ -Wall "
    let compileflag="-o %<"
    exec compilecmd." % ".compileflag
endfunc

" 編譯Haskell原始檔
func! CompileHaskell()
    exec "w"
    let compilecmd="!ghc --make "
    let compileflag="-o %<"
    exec compilecmd." % ".compileflag
endfunc

" 編譯Java原始檔
func! CompileJava()
    exec "w"
    exec "!javac %"
endfunc

" 編譯C#原始檔
func! CompileCs()
    exec "w"
    exec "!csc %"
endfunc

" 編譯Gas原始檔
func! CompileGas()
    exec "w"
    exec "!gcc -Wall -ggdb -o %< %"
endfunc

" 執行Shell原始檔
func! RunShell()
    exec "w"
    exec "!sh %"
endfunc

" 執行Lua原始檔
func! RunLua()
    exec "w"
    exec "!lua %"
endfunc

" 執行Perl原始檔
func! RunPerl()
    exec "w"
    exec "!perl %"
endfunc

" 執行Python原始檔
func! RunPython()
    exec "w"
    exec "!python %"
endfunc

" 執行Ruby原始檔
func! RunRuby()
    exec "w"
    exec "!ruby %"
endfunc

" 檢測PHP程式語法
func! RunPHP()
    exec "w"
    exec "!php -l %"
endfunc

" vala
func! CompileVala()
    exec "w"
    exec "!valac --pkg gtk+-3.0 %"
    exec "!./%<"
endfunc

" 根據檔案型別自動選擇相應的編譯函式
func! CompileCode()
    exec "w"
    if &filetype == "c"
        exec "call CompileGcc()"
    elseif &filetype == "cpp"
        exec "call CompileCpp()"
    elseif &filetype == "haskell"
        exec "call CompileHaskell()"
    elseif &filetype == "java"
        exec "call CompileJava()"
    elseif &filetype == "cs"
        exec "call CompileCs()"
    elseif &filetype == "asm"
        exec "call CompileGas()"
    elseif &filetype == "sh"
        exec "call RunShell()"
    elseif &filetype == "lua"
        exec "call RunLua()"
    elseif &filetype == "perl"
        exec "call RunPerl()"
    elseif &filetype == "python"
        exec "call RunPython()"
    elseif &filetype == "ruby"
        exec "call RunRuby()"
    elseif &filetype == "php"
        exec "call RunPHP()"
    elseif &filetype == "vala"
        exec "call CompileVala()"
    endif
endfunc

" 執行可執行檔案
func! RunResult()
    exec "w"
    if &filetype == "c"
        exec "! %<"
    elseif &filetype == "cpp"
        exec "! %<"
    elseif &filetype == "haskell"
        exec "! %<"
    elseif &filetype == "java"
        exec "!java %<"
    elseif &filetype == "cs"
        exec "! %<"
    elseif &filetype == "asm"
        exec "! %<"
    elseif &filetype == "sh"
        exec "!sh %<.sh"
    elseif &filetype == "lua"
        exec "!lua %<.lua"
    elseif &filetype == "perl"
        exec "!perl %<.pl"
    elseif &filetype == "python"
        exec "!python %<.py"
    elseif &filetype == "ruby"
        exec "!ruby %<.rb"
    endif
endfunc


" Ctrl + G 一鍵儲存、編譯
" Ctrl + R 一鍵儲存、執行
map <C-g> :call CompileCode()<CR>
imap <C-g> <ESC>:call CompileCode()<CR>
vmap <C-g> <ESC>:call CompileCode()<CR>

map <C-r> :call RunResult()<CR>
imap <C-r> <ESC>:call RunResult()<CR>
vmap <C-r> <ESC>:call RunResult()<CR>

" 對齊線高亮顯示 
" 利用自帶的 cc 即 colorcolum
" -----------------------------------------------------
" 使用  ,ch 來toggle對齊線
map ,ch :call SetColorColumn()<CR>
function! SetColorColumn()
    let col_num = virtcol(".")
    let cc_list = split(&cc, ',')
    if count(cc_list, string(col_num)) <= 0
        execute "set cc+=".col_num
    else
        execute "set cc-=".col_num
    endif
endfunction