" vim:shiftwidth=2:tabstop=8:expandtab

" WARNING: Vim 6.x typically has problems using encoding UTF-8 _and_
" localized CJK (Chinese, Japanese, and Korean) messages on CJK versions
" of Windows (or other version of Windows with the legacy encoding set
" to a CJK one).  By default this script will enable UTF-8 in GVIM,
" which can cause this problem.  A patch (and the patched Win32 binary)
" is available at <URL:http://wyw.dcweb.cn/>.  You may also choose to
" work around this problem by setting the environment variable LANG as
" follows:
"
"   set LANG=en (English msg only; other non-CJK locales will do too)
"
" or
"
"   set LANG=zh_CN.CP936 (spell out and use the legacy encoding)
"
" Vim 7 has not this problem (and is now recommended).

if has('autocmd')
  " Remove ALL autocommands for the current group
  au!

  " Mark .asm files MASM-type assembly
  au BufNewFile,BufReadPre *.asm let b:asmsyntax='masm'

  " Load doxygen syntax file for c/cpp/idl files
  let mysyntaxfile=$VIM . '\vimfiles\syntax\doxygen_load.vim'
endif

if has('gui_running')
  let do_syntax_sel_menu=1
endif

set nocompatible
source $VIMRUNTIME/vimrc_example.vim
if has('gui_running')
  source $VIMRUNTIME/mswin.vim
  unmap <C-Y>|            " <C-Y> is still allowed in insert mode
  " Key mapping to switch windows quickly (<C-Tab> is already mapped)
  nnoremap <C-S-Tab> <C-W>W
  inoremap <C-S-Tab> <C-O><C-W>W
endif

set autoindent
set nobackup
set formatoptions+=mM
set fileencodings=ucs-bom,utf-8,cp936
set grepprg=grep\ -n
set statusline=%<%f\ %h%m%r%=%k[%{(&fenc==\"\")?&enc:&fenc}%{(&bomb?\",BOM\":\"\")}]\ %-14.(%l,%c%V%)\ %P
set tags+=C:\Program\\\ Files\Vim\vimfiles\systags      " help ft-c-omni
set path=.,
        \D:/mingw/lib/gcc-lib/mingw32/2.95.3-8/include,
        \D:/mingw/include,
        \D:/mingw/include/g++-3,
        \,

" The matchparen plugin (standard in Vim 7) works better than 'showmatch'
if v:version < 700
  set showmatch
endif

" Set suitable spelling convention for International English
if v:version >= 700 && has('syntax')
  " Use the British spelling convention of Vim 7
  set spelllang=en_gb
elseif has('eval')
  " Use Canadian spelling convention of engspchk (Vim script #195)
  let spchkdialect='can'
endif

" Function to find the absolute path of a runtime file
if has('eval')
  function FindRuntimeFile(filename, ...)
    if a:0 != 0 && a:1 =~ 'w'
      let require_writable = 1
    else
      let require_writable = 0
    endif
    let runtimepaths = &runtimepath . ','
    while strlen(runtimepaths) != 0
      let filepath = substitute(runtimepaths, ',.*', '', '') . '/' . a:filename
      if filereadable(filepath)
        if !require_writable || filewritable(filepath)
          return filepath
        endif
      endif
      let runtimepaths = substitute(runtimepaths, '[^,]*,', '', '')
    endwhile
    return ''
  endfunction
endif

" Personal setting for working with Windows NT/2000/XP (requires tee in path)
if &shell =~? 'cmd'
  "set shellxquote=\"
  set shellpipe=2>&1\|\ tee
endif

" Key mappings to ease browsing long lines
noremap  <C-J>         gj
noremap  <C-K>         gk
inoremap <M-Home> <C-O>g0
inoremap <M-End>  <C-O>g$

" Key mappings for quick arithmetic inside Vim
nnoremap <silent> <Leader>ma yypV:!calcu <C-R>"<CR>k$
vnoremap <silent> <Leader>ma yo<ESC>pV:!calcu <C-R>"<CR>k$
nnoremap <silent> <Leader>mr yyV:!calcu <C-R>"<CR>$
vnoremap <silent> <Leader>mr ygvmaomb:r !calcu <C-R>"<CR>"ay$dd`bv`a"ap

" Key mapping to stop the search highlight
nmap <silent> <F2>      :nohlsearch<CR>
imap <silent> <F2> <C-O>:nohlsearch<CR>

" Key mapping to toggle the display of status line for the last window
nmap <silent> <F6> :if &laststatus == 1<bar>
                     \set laststatus=2<bar>
                     \echo<bar>
                   \else<bar>
                     \set laststatus=1<bar>
                   \endif<CR>

" Key mappings for quickfix commands, tags, and buffers
nmap <F11>   :cn<CR>
nmap <F12>   :cp<CR>
nmap <M-F11> :copen<CR>
nmap <M-F12> :cclose<CR>
nmap <C-F11> :tn<CR>
nmap <C-F12> :tp<CR>
nmap <S-F11> :n<CR>
nmap <S-F12> :prev<CR>

" Key mapping for the taglist.vim plugin
nmap <F9>      :Tlist<CR>
imap <F9> <C-O>:Tlist<CR>

" Function to turn each paragraph to a line (to work with, say, MS Word)
function! ParagraphToLine()
  normal ma
  if &formatoptions =~ 'w'
    let reg_bak=@"
    normal G$vy
    if @" =~ '\s'
      normal o
    endif
    let @"=reg_bak
    silent! %s/\(\S\)$/\1\r/e
  else
    normal Go
  endif
  silent! g/\S/,/^\s*$/j
  silent! %s/\s\+$//e
  normal `a
endfunction

" Non-GUI setting
if !has('gui_running')
  " English messages only
  language messages en

  " Do not increase the windows width in the taglist.vim plugin
  if has('eval')
    let Tlist_Inc_Winwidth=0
  endif

  " Set text-mode menu
  if has('wildmenu')
    set wildmenu
    set cpoptions-=<
    set wildcharm=<C-Z>
    nmap <F10>      :emenu <C-Z>
    imap <F10> <C-O>:emenu <C-Z>
  endif

  " Change encoding according to the current console code page
  if &termencoding != '' && &termencoding != &encoding
    let &encoding=&termencoding
    let &fileencodings='ucs-bom,utf-8,' . &encoding
  endif
endif

" Display window width and height in GUI
if has('gui_running') && has('statusline')
  let &statusline=substitute
                 \(&statusline, '%=', '%=%{winwidth(0)}x%{winheight(0)}  ', '')
  set laststatus=2
endif

" Set up language and font in GUI
if has('gui_running') && has('multi_byte')
  function! UTF8_East()
    exec 'language messages ' . s:east_lang . '.UTF-8'
    set ambiwidth=double
    set encoding=utf-8
    set guifont=
  endfunction

  function! UTF8_West()
    exec 'language messages ' . s:west_lang . '.UTF-8'
    set ambiwidth=single
    set encoding=utf-8
    set guifont=Courier_New:h10:cDEFAULT
  endfunction

  function! UTF8_SwitchMode()
    if &ambiwidth == 'single'
      call UTF8_East()
    else
      call UTF8_West()
    endif
  endfunction

  " Set encoding (and possibly fileencodings)
  if $LANG !~ '\.' || $LANG =~? '\.UTF-8$'
    set encoding=utf-8
  else
    let &encoding=matchstr($LANG, '\.\zs.*')
    let &fileencodings='ucs-bom,utf-8,' . &encoding
  endif

  " Delmenu here has a strange side-effect to make the translation for
  " `tear off this menu' display correctly, but will disable the menu
  " for engspchk
  if v:version >= 700 || v:lang !~? '^\(C\|en\)\(_\|\.\|$\)'
    runtime! delmenu.vim
  endif

  " Extract the current east/west language settings
  if v:lang =~? '^\(zh\)\|\(ja\)\|\(ko\)'
    let s:east_lang=matchstr(v:lang, '^[a-zA-Z_]*\ze\(\.\|$\)')
    let s:west_lang='en'
    let s:default_east_lang=1
  else
    let s:east_lang='zh_CN'
    let s:west_lang=matchstr(v:lang, '^[a-zA-Z_]*\ze\(\.\|$\)')
    let s:default_east_lang=0
  endif

  " Set a suitable GUI font and the ambiwidth option
  if &encoding == 'utf-8'
    if s:default_east_lang
      call UTF8_East()
    else
      call UTF8_West()
    endif
  elseif !s:default_east_lang
    set guifont=Courier_New:h10:cDEFAULT
  endif

  " Key mapping to switch the east/west UTF-8 mode
  nmap <F8>      :call UTF8_SwitchMode()<CR>
  imap <F8> <C-O>:call UTF8_SwitchMode()<CR>
endif

" Key mapping to toggle spelling check in Vim 7
if v:version >= 700 && has('syntax') && has('eval')
  nmap <silent> <F7>      :setlocal spell!<CR>
  imap <silent> <F7> <C-O>:setlocal spell!<CR>
  let spellfile_path = FindRuntimeFile('spell/en.' . &encoding . '.add', 'w')
  if spellfile_path != ''
    exec 'nmap <M-F7> :sp ' . spellfile_path . '<CR><bar><C-W>_'
  endif
endif

if has('autocmd')
  function! SetInitialFileEncoding()
    if s:legacy_encoding != ''
      exec 'set fileencoding=' . s:legacy_encoding
    endif
  endfunction

  function! SetFileEncodings(encodings)
    let b:my_fileencodings_bak=&fileencodings
    let &fileencodings=a:encodings
  endfunction

  function! RestoreFileEncodings()
    let &fileencodings=b:my_fileencodings_bak
    unlet b:my_fileencodings_bak
  endfunction

  function! CheckFileEncoding()
    if &modified && &fileencoding != ''
      exec 'e! ++enc=' . &fileencoding
    endif
  endfunction

  function! ConvertHtmlEncoding(encoding)
    if a:encoding ==? 'gb2312'
      return 'cp936'            " GB2312 imprecisely means CP936 in HTML
    elseif a:encoding ==? 'iso-8859-1'
      return 'latin1'           " The canonical encoding name in Vim
    elseif a:encoding ==? 'utf8'
      return 'utf-8'            " Other encoding aliases should follow here
    else
      return a:encoding
    endif
  endfunction

  function! DetectHtmlEncoding()
    if &filetype != 'html'
      return
    endif
    normal m`
    normal gg
    if search('\c<meta http-equiv=\("\?\)Content-Type\1 content="text/html; charset=[-A-Za-z0-9_]\+">') != 0
      let reg_bak=@"
      normal y$
      let charset=matchstr(@", 'text/html; charset=\zs[-A-Za-z0-9_]\+')
      let charset=ConvertHtmlEncoding(charset)
      normal ``
      let @"=reg_bak
      if &fileencodings == ''
        let auto_encodings=',' . &encoding . ','
      else
        let auto_encodings=',' . &fileencodings . ','
      endif
      if charset !=? &fileencoding &&
         \(auto_encodings =~ ',' . &fileencoding . ',' || &fileencoding == '')
        silent! exec 'e ++enc=' . charset
      endif
    else
      normal ``
    endif
  endfunction

  function! GnuIndent()
    setlocal cinoptions=>4,n-2,{2,^-2,:2,=2,g0,h2,p5,t0,+2,(0,u0,w1,m1
    setlocal shiftwidth=2
    setlocal tabstop=8
  endfunction

  function! RemoveTrailingSpace()
    if $VIM_HATE_SPACE_ERRORS != '0' &&
          \(&filetype == 'c' || &filetype == 'cpp' || &filetype == 'vim')
      normal m`
      silent! :%s/\s\+$//e
      normal ``
    endif
  endfunction

  " Legacy encoding should be the one listed at the end of fileencodings
  let s:legacy_encoding=matchstr(&fileencodings, ',\zs[^,]\+$')

  " Set default file encoding to the legacy encoding
  call SetInitialFileEncoding()

  " Highlight space errors in C/C++ source files (Vim tip #935)
  if $VIM_HATE_SPACE_ERRORS != '0'
    let c_space_errors=1
  endif

  " Use the legacy encoding for CVS in cvsmenu (Vim script #1245)
  let CVScvsoutputencoding=s:legacy_encoding

  " Show syntax highlighting attributes of character under cursor (Vim
  " script #383)
  map <Leader>a :call SyntaxAttr()<CR>

  " Automatically find scripts in the autoload directory
  au FuncUndefined Syn* exec 'runtime autoload/' . expand('<afile>') . '.vim'

  " File type related autosetting
  au FileType c,cpp     setlocal cinoptions=:0,g0,(0,w1 shiftwidth=4 tabstop=4
  au FileType diff      setlocal shiftwidth=4 tabstop=4
  au FileType changelog setlocal textwidth=76
  au FileType html      setlocal indentexpr=
  au FileType mail      setlocal expandtab formatoptions+=aw

  " Text file encoding autodetection
  au BufReadPre  *.gb               call SetFileEncodings('cp936')
  au BufReadPre  *.big5             call SetFileEncodings('cp950')
  au BufReadPre  *.nfo              call SetFileEncodings('cp437')
  au BufReadPost *.gb,*.big5,*.nfo  call RestoreFileEncodings()
  au BufWinEnter *.txt              call CheckFileEncoding()

  " Detect charset encoding in an HTML file
  au BufReadPost *.htm* nested      call DetectHtmlEncoding()

  " Ensure C/C++ headers are always recognized regardless of the suffix
  au BufEnter */include/*           setf cpp

  " Setting for files following the GNU coding standard
  au BufEnter D:/WuYongwei/cvssrc/socket++/*  call GnuIndent()
  au BufEnter D:/mingw*             call GnuIndent()

  " Remove trailing spaces for C/C++ and Vim files
  au BufWritePre *                  call RemoveTrailingSpace()
endif