"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" This vimrc is based on the vimrc by Amix, URL:
"   http://www.amix.dk/vim/vimrc.html
"
" Maintainer: uprush
"   http://www.sukekun.com/
"   http://uprush.net
" Version: 0.9
" Last Change: 2008-07-18 23:01:27
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""

set nocompatible

" Platform
function! MySys()
  if has("win32")
    return "windows"
  else
    return "linux"
  endif
endfunction

" For windows version
if MySys() == 'windows'
    "start gvim maximized
    if has("autocmd")
        au GUIEnter * simalt ~x
    endif

    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
endif

"Enable msvin
source $VIMRUNTIME/mswin.vim
behave mswin

"Enable filetype
filetype on
filetype plugin on
filetype indent on

"Set mapleader
let mapleader = ","
let g:mapleader = ","

"印刷用
if has('printer')
  if has('win32')
     set printfont=MS_Gothic:h9:cSHIFTJIS
  elseif has("unix")
     set guifont=IPA\ モナー\ ゴシック\ 12
     set printencoding=euc-jp
     if exists('&printmbcharset')
        set printmbcharset=JIS_X_1983
        set printmbfont=r:Ryumin-Light,b:Ryumin-Light,a:yes,c:yes
     endif
  endif
endif

" if windows, detect mac format
if $OSTYPE=='cygwin' || $TERM=='cygwin' || exists("$HOMEDRIVE")
  set fileformats+=mac
endif

" Switch syntax highlighting on, when the terminal has colors
" Also switch on highlighting the last used search pattern.
if &t_Co > 2 || has("gui_running")
  syntax on
  set hlsearch
endif
if &term=="xterm"
     set t_Co=8
     set t_Sb=^[[4%dm
     set t_Sf=^[[3%dm
endif

" colorscheme
if has("gui_running")
  colorscheme desert
else
  colorscheme desert_term
endif

" change current dir when bufenter
" autocmd BufEnter * call Change_curr_dir()
function! Change_curr_dir()
    let _dir = expand("%:p:h")
    exec "cd " . _dir
    unlet _dir
endfunction

set nobackup    "no backup
set noswapfile  "no swap file
set iminsert=0  "入力モードでのIMEのデフォルト状態
set imsearch=0  "検索モードでのIMEのデフォルト状態
set statusline=%<%f\ %m%r%h%w%{'['.(&fenc!=''?&fenc:&enc).']['.&ff.']'}%=%l,%c%V%8P " ステータスラインに文字コードと改行文字を表示する
set nowrapscan    " 検索でファイル終端に来たら先頭に戻らない
set laststatus=2  " ステータスラインを常に表示
set fencs=ucs-bom,utf-8,euc-jp,cp932,big5,cp936,iso-2022-jp
set go-=T   " toolbar 非表示
set go-=m   " menu 非表示
set ts=4    " tabspace
set sw=4    " indent
set smarttab
set expandtab   "tab -> space
set ai  "Auto indent
set si  "Smart indet
set ignorecase  "検索時大文字と小文字を区別しない
set backspace=eol,start,indent  "インデント等をBSで削除できるように
set lz  "Do not redraw, when running macros.. lazyredraw
"No sound on errors.
set noerrorbells
set novisualbell
set t_vb=
set mouse=a     "Have the mouse enabled all the time:
set incsearch   "増分検索
set completeopt=longest,menu    "Do not show Omni preview window

""""""""""""""""""""""""""""""
" Visual
""""""""""""""""""""""""""""""
" From an idea by Michael Naumann
function! 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"
  else
    execute "normal /" . l:pattern . "^M"
  endif
  let @/ = l:pattern
  let @" = l:saved_reg
endfunction

"Basically you press * or # to search for the current selection !! Really useful
vnoremap <silent> * :call VisualSearch('f')<CR>:let &hlsearch=&hlsearch<CR>
vnoremap <silent> # :call VisualSearch('b')<CR>:let &hlsearch=&hlsearch<CR>


" 挿入モード中に日付を形式で挿入
inoremap <C-D> <C-R>=strftime("%Y-%m-%d")<CR>
inoremap <C-T> <C-R>=strftime("%H:%M:%S")<CR>

" Escを押すと、Highlightを消す
map <F2> :noh<CR>
"nnoremap <silent> <ESC> <ESC>:noh<CR>
" tabnew
nmap <silent> <leader>t :tabnew<cr>

" Switch to buffer according to file name
function! SwitchToBuf(filename)
    let fullfn = substitute(a:filename, "^\\~/", $HOME . "/", "")
    " find in current tab
    let bufwinnr = bufwinnr(fullfn)
    if bufwinnr != -1
        exec bufwinnr . "wincmd w"
        return
    else
        " find in each tab
        tabfirst
        let tab = 1
        while tab <= tabpagenr("$")
            let bufwinnr = bufwinnr(fullfn)
            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 " . fullfn
    endif
endfunction

"Fast edit vimrc
if MySys() == 'linux'
    map <silent> <leader>ss :source ~/.vimrc<cr>
    map <silent> <leader>ee :call SwitchToBuf("~/.vimrc")<cr>
    autocmd! bufwritepost .vimrc source ~/.vimrc
elseif MySys() == 'windows'
    map <silent> <leader>ss :source ~/_vimrc<cr>
    map <silent> <leader>ee :call SwitchToBuf("~/_vimrc")<cr>
    autocmd! bufwritepost _vimrc source ~/_vimrc
endif

"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Editing mappings etc.
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
func! DeleteTrailingWS()
  %s/\s\+$//ge
endfunc
nmap <silent> <leader>ws :call DeleteTrailingWS()<cr>:w<cr>
" delete DOS return(^M)
nmap <silent> <leader>dr :%s/\r//g<cr>:w<cr>


"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Buffer realted
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
"Restore cursor to file position in previous editing session
set viminfo='10,\"100,:20,n~/.viminfo
au BufReadPost * if line("'\"") > 0|if line("'\"") <= line("$")|exe("norm '\"")|else|exe "norm $"|endif|endif


"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Complete
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Enable syntax
if has("autocmd") && exists("+omnifunc")
  autocmd Filetype *
        \if &omnifunc == "" |
        \  setlocal omnifunc=syntaxcomplete#Complete |
        \endif
endif
"pulldownあり:pulldownの次ページへ、なし:CTRL-X CTRL-O
inoremap <expr> <C-J>      pumvisible()?"\<PageDown>\<C-N>\<C-P>":"\<C-X><C-O>"
"pulldownあり:pulldownの前ページへ、なし:CTRL-K
inoremap <expr> <C-K>      pumvisible()?"\<PageUp>\<C-P>\<C-N>":"\<C-K>"


"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" netrw
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
let g:netrw_list_hide= '^\..*, *.swp'
nmap <silent> <leader>fe :call Change_curr_dir() <cr>: tabnew .<cr>
nmap <BS> :Explore<cr>


"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" filetype
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
autocmd FileType js,java :set shiftwidth=4 | set expandtab | set ts=4
autocmd FileType jsp,html,vm,xml :set shiftwidth=2 | set expandtab | set ts=2
autocmd BufRead *.log :setl nowrap
autocmd BufRead *.log :setl guioptions+=b
autocmd FileType c,cpp  setl fdm=syntax | setl fen


"+-------------------------------------------------- +
"|     For Plugin                                    |
"+-------------------------------------------------- +

" sketch
map <F11> :call ToggleSketch()<CR>

" sqlutil
let g:sqlutil_align_where = 1
let g:sqlutil_align_comma = 1
vmap <silent>sf <Plug>SQLU_Formatter<CR>

"taglist
if MySys() == "windows"
  let Tlist_Ctags_Cmd = "ctags"
elseif MySys() == "linux"
  let Tlist_Ctags_Cmd = "/usr/bin/ctags"
endif
let Tlist_Show_One_File = 1
let Tlist_Exit_OnlyWindow = 1
let Tlist_Use_Right_Window = 1
map <silent> <leader>tl :TlistToggle<cr>

""""""""""""""""""""""""""""""
" mark setting
""""""""""""""""""""""""""""""
nmap <silent> <leader>hl <Plug>MarkSet
vmap <silent> <leader>hl <Plug>MarkSet
nmap <silent> <leader>hh <Plug>MarkClear
vmap <silent> <leader>hh <Plug>MarkClear
nmap <silent> <leader>hr <Plug>MarkRegex
vmap <silent> <leader>hr <Plug>MarkRegex


""""""""""""""""""""""""""""""
" showmarks setting
""""""""""""""""""""""""""""""
" Enable ShowMarks
let showmarks_enable = 1
" Show which marks
let showmarks_include = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
" Ignore help, quickfix, non-modifiable buffers
let showmarks_ignore_type = "hqm"
" Hilight lower & upper marks
let showmarks_hlline_lower = 1
let showmarks_hlline_upper = 1


""""""""""""""""""""""""""""""
" markbrowser setting
""""""""""""""""""""""""""""""
nmap <silent> <leader>mk :MarksBrowser<cr>


""""""""""""""""""""""""""""""
" lookupfile setting
""""""""""""""""""""""""""""""
let g:LookupFile_MinPatLength = 2
let g:LookupFile_PreserveLastPattern = 0
let g:LookupFile_PreservePatternHistory = 0
let g:LookupFile_AlwaysAcceptFirst = 1
let g:LookupFile_AllowNewFiles = 0
if filereadable("/home/uprush/workspace/sukekun/filenametags")
    let g:LookupFile_TagExpr = '"/home/uprush/workspace/sukekun/filenametags"'
endif
nmap <silent> <leader>lt :tabnew<cr>:LookupFile<cr>
nmap <silent> <leader>lk :LookupFile<cr>
nmap <silent> <leader>ll :LUBufs<cr>
nmap <silent> <leader>lw :LUWalk<cr>

" lookup file with ignore case
function! LookupFile_IgnoreCaseFunc(pattern)
    let _tags = &tags
    try
        let &tags = eval(g:LookupFile_TagExpr)
        let newpattern = '\c' . a:pattern
        let tags = taglist(newpattern)
    catch
        echohl ErrorMsg | echo "Exception: " . v:exception | echohl NONE
        return ""
    finally
        let &tags = _tags
    endtry

    " Show the matches for what is typed so far.
    let files = map(tags, 'v:val["filename"]')
    return files
endfunction
let g:LookupFile_LookupFunc = 'LookupFile_IgnoreCaseFunc'


""""""""""""""""""""""""""""""
" HTML related
""""""""""""""""""""""""""""""
" HTML entities - used by xml edit plugin
let xml_use_xhtml = 1
"To HTML
let html_use_css = 1
let html_number_lines = 0
let use_xhtml = 1

""""""""""""""""""""""""""""""
" SuperTab
""""""""""""""""""""""""""""""
let g:SuperTabRetainCompletionType = 1
let g:SuperTabDefaultCompletionType = "<C-X><C-P>"

""""""""""""""""""""""""""""""
" minibuf explorer
""""""""""""""""""""""""""""""
"let g:miniBufExplMapWindowNavVim = 1
"let g:miniBufExplMapWindowNavArrows = 1
"let g:miniBufExplMapCTabSwitchBufs = 1
"let g:miniBufExplModSelTarget = 1 

""""""""""""""""""""""""""""""
" project
""""""""""""""""""""""""""""""
let g:proj_flags="imstvcg"